/** * applyParsley * @return this **/ public function applyParsley() { $this->parsleyEnabled = true; Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js'); Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/parsley/parsley.remote.min.js'); $lang = i18n::get_lang_from_locale(i18n::get_locale()); if ($lang != 'en') { Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/parsley/i18n/' . $lang . '.js'); } if ($this->form) { if ($this->defaultJS) { $this->form->addExtraClass('parsley'); Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/zenvalidator.js'); } else { $this->form->addExtraClass('custom-parsley'); } foreach ($this->constraints as $fieldName => $constraints) { foreach ($constraints as $constraint) { $constraint->applyParsley(); } } } return $this; }
/** * @param $locale */ public function __construct($locale = null) { $this->defaultLocale = $locale ? $locale : i18n::get_lang_from_locale(i18n::default_locale()); $this->basePath = Director::baseFolder(); $this->baseSavePath = Director::baseFolder(); parent::__construct(); }
/** * Get a set of content languages (for quick language navigation) * @example * <code> * <!-- in your template --> * <ul class="langNav"> * <% loop Languages %> * <li><a href="$Link" class="$LinkingMode" title="$Title.ATT">$Language</a></li> * <% end_loop %> * </ul> * </code> * * @return ArrayList|null */ public function Languages() { $locales = TranslatableUtility::get_content_languages(); // there's no need to show a navigation when there's less than 2 languages. So return null if (count($locales) < 2) { return null; } $currentLocale = Translatable::get_current_locale(); $homeTranslated = null; if ($home = SiteTree::get_by_link('home')) { /** @var SiteTree $homeTranslated */ $homeTranslated = $home->getTranslation($currentLocale); } /** @var ArrayList $langSet */ $langSet = ArrayList::create(); foreach ($locales as $locale => $name) { Translatable::set_current_locale($locale); /** @var SiteTree $translation */ $translation = $this->owner->hasTranslation($locale) ? $this->owner->getTranslation($locale) : null; $langSet->push(new ArrayData(array('Locale' => $locale, 'RFC1766' => i18n::convert_rfc1766($locale), 'Language' => DBField::create_field('Varchar', strtoupper(i18n::get_lang_from_locale($locale))), 'Title' => DBField::create_field('Varchar', html_entity_decode(i18n::get_language_name(i18n::get_lang_from_locale($locale), true), ENT_NOQUOTES, 'UTF-8')), 'LinkingMode' => $currentLocale == $locale ? 'current' : 'link', 'Link' => $translation ? $translation->AbsoluteLink() : ($homeTranslated ? $homeTranslated->Link() : '')))); } Translatable::set_current_locale($currentLocale); i18n::set_locale($currentLocale); return $langSet; }
/** * Retrieves information about this object in the CURRENT locale * * @param string $locale The locale information to request, or null to use the default locale * @return ArrayData Mapped list of locale properties */ public function CurrentLocaleInformation() { $locale = Fluent::current_locale(); // Store basic locale information $data = array('Locale' => $locale, 'LocaleRFC1766' => i18n::convert_rfc1766($locale), 'Alias' => Fluent::alias($locale), 'Title' => i18n::get_locale_name($locale), 'LanguageNative' => i18n::get_language_name(i18n::get_lang_from_locale($locale), true)); return new ArrayData($data); }
/** * Updates the CMS fields adding the fields defined in this extension * @param {FieldList} $fields Field List that new fields will be added to */ public function updateCMSFields(FieldList $fields) { $urlSegmentField = $fields->dataFieldByName('URLSegment'); if ($urlSegmentField) { $baseLink = Controller::join_links(Director::absoluteBaseURL(), (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL') ? $this->owner->Locale : i18n::get_lang_from_locale($this->owner->Locale)) . '/', SiteTree::config()->nested_urls && $this->owner->ParentID ? $this->owner->Parent()->RelativeLink(true) : null); $urlSegmentField->setURLPrefix($baseLink); } }
function __construct($name, $title = null, $value = null) { parent::__construct($name, $title, $value); Requirements::javascript(FORM_EXTRAS_PATH . '/javascript/tinymce/tinymce.min.js'); $lang = i18n::get_lang_from_locale(i18n::get_locale()); if ($lang != 'en') { Requirements::javascript(FORM_EXTRAS_PATH . '/javascript/tinymce/langs/' . $lang . '.js'); } }
/** * Load extra validator * @param string $name * */ public function loadExtra($name) { $useCurrent = ZenValidator::config()->use_current; $parsleyFolder = 'parsley'; if ($useCurrent) { $parsleyFolder = 'parsley_current'; } Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/' . $parsleyFolder . '/extra/validator/' . $name . '.js'); $lang = i18n::get_lang_from_locale(i18n::get_locale()); Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/' . $parsleyFolder . '/i18n/' . $lang . '.extra.js'); }
/** * Adds in the requirements for the field * @param {array} $properties Array of properties for the form element (not used) * @return {string} Rendered field template */ public function Field($properties = array()) { $siteKey = self::config()->site_key; $secretKey = self::config()->secret_key; if (empty($siteKey) || empty($secretKey)) { user_error('You must configure Nocaptcha.site_key and Nocaptcha.secret_key, you can retrieve these at https://google.com/recaptcha', E_USER_ERROR); } Requirements::javascript(NOCAPTCHA_BASE . '/javascript/NocaptchaField.js'); Requirements::customScript("var _noCaptchaFields=_noCaptchaFields || [];_noCaptchaFields.push('" . $this->ID() . "');"); Requirements::customScript("(function() {\n" . " var gr = document.createElement('script'); gr.type = 'text/javascript'; gr.async = true;\n" . " gr.src = ('https:' == document.location.protocol ? 'https://www' : 'http://www') + " . "'.google.com/recaptcha/api.js?render=explicit&hl=" . i18n::get_lang_from_locale(i18n::get_locale()) . "&onload=noCaptchaFieldRender';\n" . " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gr, s);\n" . "})();\n", 'NocaptchaField-lib'); return parent::Field($properties); }
public function __construct($name, $title = null, $value = null) { parent::__construct($name, $title, $value); if ($this->getFileManager()) { FormExtraJquery::include_jquery(); } Requirements::javascript(FORM_EXTRAS_PATH . '/javascript/tinymce/tinymce.min.js'); $lang = i18n::get_lang_from_locale(i18n::get_locale()); if ($lang != 'en') { Requirements::javascript(FORM_EXTRAS_PATH . '/javascript/tinymce/langs/' . $lang . '.js'); } }
protected static function enable_custom_translations() { $locale = i18n::get_locale(); $lang = i18n::get_lang_from_locale($locale); $profileDir = self::getProfileDir(); $translators = array_reverse(i18n::get_translators(), true); // Make sure to include base translations i18n::include_by_locale($lang); foreach ($translators as $priority => $translators) { foreach ($translators as $name => $translator) { /* @var $adapter Zend_Translate_Adapter */ $adapter = $translator->getAdapter(); // Load translations from profile $filename = $adapter->getFilenameForLocale($lang); $filepath = Director::baseFolder() . "/mysite/lang/" . $profileDir . '/' . $filename; if ($filename && !file_exists($filepath)) { continue; } $adapter->addTranslation(array('content' => $filepath, 'locale' => $lang)); } } }
public function contentcontrollerInit() { $useBrowserLanguage = Config::inst()->get('GoogleDirections', 'use_browser_language'); if ($useBrowserLanguage) { Requirements::javascript("http://maps.google.com/maps/api/js?sensor=false"); } else { $locale = i18n::get_locale(); $language = i18n::get_lang_from_locale($locale); Requirements::javascript("http://maps.google.com/maps/api/js?sensor=false&language={$language}"); } Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.min.js'); Requirements::add_i18n_javascript(GOOGLEDIRECTIONS_BASE . '/javascript/lang'); Requirements::javascript(GOOGLEDIRECTIONS_BASE . '/javascript/googledirections.js'); Requirements::css(GOOGLEDIRECTIONS_BASE . '/css/googledirections.css'); // Build a defaultmap if there is one defined $startupMap = $this->owner->GoogleMaps()->filter(array('ShowOnStartup' => true))->first(); if ($startupMap) { $address = $startupMap->Address; $latlng = $startupMap->LatLng; $infoText = $startupMap->InfoText; $infoText = str_replace("", "''", $infoText); if ($address || $latlng) { Requirements::customScript(<<<JS \t\t\t\t\t(function(\$) { \t\t\t\t\t\t\$(document).ready(function() { \t\t\t\t\t\t\tlocations.defaultMap = { \t\t\t\t\t\t\t\tinfoText: '{$infoText}', \t\t\t\t\t\t\t\taddress: '{$address}', \t\t\t\t\t\t\t\tlatlng: '{$latlng}' \t\t\t\t\t\t\t}; \t\t\t\t\t\t\tshowStartupMap('defaultMap'); \t\t\t\t\t\t}); \t\t\t\t\t}(jQuery)); JS ); } } }
public function __construct($arg1 = null, $arg2 = null) { if ($arg1 === null) { $arg1 = new TextField('StreetName', ''); $arg1->setAttribute('placeholder', _t('GeoMemberExtension.STREETNAME')); $arg1->setAttribute('style', 'width:300px'); } if ($arg2 === null) { $arg2 = new TextField('StreetNumber', ''); $arg2->setAttribute('placeholder', _t('GeoMemberExtension.STREETNUMBER')); $arg2->setAttribute('style', 'width:75px'); } $this->streetNameField = $arg1; $this->streetNumberField = $arg2; $lang = i18n::get_lang_from_locale(i18n::get_locale()); if ($lang == 'fr') { parent::__construct($arg2, $arg1); } else { parent::__construct($arg1, $arg2); } $this->setTitle(_t('GeoMemberExtension.ADDRESSHEADER', 'Address')); $this->setFieldHolderTemplate('AddressFieldHolder'); }
function get_silverstripe_language() { $locale = i18n::get_locale(); if (class_exists('Fluent')) { $locale = Fluent::get_persist_locale(); } $lang = i18n::get_lang_from_locale($locale); if ($lang == 'en') { return 'en_EN'; } if ($lang == 'fr') { return 'fr_FR'; } // Otherwise look in lang folder $ulocale = str_replace('-', '_', $locale); $lang_folder = dirname(__DIR__) . '/lang/'; if (is_file($lang_folder . $lang . '.php')) { return $lang; } if (is_file($lang_folder . $ulocale . '.php')) { return $ulocale; } return 'en_EN'; }
public function ShortLocale() { return i18n::get_lang_from_locale(i18n::get_locale()); }
/** * Add i18n files from the given javascript directory. SilverStripe expects that the given * directory will contain a number of JavaScript files named by language: en_US.js, de_DE.js, * etc. * * @param string $langDir The JavaScript lang directory, relative to the site root, e.g., * 'framework/javascript/lang' * @param bool $return Return all relative file paths rather than including them in * requirements * @param bool $langOnly Only include language files, not the base libraries * * @return array */ public function add_i18n_javascript($langDir, $return = false, $langOnly = false) { $files = array(); $base = Director::baseFolder() . '/'; if (i18n::config()->js_i18n) { // Include i18n.js even if no languages are found. The fact that // add_i18n_javascript() was called indicates that the methods in // here are needed. if (!$langOnly) { $files[] = FRAMEWORK_DIR . '/javascript/i18n.js'; } if (substr($langDir, -1) != '/') { $langDir .= '/'; } $candidates = array('en.js', 'en_US.js', i18n::get_lang_from_locale(i18n::default_locale()) . '.js', i18n::default_locale() . '.js', i18n::get_lang_from_locale(i18n::get_locale()) . '.js', i18n::get_locale() . '.js'); foreach ($candidates as $candidate) { if (file_exists($base . DIRECTORY_SEPARATOR . $langDir . $candidate)) { $files[] = $langDir . $candidate; } } } else { // Stub i18n implementation for when i18n is disabled. if (!$langOnly) { $files[] = FRAMEWORK_DIR . '/javascript/i18nx.js'; } } if ($return) { return $files; } else { foreach ($files as $file) { $this->javascript($file); } } }
public function translate(SS_HTTPRequest $request) { $locales = ""; if (SiteTree::has_extension("Translatable")) { $locales = Translatable::get_allowed_locales(); } else { $locales = array("it_IT"); } $locales_list = new ArrayList(); foreach ($locales as $key => $value) { $obj = new ViewableData(); $obj->__set("Locale", $value); $obj->__set("LocaleName", i18n::get_locale_name($value)); $obj->__set("Lang", i18n::get_lang_from_locale($value)); $locales_list->push($obj); } if ($request->isAjax()) { if (isset($_POST["collect"])) { foreach ($locales as $value) { $c = new TextCollector($value); $c->run(LanguageAdmin::$modules, true); } die(_t("SUCCESSFULL_COLLECT", "The text was collected.")); } if (isset($_POST["save"])) { $lang_array[$_POST["locale"]] = $_POST[$_POST["locale"]]; $file = $_POST["file"]; $yml_file = sfYaml::dump($lang_array); if ($fh = fopen($file, "w")) { fwrite($fh, $yml_file); fclose($fh); file_get_contents("http://{$_SERVER['HTTP_HOST']}?flush"); } else { throw new LogicException("Cannot write language file! Please check permissions of {$langFile}"); } die; } $files = $this->getFiles(); if (isset($_POST["loadfiles"])) { // die($this->getYaml($_POST["loadfiles"])); $this->customise(array("Translations" => $this->getYaml($_POST["loadfiles"]), "Modules" => $files, "Locales" => $locales_list)); $content = $this->renderWith('LanguageAdmin_Content'); return $content; } else { $this->customise(array("Modules" => $files, "Translations" => $this->getYaml($files->filter(array('Locale' => $locales_list->first()->Locale))->first()->Path), "Locales" => $locales_list, "CurrentLocale" => $locales_list->first()->LocaleName)); $content = $this->renderWith('LanguageAdmin_Content'); return $content; } } else { $files = $this->getFiles(); $this->customise(array("Modules" => $files, "Translations" => $this->getYaml($files->filter(array('Locale' => $locales_list->first()->Locale))->first()->Path), "Locales" => $locales_list, "CurrentLocale" => $locales_list->first()->LocaleName)); $content = $this->renderWith($this->getViewer('translate')); return $content; } }
/** * Retrieves information about this object in the specified locale * * @param string $locale The locale information to request, or null to use the default locale * @return ArrayData Mapped list of locale properties */ public function LocaleInformation($locale = null) { // Check locale if (empty($locale)) { $locale = Fluent::default_locale(); } // Check linking mode $linkingMode = 'link'; if ($this->owner->hasMethod('canViewInLocale') && !$this->owner->canViewInLocale($locale)) { $linkingMode = 'invalid'; } elseif ($locale === Fluent::current_locale()) { $linkingMode = 'current'; } // Check link $link = $this->owner->LocaleLink($locale); // Store basic locale information $data = array('Locale' => $locale, 'LocaleRFC1766' => i18n::convert_rfc1766($locale), 'Alias' => Fluent::alias($locale), 'Title' => i18n::get_locale_name($locale), 'LanguageNative' => i18n::get_language_name(i18n::get_lang_from_locale($locale), true), 'Link' => $link, 'AbsoluteLink' => $link ? Director::absoluteURL($link) : null, 'LinkingMode' => $linkingMode); return new ArrayData($data); }
/** * * Fetch a native language string from the `i18n` class via a passed locale * in the format "XX_xx". In the event a match cannot be found in any framework * resource, an empty string is returned. * * @param string $locale e.g. "pt_BR" * @return string The native language string for that locale e.g. "português (Brazil)" */ public static function locale_native_name($locale) { // Attempts to fetch the native language string via the `i18n::$common_languages` array if ($native = i18n::get_language_name(i18n::get_lang_from_locale($locale), true)) { return $native; } // Attempts to fetch the native language string via the `i18n::$common_locales` array $commonLocales = i18n::get_common_locales(true); if (!empty($commonLocales[$locale])) { return $commonLocales[$locale]; } // Nothing else to go on, so return an empty string for a consistent API return ''; }
/** * Includes all available language files for a certain defined locale. * If the locale is a fully qualified locale (e.g. "en_US" rather than "en"), * will load the base locale file as well (if available). * * @param string $locale All resources from any module in locale $locale will be loaded * @param Boolean $clean Clean old caches? */ static function include_by_locale($locale, $clean = false) { $lang = i18n::get_lang_from_locale($locale); if($clean) { $cache = Zend_Translate::getCache(); if($cache) $cache->clean(Zend_Cache::CLEANING_MODE_ALL); } // Automatically include fallback language (if applicable) // TODO Also include custom Zend_Translate routing languages $selectedLocales = array_unique(array($lang, $locale)); // Sort modules by inclusion priority, then alphabetically // TODO Should be handled by priority flags within modules $prios = array('sapphire' => 10, 'framework' => 10, 'admin' => 11, 'cms' => 12, 'mysite' => 90); $modules = SS_ClassLoader::instance()->getManifest()->getModules(); ksort($modules); uksort( $modules, function($a, $b) use(&$prios) { $prioA = (isset($prios[$a])) ? $prios[$a] : 50; $prioB = (isset($prios[$b])) ? $prios[$b] : 50; return ($prioA > $prioB); } ); // Loop in reverse order, meaning the translator with the highest priority goes first $translators = array_reverse(self::get_translators(), true); foreach($translators as $priority => $translators) { foreach($translators as $name => $translator) { $adapter = $translator->getAdapter(); // Load translations from modules foreach($modules as $module) { foreach($selectedLocales as $selectedLocale) { $filename = $adapter->getFilenameForLocale($selectedLocale); $filepath = "{$module}/lang/" . $filename; if($filename && !file_exists($filepath)) continue; $adapter->addTranslation( array('content' => $filepath, 'locale' => $selectedLocale) ); } } // Load translations from themes // TODO Replace with theme listing once implemented in TemplateManifest $themesBase = Director::baseFolder() . '/themes'; if(is_dir($themesBase)) { foreach(scandir($themesBase) as $theme) { if( strpos($theme, SSViewer::current_theme()) === 0 && file_exists("{$themesBase}/{$theme}/lang/") ) { foreach($selectedLocales as $selectedLocale) { $filename = $adapter->getFilenameForLocale($selectedLocale); $filepath = "{$themesBase}/{$theme}/lang/" . $filename; if($filename && !file_exists($filepath)) continue; $adapter->addTranslation( array('content' => $filepath, 'locale' => $selectedLocale) ); } } } } // Add empty translations to ensure the locales are "registered" with isAvailable(), // and the next invocation of include_by_locale() doesn't cause a new reparse. foreach($selectedLocales as $selectedLocale) { $adapter->addTranslation( array( 'content' => array('_' => '_'), 'locale' => $selectedLocale, 'usetranslateadapter' => true ) ); } } } }
/** * Load extra validator * @param string $name * */ function loadExtra($name) { Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/parsley/extra/validator/' . $name . '.js'); $lang = i18n::get_lang_from_locale(i18n::get_locale()); Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/parsley/i18n/' . $lang . '.extra.js'); }
/** * Sets i18n locale and adds Content-language to meta tags. * @param string $locale */ public static function setup_locale($locale = "") { if ($locale != "") { Requirements::insertHeadTags('<meta http-equiv="Content-language" content="' . i18n::get_lang_from_locale($locale) . '" />'); i18n::set_locale($locale); } else { Debug::show("Your locale is not properly set. Remember that for using this function you need to use Object::add_extension('SiteTree', 'Translatable'); in your project _config.php"); } }
/** * Determines which language to use for jQuery UI, which * can be different from the value set in i18n. * * @return String */ protected function getLang() { $locale = $this->getField()->getLocale(); if ($this->getField()->getConfig('jslocale')) { // Undocumented config property for now, might move to the jQuery view helper $lang = $this->getField()->getConfig('jslocale'); } else { if (array_key_exists($locale, self::$locale_map)) { // Specialized mapping for combined lang properties $lang = self::$locale_map[$locale]; } else { // Fall back to default lang (meaning "en_US" turns into "en") $lang = i18n::get_lang_from_locale($locale); } } return $lang; }
/** * Get the class dropdown used in the CMS to change the class of a page. This returns the list of options in the * dropdown as a Map from class name to singular name. Filters by {@link SiteTree->canCreate()}, as well as * {@link SiteTree::$needs_permission}. * * @return array */ protected function getClassDropdown() { $classes = self::page_type_classes(); $currentClass = null; $result = array(); $result = array(); foreach ($classes as $class) { $instance = singleton($class); // if the current page type is this the same as the class type always show the page type in the list if ($this->ClassName != $instance->ClassName) { if ($instance instanceof HiddenClass || !$instance->canCreate()) { continue; } } if ($perms = $instance->stat('need_permission')) { if (!$this->can($perms)) { continue; } } $pageTypeName = $instance->i18n_singular_name(); $currentClass = $class; $result[$class] = $pageTypeName; // If we're in translation mode, the link between the translated pagetype title and the actual classname // might not be obvious, so we add it in parantheses. Example: class "RedirectorPage" has the title // "Weiterleitung" in German, so it shows up as "Weiterleitung (RedirectorPage)" if (i18n::get_lang_from_locale(i18n::get_locale()) != 'en') { $result[$class] = $result[$class] . " ({$class})"; } } // sort alphabetically, and put current on top asort($result); if ($currentClass) { $currentPageTypeName = $result[$currentClass]; unset($result[$currentClass]); $result = array_reverse($result); $result[$currentClass] = $currentPageTypeName; $result = array_reverse($result); } return $result; }
public function Field($properties = array()) { Requirements::javascript('pixlr/javascript/pixlr.js'); Requirements::javascript('pixlr/javascript/pixlr.jquery.js'); Requirements::javascript('pixlr/javascript/pixlr-image-field.js'); $fieldAttributes = array('id' => $this->id(), 'class' => 'pixlrTrigger', 'value' => Convert::raw2att($this->label), 'type' => 'button'); $targetUrl = strlen($this->targetUrl) ? $this->targetUrl : Director::absoluteURL('pixlr/saveimage'); $exitUrl = strlen($this->exitUrl) ? $this->exitUrl : Director::absoluteURL('pixlr/closepixlr'); // now add any additional parameters onto the end of the target string $sep = strpos($targetUrl, '?') ? '&' : '?'; foreach ($this->returnParams as $param => $v) { $targetUrl .= $sep . $param . '=' . $v; $sep = '&'; } $loc = ($m = Member::currentUser()) ? i18n::get_lang_from_locale($m->Locale) : 'en'; $title = isset($this->returnParams['title']) ? $this->returnParams['title'] : 'New Image'; $opts = array('referrer' => Convert::raw2js('SilverStripe CMS'), 'loc' => $loc, 'title' => $this->value && is_object($this->value) ? Convert::raw2js($this->value->Name) : $title, 'locktarget' => 'true', 'exit' => $exitUrl, 'target' => $targetUrl, 'method' => 'get', 'copy' => false); // where should we open the editor? as in, which window is it rooted in? $openin = 'window'; if ($this->value) { if ($this->config()->use_credentials) { $opts['credentials'] = 'true'; $opts['image'] = Convert::raw2js(Director::absoluteBaseURL() . $this->value->Filename); } else { // need to post the image to their server first, so we'll stick the image ID into the // page, and let the jquery plugin handle uploading it to pixlr first if (is_object($this->value)) { $opts['id'] = $this->value->ID; } else { $opts['id'] = $this->value; } $opts['preload'] = Director::absoluteURL('pixlr/sendimage'); // In silverstripe, when editing an image it actually occurs in an iframe popup contained within // another iframe. Because we want the editor to appear mounted in the top level window, // we have to explicitly add it to the correct location // $openin = 'window.parent.parent'; } $opts['locktitle'] = 'true'; $opts['mode'] = 'popup'; } $opts['service'] = $this->editorMode; // $opts = Convert::raw2json($opts); $opts['openobjname'] = $openin; $fieldAttributes['data-pixlr-editor'] = json_encode($opts); // $script = <<<JSCRIPT //jQuery().ready(function () { //var opts = $opts; //opts.openin = $openin; //jQuery('#{$this->id()}').pixlrize(opts); //}); //JSCRIPT; // Requirements::customScript($script, 'pixlr-'.$this->id()); return $this->createTag('input', $fieldAttributes); }
/** * Map shop data to omnipay fields * * @param array $customData Usually user submitted data. * * @return array */ protected function getGatewayData($customData) { $shipping = $this->order->getShippingAddress(); $billing = $this->order->getBillingAddress(); $numPayments = Payment::get()->where(array('"OrderID" = ?' => $this->order->ID))->count(); $numPayments--; $transactionId = strtoupper(i18n::get_lang_from_locale(i18n::get_locale())) . $this->order->Reference . ($numPayments > 0 ? '-' . $numPayments : ''); if (Director::isDev()) { $transactionId .= Member::currentUser() ? '-' . Member::currentUserID() : ''; } return array_merge($customData, array('transactionId' => $transactionId, 'firstName' => $this->order->FirstName, 'lastName' => $this->order->Surname, 'email' => $this->order->Email, 'company' => $this->order->Company, 'billingAddress1' => $billing->Address, 'billingAddress2' => $billing->AddressLine2, 'billingCity' => $billing->City, 'billingPostcode' => $billing->PostalCode, 'billingState' => $billing->State, 'billingCountry' => $billing->Country, 'billingPhone' => $billing->Phone, 'shippingAddress1' => $shipping->Address, 'shippingAddress2' => $shipping->AddressLine2, 'shippingCity' => $shipping->City, 'shippingPostcode' => $shipping->PostalCode, 'shippingState' => $shipping->State, 'shippingCountry' => $shipping->Country, 'shippingPhone' => $shipping->Phone)); }
/** * This is the main translator function. Returns the string defined by $class and $entity according to the * currently set locale. * * @param string $entity Entity that identifies the string. It must be in the form "Namespace.Entity" where * Namespace will be usually the class name where this string is used and Entity identifies * the string inside the namespace. * @param string $string The original string itself. In a usual call this is a mandatory parameter, but if you are * reusing a string which has already been "declared" (using another call to this function, * with the same class and entity), you can omit it. * @param string $context (optional) If the string can be difficult to translate by any reason, you can help * translators with some more info using this param * @param string injectionArray (optional) array of key value pairs that are used to replace corresponding * expressions in {curly brackets} in the $string. The injection array can also be * used as the their argument to the _t() function * @return string The translated string, according to the currently set locale {@link i18n::set_locale()} */ public static function _t($entity, $string = "", $context = "", $injection = "") { if (is_numeric($context) && in_array($context, array(PR_LOW, PR_MEDIUM, PR_HIGH))) { Deprecation::notice('3.0', 'The $priority argument to _t() is deprecated, please use module inclusion priorities instead', Deprecation::SCOPE_GLOBAL); } //fetch the injection array out of the parameters (if it is present) $argList = func_get_args(); $argNum = func_num_args(); //_t($entity, $string = "", $context (optional), $injectionArray (optional)) $injectionArray = null; for ($i = 0; $i < $argNum; $i++) { if (is_array($argList[$i])) { //we have reached the injectionArray $injectionArray = $argList[$i]; //any array in the args will be the injection array } } // get current locale (either default or user preference) $locale = i18n::get_locale(); $lang = i18n::get_lang_from_locale($locale); // Only call getter if static isn't already defined (for performance reasons) $translatorsByPrio = self::$translators; if (!$translatorsByPrio) { $translatorsByPrio = self::get_translators(); } $returnValue = is_string($string) ? $string : ''; // Fall back to default string argument foreach ($translatorsByPrio as $priority => $translators) { foreach ($translators as $name => $translator) { $adapter = $translator->getAdapter(); // at this point, we need to ensure the language and locale are loaded // as include_by_locale() doesn't load a fallback. // TODO Remove reliance on global state, by refactoring into an i18nTranslatorManager // which is instanciated by core with a $clean instance variable. if (!$adapter->isAvailable($lang)) { i18n::include_by_locale($lang, isset($_GET['flush'])); } if (!$adapter->isAvailable($locale)) { i18n::include_by_locale($locale, isset($_GET['flush'])); } $translation = $adapter->translate($entity, $locale); // Return translation only if we found a match thats not the entity itself (Zend fallback) if ($translation && $translation != $entity) { $returnValue = $translation; break 2; } } } // inject the variables from injectionArray (if present) if ($injectionArray) { $regex = '/\\{[\\w\\d]*\\}/i'; if (!preg_match($regex, $returnValue)) { // Legacy mode: If no injection placeholders are found, // replace sprintf placeholders in fixed order. // Fail silently in case the translation is outdated $replaced = @vsprintf($returnValue, array_values($injectionArray)); if ($replaced) { $returnValue = $replaced; } } else { if (!ArrayLib::is_associative($injectionArray)) { // Legacy mode: If injection placeholders are found, // but parameters are passed without names, replace them in fixed order. $returnValue = preg_replace_callback($regex, function ($matches) use(&$injectionArray) { return $injectionArray ? array_shift($injectionArray) : ''; }, $returnValue); } else { // Standard placeholder replacement with named injections and variable order. foreach ($injectionArray as $variable => $injection) { $placeholder = '{' . $variable . '}'; $returnValue = str_replace($placeholder, $injection, $returnValue, $count); if (!$count) { SS_Log::log(sprintf("Couldn't find placeholder '%s' in translation string '%s' (id: '%s')", $placeholder, $returnValue, $entity), SS_Log::NOTICE); } } } } } return $returnValue; }
/** * Get a tabset with a tab for every language containing the translatable fields. * Example usage: * <code> * public function getCMSFields(){ * $fields = FieldList::create(); * $fields->add($this->getTranslatableTabSet()); * return $fields; * } * </code> * @param string $title the title of the tabset to return. Defaults to "Root" * @param bool $showNativeFields whether or not to show native tab labels (eg. Español instead of Spanish) * @return TabSet */ public function getTranslatableTabSet($title = 'Root', $showNativeFields = true) { /** @var TabSet $set */ $set = TabSet::create($title); // get target locales $locales = self::get_target_locales(); // get translated fields $fieldNames = self::get_localized_class_fields($this->owner->class); if (empty($fieldNames)) { user_error('No localized fields for the given object found', E_USER_WARNING); } $ambiguity = array(); foreach ($locales as $locale) { $langCode = i18n::get_lang_from_locale($locale); foreach ($locales as $l) { if ($l != $locale && i18n::get_lang_from_locale($l) == $langCode) { $parts = explode('_', $l); $localePart = end($parts); $ambiguity[$l] = $localePart; } } } foreach ($locales as $locale) { if (!$this->canTranslate(null, $locale)) { continue; } $lang = i18n::get_language_name(i18n::get_lang_from_locale($locale), $showNativeFields); if (!$lang) { // fallback if get_lang_name doesn't return anything for the language code $lang = i18n::get_language_name($locale, $showNativeFields); } $langName = ucfirst(html_entity_decode($lang, ENT_NOQUOTES, 'UTF-8')); if (isset($ambiguity[$locale])) { $langName .= ' (' . $ambiguity[$locale] . ')'; } /** @var Tab $tab */ $tab = Tab::create($locale, $langName); foreach ($fieldNames as $fieldName) { $tab->push($this->getLocalizedFormField($fieldName, $locale)); } $set->push($tab); } return $set; }
/** * @deprecated 2.4 Use default_locale() */ static function default_lang() { return i18n::get_lang_from_locale(self::default_locale()); }
/** * Returns the script direction in format compatible with the HTML "dir" attribute. * * @see http://www.w3.org/International/tutorials/bidi-xhtml/ * @param String $locale Optional locale incl. region (underscored) * @return String "rtl" or "ltr" */ public static function get_script_direction($locale = null) { require_once 'Zend/Locale/Data.php'; if (!$locale) { $locale = i18n::get_locale(); } try { $dir = Zend_Locale_Data::getList($locale, 'layout'); } catch (Zend_Locale_Exception $e) { $dir = Zend_Locale_Data::getList(i18n::get_lang_from_locale($locale), 'layout'); } return $dir && $dir['characters'] == 'right-to-left' ? 'rtl' : 'ltr'; }
public function init() { parent::init(); // load the jquery $lang = i18n::get_lang_from_locale(i18n::get_locale()); Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js'); Requirements::javascript(USERFORMS_DIR . '/thirdparty/jquery-validate/jquery.validate.min.js'); Requirements::add_i18n_javascript(USERFORMS_DIR . '/javascript/lang'); Requirements::javascript(USERFORMS_DIR . '/javascript/UserForm_frontend.js'); Requirements::javascript(USERFORMS_DIR . "/thirdparty/jquery-validate/localization/messages_{$lang}.min.js"); Requirements::javascript(USERFORMS_DIR . "/thirdparty/jquery-validate/localization/methods_{$lang}.min.js"); if ($this->HideFieldLabels) { Requirements::javascript(USERFORMS_DIR . '/thirdparty/Placeholders.js/Placeholders.min.js'); } }