protected function parseData($path) { preg_match('~guide-?(.*)/(.+)\\.md$~', $path, $matches); $language = $matches[1] ? $matches[1] : Yii::$app->sourceLanguage; $language = Locale::getPrimaryLanguage($language); $slug = strtolower($matches[2]); $doc = file_get_contents($path); $doc = Markdown::process($doc, 'gfm'); $html = new HTMLDocument(); @$html->loadHTML($doc); $html->addPrefix("/{lang}/", 'a', 'href'); $imgPath = dirname($path) . '/images'; $imgPath = $this->publishImages($imgPath); if ($imgPath) { $html->addPrefix(function ($src) use($imgPath) { return $imgPath . '/' . basename($src); }, 'img', 'src'); } foreach (['h1', 'h2', 'h3', 'h4'] as $tag) { /** @var \DOMElement $item */ foreach ($html->getElementsByTagName($tag) as $item) { /** @var \DOMElement $span */ if ($span = $item->getElementsByTagName('span')[0]) { $item->setAttribute('id', $span->getAttribute('id')); } } } /** @var DOMElement $title */ $title = $html->getElementsByTagName('h1')[0]; return ['language' => $language, 'slug' => $slug, 'title' => $title->textContent, 'description' => $html->saveHTML()]; }
/** * @param $name * @return string */ public function __invoke($name) { if ($this->fragments == null) { // $serviceManager = $this->event->getApplication()->getServiceManager(); // get translator $translator = $serviceManager->get('Translator'); $locale = $translator->getLocale(); $language = \Locale::getPrimaryLanguage($locale); // try to get fragments from cache $cache = $serviceManager->get('Application\\Cache'); if ($cache) { $cacheKey = sprintf('page-fragments-%s-%s', $this->page->getId(), $language); $page_fragments = $cache->getItem($cacheKey); } // fetch from the DB if ($page_fragments == null) { /** @var \Doctrine\ORM\EntityManager $entity_manager */ $entity_manager = $serviceManager->get('Doctrine\\ORM\\EntityManager'); $page_fragments_repository = $entity_manager->getRepository('Msingi\\Cms\\Entity\\PageFragment'); $page_fragments = $page_fragments_repository->fetchFragmentsArray($this->page->getId(), $language); } // store to cache if ($cache) { $cache->setItem($cacheKey, $page_fragments); } $this->fragments = $page_fragments; } return isset($this->fragments[$name]) ? $this->fragments[$name] : ''; }
/** * Validates a Locale * * @param string $locale The locale to be validated * @param Constraint $constraint Locale Constraint * * @throws UnexpectedTypeException */ public function validate($locale, Constraint $constraint) { if (null === $locale || '' === $locale) { return; } if (!is_scalar($locale) && !(is_object($locale) && method_exists($locale, '__toString'))) { throw new UnexpectedTypeException($locale, 'string'); } $locale = (string) $locale; if ($this->strictMode) { if (!in_array($locale, $this->getAllowedLocales())) { $this->context->addViolation($constraint->message, array('%string%' => $locale)); } } else { if ($this->intlExtension) { $primary = \Locale::getPrimaryLanguage($locale); } else { $splittedLocale = explode('_', $locale); $primary = count($splittedLocale) > 1 ? $splittedLocale[0] : $locale; } if (!in_array($locale, $this->getAllowedLocales()) && !in_array($primary, $this->getAllowedLocales())) { $this->context->addViolation($constraint->message, array('%string%' => $locale)); } } }
/** {@inheritdoc} */ public function __invoke(\Interop\Container\ContainerInterface $container, $name, callable $callback, array $options = null) { $locale = \Locale::getDefault(); $primaryLanguage = \Locale::getPrimaryLanguage($locale); $mvcTranslator = $callback(); $mvcTranslator->setPluginManager($container->get('TranslatorPluginManager')); $translator = $mvcTranslator->getTranslator(); // Set language $translator->setLocale($locale); if ($primaryLanguage != $locale) { // Set primary language as fallback, i.e. "de" if locale is "de_DE". // This enables translation file patterns for "de" to match all // variants. $translator->setFallbackLocale($primaryLanguage); } // Load translations for ZF validator messages $translator->addTranslationFilePattern('phparray', \Zend\I18n\Translator\Resources::getBasePath(), \Zend\I18n\Translator\Resources::getPatternForValidator()); // Set up event listener for missing translations if ($primaryLanguage != 'en') { $config = $container->get('Library\\UserConfig'); if (@$config['debug']['report missing translations']) { $translator->enableEventManager(); $translator->getEventManager()->attach(\Zend\I18n\Translator\Translator::EVENT_MISSING_TRANSLATION, array($this, 'onMissingTranslation')); } } return $mvcTranslator; }
/** * Action for locale switch * * @param \Symfony\Component\HttpFoundation\Request $request * @param $_locale The locale to set * * @return \Symfony\Bundle\FrameworkBundle\Controller\RedirectResponse * * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ public function switchAction(Request $request, $_locale) { // Check if the Language is allowed if (!in_array(\Locale::getPrimaryLanguage($_locale), $this->allowedLanguages)) { throw new NotFoundHttpException('This language is not available'); } // tries to detect a Region from the user-provided locales $providedLanguages = $request->getLanguages(); $locales = array(); foreach ($providedLanguages as $locale) { if (strpos($locale . '_', $_locale) !== false && strlen($locale) > 2) { $locales[] = $locale; } } if (count($locales) > 0) { $this->session->set('localeIdentified', $locales[0]); } else { $this->session->set('localeIdentified', $_locale); } // Add the listener $this->session->set('setLocaleCookie', true); // Redirect the User if ($request->headers->has('referer') && true === $this->useReferrer) { return new RedirectResponse($request->headers->get('referer')); } if (null !== $this->redirectToRoute) { return new RedirectResponse($this->router->generate($this->redirectToRoute)); } return new RedirectResponse($request->getScheme() . '://' . $request->getHttpHost() . $this->redirectToUrl); }
/** * Get options array for locale dropdown * * @param bool $translatedName translation flag * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _getOptionLocales($translatedName = false) { $currentLocale = $this->localeResolver->getLocale(); $locales = \ResourceBundle::getLocales('') ?: []; $languages = (new LanguageBundle())->get($currentLocale)['Languages']; $countries = (new RegionBundle())->get($currentLocale)['Countries']; $options = []; $allowedLocales = $this->_config->getAllowedLocales(); foreach ($locales as $locale) { if (!in_array($locale, $allowedLocales)) { continue; } $language = \Locale::getPrimaryLanguage($locale); $country = \Locale::getRegion($locale); if (!$languages[$language] || !$countries[$country]) { continue; } if ($translatedName) { $label = ucwords(\Locale::getDisplayLanguage($locale, $locale)) . ' (' . \Locale::getDisplayRegion($locale, $locale) . ') / ' . $languages[$language] . ' (' . $countries[$country] . ')'; } else { $label = $languages[$language] . ' (' . $countries[$country] . ')'; } $options[] = ['value' => $locale, 'label' => $label]; } return $this->_sortOptionArray($options); }
/** * Returns a carrier name for the given phone number, in the language provided. The carrier name * is the one the number was originally allocated to, however if the country supports mobile * number portability the number might not belong to the returned carrier anymore. If no mapping * is found an empty string is returned. * * <p>This method assumes the validity of the number passed in has already been checked, and that * the number is suitable for carrier lookup. We consider mobile and pager numbers possible * candidates for carrier lookup. * * @param PhoneNumber $number a valid phone number for which we want to get a carrier name * @param string $languageCode the language code in which the name should be written * @return string a carrier name for the given phone number */ public function getNameForValidNumber(PhoneNumber $number, $languageCode) { $languageStr = \Locale::getPrimaryLanguage($languageCode); $scriptStr = ""; $regionStr = \Locale::getRegion($languageCode); return $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr); }
public static function getBestFit($locale) { $primary = Locale::getPrimaryLanguage($locale); foreach (self::getSystemLocales() as $systemLocale) { if ($primary === Locale::getPrimaryLanguage($systemLocale)) { return $systemLocale; } } }
/** * @return Generator|array */ protected function getLangRows() { foreach ($this->getLanguages() as $locale) { $primaryLanguage = Locale::getPrimaryLanguage($locale); $displayLanguage = Locale::getDisplayLanguage($locale, $primaryLanguage); $displayLanguage = mb_convert_case($displayLanguage, MB_CASE_TITLE, "UTF-8"); (yield [$primaryLanguage, $displayLanguage, $locale, 10]); } }
/** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $configs = $this->options; $resolver->setDefaults(array('culture' => \Locale::getPrimaryLanguage(\Locale::getDefault()), 'widget' => 'choice', 'years' => range(date('Y') - 5, date('Y') + 5), 'configs' => array('dateFormat' => null)))->setNormalizers(array('configs' => function (Options $options, $value) use($configs) { $result = array_merge($configs, $value); if ('single_text' !== $options['widget'] || isset($result['buttonImage'])) { $result['showOn'] = 'button'; } return $result; })); }
public function handle($request, Closure $next) { if (Session::has('applocale') and array_key_exists(Session::get('applocale'), Config::get('languages'))) { App::setLocale(Session::get('applocale')); setlocale(LC_TIME, Session::get('applocale')); Carbon::setLocale(\Locale::getPrimaryLanguage(Session::get('applocale'))); } else { App::setLocale(Config::get('app.fallback_locale')); setlocale(LC_TIME, Config::get('app.fallback_locale')); Carbon::setLocale(\Locale::getPrimaryLanguage(Config::get('app.fallback_locale'))); } return $next($request); }
/** * Called after routing * * @param MvcEvent $event */ public function onRoute(MvcEvent $event) { $serviceManager = $event->getApplication()->getServiceManager(); /* @var RouteMatch $routeMatch */ $routeMatch = $event->getRouteMatch(); $language = ''; // check if the language is set by routing (parameter, domain name, etc) if ($routeMatch->getParam('language') == '') { // get route $route = explode('/', $routeMatch->getMatchedRouteName()); // $module = $route[0]; /** @var \Msingi\Cms\Settings $settings */ $settings = $event->getApplication()->getServiceManager()->get('Settings'); // get defaults from settings $multilanguage = (bool) $settings->get($module . ':languages:multilanguage'); $language_default = $settings->get($module . ':languages:default'); $languages_enabled = $settings->get($module . ':languages:enabled'); if ($multilanguage && is_array($languages_enabled)) { /** @var \Zend\Http\Request $request */ $request = $event->getRequest(); // try to get language from cookie if ($request->getCookie('language') != '') { $language = $event->getRequest()->getCookie('language'); } // try to get language from browser if ($language == '' && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $language = \Locale::getPrimaryLanguage(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE'])); } // fallback to default language if given one is not supported if (!in_array($language, $languages_enabled)) { $language = $language_default; } } else { // not multilanguage module, use default language $language = $language_default; } $routeMatch->setParam('language', $language); } else { $language = $routeMatch->getParam('language'); $language_default = $language; } // translator $translator = $serviceManager->get('Translator'); $translator->setLocale($language)->setFallbackLocale($language_default); // cache $cache = $serviceManager->get('Application\\Cache'); if ($cache) { $translator->setCache($cache); } }
/** * * * @param string $templateName * @param string $to * @param array $params * @return */ public function __invoke($templateName, $to, array $params = array()) { // set mail language if not given if (!isset($params['language']) && $this->translator) { $params['language'] = \Locale::getPrimaryLanguage($this->translator->getLocale()); } // set root url if not given if (!isset($params['root_url']) && $this->router) { $params['root_url'] = rtrim($this->router->assemble(array('language' => $params['language']), array('name' => 'frontend/index')), '/'); } // $params['to'] = $to; return $this->mailer->sendMail($templateName, $to, $params); }
public function handle($request, Closure $next) { $sessionAppLocale = session()->get('applocale'); if (session()->has('applocale') and array_key_exists($sessionAppLocale, Config::get('languages'))) { app()->setLocale($sessionAppLocale); setlocale(LC_TIME, $sessionAppLocale); Carbon::setLocale(\Locale::getPrimaryLanguage($sessionAppLocale)); return $next($request); } $fallbackLocale = Config::get('app.fallback_locale'); app()->setLocale($fallbackLocale); setlocale(LC_TIME, $fallbackLocale); Carbon::setLocale(\Locale::getPrimaryLanguage($fallbackLocale)); return $next($request); }
/** * @param string $locale * @return Context */ public function build($locale = null) { $context = Context::of(); foreach ($this->defaults as $key => $default) { $context[$key] = $default; } if (is_null($locale)) { $locale = $context->getLocale(); } $locale = $this->converter->convert($locale); $fallbackLanguages = $this->fallbackLanguages; $language = \Locale::getPrimaryLanguage($locale); $languages = [$language]; if (isset($fallbackLanguages[$language])) { $languages = array_merge($languages, $fallbackLanguages[$language]); } $context->setLanguages($languages)->setLocale($locale); return $context; }
/** * Retrieve list of locales * * @return array */ public function getLocaleList() { $languages = (new LanguageBundle())->get(Resolver::DEFAULT_LOCALE)['Languages']; $countries = (new RegionBundle())->get(Resolver::DEFAULT_LOCALE)['Countries']; $locales = \ResourceBundle::getLocales('') ?: []; $list = []; foreach ($locales as $locale) { if (!in_array($locale, $this->allowedLocales)) { continue; } $language = \Locale::getPrimaryLanguage($locale); $country = \Locale::getRegion($locale); if (!$languages[$language] || !$countries[$country]) { continue; } $list[$locale] = $languages[$language] . ' (' . $countries[$country] . ')'; } asort($list); return $list; }
/** * @param string $name * @return string */ public function __invoke($name) { if ($this->meta == null) { $serviceManager = $this->event->getApplication()->getServiceManager(); $translator = $serviceManager->get('Translator'); $locale = $translator->getLocale(); /** @var \Msingi\Cms\Repository\PageI18ns $meta_repository */ $meta_repository = $this->getEntityManager()->getRepository('Msingi\\Cms\\Entity\\PageI18n'); $this->meta = $meta_repository->fetchOrCreate($this->page, \Locale::getPrimaryLanguage($locale)); } switch ($name) { case 'title': return $this->meta->getTitle(); case 'keywords': return $this->meta->getKeywords(); case 'description': return $this->meta->getDescription(); } return ''; }
protected function getHeaderViewData($title, Request $request = null) { $session = $this->get('session'); $header = new Header($title); $header->stores = new Url($this->trans('header.stores'), ''); $header->help = new Url($this->trans('header.help'), ''); $header->callUs = new Url($this->trans('header.callUs', ['phone' => $this->config['sunrise.header.callUs']]), ''); $header->location = new ViewData(); $languages = new ViewDataCollection(); $routeParams = $request->get('_route_params'); $queryParams = \GuzzleHttp\Psr7\parse_query($request->getQueryString()); foreach ($this->config['languages'] as $language) { $languageEntry = new ViewData(); if ($language == \Locale::getPrimaryLanguage($this->locale)) { $languageEntry->selected = true; } $languageEntry->label = $this->trans('header.languages.' . $language); $routeParams['_locale'] = $language; $languageUri = $this->generateUrl($request->get('_route'), $routeParams); $uri = new Uri($languageUri); $languageEntry->value = (string) $uri->withQuery(\GuzzleHttp\Psr7\build_query($queryParams)); $languages->add($languageEntry); } $header->location->language = $languages; // $countries = new ViewDataCollection(); // foreach ($this->config['countries'] as $country) { // $countryEntry = new ViewData(); // $countryEntry->label = $this->trans('header.countries.' . $country); // $countryEntry->value = $country; // $countries->add($countryEntry); // } // // $header->location->country = $countries; $header->user = new ViewData(); $header->user->isLoggedIn = false; $header->user->signIn = new Url('Login', ''); $header->miniCart = new ViewData(); $header->miniCart->totalItems = $session->get('cartNumItems', 0); $header->navMenu = $this->getNavMenu(); return $header; }
public function onRenderCommon(MvcEvent $event) { $response = $event->getResponse(); if (!$response instanceof HttpResponse) { return; } $services = $event->getApplication()->getServiceManager(); $locales = $services->get('LocaleManager'); $locale = $locales->getLocale(); // HTML TAG view helper if ($services->has('ViewHelperManager')) { $viewHelperManager = $services->get('ViewHelperManager'); if ($viewHelperManager instanceof HelperPluginManager) { // HtmlTag if ($viewHelperManager->has('htmlTag')) { $htmlTag = $viewHelperManager->get('htmlTag'); $htmlTag->setAttribute('lang', \Locale::getPrimaryLanguage($locale)); } } } }
/** * Validates a Locale * * @param string $locale The locale to be validated * @param Constraint $constraint Locale Constraint * * @throws \Symfony\Component\Validator\Exception\UnexpectedTypeException */ public function validate($locale, Constraint $constraint) { if (null === $locale || '' === $locale) { return; } if (!is_scalar($locale) && !(is_object($locale) && method_exists($locale, '__toString'))) { throw new UnexpectedTypeException($locale, 'string'); } $locale = (string) $locale; if ($this->intlExtension) { $primary = \Locale::getPrimaryLanguage($locale); $region = \Locale::getRegion($locale); $locales = Intl::getLocaleBundle()->getLocales(); if (null !== $region && strtolower($primary) != strtolower($region) && !in_array($locale, $locales) && !in_array($primary, $locales)) { $this->context->addViolation($constraint->message, array('%string%' => $locale)); } } else { $splittedLocale = explode('_', $locale); $splitCount = count($splittedLocale); if ($splitCount == 1) { $primary = $splittedLocale[0]; if (!in_array($primary, $this->iso639)) { $this->context->addViolation($constraint->message, array('%string%' => $locale)); } } elseif ($splitCount == 2) { $primary = $splittedLocale[0]; $region = $splittedLocale[1]; if (!in_array($primary, $this->iso639) && !in_array($region, $this->iso3166)) { $this->context->addViolation($constraint->message, array('%string%' => $locale)); } } elseif ($splitCount > 2) { $primary = $splittedLocale[0]; $script = $splittedLocale[1]; $region = $splittedLocale[2]; if (!in_array($primary, $this->iso639) && !in_array($region, $this->iso3166) && !in_array($script, $this->script)) { $this->context->addViolation($constraint->message, array('%string%' => $locale)); } } } }
/** * @param $locale * @param $clientCredentials * @param $fallbackLanguages * @return static */ public function build($locale, $clientCredentials = null, $fallbackLanguages = null) { if (is_null($clientCredentials)) { $clientCredentials = $this->clientCredentials; } if (is_null($fallbackLanguages)) { $fallbackLanguages = $this->fallbackLanguages; } $language = \Locale::getPrimaryLanguage($locale); $languages = array_merge([$language], $fallbackLanguages[$language]); $context = Context::of()->setLanguages($languages)->setGraceful(true)->setLocale($locale); if (getenv('SPHERE_CLIENT_ID')) { $config = ['client_id' => getenv('SPHERE_CLIENT_ID'), 'client_secret' => getenv('SPHERE_CLIENT_SECRET'), 'project' => getenv('SPHERE_PROJECT')]; } else { $config = $clientCredentials; } $config = Config::fromArray($config)->setContext($context); if (is_null($this->logger)) { return Client::ofConfigAndCache($config, $this->cache); } return Client::ofConfigCacheAndLogger($config, $this->cache, $this->logger); }
/** * @return array */ public function getValueOptions() { if (empty($this->valueOptions)) { $this->valueOptions = array(); $enabledLocales = $this->getServiceLocator()->get('Locale')->getAvailableFlags(); if ($this->onlyEnabledLocales) { $enabledLocales = array_filter($enabledLocales); } foreach ($enabledLocales as $locale => $enabled) { $main = IntlLocale::getPrimaryLanguage($locale); $sub = IntlLocale::getRegion($locale); $mainKey = 'locale.main.' . $main; $localeKey = 'locale.sub.' . $locale; if (!empty($this->valueOptions[$mainKey])) { $this->valueOptions[$mainKey]['options'][$locale] = $localeKey; } elseif (!$sub && empty($this->valueOptions[$locale])) { $this->valueOptions[$locale] = $mainKey; } else { if ($sub && !empty($this->valueOptions[$main])) { $this->valueOptions[$mainKey]['options'] = array($main => 'locale.sub.' . $main); unset($this->valueOptions[$main]); } $this->valueOptions[$mainKey]['options'][$locale] = $localeKey; $this->valueOptions[$mainKey]['label'] = $mainKey; } } foreach ($this->valueOptions as &$valueGroup) { if (is_array($valueGroup) && isset($valueGroup['options']) && is_array($valueGroup['options'])) { ksort($valueGroup['options']); } } $first = reset($this->valueOptions); if (count($this->valueOptions) === 1 && is_array($first) && !empty($first['options'])) { $this->valueOptions = $first['options']; } } return parent::getValueOptions(); }
/** * @internal */ public function onBootstrap(\Zend\EventManager\EventInterface $e) { \Zend\Filter\StaticFilter::getPluginManager()->setInvokableClass('Library\\FixEncodingErrors', 'Library\\Filter\\FixEncodingErrors'); $serviceManager = $e->getApplication()->getServiceManager(); // Register form element view helpers $formElementHelper = $serviceManager->get('ViewHelperManager')->get('formElement'); $formElementHelper->addClass('Library\\Form\\Element\\SelectSimple', 'formselectsimple'); $formElementHelper->addType('select_untranslated', 'formselectuntranslated'); if (\Locale::getPrimaryLanguage(\Locale::getDefault()) != 'en') { $mvcTranslator = $serviceManager->get('MvcTranslator'); if (Application::isDevelopment()) { $translator = $mvcTranslator->getTranslator(); $translator->enableEventManager(); $translator->getEventManager()->attach(\Zend\I18n\Translator\Translator::EVENT_MISSING_TRANSLATION, array($this, 'onMissingTranslation')); } // Validators have no translator by default. Attach translator, but // use a different text domain to avoid warnings if the Zend // translations are not loaded. For custom messages, the text domain // must be reset manually to 'default' for individual validators. \Zend\Validator\AbstractValidator::setDefaultTranslator($mvcTranslator); \Zend\Validator\AbstractValidator::setDefaultTranslatorTextDomain('Zend'); } }
/** * @param ServiceLocatorInterface $serviceLocator * @return mixed */ protected function getPages(ServiceLocatorInterface $serviceLocator) { if (null === $this->pages) { // get translator $translator = $serviceLocator->get('Translator'); $locale = $translator->getLocale(); $language = \Locale::getPrimaryLanguage($locale); // try to get menu from cache $cache = $serviceLocator->get('Application\\Cache'); if ($cache) { $cacheKey = sprintf('menu-%s-%s', $this->getName(), $language); $pages = $cache->getItem($cacheKey); } if (!$pages) { $pages = $this->fetchPages($serviceLocator, $language); } if ($cache) { $cache->setItem($cacheKey, $pages); } $this->pages = $this->preparePages($serviceLocator, $pages); } return $this->pages; }
public function negociateLocale() { $front_controller = __FrontController::getInstance(); $request = $front_controller->getRequest(); $app_name = md5(__ApplicationContext::getInstance()->getPropertyContent('APP_NAME')); if ($request != null && $request->hasCookie('__LOCALE__' . $app_name)) { $locale_code = $request->getCookie('__LOCALE__' . $app_name); $return_value = new __Locale($locale_code); } else { if (key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) { $http_accept_language = $_SERVER['HTTP_ACCEPT_LANGUAGE']; } if (!empty($http_accept_language)) { //by default: if (class_exists('Locale')) { $accepted_locale = Locale::acceptFromHttp($http_accept_language); $candidate_language = Locale::getPrimaryLanguage($accepted_locale); } else { $accepted_languages = preg_split('/,/', $http_accept_language); $candidate_language = $this->_getLanguageIsoCode($accepted_languages[0]); } } if (isset($candidate_language) && __I18n::getInstance()->isSupportedLanguage($candidate_language)) { $primary_language = $candidate_language; } else { $primary_language = __I18n::getInstance()->getDefaultLanguageIsoCode(); } $return_value = new __Locale($primary_language); $auth_cookie = new __Cookie('__LOCALE__' . $app_name, $primary_language, session_cache_expire() * 60, '/'); $response = __FrontController::getInstance()->getResponse(); if ($response != null) { $response->addCookie($auth_cookie); } } return $return_value; }
/** * Method to parse a language/locale key and return a simple language string. * * @param string $lang The language/locale key. For example: en-GB * * @return string The simple language string. For example: en * * @since 2.5 */ public static function getPrimaryLanguage($lang) { static $data; // Only parse the identifier if necessary. if (!isset($data[$lang])) { if (is_callable(array('Locale', 'getPrimaryLanguage'))) { // Get the language key using the Locale package. $data[$lang] = Locale::getPrimaryLanguage($lang); } else { // Get the language key using string position. $data[$lang] = JString::substr($lang, 0, JString::strpos($lang, '-')); } } return $data[$lang]; }
/** * * * @param $Path * @param $Controller */ public function init($Path, $Controller) { $Smarty = $this->smarty(); // Get a friendly name for the controller. $ControllerName = get_class($Controller); if (StringEndsWith($ControllerName, 'Controller', true)) { $ControllerName = substr($ControllerName, 0, -10); } // Get an ID for the body. $BodyIdentifier = strtolower($Controller->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::alphaNumeric(strtolower($Controller->RequestMethod))); $Smarty->assign('BodyID', $BodyIdentifier); //$Smarty->assign('Config', Gdn::Config()); // Assign some information about the user. $Session = Gdn::session(); if ($Session->isValid()) { $User = array('Name' => $Session->User->Name, 'Photo' => '', 'CountNotifications' => (int) val('CountNotifications', $Session->User, 0), 'CountUnreadConversations' => (int) val('CountUnreadConversations', $Session->User, 0), 'SignedIn' => true); $Photo = $Session->User->Photo; if ($Photo) { if (!IsUrl($Photo)) { $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s')); } } else { if (function_exists('UserPhotoDefaultUrl')) { $Photo = UserPhotoDefaultUrl($Session->User, 'ProfilePhoto'); } elseif ($ConfigPhoto = C('Garden.DefaultAvatar')) { $Photo = Gdn_Upload::url($ConfigPhoto); } else { $Photo = Asset('/applications/dashboard/design/images/defaulticon.png', true); } } $User['Photo'] = $Photo; } else { $User = false; /*array( 'Name' => '', 'CountNotifications' => 0, 'SignedIn' => FALSE);*/ } $Smarty->assign('User', $User); // Make sure that any datasets use arrays instead of objects. foreach ($Controller->Data as $Key => $Value) { if ($Value instanceof Gdn_DataSet) { $Controller->Data[$Key] = $Value->resultArray(); } elseif ($Value instanceof stdClass) { $Controller->Data[$Key] = (array) $Value; } } $BodyClass = val('CssClass', $Controller->Data, '', true); $Sections = Gdn_Theme::section(null, 'get'); if (is_array($Sections)) { foreach ($Sections as $Section) { $BodyClass .= ' Section-' . $Section; } } $Controller->Data['BodyClass'] = $BodyClass; // Set the current locale for themes to take advantage of. $Locale = Gdn::locale()->Locale; $CurrentLocale = array('Key' => $Locale, 'Lang' => str_replace('_', '-', $Locale)); if (class_exists('Locale')) { $CurrentLocale['Language'] = Locale::getPrimaryLanguage($Locale); $CurrentLocale['Region'] = Locale::getRegion($Locale); $CurrentLocale['DisplayName'] = Locale::getDisplayName($Locale, $Locale); $CurrentLocale['DisplayLanguage'] = Locale::getDisplayLanguage($Locale, $Locale); $CurrentLocale['DisplayRegion'] = Locale::getDisplayRegion($Locale, $Locale); } $Smarty->assign('CurrentLocale', $CurrentLocale); $Smarty->assign('Assets', (array) $Controller->Assets); $Smarty->assign('Path', Gdn::request()->path()); // Assign the controller data last so the controllers override any default data. $Smarty->assign($Controller->Data); $Smarty->Controller = $Controller; // for smarty plugins $Smarty->security = true; $Smarty->security_settings['IF_FUNCS'] = array_merge($Smarty->security_settings['IF_FUNCS'], array('Category', 'CheckPermission', 'InSection', 'InCategory', 'MultiCheckPermission', 'GetValue', 'SetValue', 'Url')); $Smarty->security_settings['MODIFIER_FUNCS'] = array_merge($Smarty->security_settings['MODIFIER_FUNCS'], array('sprintf')); $Smarty->secure_dir = array($Path); }
private function generateLocaleName($locale, $displayLocale) { $name = null; $lang = \Locale::getPrimaryLanguage($locale); $script = \Locale::getScript($locale); $region = \Locale::getRegion($locale); $variants = \Locale::getAllVariants($locale); // Currently the only available variant is POSIX, which we don't want // to include in the list if (count($variants) > 0) { return null; } // Some languages are translated together with their region, // i.e. "en_GB" is translated as "British English" // we don't include these languages though because they mess up // the name sorting // $name = $this->langBundle->getLanguageName($displayLocale, $lang, $region); // Some languages are simply not translated // Example: "az" (Azerbaijani) has no translation in "af" (Afrikaans) if (null === ($name = $this->languageBundle->getLanguageName($lang, null, $displayLocale))) { return null; } // "as" (Assamese) has no "Variants" block //if (!$langBundle->get('Variants')) { // continue; //} $extras = array(); // Discover the name of the script part of the locale // i.e. in zh_Hans_MO, "Hans" is the script if ($script) { // Some scripts are not translated into every language if (null === ($scriptName = $this->languageBundle->getScriptName($script, $lang, $displayLocale))) { return null; } $extras[] = $scriptName; } // Discover the name of the region part of the locale // i.e. in de_AT, "AT" is the region if ($region) { // Some regions are not translated into every language if (null === ($regionName = $this->regionBundle->getCountryName($region, $displayLocale))) { return null; } $extras[] = $regionName; } if (count($extras) > 0) { // Remove any existing extras // For example, in German, zh_Hans is "Chinesisch (vereinfacht)". // The latter is the script part which is already included in the // extras and will be appended again with the other extras. if (preg_match('/^(.+)\\s+\\([^\\)]+\\)$/', $name, $matches)) { $name = $matches[1]; } $name .= ' (' . implode(', ', $extras) . ')'; } return $name; }
/** * Get language code. * * If param $case is not set the result will be in LOWER case (e. g. "de") by default. * * @param string $case [optional] Convert value to case (Text::LOWER, Text::UPPER or Text::NONE) * * @return string */ public function getLanguage($case = Text::NONE) { return Text::toCase(\Locale::getPrimaryLanguage($this->locale), $case); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $request = $e->getApplication()->getServiceManager()->get('Request'); $moduleRouteListener->attach($eventManager); $adapter = $e->getApplication()->getServiceManager()->get('Zend\\Db\\Adapter\\Adapter'); $config = $e->getApplication()->getServiceManager()->get('Configuration'); $locale = null; $eventManager->attach(new UserRegisterListener($adapter)); $eventManager->attach(new LogListener()); // Add ACL information to the Navigation view helper $authorize = $e->getApplication()->getServiceManager()->get('BjyAuthorize\\Service\\Authorize'); $acl = $authorize->getAcl(); $role = $authorize->getIdentity(); \Zend\View\Helper\Navigation::setDefaultAcl($acl); \Zend\View\Helper\Navigation::setDefaultRole($role); // translating system $sessionConfig = new SessionConfig(); $sessionConfig->setOptions($config['session']); $sessionManager = new SessionManager($sessionConfig); $sessionManager->start(); $session = new Container('base'); // Get the visitor language selection $translator = $e->getApplication()->getServiceManager()->get('translator'); // get the locale from the cookie $headCookie = $request->getHeaders()->get('Cookie'); if (!empty($headCookie) && array_key_exists('locale', get_object_vars($headCookie))) { $locale = $headCookie->locale; } if (empty($locale)) { // if there is not set any cookie $locale = $session->offsetGet('locale'); // Get the locale from the session if (empty($locale)) { // if there is not any session set yet $headers = $request->getHeaders(); if ($headers->has('Accept-Language')) { $locales = $headers->get('Accept-Language')->getPrioritized(); $first = array_shift($locales); $locale = $first->getLanguage(); if (!empty($locale) && 2 == strlen($locale)) { $locale .= "_" . strtoupper($locale); } } if (empty($locale)) { // if the browser has no locale set, we have to get the default INTL global locale setting $locale = \Locale::getPrimaryLanguage(\Locale::getDefault()); // Gets the default locale value from the INTL global 'default_locale' } } } else { #\Zend\Debug\debug::dump("Cookie set with locale: $locale"); } $translator->setLocale(\Locale::acceptFromHttp($locale)); $translator->setLocale($locale)->setFallbackLocale('en_US'); \Zend\Validator\AbstractValidator::setDefaultTranslator($translator); \Zend\Validator\AbstractValidator::setDefaultTranslatorTextDomain(); }