예제 #1
0
 /**
  * Sets the application locale and translation based on the locale param, if
  * one is not provided it defaults to english
  *
  * @param Zend_Controller_Request_Abstract $request
  * @return Void
  */
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     $config = Zend_Registry::get('config');
     $frontController = Zend_Controller_Front::getInstance();
     $params = $request->getParams();
     $registry = Zend_Registry::getInstance();
     // Steps setting the locale.
     // 1. Default language is set in config
     // 2. TLD in host header
     // 3. Locale params specified in request
     $locale = $registry->get('Zend_Locale');
     // Check host header TLD.
     $tld = preg_replace('/^.*\\./', '', $request->getHeader('Host'));
     // Provide a list of tld's and their corresponding default languages
     $tldLocales = $frontController->getParam('tldLocales');
     if (is_array($tldLocales) && array_key_exists($tld, $tldLocales)) {
         // The TLD in the request matches one of our specified TLD -> Locales
         $locale->setLocale(strtolower($tldLocales[$tld]));
     } elseif (isset($params['locale'])) {
         // There is a locale specified in the request params.
         $locale->setLocale(strtolower($params['locale']));
     }
     // Now that our locale is set, let's check which language has been selected
     // and try to load a translation file for it.
     $language = $locale->getLanguage();
     $translate = Garp_I18n::getTranslateByLocale($locale);
     Zend_Registry::set('Zend_Translate', $translate);
     Zend_Form::setDefaultTranslator($translate);
     if (!$config->resources->router->locale->enabled) {
         return;
     }
     $path = '/' . ltrim($request->getPathInfo(), '/\\');
     // If the language is in the path, then we will want to set the baseUrl
     // to the specified language.
     $langIsInUrl = preg_match('/^\\/' . $language . '\\/?/', $path);
     $uiDefaultLangIsInUrl = false;
     $uiDefaultLanguage = false;
     if (isset($config->resources->locale->uiDefault)) {
         $uiDefaultLanguage = $config->resources->locale->uiDefault;
         $uiDefaultLangIsInUrl = preg_match('/^\\/' . $uiDefaultLanguage . '\\/?/', $path);
     }
     if ($langIsInUrl || $uiDefaultLangIsInUrl) {
         if ($uiDefaultLangIsInUrl) {
             $frontController->setBaseUrl($frontController->getBaseUrl() . '/' . $uiDefaultLanguage);
         } else {
             $frontController->setBaseUrl($frontController->getBaseUrl() . '/' . $language);
         }
     } elseif (!empty($config->resources->router->locale->enabled) && $config->resources->router->locale->enabled) {
         $redirectUrl = '/' . $language . $path;
         if ($frontController->getRouter()->getCurrentRouteName() === 'admin' && !empty($config->resources->locale->adminDefault)) {
             $adminDefaultLanguage = $config->resources->locale->adminDefault;
             $redirectUrl = '/' . $adminDefaultLanguage . $path;
         } elseif ($uiDefaultLanguage) {
             $redirectUrl = '/' . $uiDefaultLanguage . $path;
         }
         $this->getResponse()->setRedirect($redirectUrl, 301);
     }
 }
예제 #2
0
 protected function _fetchRecordsInDefaultLanguage(Garp_Model_Db $model)
 {
     $i18nColumns = array_filter($model->getConfiguration('fields'), function ($col) {
         return $col['multilingual'];
     });
     $i18nColumns = array_map(function ($col) {
         return $col['name'];
     }, $i18nColumns);
     $i18nModel = $model->getObserver('Translatable')->getI18nModel($model);
     $foreignKeyColumns = $this->_getForeignKeyColumns($i18nModel, $model);
     return $i18nModel->fetchAll($i18nModel->select()->from($i18nModel->getName(), array_merge($i18nColumns, $foreignKeyColumns))->where('lang = ?', Garp_I18n::getDefaultLocale()));
 }
 /**
  * Populate the subject model's referenceMap with
  * localized versions of the given model.
  * @param String|Garp_Model_Db $relatedModel
  * @return Void
  */
 public function populate($relatedModel, $ruleKey = null)
 {
     // Sanity check: does the model have a reference to the
     // given model in the first place?
     // This will throw an exception if not.
     $relatedModel = $relatedModel instanceof Garp_Model_Db ? get_class($relatedModel) : $relatedModel;
     $relatedModel = (substr($relatedModel, 0, 6) !== 'Model_' ? 'Model_' : '') . $relatedModel;
     $ref = $this->_model->getReference($relatedModel, $ruleKey);
     $locales = Garp_I18n::getLocales();
     foreach ($locales as $locale) {
         $factory = new Garp_I18n_ModelFactory($locale);
         $localizedModel = $factory->getModel($relatedModel);
         $localizedModelName = get_class($localizedModel);
         $cleanLocalizedName = $localizedModel->getNameWithoutNamespace();
         $this->_model->addReference($cleanLocalizedName, $ref[Zend_Db_Table_Abstract::COLUMNS], $localizedModelName, $ref[Zend_Db_Table_Abstract::REF_COLUMNS]);
     }
     return $this;
 }
