PageRenderTime 46ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/Aapje/quoted-for-the-win
PHP | 656 lines | 431 code | 51 blank | 174 comment | 88 complexity | 09ae97fec55d053efa1e7fc23a53d1c3 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(
  130. $this->settings[$Model->alias],
  131. $this->runtime[$Model->alias]['fields']
  132. );
  133. $addFields = array();
  134. if (empty($query['fields'])) {
  135. $addFields = $fields;
  136. } elseif (is_array($query['fields'])) {
  137. $isAllFields = (
  138. in_array($Model->alias . '.' . '*', $query['fields']) ||
  139. in_array($Model->escapeField('*'), $query['fields'])
  140. );
  141. foreach ($fields as $key => $value) {
  142. $field = (is_numeric($key)) ? $value : $key;
  143. if (
  144. $isAllFields ||
  145. in_array($Model->alias . '.' . $field, $query['fields']) ||
  146. in_array($field, $query['fields'])
  147. ) {
  148. $addFields[] = $field;
  149. }
  150. }
  151. }
  152. $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
  153. if ($addFields) {
  154. foreach ($addFields as $_f => $field) {
  155. $aliasField = is_numeric($_f) ? $field : $_f;
  156. foreach (array($aliasField, $Model->alias . '.' . $aliasField) as $_field) {
  157. $key = array_search($_field, (array)$query['fields']);
  158. if ($key !== false) {
  159. unset($query['fields'][$key]);
  160. }
  161. }
  162. $query = $this->_addJoin($Model, $query, $field, $aliasField, $locale);
  163. }
  164. }
  165. $this->runtime[$Model->alias]['beforeFind'] = $addFields;
  166. unset($this->_joinTable, $this->_runtimeModel);
  167. return $query;
  168. }
  169. /**
  170. * Check a query's conditions for translated fields.
  171. * Return an array of translated fields found in the conditions.
  172. *
  173. * @param Model $Model The model being read.
  174. * @param array $query The query array.
  175. * @return array The list of translated fields that are in the conditions.
  176. */
  177. protected function _checkConditions(Model $Model, $query) {
  178. $conditionFields = array();
  179. if (empty($query['conditions']) || (!empty($query['conditions']) && !is_array($query['conditions'])) ) {
  180. return $conditionFields;
  181. }
  182. foreach ($query['conditions'] as $col => $val) {
  183. foreach ($this->settings[$Model->alias] as $field => $assoc) {
  184. if (is_numeric($field)) {
  185. $field = $assoc;
  186. }
  187. if (strpos($col, $field) !== false) {
  188. $conditionFields[] = $field;
  189. }
  190. }
  191. }
  192. return $conditionFields;
  193. }
  194. /**
  195. * Appends a join for translated fields.
  196. *
  197. * @param Model $Model The model being worked on.
  198. * @param object $joinTable The jointable object.
  199. * @param array $query The query array to append a join to.
  200. * @param string $field The field name being joined.
  201. * @param string $aliasField The aliased field name being joined.
  202. * @param string|array $locale The locale(s) having joins added.
  203. * @return array The modfied query
  204. */
  205. protected function _addJoin(Model $Model, $query, $field, $aliasField, $locale) {
  206. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  207. $RuntimeModel = $this->_runtimeModel;
  208. $joinTable = $this->_joinTable;
  209. $aliasVirtual = "i18n_{$field}";
  210. $alias = "I18n__{$field}";
  211. if (is_array($locale)) {
  212. foreach ($locale as $_locale) {
  213. $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
  214. $aliasLocale = "{$alias}__{$_locale}";
  215. $Model->virtualFields[$aliasVirtualLocale] = "{$aliasLocale}.content";
  216. if (!empty($query['fields']) && is_array($query['fields'])) {
  217. $query['fields'][] = $aliasVirtualLocale;
  218. }
  219. $query['joins'][] = array(
  220. 'type' => 'LEFT',
  221. 'alias' => $aliasLocale,
  222. 'table' => $joinTable,
  223. 'conditions' => array(
  224. $Model->escapeField() => $db->identifier("{$aliasLocale}.foreign_key"),
  225. "{$aliasLocale}.model" => $Model->name,
  226. "{$aliasLocale}.{$RuntimeModel->displayField}" => $aliasField,
  227. "{$aliasLocale}.locale" => $_locale
  228. )
  229. );
  230. }
  231. } else {
  232. $Model->virtualFields[$aliasVirtual] = "{$alias}.content";
  233. if (!empty($query['fields']) && is_array($query['fields'])) {
  234. $query['fields'][] = $aliasVirtual;
  235. }
  236. $query['joins'][] = array(
  237. 'type' => 'INNER',
  238. 'alias' => $alias,
  239. 'table' => $joinTable,
  240. 'conditions' => array(
  241. "{$Model->alias}.{$Model->primaryKey}" => $db->identifier("{$alias}.foreign_key"),
  242. "{$alias}.model" => $Model->name,
  243. "{$alias}.{$RuntimeModel->displayField}" => $aliasField,
  244. "{$alias}.locale" => $locale
  245. )
  246. );
  247. }
  248. return $query;
  249. }
  250. /**
  251. * afterFind Callback
  252. *
  253. * @param Model $Model Model find was run on
  254. * @param array $results Array of model results.
  255. * @param boolean $primary Did the find originate on $model.
  256. * @return array Modified results
  257. */
  258. public function afterFind(Model $Model, $results, $primary) {
  259. $Model->virtualFields = $this->runtime[$Model->alias]['virtualFields'];
  260. $this->runtime[$Model->alias]['virtualFields'] = $this->runtime[$Model->alias]['fields'] = array();
  261. $locale = $this->_getLocale($Model);
  262. if (empty($locale) || empty($results) || empty($this->runtime[$Model->alias]['beforeFind'])) {
  263. return $results;
  264. }
  265. $beforeFind = $this->runtime[$Model->alias]['beforeFind'];
  266. foreach ($results as $key => &$row) {
  267. $results[$key][$Model->alias]['locale'] = (is_array($locale)) ? current($locale) : $locale;
  268. foreach ($beforeFind as $_f => $field) {
  269. $aliasField = is_numeric($_f) ? $field : $_f;
  270. $aliasVirtual = "i18n_{$field}";
  271. if (is_array($locale)) {
  272. foreach ($locale as $_locale) {
  273. $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
  274. if (!isset($row[$Model->alias][$aliasField]) && !empty($row[$Model->alias][$aliasVirtualLocale])) {
  275. $row[$Model->alias][$aliasField] = $row[$Model->alias][$aliasVirtualLocale];
  276. $row[$Model->alias]['locale'] = $_locale;
  277. }
  278. unset($row[$Model->alias][$aliasVirtualLocale]);
  279. }
  280. if (!isset($row[$Model->alias][$aliasField])) {
  281. $row[$Model->alias][$aliasField] = '';
  282. }
  283. } else {
  284. $value = '';
  285. if (!empty($row[$Model->alias][$aliasVirtual])) {
  286. $value = $row[$Model->alias][$aliasVirtual];
  287. }
  288. $row[$Model->alias][$aliasField] = $value;
  289. unset($row[$Model->alias][$aliasVirtual]);
  290. }
  291. }
  292. }
  293. return $results;
  294. }
  295. /**
  296. * beforeValidate Callback
  297. *
  298. * @param Model $Model Model invalidFields was called on.
  299. * @return boolean
  300. */
  301. public function beforeValidate(Model $Model) {
  302. unset($this->runtime[$Model->alias]['beforeSave']);
  303. $this->_setRuntimeData($Model);
  304. return true;
  305. }
  306. /**
  307. * beforeSave callback.
  308. *
  309. * Copies data into the runtime property when `$options['validate']` is
  310. * disabled. Or the runtime data hasn't been set yet.
  311. *
  312. * @param Model $Model Model save was called on.
  313. * @return boolean true.
  314. */
  315. public function beforeSave(Model $Model, $options = array()) {
  316. if (isset($options['validate']) && $options['validate'] == false) {
  317. unset($this->runtime[$Model->alias]['beforeSave']);
  318. }
  319. if (isset($this->runtime[$Model->alias]['beforeSave'])) {
  320. return true;
  321. }
  322. $this->_setRuntimeData($Model);
  323. return true;
  324. }
  325. /**
  326. * Sets the runtime data.
  327. *
  328. * Used from beforeValidate() and beforeSave() for compatibility issues,
  329. * and to allow translations to be persisted even when validation
  330. * is disabled.
  331. *
  332. * @param Model $Model
  333. * @return void
  334. */
  335. protected function _setRuntimeData(Model $Model) {
  336. $locale = $this->_getLocale($Model);
  337. if (empty($locale)) {
  338. return true;
  339. }
  340. $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
  341. $tempData = array();
  342. foreach ($fields as $key => $value) {
  343. $field = (is_numeric($key)) ? $value : $key;
  344. if (isset($Model->data[$Model->alias][$field])) {
  345. $tempData[$field] = $Model->data[$Model->alias][$field];
  346. if (is_array($Model->data[$Model->alias][$field])) {
  347. if (is_string($locale) && !empty($Model->data[$Model->alias][$field][$locale])) {
  348. $Model->data[$Model->alias][$field] = $Model->data[$Model->alias][$field][$locale];
  349. } else {
  350. $values = array_values($Model->data[$Model->alias][$field]);
  351. $Model->data[$Model->alias][$field] = $values[0];
  352. }
  353. }
  354. }
  355. }
  356. $this->runtime[$Model->alias]['beforeSave'] = $tempData;
  357. }
  358. /**
  359. * afterSave Callback
  360. *
  361. * @param Model $Model Model the callback is called on
  362. * @param boolean $created Whether or not the save created a record.
  363. * @return void
  364. */
  365. public function afterSave(Model $Model, $created) {
  366. if (!isset($this->runtime[$Model->alias]['beforeValidate']) && !isset($this->runtime[$Model->alias]['beforeSave'])) {
  367. return true;
  368. }
  369. $locale = $this->_getLocale($Model);
  370. if (isset($this->runtime[$Model->alias]['beforeValidate'])) {
  371. $tempData = $this->runtime[$Model->alias]['beforeValidate'];
  372. } else {
  373. $tempData = $this->runtime[$Model->alias]['beforeSave'];
  374. }
  375. unset($this->runtime[$Model->alias]['beforeValidate'], $this->runtime[$Model->alias]['beforeSave']);
  376. $conditions = array('model' => $Model->alias, 'foreign_key' => $Model->id);
  377. $RuntimeModel = $this->translateModel($Model);
  378. $fields = array_merge(
  379. $this->settings[$Model->alias],
  380. $this->runtime[$Model->alias]['fields']
  381. );
  382. if ($created) {
  383. // set each field value to an empty string
  384. foreach ($fields as $key => $field) {
  385. if (!is_numeric($key)) {
  386. $field = $key;
  387. }
  388. if (!isset($tempData[$field])) {
  389. $tempData[$field] = '';
  390. }
  391. }
  392. }
  393. foreach ($tempData as $field => $value) {
  394. unset($conditions['content']);
  395. $conditions['field'] = $field;
  396. if (is_array($value)) {
  397. $conditions['locale'] = array_keys($value);
  398. } else {
  399. $conditions['locale'] = $locale;
  400. if (is_array($locale)) {
  401. $value = array($locale[0] => $value);
  402. } else {
  403. $value = array($locale => $value);
  404. }
  405. }
  406. $translations = $RuntimeModel->find('list', array(
  407. 'conditions' => $conditions,
  408. 'fields' => array($RuntimeModel->alias . '.locale', $RuntimeModel->alias . '.id')
  409. ));
  410. foreach ($value as $_locale => $_value) {
  411. $RuntimeModel->create();
  412. $conditions['locale'] = $_locale;
  413. $conditions['content'] = $_value;
  414. if (array_key_exists($_locale, $translations)) {
  415. $RuntimeModel->save(array(
  416. $RuntimeModel->alias => array_merge(
  417. $conditions, array('id' => $translations[$_locale])
  418. )
  419. ));
  420. } else {
  421. $RuntimeModel->save(array($RuntimeModel->alias => $conditions));
  422. }
  423. }
  424. }
  425. }
  426. /**
  427. * afterDelete Callback
  428. *
  429. * @param Model $Model Model the callback was run on.
  430. * @return void
  431. */
  432. public function afterDelete(Model $Model) {
  433. $RuntimeModel = $this->translateModel($Model);
  434. $conditions = array(
  435. 'model' => $Model->alias,
  436. 'foreign_key' => $Model->id
  437. );
  438. $RuntimeModel->deleteAll($conditions);
  439. }
  440. /**
  441. * Get selected locale for model
  442. *
  443. * @param Model $Model Model the locale needs to be set/get on.
  444. * @return mixed string or false
  445. */
  446. protected function _getLocale(Model $Model) {
  447. if (!isset($Model->locale) || is_null($Model->locale)) {
  448. $I18n = I18n::getInstance();
  449. $I18n->l10n->get(Configure::read('Config.language'));
  450. $Model->locale = $I18n->l10n->locale;
  451. }
  452. return $Model->locale;
  453. }
  454. /**
  455. * Get instance of model for translations.
  456. *
  457. * If the model has a translateModel property set, this will be used as the class
  458. * name to find/use. If no translateModel property is found 'I18nModel' will be used.
  459. *
  460. * @param Model $Model Model to get a translatemodel for.
  461. * @return Model
  462. */
  463. public function translateModel(Model $Model) {
  464. if (!isset($this->runtime[$Model->alias]['model'])) {
  465. if (!isset($Model->translateModel) || empty($Model->translateModel)) {
  466. $className = 'I18nModel';
  467. } else {
  468. $className = $Model->translateModel;
  469. }
  470. $this->runtime[$Model->alias]['model'] = ClassRegistry::init($className, 'Model');
  471. }
  472. if (!empty($Model->translateTable) && $Model->translateTable !== $this->runtime[$Model->alias]['model']->useTable) {
  473. $this->runtime[$Model->alias]['model']->setSource($Model->translateTable);
  474. } elseif (empty($Model->translateTable) && empty($Model->translateModel)) {
  475. $this->runtime[$Model->alias]['model']->setSource('i18n');
  476. }
  477. return $this->runtime[$Model->alias]['model'];
  478. }
  479. /**
  480. * Bind translation for fields, optionally with hasMany association for
  481. * fake field.
  482. *
  483. * *Note* You should avoid binding translations that overlap existing model properties.
  484. * This can cause un-expected and un-desirable behavior.
  485. *
  486. * @param Model $Model instance of model
  487. * @param string|array $fields string with field or array(field1, field2=>AssocName, field3)
  488. * @param boolean $reset Leave true to have the fields only modified for the next operation.
  489. * if false the field will be added for all future queries.
  490. * @return boolean
  491. * @throws CakeException when attempting to bind a translating called name. This is not allowed
  492. * as it shadows Model::$name.
  493. */
  494. public function bindTranslation(Model $Model, $fields, $reset = true) {
  495. if (is_string($fields)) {
  496. $fields = array($fields);
  497. }
  498. $associations = array();
  499. $RuntimeModel = $this->translateModel($Model);
  500. $default = array(
  501. 'className' => $RuntimeModel->alias,
  502. 'foreignKey' => 'foreign_key'
  503. );
  504. foreach ($fields as $key => $value) {
  505. if (is_numeric($key)) {
  506. $field = $value;
  507. $association = null;
  508. } else {
  509. $field = $key;
  510. $association = $value;
  511. }
  512. if ($association === 'name') {
  513. throw new CakeException(
  514. __d('cake_dev', 'You cannot bind a translation named "name".')
  515. );
  516. }
  517. $this->_removeField($Model, $field);
  518. if (is_null($association)) {
  519. if ($reset) {
  520. $this->runtime[$Model->alias]['fields'][] = $field;
  521. } else {
  522. $this->settings[$Model->alias][] = $field;
  523. }
  524. } else {
  525. if ($reset) {
  526. $this->runtime[$Model->alias]['fields'][$field] = $association;
  527. } else {
  528. $this->settings[$Model->alias][$field] = $association;
  529. }
  530. foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) {
  531. if (isset($Model->{$type}[$association]) || isset($Model->__backAssociation[$type][$association])) {
  532. trigger_error(
  533. __d('cake_dev', 'Association %s is already bound to model %s', $association, $Model->alias),
  534. E_USER_ERROR
  535. );
  536. return false;
  537. }
  538. }
  539. $associations[$association] = array_merge($default, array('conditions' => array(
  540. 'model' => $Model->alias,
  541. $RuntimeModel->displayField => $field
  542. )));
  543. }
  544. }
  545. if (!empty($associations)) {
  546. $Model->bindModel(array('hasMany' => $associations), $reset);
  547. }
  548. return true;
  549. }
  550. /**
  551. * Update runtime setting for a given field.
  552. *
  553. * @param string $field The field to update.
  554. */
  555. protected function _removeField(Model $Model, $field) {
  556. if (array_key_exists($field, $this->settings[$Model->alias])) {
  557. unset($this->settings[$Model->alias][$field]);
  558. } elseif (in_array($field, $this->settings[$Model->alias])) {
  559. $this->settings[$Model->alias] = array_merge(array_diff($this->settings[$Model->alias], array($field)));
  560. }
  561. if (array_key_exists($field, $this->runtime[$Model->alias]['fields'])) {
  562. unset($this->runtime[$Model->alias]['fields'][$field]);
  563. } elseif (in_array($field, $this->runtime[$Model->alias]['fields'])) {
  564. $this->runtime[$Model->alias]['fields'] = array_merge(array_diff($this->runtime[$Model->alias]['fields'], array($field)));
  565. }
  566. }
  567. /**
  568. * Unbind translation for fields, optionally unbinds hasMany association for
  569. * fake field
  570. *
  571. * @param Model $Model instance of model
  572. * @param string|array $fields string with field, or array(field1, field2=>AssocName, field3), or null for
  573. * unbind all original translations
  574. * @return boolean
  575. */
  576. public function unbindTranslation(Model $Model, $fields = null) {
  577. if (empty($fields) && empty($this->settings[$Model->alias])) {
  578. return false;
  579. }
  580. if (empty($fields)) {
  581. return $this->unbindTranslation($Model, $this->settings[$Model->alias]);
  582. }
  583. if (is_string($fields)) {
  584. $fields = array($fields);
  585. }
  586. $associations = array();
  587. foreach ($fields as $key => $value) {
  588. if (is_numeric($key)) {
  589. $field = $value;
  590. $association = null;
  591. } else {
  592. $field = $key;
  593. $association = $value;
  594. }
  595. $this->_removeField($Model, $field);
  596. if (!is_null($association) && (isset($Model->hasMany[$association]) || isset($Model->__backAssociation['hasMany'][$association]))) {
  597. $associations[] = $association;
  598. }
  599. }
  600. if (!empty($associations)) {
  601. $Model->unbindModel(array('hasMany' => $associations), false);
  602. }
  603. return true;
  604. }
  605. }