/** * method that handles the on missing translation event * * @param CMissingTranslationEvent $event * @return string the message to translate or the translated message if autoTranslate is set to true */ function missingTranslation($event) { Yii::import('translate.models.MessageSource'); $attributes = array('category' => $event->category, 'message' => $event->message); if (($model = MessageSource::model()->find('message=:message AND category=:category', $attributes)) === null) { $model = new MessageSource(); $model->attributes = $attributes; if (!$model->save()) { return Yii::log(TranslateModule::t('Message ' . $event->message . ' could not be added to messageSource table')); } } if ($model->id) { if ($this->autoTranslate && substr($event->language, 0, 2) !== substr(Yii::app()->sourceLanguage, 0, 2)) { //&& key_exists($event->language,$this->getGoogleAcceptedLanguages($event->language)) Yii::import('translate.models.Message'); $translation = $this->googleTranslate($event->message, $event->language, Yii::app()->sourceLanguage); $messageModel = new Message(); $messageModel->attributes = array('id' => $model->id, 'language' => $event->language, 'translation' => $translation); if ($messageModel->save()) { $event->message = $translation; } else { return Yii::log(TranslateModule::t('Message ' . $event->message . ' could not be translated with auto-translate')); } } elseif (substr($event->language, 0, 2) !== substr(Yii::app()->sourceLanguage, 0, 2) || Yii::app()->getMessages()->forceTranslation) { self::$messages[$model->id] = array('language' => $event->language, 'message' => $event->message, 'category' => $event->category); } } return $event; }
/** * Adds new message source to the database * * @param String $category Category of the source message * @param String $source The source message */ public static function addNewSource($category, $source) { assert('is_string($category) && !empty($category)'); assert('is_string($source) && !empty($source)'); $model = new MessageSource(); $model->category = $category; $model->source = $source; if (!$model->save()) { throw new FailedToSaveModelException(); } return $model; }
/** * Creates a message if form has been submitted or renders the creation/update form */ public function actionCreate() { if (isset($_POST['Message'])) { $resp = array('color' => '#FF6600', 'background_color' => '#FFFFCC', 'position' => 'top', 'removebutton' => 0); $model = new Message(); $model->setAttributes($_POST['Message']); if ($model->save()) { $resp['message'] = Yii::t('translate', 'Message successfully saved'); $resp['id'] = $model->id; } else { $errors = $this->errors($model); $resp['message'] = Yii::t('translate', '<p>Unable to save the message. Something went wrong!<p/>' . implode('<br/>', $errors)); } echo $this->je($resp); Yii::app()->end(); } $id = (int) Yii::app()->request->getParam('id'); $lang = Yii::app()->request->getParam('lang'); if ($id && $lang) { $model = MessageSource::model()->findByPk($id); if ($model) { $message = $model->loadMessage(); $message->id = $model->id; $message->language = $lang; $this->renderPartial('form', array('model' => $message)); } else { throw new CHttpException(400); } } else { throw new CHttpException(404, 'The requested page does not exist.'); } }
/** * Initialize the TTranslate translation components */ public static function init($catalogue = 'messages') { static $saveEventHandlerAttached = false; //initialized the default class wide formatter if (!isset(self::$formatters[$catalogue])) { $app = Prado::getApplication()->getGlobalization(); $config = $app->getTranslationConfiguration(); $source = MessageSource::factory($config['type'], $config['source'], $config['filename']); $source->setCulture($app->getCulture()); if (TPropertyValue::ensureBoolean($config['cache'])) { $source->setCache(new MessageCache($config['cache'])); } self::$formatters[$catalogue] = new MessageFormat($source, $app->getCharset()); //mark untranslated text if ($ps = $config['marker']) { self::$formatters[$catalogue]->setUntranslatedPS(array($ps, $ps)); } //save the message on end request // Do it only once ! if (!$saveEventHandlerAttached && TPropertyValue::ensureBoolean($config['autosave'])) { Prado::getApplication()->attachEventHandler('OnEndRequest', array('Translation', 'saveMessages')); $saveEventHandlerAttached = true; } } }
public static function setupBeforeClass() { parent::setUpBeforeClass(); foreach (self::$testMessages as $source => $translation) { $sourceModel = MessageSource::addNewSource(self::$testCategory, $source); MessageTranslation::addNewTranslation(self::$testLanguageCode, $sourceModel, $translation); } }
/** * Get the list of messages for a particular catalogue. * @param TEventParameter event parameter. */ function onLoad($param) { $settings = $this->Module->getSettings(); $source = MessageSource::factory($settings['type'], $settings['source']); $source->setCulture($settings['culture']); $source->load($settings['catalogue']); $messages = $source->read(); $messages = $messages[key($messages)]; $this->MessageList->setDataSource($messages); $this->dataBind(); parent::onLoad($param); }
/** * Initialize the TTranslate translation components */ public static function init() { //initialized the default class wide formatter if (is_null(self::$formatter)) { $app = pradoGetApplication()->getGlobalization(); //var_dump($app); $source = MessageSource::factory($app->Translation['type'], $app->Translation['source'], $app->Translation['filename']); $source->setCulture($app->Culture); if ($app->Cache) { $source->setCache(new MessageCache($app->Cache)); } self::$formatter = new MessageFormat($source, $app->Charset); } }
function testAltCatalogue() { $source = MessageSource::factory($this->type, $this->source); $source->setCulture('en_AU'); $source->setCache(new MessageCache('./tmp')); $formatter = new MessageFormat($source); $formatter->Catalogue = 'tests'; //from a different catalogue $this->assertEqual($formatter->format('Hello'), 'Howdy!'); $this->assertEqual($formatter->format('Welcome'), 'Ho Ho!'); $this->assertEqual($formatter->format('Goodbye'), 'Sayonara'); //switch to 'messages' catalogue $this->assertEqual($formatter->format('Hello', null, 'messages'), 'G\'day Mate!'); }
/** * Imports one message string to the database * * @param String $languageCode The language code * @param String $category The category of the translation * @param String $source Message source * @param String $translation Message translation * @return Integer Id of the added translation or false * @throws NotSupportedException */ public static function importOneMessage($languageCode, $category, $source, $translation) { assert('is_string($languageCode) && !empty($languageCode)'); assert('is_string($category) && !empty($category)'); assert('is_string($source) && !empty($source)'); assert('is_string($translation) && !empty($translation)'); if (!is_string($languageCode) || empty($languageCode) || !is_string($category) || empty($category) || !is_string($source) || empty($source) || !is_string($translation) || empty($translation)) { throw new NotSupportedException(); } try { $sourceModel = MessageSource::getByCategoryAndSource($category, $source); } catch (NotFoundException $e) { $sourceModel = MessageSource::addNewSource($category, $source); } try { $translationModel = MessageTranslation::getBySourceIdAndLangCode($sourceModel->id, $languageCode); $translationModel->updateTranslation($translation); } catch (NotFoundException $e) { $translationModel = MessageTranslation::addNewTranslation($languageCode, $sourceModel, $translation); } return $translationModel->id; }
/** * Do string translation. * @param string the string to translate. * @param array a list of string to substitute. * @param string get the translation from a particular message * catalogue. * @return string translated string. */ protected function formatString($string, $args = array(), $catalogue = null) { if (empty($catalogue)) { if (empty($this->Catalogue)) { $catalogue = 'messages'; } else { $catalogue = $this->Catalogue; } } $this->loadCatalogue($catalogue); if (empty($args)) { $args = array(); } foreach ($this->messages[$catalogue] as $variant) { // foreach of the translation units foreach ($variant as $source => $result) { // we found it, so return the target translation if ($source == $string) { //check if it contains only strings. if (is_string($result)) { $target = $result; } else { $target = $result[0]; } //found, but untranslated if (empty($target)) { return $this->postscript[0] . strtr($string, $args) . $this->postscript[1]; } else { return strtr($target, $args); } } } } // well we did not find the translation string. $this->source->append($string); return $this->postscript[0] . strtr($string, $args) . $this->postscript[1]; }
/** * Deletes a record * @param integer $id the ID of the model to be deleted * @param string $language the language of the model to de deleted */ public function actionMissingdelete($id) { if (!Yii::app()->user->isGuest) { if (Yii::app()->getRequest()->getIsPostRequest()) { $model = MessageSource::model()->findByPk($id); if ($model->delete()) { if (Yii::app()->getRequest()->getIsAjaxRequest()) { echo TranslateModule::t('Message deleted successfully'); Yii::app()->end(); } else { $this->redirect(Yii::app()->getRequest()->getUrlReferrer()); } } } else { throw new CHttpException(400); } } else { throw new CHttpException(404, "Error Processing Request"); } }
public function attributeLabels() { return array('id' => Yii::t('translate', 'ID'), 'language' => Yii::t('translate', 'Language'), 'translation' => Yii::t('translate', 'Translation'), 'category' => MessageSource::model()->getAttributeLabel('category'), 'message' => MessageSource::model()->getAttributeLabel('message')); }
<div class="row buttons"> <?php echo CHtml::submitButton(TranslateModule::t($action)); ?> </div> <?php $this->endWidget(); ?> </div><!-- form --> </div> <div class="col-lg-8"> <?php $modell = new MessageSource('search'); $modell->unsetAttributes(); // clear any default values if (isset($_GET['MessageSource'])) { $modell->attributes = $_GET['MessageSource']; } $modell->language = TranslateModule::translator()->getLanguage(); $this->renderPartial('missing', array('model' => $modell)); ?> </div> </div> <script> $(document).ready(function () { $("#Message_translation").focus(); });
<?php Yii::app()->controller->pageTitle = TranslateModule::t('Manage Messages'); ?> <?php $source = MessageSource::model()->findAll(); $this->widget('zii.widgets.grid.CGridView', array('id' => 'message-grid', 'dataProvider' => $model->search(), 'filter' => $model, 'columns' => array(array('name' => 'id', 'filter' => CHtml::listData($source, 'id', 'id')), array('name' => 'message', 'filter' => CHtml::listData($source, 'message', 'message')), array('name' => 'category', 'filter' => CHtml::listData($source, 'category', 'category')), array('name' => 'language', 'filter' => CHtml::listData($model->findAll(new CDbCriteria(array('group' => 'language'))), 'language', 'language')), 'translation', array('class' => 'CButtonColumn', 'template' => '{update}', 'buttons' => array('update' => array('label' => t('Edit'), 'imageUrl' => false, 'url' => 'Yii::app()->getController()->createUrl("update",array("id"=>$data->id,"language"=>$data->language))'))), array('class' => 'CButtonColumn', 'template' => '{delete}', 'buttons' => array('delete' => array('label' => t('Delete'), 'imageUrl' => false, 'url' => 'Yii::app()->getController()->createUrl("delete",array("id"=>$data->id,"language"=>$data->language))'))))));
/** * Method that handles the on missing translation event. If no messagesource is found * then add it to the DB for its future edition from the user's control panel -that is up to you! :). * @param CMissingTranslationEvent $event * @return string the message to translate */ public static function missingTranslation($event) { Yii::import('translate.models.MessageSource'); $attributes = array('category' => $event->category, 'message' => $event->message); if (($model = MessageSource::model()->find('message=:message AND category=:category', $attributes)) === null) { $model = new MessageSource(); $model->attributes = $attributes; if (!$model->save()) { return Yii::log(Yii::t(__CLASS__, 'Message ' . $event->message . ' could not be added to messageSource table')); } } if ($model->id) { if (substr($event->language, 0, 2) !== substr(Yii::app()->sourceLanguage, 0, 2) || Yii::app()->getMessages()->forceTranslation && !array_key_exists($model->id, self::$_missingTranslations)) { Yii::trace('--- ADDED TRANSLATION ---', 'translate'); $url = Yii::app()->getController()->createUrl('/translate/translate/create', array('id' => $model->id, 'lang' => $event->language)); self::$_missingTranslations[$model->id] = array('ref' => $model->id, 'text' => self::c(strip_tags($model->message), 45), 'url' => $url); } } return $event; }
function testDirectoryTypeSaveUpdateDelete() { $MObackup = './messages/en_AU/tests.mo.bak'; $MOfile = './messages/en_AU/tests.mo'; $PObackup = './messages/en_AU/tests.po.bak'; $POfile = './messages/en_AU/tests.po'; //restore using the back file copy($MObackup, $MOfile); copy($PObackup, $POfile); //test that the back file doesn't contain the 'Testing123' string. $this->assertNoUnwantedPattern('/Testing123/', file_get_contents($MOfile)); $this->assertNoUnwantedPattern('/Testing123/', file_get_contents($POfile)); $source = MessageSource::factory($this->type, $this->source); $source->setCulture('en_AU'); $source->setCache(new MessageCache('./tmp')); $formatter = new MessageFormat($source); //add a untranslated string, note, doesn't matter which catalogue $this->assertEqual($formatter->format('Testing123'), 'Testing123'); //save it to the 'tests' catalgoue $this->assertTrue($formatter->getSource()->save('tests')); //check the contents //$this->assertWantedPattern('/Testing123/',file_get_contents($MOfile)); $this->assertWantedPattern('/Testing123/', file_get_contents($POfile)); //testing for update. Update it to the 'tests' catalogue $this->assertTrue($formatter->getSource()->update('Testing123', '123Test', 'update comments', 'tests')); $this->assertWantedPattern('/123Test/', file_get_contents($MOfile)); //now doing some delete from the 'tests' catalogue $this->assertFalse($formatter->getSource()->delete('Test123', 'tests')); $this->assertTrue($formatter->getSource()->delete('Testing123', 'tests')); $this->assertNoUnwantedPattern('/Testing123/', file_get_contents($MOfile)); $this->assertNoUnwantedPattern('/Testing123/', file_get_contents($POfile)); //restore using the backup file. copy($MObackup, $MOfile); copy($PObackup, $POfile); }
/** * Override of the parent method using RedBean. * @param $category * @param $languageCode * @return array */ protected function loadMessagesFromDb($category, $languageCode) { assert('is_string($category)'); assert('is_string($languageCode)'); $sourceTableName = MessageSource::getTableName(); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('MessageTranslation'); $joinTablesAdapter->addFromTableAndGetAliasName($sourceTableName, "{$sourceTableName}_id"); $where = " messagesource.`category` = '{$category}' AND" . " messagetranslation.`language` = '{$languageCode}' "; $beans = MessageTranslation::getSubset($joinTablesAdapter, null, null, $where); $messages = array(); foreach ($beans as $bean) { $messages[$bean->messagesource->source] = $bean->translation; } return $messages; }
echo CHtml::script("\r\n \$('#" . TranslateModule::translator()->languageKey . '-pager' . " a').click(function(){\r\n \$dialog=\$('#" . TranslateModule::translator()->languageKey . '-dialog' . "').load(\$(this).attr('href'));\r\n return false;\r\n });\r\n "); } } ?> <div class="form"> <?php echo CHtml::beginForm(); ?> <table> <thead> <th><?php echo MessageSource::model()->getAttributeLabel('category'); ?> </th> <th><?php echo MessageSource::model()->getAttributeLabel('message'); ?> </th> <th><?php echo Message::model()->getAttributeLabel('translation'); ?> </th> <?php echo $google ? CHtml::tag('th') : null; ?> </thead> <tbody> <?php $this->widget('zii.widgets.CListView', array('dataProvider' => new CArrayDataProvider($models), 'pager' => array('id' => TranslateModule::translator()->languageKey . '-pager', 'class' => 'CLinkPager'), 'viewData' => array('messages' => $messages, 'google' => $google), 'itemView' => '_form')); ?> </tbody>
/** * Update a message translation. * @param string the message id/source * @param string the translated message * @param string comments * @param array translation settings. * @return true if translation was updated, false otherwise. */ function updateMessage($text, $target, $comments, $settings) { $source = MessageSource::factory($settings['type'], $settings['source']); $app = $this->Application->getGlobalization(); if ($app->Cache) { $source->setCache(new MessageCache($app->Cache)); } $source->setCulture($settings['culture']); return $source->update($text, $target, $comments, $settings['catalogue']); }