PageRenderTime 74ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/ds10/agent-j
PHP | 616 lines | 388 code | 55 blank | 173 comment | 87 complexity | e8f1a4bf6bc4b7409904fa262c434d3e MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, LGPL-3.0, GPL-2.0, LGPL-2.1, MIT
  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->alias . '.' . $model->primaryKey) . ')) ' . $db->alias . 'count';
  112. $query['joins'][] = array(
  113. 'type' => 'INNER',
  114. 'alias' => $RuntimeModel->alias,
  115. 'table' => $joinTable,
  116. 'conditions' => array(
  117. $model->alias . '.' . $model->primaryKey => $db->identifier($RuntimeModel->alias . '.foreign_key'),
  118. $RuntimeModel->alias . '.model' => $model->name,
  119. $RuntimeModel->alias . '.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->alias . '.*', $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 and possibly a field.
  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 mixed $locale The locale(s) having joins added.
  192. * @param boolean $addField Whether or not to add a field.
  193. * @return array The modfied query
  194. */
  195. protected function _addJoin(Model $model, $query, $field, $aliasField, $locale, $addField = false) {
  196. $db = ConnectionManager::getDataSource($model->useDbConfig);
  197. $RuntimeModel = $this->_runtimeModel;
  198. $joinTable = $this->_joinTable;
  199. if (is_array($locale)) {
  200. foreach ($locale as $_locale) {
  201. $model->virtualFields['i18n_' . $field . '_' . $_locale] = 'I18n__' . $field . '__' . $_locale . '.content';
  202. if (!empty($query['fields']) && is_array($query['fields'])) {
  203. $query['fields'][] = 'i18n_' . $field . '_' . $_locale;
  204. }
  205. $query['joins'][] = array(
  206. 'type' => 'LEFT',
  207. 'alias' => 'I18n__' . $field . '__' . $_locale,
  208. 'table' => $joinTable,
  209. 'conditions' => array(
  210. $model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}__{$_locale}.foreign_key"),
  211. 'I18n__' . $field . '__' . $_locale . '.model' => $model->name,
  212. 'I18n__' . $field . '__' . $_locale . '.' . $RuntimeModel->displayField => $aliasField,
  213. 'I18n__' . $field . '__' . $_locale . '.locale' => $_locale
  214. )
  215. );
  216. }
  217. } else {
  218. $model->virtualFields['i18n_' . $field] = 'I18n__' . $field . '.content';
  219. if (!empty($query['fields']) && is_array($query['fields'])) {
  220. $query['fields'][] = 'i18n_' . $field;
  221. }
  222. $query['joins'][] = array(
  223. 'type' => 'INNER',
  224. 'alias' => 'I18n__' . $field,
  225. 'table' => $joinTable,
  226. 'conditions' => array(
  227. $model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}.foreign_key"),
  228. 'I18n__' . $field . '.model' => $model->name,
  229. 'I18n__' . $field . '.' . $RuntimeModel->displayField => $aliasField,
  230. 'I18n__' . $field . '.locale' => $locale
  231. )
  232. );
  233. }
  234. return $query;
  235. }
  236. /**
  237. * afterFind Callback
  238. *
  239. * @param Model $model Model find was run on
  240. * @param array $results Array of model results.
  241. * @param boolean $primary Did the find originate on $model.
  242. * @return array Modified results
  243. */
  244. public function afterFind(Model $model, $results, $primary) {
  245. $model->virtualFields = $this->runtime[$model->alias]['virtualFields'];
  246. $this->runtime[$model->alias]['virtualFields'] = $this->runtime[$model->alias]['fields'] = array();
  247. $locale = $this->_getLocale($model);
  248. if (empty($locale) || empty($results) || empty($this->runtime[$model->alias]['beforeFind'])) {
  249. return $results;
  250. }
  251. $beforeFind = $this->runtime[$model->alias]['beforeFind'];
  252. foreach ($results as $key => &$row) {
  253. $results[$key][$model->alias]['locale'] = (is_array($locale)) ? current($locale) : $locale;
  254. foreach ($beforeFind as $_f => $field) {
  255. $aliasField = is_numeric($_f) ? $field : $_f;
  256. if (is_array($locale)) {
  257. foreach ($locale as $_locale) {
  258. if (!isset($row[$model->alias][$aliasField]) && !empty($row[$model->alias]['i18n_' . $field . '_' . $_locale])) {
  259. $row[$model->alias][$aliasField] = $row[$model->alias]['i18n_' . $field . '_' . $_locale];
  260. $row[$model->alias]['locale'] = $_locale;
  261. }
  262. unset($row[$model->alias]['i18n_' . $field . '_' . $_locale]);
  263. }
  264. if (!isset($row[$model->alias][$aliasField])) {
  265. $row[$model->alias][$aliasField] = '';
  266. }
  267. } else {
  268. $value = '';
  269. if (!empty($row[$model->alias]['i18n_' . $field])) {
  270. $value = $row[$model->alias]['i18n_' . $field];
  271. }
  272. $row[$model->alias][$aliasField] = $value;
  273. unset($row[$model->alias]['i18n_' . $field]);
  274. }
  275. }
  276. }
  277. return $results;
  278. }
  279. /**
  280. * beforeValidate Callback
  281. *
  282. * @param Model $model Model invalidFields was called on.
  283. * @return boolean
  284. */
  285. public function beforeValidate(Model $model) {
  286. unset($this->runtime[$model->alias]['beforeSave']);
  287. $this->_setRuntimeData($model);
  288. return true;
  289. }
  290. /**
  291. * beforeSave callback.
  292. *
  293. * Copies data into the runtime property when `$options['validate']` is
  294. * disabled. Or the runtime data hasn't been set yet.
  295. *
  296. * @param Model $model Model save was called on.
  297. * @return boolean true.
  298. */
  299. public function beforeSave(Model $model, $options = array()) {
  300. if (isset($options['validate']) && $options['validate'] == false) {
  301. unset($this->runtime[$model->alias]['beforeSave']);
  302. }
  303. if (isset($this->runtime[$model->alias]['beforeSave'])) {
  304. return true;
  305. }
  306. $this->_setRuntimeData($model);
  307. return true;
  308. }
  309. /**
  310. * Sets the runtime data.
  311. *
  312. * Used from beforeValidate() and beforeSave() for compatibility issues,
  313. * and to allow translations to be persisted even when validation
  314. * is disabled.
  315. *
  316. * @param Model $model
  317. * @return void
  318. */
  319. protected function _setRuntimeData(Model $model) {
  320. $locale = $this->_getLocale($model);
  321. if (empty($locale)) {
  322. return true;
  323. }
  324. $fields = array_merge($this->settings[$model->alias], $this->runtime[$model->alias]['fields']);
  325. $tempData = array();
  326. foreach ($fields as $key => $value) {
  327. $field = (is_numeric($key)) ? $value : $key;
  328. if (isset($model->data[$model->alias][$field])) {
  329. $tempData[$field] = $model->data[$model->alias][$field];
  330. if (is_array($model->data[$model->alias][$field])) {
  331. if (is_string($locale) && !empty($model->data[$model->alias][$field][$locale])) {
  332. $model->data[$model->alias][$field] = $model->data[$model->alias][$field][$locale];
  333. } else {
  334. $values = array_values($model->data[$model->alias][$field]);
  335. $model->data[$model->alias][$field] = $values[0];
  336. }
  337. }
  338. }
  339. }
  340. $this->runtime[$model->alias]['beforeSave'] = $tempData;
  341. }
  342. /**
  343. * afterSave Callback
  344. *
  345. * @param Model $model Model the callback is called on
  346. * @param boolean $created Whether or not the save created a record.
  347. * @return void
  348. */
  349. public function afterSave(Model $model, $created) {
  350. if (!isset($this->runtime[$model->alias]['beforeValidate']) && !isset($this->runtime[$model->alias]['beforeSave'])) {
  351. return true;
  352. }
  353. $locale = $this->_getLocale($model);
  354. if (isset($this->runtime[$model->alias]['beforeValidate'])) {
  355. $tempData = $this->runtime[$model->alias]['beforeValidate'];
  356. } else {
  357. $tempData = $this->runtime[$model->alias]['beforeSave'];
  358. }
  359. unset($this->runtime[$model->alias]['beforeValidate'], $this->runtime[$model->alias]['beforeSave']);
  360. $conditions = array('model' => $model->alias, 'foreign_key' => $model->id);
  361. $RuntimeModel = $this->translateModel($model);
  362. foreach ($tempData as $field => $value) {
  363. unset($conditions['content']);
  364. $conditions['field'] = $field;
  365. if (is_array($value)) {
  366. $conditions['locale'] = array_keys($value);
  367. } else {
  368. $conditions['locale'] = $locale;
  369. if (is_array($locale)) {
  370. $value = array($locale[0] => $value);
  371. } else {
  372. $value = array($locale => $value);
  373. }
  374. }
  375. $translations = $RuntimeModel->find('list', array('conditions' => $conditions, 'fields' => array($RuntimeModel->alias . '.locale', $RuntimeModel->alias . '.id')));
  376. foreach ($value as $_locale => $_value) {
  377. $RuntimeModel->create();
  378. $conditions['locale'] = $_locale;
  379. $conditions['content'] = $_value;
  380. if (array_key_exists($_locale, $translations)) {
  381. $RuntimeModel->save(array($RuntimeModel->alias => array_merge($conditions, array('id' => $translations[$_locale]))));
  382. } else {
  383. $RuntimeModel->save(array($RuntimeModel->alias => $conditions));
  384. }
  385. }
  386. }
  387. }
  388. /**
  389. * afterDelete Callback
  390. *
  391. * @param Model $model Model the callback was run on.
  392. * @return void
  393. */
  394. public function afterDelete(Model $model) {
  395. $RuntimeModel = $this->translateModel($model);
  396. $conditions = array('model' => $model->alias, 'foreign_key' => $model->id);
  397. $RuntimeModel->deleteAll($conditions);
  398. }
  399. /**
  400. * Get selected locale for model
  401. *
  402. * @param Model $model Model the locale needs to be set/get on.
  403. * @return mixed string or false
  404. */
  405. protected function _getLocale(Model $model) {
  406. if (!isset($model->locale) || is_null($model->locale)) {
  407. $I18n = I18n::getInstance();
  408. $I18n->l10n->get(Configure::read('Config.language'));
  409. $model->locale = $I18n->l10n->locale;
  410. }
  411. return $model->locale;
  412. }
  413. /**
  414. * Get instance of model for translations.
  415. *
  416. * If the model has a translateModel property set, this will be used as the class
  417. * name to find/use. If no translateModel property is found 'I18nModel' will be used.
  418. *
  419. * @param Model $model Model to get a translatemodel for.
  420. * @return Model
  421. */
  422. public function translateModel(Model $model) {
  423. if (!isset($this->runtime[$model->alias]['model'])) {
  424. if (!isset($model->translateModel) || empty($model->translateModel)) {
  425. $className = 'I18nModel';
  426. } else {
  427. $className = $model->translateModel;
  428. }
  429. $this->runtime[$model->alias]['model'] = ClassRegistry::init($className, 'Model');
  430. }
  431. if (!empty($model->translateTable) && $model->translateTable !== $this->runtime[$model->alias]['model']->useTable) {
  432. $this->runtime[$model->alias]['model']->setSource($model->translateTable);
  433. } elseif (empty($model->translateTable) && empty($model->translateModel)) {
  434. $this->runtime[$model->alias]['model']->setSource('i18n');
  435. }
  436. return $this->runtime[$model->alias]['model'];
  437. }
  438. /**
  439. * Bind translation for fields, optionally with hasMany association for
  440. * fake field.
  441. *
  442. * *Note* You should avoid binding translations that overlap existing model properties.
  443. * This can cause un-expected and un-desirable behavior.
  444. *
  445. * @param Model $model instance of model
  446. * @param string|array $fields string with field or array(field1, field2=>AssocName, field3)
  447. * @param boolean $reset
  448. * @return boolean
  449. * @throws CakeException when attempting to bind a translating called name. This is not allowed
  450. * as it shadows Model::$name.
  451. */
  452. public function bindTranslation(Model $model, $fields, $reset = true) {
  453. if (is_string($fields)) {
  454. $fields = array($fields);
  455. }
  456. $associations = array();
  457. $RuntimeModel = $this->translateModel($model);
  458. $default = array('className' => $RuntimeModel->alias, 'foreignKey' => 'foreign_key');
  459. foreach ($fields as $key => $value) {
  460. if (is_numeric($key)) {
  461. $field = $value;
  462. $association = null;
  463. } else {
  464. $field = $key;
  465. $association = $value;
  466. }
  467. if ($association === 'name') {
  468. throw new CakeException(
  469. __d('cake_dev', 'You cannot bind a translation named "name".')
  470. );
  471. }
  472. $this->_updateSettings($model, $field);
  473. if (is_null($association)) {
  474. if ($reset) {
  475. $this->runtime[$model->alias]['fields'][] = $field;
  476. } else {
  477. $this->settings[$model->alias][] = $field;
  478. }
  479. } else {
  480. if ($reset) {
  481. $this->runtime[$model->alias]['fields'][$field] = $association;
  482. } else {
  483. $this->settings[$model->alias][$field] = $association;
  484. }
  485. foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) {
  486. if (isset($model->{$type}[$association]) || isset($model->__backAssociation[$type][$association])) {
  487. trigger_error(
  488. __d('cake_dev', 'Association %s is already bound to model %s', $association, $model->alias),
  489. E_USER_ERROR
  490. );
  491. return false;
  492. }
  493. }
  494. $associations[$association] = array_merge($default, array('conditions' => array(
  495. 'model' => $model->alias,
  496. $RuntimeModel->displayField => $field
  497. )));
  498. }
  499. }
  500. if (!empty($associations)) {
  501. $model->bindModel(array('hasMany' => $associations), $reset);
  502. }
  503. return true;
  504. }
  505. /**
  506. * Update runtime setting for a given field.
  507. *
  508. * @param string $field The field to update.
  509. */
  510. protected function _updateSettings(Model $model, $field) {
  511. if (array_key_exists($field, $this->settings[$model->alias])) {
  512. unset($this->settings[$model->alias][$field]);
  513. } elseif (in_array($field, $this->settings[$model->alias])) {
  514. $this->settings[$model->alias] = array_merge(array_diff_assoc($this->settings[$model->alias], array($field)));
  515. }
  516. if (array_key_exists($field, $this->runtime[$model->alias]['fields'])) {
  517. unset($this->runtime[$model->alias]['fields'][$field]);
  518. } elseif (in_array($field, $this->runtime[$model->alias]['fields'])) {
  519. $this->runtime[$model->alias]['fields'] = array_merge(array_diff_assoc($this->runtime[$model->alias]['fields'], array($field)));
  520. }
  521. }
  522. /**
  523. * Unbind translation for fields, optionally unbinds hasMany association for
  524. * fake field
  525. *
  526. * @param Model $model instance of model
  527. * @param mixed $fields string with field, or array(field1, field2=>AssocName, field3), or null for
  528. * unbind all original translations
  529. * @return boolean
  530. */
  531. public function unbindTranslation(Model $model, $fields = null) {
  532. if (empty($fields) && empty($this->settings[$model->alias])) {
  533. return false;
  534. }
  535. if (empty($fields)) {
  536. return $this->unbindTranslation($model, $this->settings[$model->alias]);
  537. }
  538. if (is_string($fields)) {
  539. $fields = array($fields);
  540. }
  541. $RuntimeModel = $this->translateModel($model);
  542. $associations = array();
  543. foreach ($fields as $key => $value) {
  544. if (is_numeric($key)) {
  545. $field = $value;
  546. $association = null;
  547. } else {
  548. $field = $key;
  549. $association = $value;
  550. }
  551. $this->_updateSettings($model, $field);
  552. if (!is_null($association) && (isset($model->hasMany[$association]) || isset($model->__backAssociation['hasMany'][$association]))) {
  553. $associations[] = $association;
  554. }
  555. }
  556. if (!empty($associations)) {
  557. $model->unbindModel(array('hasMany' => $associations), false);
  558. }
  559. return true;
  560. }
  561. }