예제 #4
0
 /**
  * @param String $model_name (not prefixed)
  * @param Garp_Db_Table_Row|Int $record The record on which the alternative is based,
  *                                      or the id thereof.
  * @param String $foreign_key Foreign key column to the parent table
  * @return Array
  * @todo Make it work with various other parameters, not just 'slug'
  */
 public function direct($model_name, $foreign_key, $record, $default_to_same_slug = true)
 {
     $record_id = $record;
     if ($record instanceof Garp_Db_Table_Row) {
         $record_id = $record_id->id;
     }
     // Add the slugs of the group in alternate languages for the language picker
     $alt_param_slug = null;
     if ($default_to_same_slug && $record instanceof Garp_Db_Table_Row) {
         $alt_param_slug = $record->slug;
     }
     $alternate_url_params = array_fill_keys(Garp_I18n::getLocales(), array('slug' => $alt_param_slug));
     $model_name = 'Model_' . $model_name . 'I18n';
     $i18n_model = new $model_name();
     $select = $i18n_model->select()->from($i18n_model->getName(), array('slug', 'lang'))->where("{$foreign_key} = ?", $record_id)->where('lang != ?', Garp_I18n::getCurrentLocale());
     $localized_recordset = $i18n_model->fetchAll($select);
     foreach ($localized_recordset as $record) {
         $alternate_url_params[$record->lang] = array('slug' => $record->slug);
     }
     return $alternate_url_params;
 }
예제 #5
0
 protected function _renderSqlForLang()
 {
     $model = $this->getModel();
     $modelId = $this->getTableName();
     $unilingualFields = $model->fields->getFields('multilingual', false);
     $multilingualFields = $this->_getMultilingualFieldsFromModel($model);
     $locale = $this->getLocale();
     $defaultLocale = Garp_I18n::getDefaultLocale();
     $table = $modelId;
     $localeTable = $table . '_' . $locale;
     $defaultLocaleTable = $table . '_' . $defaultLocale;
     $sql = 'SELECT ';
     //  Unilingual fields
     $unilingualFieldRefs = array();
     foreach ($unilingualFields as $field) {
         $unilingualFieldRefs[] = '`' . $table . '`.`' . $field->name . '` AS `' . $field->name . '`';
     }
     $sql .= implode(', ', $unilingualFieldRefs) . ', ';
     //  Multilingual fields
     $multilingualFieldRefs = array();
     foreach ($multilingualFields as $field) {
         $multilingualFieldRefs[] = "`{$modelId}_{$locale}`.{$field->name} AS `{$field->name}`";
         /*
                     $multilingualFieldRefs[] = $locale === $defaultLocale ?
            "`{$modelId}_{$locale}`.{$field->name} AS `{$field->name}`" :
            "IF(`{$modelId}_{$locale}`.`{$field->name}` <> '' AND `{$modelId}_{$locale}`.`{$field->name}` IS NOT NULL, `{$modelId}_{$locale}`.`{$field->name}`, `{$modelId}_{$defaultLocale}`.`{$field->name}`) AS `{$field->name}`"
                     ;
         */
     }
     $sql .= implode(', ', $multilingualFieldRefs) . ' ';
     //  Join translated tables
     $sql .= 'FROM `' . $modelId . '`';
     $sql .= $this->_renderJoinForLocale($locale);
     //if ($locale !== $defaultLocale) {
     //$sql .= $this->_renderJoinForLocale($defaultLocale);
     //}
     return $sql;
 }
