PageRenderTime 188ms CodeModel.GetById 61ms app.highlight 60ms RepoModel.GetById 60ms app.codeStats 1ms

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

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