예제 #6
0
 /**
  * Clear the Memcached cache that stores queries and ini files and whatnot.
  *
  * @param Array|Garp_Model_Db $modelNames
  * @return Void
  */
 public static function purgeMemcachedCache($modelNames = array())
 {
     if (!Zend_Registry::isRegistered('CacheFrontend')) {
         return;
     }
     if (!Zend_Registry::get('CacheFrontend')->getOption('caching')) {
         // caching is disabled
         return;
     }
     if ($modelNames instanceof Garp_Model_Db) {
         $modelNames = self::getTagsFromModel($modelNames);
     }
     if (empty($modelNames)) {
         $cacheFront = Zend_Registry::get('CacheFrontend');
         return $cacheFront->clean(Zend_Cache::CLEANING_MODE_ALL);
     }
     foreach ($modelNames as $modelName) {
         $model = new $modelName();
         self::_incrementMemcacheVersion($model);
         if (!$model->getObserver('Translatable')) {
             continue;
         }
         // Make sure cache is cleared for all languages.
         $locales = Garp_I18n::getLocales();
         foreach ($locales as $locale) {
             try {
                 $modelFactory = new Garp_I18n_ModelFactory($locale);
                 $i18nModel = $modelFactory->getModel($model);
                 self::_incrementMemcacheVersion($i18nModel);
             } catch (Garp_I18n_ModelFactory_Exception_ModelAlreadyLocalized $e) {
                 // all good in the hood  。^‿^。
             }
         }
     }
 }
예제 #7
0
 protected function _setCmsClosedMessage()
 {
     $config = Zend_Registry::get('config');
     if (!isset($config->cms->closed) || !$config->cms->closed) {
         return;
     }
     $this->view->isClosed = true;
     try {
         $snippetModel = new Model_Snippet();
         if ($snippetModel->isMultilingual()) {
             $snippetModel = instance(new Garp_I18n_ModelFactory())->getModel('Snippet');
         }
         $snippet = $snippetModel->fetchByIdentifier('cms closed message');
         $cmsClosedMessage = $snippet->html;
         if (isset($cmsClosedMessage[Garp_I18n::getCurrentLocale()])) {
             $cmsClosedMessage = $cmsClosedMessage[Garp_I18n::getCurrentLocale()];
         }
         $this->view->cmsClosedMessage = $cmsClosedMessage;
     } catch (Exception $e) {
         throw $e;
         $this->view->cmsClosedMessage = '<p>The CMS is closed.</p>';
     }
 }
예제 #8
0
 protected function _createI18nViews(Garp_Spawn_Model_Base $model)
 {
     $locales = Garp_I18n::getLocales();
     foreach ($locales as $locale) {
         $view = new Garp_Spawn_MySql_View_I18n($model, $locale);
         $view->create();
     }
 }
예제 #9
0
 /**
  * Check if value is a multilingual array.
  *
  * @param mixed $value
  * @return bool
  */
 protected function _isMultilingualArray($value)
 {
     if (!is_array($value)) {
         return false;
     }
     $locales = Garp_I18n::getLocales();
     $keys = array_keys($value);
     sort($locales);
     sort($keys);
     return $locales === $keys;
 }
예제 #10
0
 protected function _modelIsLocalized($model)
 {
     $languages = Garp_I18n::getLocales();
     if (!is_array($languages)) {
         return false;
     }
     foreach ($languages as $lang) {
         $langSuffix = ucfirst($lang);
         if (preg_match("/[a-z0-9]+{$langSuffix}\$/", $model)) {
             return true;
         }
     }
     return false;
 }
예제 #11
0
 /**
  * OPTIONS
  *
  * @param array $params
  * @return array
  */
 public function options(array $params)
 {
     $schema = new Garp_Content_Api_Rest_Schema('rest');
     if (!array_get($params, 'datatype')) {
         $out = array();
         $out['root'] = (string) new Garp_Util_FullUrl(array(array(), 'rest'));
         $out['i18n'] = array('locales' => Garp_I18n::getLocales(), 'default' => Garp_I18n::getDefaultLocale());
         $out['urls'] = $this->_getUrlsForOptions();
         $out['models'] = $schema->getModelPaths();
         return $this->_formatResponse($out, 200);
     }
     if (array_get($params, 'id') || array_get($params, 'relatedType')) {
         return $this->_formatResponse(null, 200, false);
     }
     return $this->_formatResponse($schema->getModelDetails($params['datatype']), 200);
 }
예제 #12
0
 protected function _saveLocalizedModels()
 {
     $locales = Garp_I18n::getLocales();
     array_walk($locales, array($this, '_saveLocalizedModel'));
 }
예제 #13
0
 protected function _getRecordLabelSqlForMultilingualRelation($relName, $rel)
 {
     $self = $this;
     return array_map(function ($lang) use($self, $relName, $rel) {
         return $self->getRecordLabelSqlForRelation($relName, $rel, $lang);
     }, Garp_I18n::getLocales());
 }
예제 #14
0
 /**
  * A real hacky solution to enable admins to search for translated content in the CMS
  *
  * @param Garp_Model_Db $model
  * @param Zend_Db_Select $select
  * @param string $likeValue
  * @return string A search clause
  */
 protected function _joinCmsSearchQuery(Garp_Model_Db $model, Zend_Db_Select &$select, $likeValue)
 {
     $languages = Garp_I18n::getLocales();
     $default_language = array(Garp_I18n::getDefaultLocale());
     $langColumn = self::LANG_COLUMN;
     // Exclude default language, since that's already joined in the joint view
     $languages = array_diff($languages, $default_language);
     $adapter = $model->getAdapter();
     $where = array();
     foreach ($languages as $language) {
         $i18nModel = $this->getI18nModel($model);
         $i18nAlias = $model->getName() . '_i18n_' . $language;
         $onClause = $i18nModel->refMapToOnClause(get_class($model), $i18nAlias, $model->getJointView());
         // join i18n model
         $select->joinLeft(array($i18nAlias => $i18nModel->getName()), "{$onClause} AND {$i18nAlias}.{$langColumn} = '{$language}'", array());
         // add WHERE clauses that search in the i18n model
         $translatedFields = $this->_translatableFields;
         foreach ($translatedFields as $i18nField) {
             $where[] = "{$i18nAlias}.{$i18nField} LIKE " . $adapter->quote($likeValue);
         }
     }
     return implode(' OR ', $where);
 }
예제 #15
0
 public function renderImagePreviewListener(Garp_Spawn_Relation $rel)
 {
     if (!$rel->multilingual) {
         return $this->renderImagePreviewListenerJs($this->getImagePreviewId($rel->column), $rel->column);
     }
     $self = $this;
     return implode("\n", array_map(function ($locale) use($rel, $self) {
         return $self->renderImagePreviewListenerJs($self->getImagePreviewId($rel->column, $locale), $rel->column, $locale);
     }, Garp_I18n::getLocales()));
 }
예제 #16
0
    return $ns . '_Cli_Command_' . $classArgument;
}, $namespaces);
$commandNames = array_filter($commandNames, 'class_exists');
// Remove the command name from the argument list
$args = array_splice($args, 1);
if (!count($commandNames)) {
    Garp_Cli::errorOut('Silly developer. This is not the command you\'re looking for.');
    // @codingStandardsIgnoreStart
    exit(1);
    // @codingStandardsIgnoreEnd
}
$commandName = current($commandNames);
$command = new $commandName();
if (!$command instanceof Garp_Cli_Command) {
    Garp_Cli::errorOut('Error: ' . $commandName . ' is not a valid Command. ' . 'Command must implement Garp_Cli_Command.');
    // @codingStandardsIgnoreStart
    exit(1);
    // @codingStandardsIgnoreEnd
}
// Since localisation is based on a URL, and URLs are not part of a commandline, no
// translatation is loaded. But we might need it to convert system messages.
$commandsWithoutTranslation = array('Spawn', 'Config', 'Gumball', 'Feature', 'Hotfix', 'Release', 'Flow', 'Cdn', 'Ssh', 'Aws', 'Config', 'Figlet', 'Folders', 'Git', 'Open', 'S3', 'Ses', 'Shell', 'Slack');
if (!in_array($classArgument, $commandsWithoutTranslation)) {
    if (!Zend_Registry::isRegistered('Zend_Translate') && Zend_Registry::isRegistered('Zend_Locale')) {
        Zend_Registry::set('Zend_Translate', Garp_I18n::getTranslateByLocale(Zend_Registry::get('Zend_Locale')));
    }
}
$command->main($args);
// @codingStandardsIgnoreStart
exit(0);
// @codingStandardsIgnoreEnd
예제 #17
0
 /**
  * Get current language from URL
  *
  * @return string
  */
 protected function _getCurrentLanguage()
 {
     if (!isset($_SERVER['REQUEST_URI'])) {
         // Probably CLI context. Return the default locale
         return Garp_I18n::getDefaultLocale();
     }
     $requestUri = $_SERVER['REQUEST_URI'];
     $bits = explode('/', $requestUri);
     // remove empty values
     $bits = array_filter($bits, 'strlen');
     // reindex the array
     $bits = array_values($bits);
     $bits = array_map('strtolower', $bits);
     $locales = $this->_getPossibleLocales();
     if (array_key_exists(0, $bits) && in_array($bits[0], $locales)) {
         return $bits[0];
     }
     return Garp_I18n::getDefaultLocale();
 }