function testFieldInDenmark() { $locale = i18n::get_locale(); i18n::set_locale('da_DK'); // Should start at 0 $field = new PercentageField('Test', 'TestField'); $this->assertEquals(0, $field->dataValue()); $this->assertEquals('0%', $field->Value()); // Entering 50 should yield 0.5 $field->setValue('50'); $this->assertEquals(0.5, $field->dataValue()); $this->assertEquals('50%', $field->Value()); // Entering 50% should yield 0.5 $field->setValue('50%'); $this->assertEquals(0.5, $field->dataValue()); $this->assertEquals('50%', $field->Value()); // Entering -50% should yield -0.5 $field->setValue('-50%'); $this->assertEquals(-0.5, $field->dataValue()); $this->assertEquals('-50%', $field->Value()); // Entering 0.5 should yield 0.5 $field->setValue('0,5'); $this->assertEquals(0.5, $field->dataValue()); $this->assertEquals('50%', $field->Value()); // Entering 0.5% should yield 0.005 $field->setValue('0,5%'); $this->assertEquals(0.005, $field->dataValue()); $this->assertEquals('0,5%', $field->Value()); i18n::set_locale($locale); }
public function testLinks() { // Run link checker $task = CheckExternalLinksTask::create(); $task->setSilent(true); // Be quiet during the test! $task->runLinksCheck(); // Get all links checked $status = BrokenExternalPageTrackStatus::get_latest(); $this->assertEquals('Completed', $status->Status); $this->assertEquals(5, $status->TotalPages); $this->assertEquals(5, $status->CompletedPages); // Check all pages have had the correct HTML adjusted for ($i = 1; $i <= 5; $i++) { $page = $this->objFromFixture('ExternalLinksTest_Page', 'page' . $i); $this->assertNotEmpty($page->Content); $this->assertEquals($page->ExpectedContent, $page->Content, "Assert that the content of page{$i} has been updated"); } // Check that the correct report of broken links is generated $links = $status->BrokenLinks()->sort('Link'); $this->assertEquals(4, $links->count()); $this->assertEquals(array('http://www.broken.com', 'http://www.broken.com/url/thing', 'http://www.broken.com/url/thing', 'http://www.nodomain.com'), array_values($links->map('ID', 'Link')->toArray())); // Check response codes are correct $expected = array('http://www.broken.com' => 403, 'http://www.broken.com/url/thing' => 404, 'http://www.nodomain.com' => 0); $actual = $links->map('Link', 'HTTPCode')->toArray(); $this->assertEquals($expected, $actual); // Check response descriptions are correct i18n::set_locale('en_NZ'); $expected = array('http://www.broken.com' => '403 (Forbidden)', 'http://www.broken.com/url/thing' => '404 (Not Found)', 'http://www.nodomain.com' => '0 (Server Not Available)'); $actual = $links->map('Link', 'HTTPCodeDescription')->toArray(); $this->assertEquals($expected, $actual); }
public function tearDown() { parent::tearDown(); i18n::set_locale($this->originalLocale); Config::inst()->remove('TimeField', 'default_config'); Config::inst()->update('TimeField', 'default_config', $this->origTimeConfig); }
public function tearDown() { parent::tearDown(); i18n::set_locale($this->originalLocale); DateField::$default_config['dateformat'] = $this->origDateFormat; TimeField::$default_config['timeformat'] = $this->origTimeFormat; }
function tearDown() { parent::tearDown(); // Static publishing will just confuse things StaticPublisher::$disable_realtime = false; i18n::set_locale($this->origLocale); }
/** * 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; }
/** * @return void */ public function onBeforeInit() { // Check if we are runing a dev build, if so check if DB needs // upgrading $controller = $this->owner->request->param("Controller"); $action = $this->owner->request->param("Action"); global $project; // Only check if the DB needs upgrading on a dev build if ($controller == "DevelopmentAdmin" && $action == "build") { // Now check if the files we need are installed // Check if we have the files we need, if not, create them if (!class_exists("Category")) { copy(BASE_PATH . "/catalogue/scaffold/Category", BASE_PATH . "/{$project}/code/model/Category.php"); } if (!class_exists("Category_Controller")) { copy(BASE_PATH . "/catalogue/scaffold/Category_Controller", BASE_PATH . "/{$project}/code/control/Category_Controller.php"); } if (!class_exists("Product")) { copy(BASE_PATH . "/catalogue/scaffold/Product", BASE_PATH . "/{$project}/code/model/Product.php"); } if (!class_exists("Product_Controller")) { copy(BASE_PATH . "/catalogue/scaffold/Product_Controller", BASE_PATH . "/{$project}/code/control/Product_Controller.php"); } } if ($controller != "DevelopmentAdmin") { if (class_exists('Subsite') && Subsite::currentSubsite()) { // Set the location i18n::set_locale(Subsite::currentSubsite()->Language); } } }
/** * Handles enabling translations for controllers that are not pages */ public function onBeforeInit() { //Bail for the root url controller and model as controller classes as they handle this internally, also disable for development admin and cms if ($this->owner instanceof MultilingualRootURLController || $this->owner instanceof MultilingualModelAsController || $this->owner instanceof LeftAndMain || $this->owner instanceof DevelopmentAdmin || $this->owner instanceof TestRunner) { return; } //Bail for pages since this would have been handled by MultilingualModelAsController, we're assuming that data has not been set to a page by other code if (method_exists($this->owner, 'data') && $this->owner->data() instanceof SiteTree) { return; } //Check if the locale is in the url $request = $this->owner->getRequest(); if ($request && $request->param('Language')) { $language = $request->param('Language'); if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { $locale = $language; } else { if (strpos($request->param('Language'), '_') !== false) { //Invalid format so redirect to the default $url = $request->getURL(true); $default = Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL') ? Translatable::default_locale() : Translatable::default_lang(); $this->owner->redirect(preg_replace('/^' . preg_quote($language, '/') . '\\//', $default . '/', $url), 301); return; } else { $locale = i18n::get_locale_from_lang($language); } } if (in_array($locale, Translatable::get_allowed_locales())) { //Set the language cookie Cookie::set('language', $language); //Set the various locales Translatable::set_current_locale($locale); i18n::set_locale($locale); } else { //Unknown language so redirect to the default $url = $request->getURL(true); $default = Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL') ? Translatable::default_locale() : Translatable::default_lang(); $this->owner->redirect(preg_replace('/^' . preg_quote($language, '/') . '\\//', $default . '/', $url), 301); } return; } //Detect the locale if ($locale = MultilingualRootURLController::detect_browser_locale()) { if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { $language = $locale; } else { $language = i18n::get_lang_from_locale($locale); } //Set the language cookie Cookie::set('language', $language); //Set the various locales Translatable::set_current_locale($locale); i18n::set_locale($locale); } }
public function testUpdateFieldLabels() { // Add custom translation for testing i18n::get_translator('core')->getAdapter()->addTranslation(array('SiteTree.METATITLE' => 'TRANS-EN Meta Title'), 'en'); $siteTree = new SiteTree(); $labels = $siteTree->fieldLabels(); $this->assertArrayHasKey('MetaTitle', $labels); $this->assertEquals('TRANS-EN Meta Title', $labels['MetaTitle']); // Set different locale, clear field label cache i18n::set_locale('de_DE'); DataObject::reset(); // Add custom translation for testing i18n::get_translator('core')->getAdapter()->addTranslation(array('SiteTree.METATITLE' => 'TRANS-DE Meta Title'), 'de_DE'); $labels = $siteTree->fieldLabels(); $this->assertEquals('TRANS-DE Meta Title', $labels['MetaTitle']); }
public function init() { parent::init(); i18n::set_locale(Session::get('language')); // You can include any CSS or JS required by your project here. // See: http://doc.silverstripe.org/framework/en/reference/requirements Requirements::css(BOWER_PATH . '/bootstrap/dist/css/bootstrap.min.css'); Requirements::css('http://fonts.googleapis.com/css?family=Raleway'); Requirements::css(BOWER_PATH . '/fancybox/source/jquery.fancybox.css'); Requirements::css(BOWER_PATH . '/font-awesome/css/font-awesome.min.css'); Requirements::css(CSS_DIR . '/customise.css'); Requirements::javascript(BOWER_PATH . '/jquery/dist/jquery.min.js'); Requirements::javascript(BOWER_PATH . '/bootstrap/dist/js/bootstrap.min.js'); Requirements::javascript(BOWER_PATH . '/fancybox/source/jquery.fancybox.pack.js'); Requirements::javascript("https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"); }
/** * @return void */ public function onBeforeInit() { if (class_exists('Subsite') && Subsite::currentSubsite()) { // Set the location i18n::set_locale(Subsite::currentSubsite()->Language); // Check if url is primary domain, if not, re-direct if ($_SERVER['HTTP_HOST'] != Subsite::currentSubsite()->getPrimaryDomain()) { $this->owner->redirect(Subsite::currentSubsite()->absoluteBaseURL()); } } // Setup currency globally based on what is set in admin $config = SiteConfig::current_site_config(); if ($config->Currency()) { Currency::setCurrencySymbol($config->Currency()->HTMLNotation); } }
protected static function init_kern_environment() { clock::stop(); config::load(); self::$log_execute_time = config::get_kern('log_execute_time', true); if (self::$log_execute_time) { self::$begin_microtime = clock::get_micro_stamp(); } clock::set_timezone(config::get_kern('time_zone', 'Asia/Shanghai')); i18n::set_locale(config::get_kern('locale', 'en_us')); self::$is_debug = config::get_kern('is_debug', false); ini_set('display_errors', config::get_kern('display_errors', self::$is_debug)); set_exception_handler([__CLASS__, 'exception_handler']); $error_reporting = config::get_kern('error_reporting', self::$is_debug ? E_ALL | E_STRICT : E_ALL & ~E_NOTICE); set_error_handler([__CLASS__, 'error_handler'], $error_reporting); loader::init(); }
public function testTranslate() { i18n::set_locale('en_US'); $this->assertEquals('Legacy translation', i18n::_t('i18nOtherModule.LEGACY'), 'Finds original strings in PHP module files'); $this->assertEquals('Legacy translation', i18n::_t('i18nOtherModule.LEGACYTHEME'), 'Finds original strings in theme files'); i18n::set_locale('de_DE'); $this->assertEquals('Legacy translation (de_DE)', i18n::_t('i18nOtherModule.LEGACY'), 'Finds translations in PHP module files'); $this->assertEquals('Legacy translation (de_DE)', i18n::_t('i18nOtherModule.LEGACYTHEME'), 'Finds original strings in theme files'); // TODO Implement likely subtags solution // i18n::set_locale('de'); // $this->assertEquals( // 'Legacy translation (de_DE)', // // defined in i18nothermodule/lang/de_DE.php // i18n::_t('i18nOtherModule.LEGACY'), // 'Finds translations in PHP module files if only language locale is set' // ); }
public function init() { parent::init(); i18n::set_locale('de_DE'); setlocale(LC_ALL, 'de_DE@euro', 'de_DE.UTF-8', 'de_DE', 'de', 'ge'); i18n::set_date_format('dd.MM.YYYY'); i18n::set_time_format('HH:mm'); Requirements::set_write_js_to_body(false); Requirements::javascript("framework/thirdparty/jquery/jquery.js"); Requirements::javascript("calendar/3rdparty/jquery-ui-1.9.2.custom.js"); Requirements::javascript("calendar/3rdparty/fullcalendar/fullcalendar.js"); Requirements::javascript("calendar/3rdparty/jQuery-Loading/toggleLoading.jquery.js"); Requirements::javascript("calendar/javascript/widget.js"); Requirements::css("framework/thirdparty/jquery-ui-themes/smoothness/jquery-ui.css"); Requirements::css("calendar/3rdparty/fullcalendar/fullcalendar.css"); Requirements::css("calendar/css/calendar.css"); }
/** * Write a Money object to the database, then re-read it to ensure it * is re-read properly. */ function testGettingWrittenDataObject() { $local = i18n::get_locale(); i18n::set_locale('en_US'); //make sure that the $ amount is not prefixed by US$, as it would be in non-US locale $obj = new MoneyTest_DataObject(); $m = new Money(); $m->setAmount(987.65); $m->setCurrency('USD'); $obj->MyMoney = $m; $this->assertEquals("\$987.65", $obj->MyMoney->Nice(), "Money field not added to data object properly when read prior to first writing the record."); $objID = $obj->write(); $moneyTest = DataObject::get_by_id('MoneyTest_DataObject', $objID); $this->assertTrue($moneyTest instanceof MoneyTest_DataObject); $this->assertEquals('USD', $moneyTest->MyMoneyCurrency); $this->assertEquals(987.65, $moneyTest->MyMoneyAmount); $this->assertEquals("\$987.65", $moneyTest->MyMoney->Nice(), "Money field not added to data object properly when read."); i18n::set_locale($local); }
public function testValidator() { i18n::set_locale('en_US'); $field = new NumericField('Number'); $field->setValue('12.00'); $validator = new RequiredFields('Number'); $this->assertTrue($field->validate($validator)); $field->setValue('12,00'); $this->assertFalse($field->validate($validator)); $field->setValue('0'); $this->assertTrue($field->validate($validator)); $field->setValue(false); $this->assertFalse($field->validate($validator)); i18n::set_locale('de_DE'); $field->setValue('12,00'); $validator = new RequiredFields(); $this->assertTrue($field->validate($validator)); $field->setValue('12.00'); $this->assertFalse($field->validate($validator)); }
public function testValidator() { i18n::set_locale('en_US'); $field = new NumericField('Number'); $field->setValue('12.00'); $validator = new RequiredFields('Number'); $this->assertTrue($field->validate($validator)); $field->setValue('12,00'); $this->assertFalse($field->validate($validator)); $field->setValue('0'); $this->assertTrue($field->validate($validator)); $field->setValue(false); $this->assertFalse($field->validate($validator)); i18n::set_locale('de_DE'); $field->setValue('12,00'); $validator = new RequiredFields(); $this->assertTrue($field->validate($validator)); $field->setValue('12.00'); $this->assertFalse($field->validate($validator)); $field->setValue(0); $this->assertRegExp("#<span[^>]+>\\s*0\\s*<\\/span>#", "" . $field->performReadonlyTransformation()->Field() . ""); }
/** * Return the date using a particular formatting string. * * @param string $format Format code string. e.g. "d M Y" (see http://php.net/date) * @param mixed $value Value to format * @return string The date in the requested format */ public static function Format($format, $value) { if ($value) { // Use current locale if different from configured i18n locale $i18nLocale = $currentLocale = i18n::get_locale(); if (class_exists("Translatable")) { $currentLocale = Translatable::get_current_locale(); } if (self::$locale) { $currentLocale = self::$locale; } if ($currentLocale != $i18nLocale) { i18n::set_locale($currentLocale); } // Set date $date = new DateTime($value); // Flag escaped chars (or there will be problems with formats like "F\D") $escapeId = '-' . time() . '-'; $format = str_replace('\\', $escapeId . '\\', $format); // Get formatted date $dateStr = $date->Format($format); // Translate all word-strings $dateStr = preg_replace_callback("/([a-z]*)([^a-z])/isU", function ($m) { if (empty($m[1])) { // Nothing to translate return $m[0]; } return _t('LocalDate.' . $m[1], $m[1]) . $m[2]; }, $dateStr . ' '); // Remove escape flags $dateStr = str_replace($escapeId, '', $dateStr); // Reset i18n locale if ($currentLocale != $i18nLocale) { i18n::set_locale($i18nLocale); } // Return translated date string return substr($dateStr, 0, strlen($dateStr) - 1); } }
/** * For field types that can contain a variety of data, e.g. Varchar, this method * informs the Faker\Generator object what kind of data to generate based on the name of the field. * For instance, a field named "FirstName" should generate a person's name. A field named "Country" should * generate a country name. * * Field names can be matched at the beginning or end of the string, for instance: * "DoctorFirstName" and "Address2" will generate a first name and an address, respectively. * * This logic can be refined in the lang file so that database fields can be named in the local language, * e.g. "Prenom" or "Pays" and still be mapped to the correct data type. * * @param string $name The name of the data type to examine * @return boolean */ public function hook($name) { $list = false; $current_locale = i18n::get_locale(); $default_lang = Config::inst()->forClass("MockDBField")->default_lang; $default_locale = i18n::get_locale_from_lang($default_lang); i18n::set_locale($default_locale); $core_list = _t('MockDataObject.' . $name); i18n::set_locale($current_locale); $user_list = _t('MockDataObject.' . $name); $list = $user_list ?: $core_list; if ($list) { $candidates = explode(",", $list); $fieldName = $this->owner->getName(); foreach ($candidates as $c) { $c = trim($c); if (preg_match('/^' . $c . '[A-Z0-9]*/', $fieldName) || preg_match('/' . $c . '$/', $fieldName)) { return true; } } } return false; }
/** * We register the common forms for SilvercartPages here. * * @return void * * @author Sebastian Diel <*****@*****.**>, * Sascha Koehler <*****@*****.**>, * Patrick Schneider <*****@*****.**> * @since 08.07.2014 */ public function onBeforeInit() { SilvercartTools::initSession(); i18n::set_default_locale(Translatable::get_current_locale()); i18n::set_locale(Translatable::get_current_locale()); $controllerParams = Controller::curr()->getURLParams(); $anonymousCustomer = SilvercartCustomer::currentAnonymousCustomer(); if ($anonymousCustomer) { Session::set('MemberLoginForm.force_message', true); if ($controllerParams['Action'] == 'changepassword') { $anonymousCustomer->logOut(); } } else { Session::set('MemberLoginForm.force_message', false); // used to redirect the logged in user to my-account page $backURL = SilvercartTools::PageByIdentifierCodeLink(self::$newPasswordBackURLIdentifierCode); $this->owner->extend('updateNewPasswordBackURL', $backURL); Session::set('BackURL', $backURL); Session::save(); } $this->owner->registerCustomHtmlForm('SilvercartQuickSearchForm', new SilvercartQuickSearchForm($this->owner)); $this->owner->registerCustomHtmlForm('SilvercartQuickLoginForm', new SilvercartQuickLoginForm($this->owner)); SilvercartPlugin::call($this->owner, 'init', array($this->owner)); }
/** * Set/Install the given locale. * This does set the i18n locale as well as the Translatable or Fluent locale (if any of these modules is installed) * @param string $locale the locale to install * @throws Zend_Locale_Exception @see Zend_Locale_Format::getDateFormat and @see Zend_Locale_Format::getTimeFormat */ public static function install_locale($locale) { // If the locale isn't given, silently fail (there might be carts that still have locale set to null) if (empty($locale)) { return; } if (class_exists('Translatable')) { Translatable::set_current_locale($locale); } else { if (class_exists('Fluent')) { Fluent::set_persist_locale($locale); } } // Do something like Fluent does to install the locale i18n::set_locale($locale); // LC_NUMERIC causes SQL errors for some locales (comma as decimal indicator) so skip foreach (array(LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_TIME) as $category) { setlocale($category, "{$locale}.UTF-8", $locale); } // Get date/time formats from Zend require_once 'Zend/Date.php'; i18n::config()->date_format = Zend_Locale_Format::getDateFormat($locale); i18n::config()->time_format = Zend_Locale_Format::getTimeFormat($locale); }
/** * ContentController * lets us extend init() through this method on SiteTree. * we will override page init to change domains if the page locale is * different than the detected locale of the domain. * * 3 Things to be aware of (while developing.. these are all accounted for here): * ¥ Intended Locale of the Domain (.fr, .de, .com?) * ¥ Page's Locale in the Database * ¥ i18n locale that is in the header. * */ public function contentcontrollerInit() { if ($this->owner->hasExtension('Translatable')) { //find the correct locale $curLoc = TranslatableDomains::getLocaleFromHost(); // compare page locale vs domain's locale // low occurance of these not matching, but important if (Translatable::get_current_locale() != $curLoc) { // check to see if the page has a translation for the url, if so, translate. // helpful for homepages where / == /home but we want the german translation.. if ($this->owner->hasTranslation($curLoc)) { //if page exists and translation exists, redirect & show translation $correctPage = $this->owner->getTranslation($curLoc); Director::redirect($correctPage->Link()); } else { //otherwise, find requested page by url, determine locale, and put us in the right domain. $newUrl = TranslatableDomains::convertLocaleToTLD($withEndSlash = false) . $this->owner->Link(); Director::redirect($newUrl); } } else { i18n::set_locale($this->owner->Locale); } } }
<?php global $project; $project = 'mysite'; global $databaseConfig; $databaseConfig = array('type' => 'MySQLDatabase', 'server' => 'localhost', 'username' => 'root', 'password' => '123456', 'database' => 'Internetrix', 'path' => ''); // Set the site locale i18n::set_locale('en_US');
"server" => 'localhost', "username" => 'root', "password" => 'root', "database" => 'FuelDemo2016', "path" => '', ); */ // ******* LIVE Database Settings ****** global $databaseConfig; $databaseConfig = array("type" => 'MySQLDatabase', "server" => 'localhost', "username" => 'fuel2', "password" => 'coyote5.!6', "database" => 'fuel2', "path" => ''); // Initial acmin account set-up - can be removed Security::setDefaultAdmin('*****@*****.**', 'apples'); // Sets the CMS logo link to go to the site base URL LeftAndMain::set_application_link(Director::baseURL()); // Set the site locale i18n::set_locale('en_GB'); date_default_timezone_set('Europe/London'); //Enable Site Search ** //FulltextSearchable::enable(); Object::add_extension('SiteConfig', 'CustomSiteConfig'); //Force redirect to www. Director::forceWWW(); //Show errors while in development only (to be removed) error_reporting(E_ALL); // Customise TinyMCE options HtmlEditorConfig::get('cms')->setOption('theme_advanced_blockformats', 'p,h1,h2,h3,h4'); HtmlEditorConfig::get('cms')->setOption('theme_advanced_disable', 'styleselect'); // TinyMCE cleanup on paste HtmlEditorConfig::get('cms')->setOption('convert_fonts_to_spans', 'false'); HtmlEditorConfig::get('cms')->setOption('paste_auto_cleanup_on_paste', 'true'); HtmlEditorConfig::get('cms')->setOption('paste_remove_styles', 'true');
public function testReadonly() { i18n::set_locale('en_US'); $field = new NumericField('Number'); $this->assertRegExp("#<span[^>]+>\\s*0\\s*<\\/span>#", "" . $field->performReadonlyTransformation()->Field() . ""); }
/** * @uses LeftAndMainExtension->init() * @uses LeftAndMainExtension->accessedCMS() * @uses CMSMenu */ function init() { parent::init(); SSViewer::setOption('rewriteHashlinks', false); // set language $member = Member::currentUser(); if (!empty($member->Locale)) { i18n::set_locale($member->Locale); } if (!empty($member->DateFormat)) { i18n::set_date_format($member->DateFormat); } if (!empty($member->TimeFormat)) { i18n::set_time_format($member->TimeFormat); } // can't be done in cms/_config.php as locale is not set yet CMSMenu::add_link('Help', _t('LeftAndMain.HELP', 'Help', 'Menu title'), self::$help_link); // Allow customisation of the access check by a extension // Also all the canView() check to execute Controller::redirect() if (!$this->canView() && !$this->response->isFinished()) { // When access /admin/, we should try a redirect to another part of the admin rather than be locked out $menu = $this->MainMenu(); foreach ($menu as $candidate) { if ($candidate->Link && $candidate->Link != $this->Link() && $candidate->MenuItem->controller && singleton($candidate->MenuItem->controller)->canView()) { return $this->redirect($candidate->Link); } } if (Member::currentUser()) { Session::set("BackURL", null); } // if no alternate menu items have matched, return a permission error $messageSet = array('default' => _t('LeftAndMain.PERMDEFAULT', "Please choose an authentication method and enter your credentials to access the CMS."), 'alreadyLoggedIn' => _t('LeftAndMain.PERMALREADY', "I'm sorry, but you can't access that part of the CMS. If you want to log in as someone else, do so below"), 'logInAgain' => _t('LeftAndMain.PERMAGAIN', "You have been logged out of the CMS. If you would like to log in again, enter a username and password below.")); return Security::permissionFailure($this, $messageSet); } // Don't continue if there's already been a redirection request. if ($this->redirectedTo()) { return; } // Audit logging hook if (empty($_REQUEST['executeForm']) && !$this->request->isAjax()) { $this->extend('accessedCMS'); } // Set the members html editor config HtmlEditorConfig::set_active(Member::currentUser()->getHtmlEditorConfigForCMS()); // Set default values in the config if missing. These things can't be defined in the config // file because insufficient information exists when that is being processed $htmlEditorConfig = HtmlEditorConfig::get_active(); $htmlEditorConfig->setOption('language', i18n::get_tinymce_lang()); if (!$htmlEditorConfig->getOption('content_css')) { $cssFiles = array(); $cssFiles[] = FRAMEWORK_ADMIN_DIR . '/css/editor.css'; // Use theme from the site config if (class_exists('SiteConfig') && ($config = SiteConfig::current_site_config()) && $config->Theme) { $theme = $config->Theme; } elseif (SSViewer::current_theme()) { $theme = SSViewer::current_theme(); } else { $theme = false; } if ($theme) { $cssFiles[] = THEMES_DIR . "/{$theme}/css/editor.css"; } else { if (project()) { $cssFiles[] = project() . '/css/editor.css'; } } // Remove files that don't exist foreach ($cssFiles as $k => $cssFile) { if (!file_exists(BASE_PATH . '/' . $cssFile)) { unset($cssFiles[$k]); } } $htmlEditorConfig->setOption('content_css', implode(',', $cssFiles)); } // Using uncompressed files as they'll be processed by JSMin in the Requirements class. // Not as effective as other compressors or pre-compressed+finetuned files, // but overall the unified minification into a single file brings more performance benefits // than a couple of saved bytes (after gzip) in individual files. // We also re-compress already compressed files through JSMin as this causes weird runtime bugs. Requirements::combine_files('lib.js', array(THIRDPARTY_DIR . '/jquery/jquery.js', FRAMEWORK_DIR . '/javascript/jquery-ondemand/jquery.ondemand.js', FRAMEWORK_ADMIN_DIR . '/javascript/lib.js', THIRDPARTY_DIR . '/jquery-ui/jquery-ui.js', THIRDPARTY_DIR . '/json-js/json2.js', THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js', THIRDPARTY_DIR . '/jquery-cookie/jquery.cookie.js', THIRDPARTY_DIR . '/jquery-query/jquery.query.js', THIRDPARTY_DIR . '/jquery-form/jquery.form.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/jquery-notice/jquery.notice.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/jsizes/lib/jquery.sizes.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/jlayout/lib/jlayout.border.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/jlayout/lib/jquery.jlayout.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/history-js/scripts/uncompressed/history.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/history-js/scripts/uncompressed/history.adapter.jquery.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/history-js/scripts/uncompressed/history.html4.js', THIRDPARTY_DIR . '/jstree/jquery.jstree.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/chosen/chosen/chosen.jquery.js', FRAMEWORK_ADMIN_DIR . '/thirdparty/jquery-hoverIntent/jquery.hoverIntent.js', FRAMEWORK_ADMIN_DIR . '/javascript/jquery-changetracker/lib/jquery.changetracker.js', FRAMEWORK_DIR . '/javascript/TreeDropdownField.js', FRAMEWORK_DIR . '/javascript/DateField.js', FRAMEWORK_DIR . '/javascript/HtmlEditorField.js', FRAMEWORK_DIR . '/javascript/TabSet.js', FRAMEWORK_DIR . '/javascript/i18n.js', FRAMEWORK_ADMIN_DIR . '/javascript/ssui.core.js', FRAMEWORK_DIR . '/javascript/GridField.js')); if (Director::isDev()) { Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/javascript/leaktools.js'); } HTMLEditorField::include_js(); Requirements::combine_files('leftandmain.js', array_unique(array_merge(array(FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.Panel.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.Tree.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.Ping.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.Content.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.EditForm.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.Menu.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.AddForm.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.Preview.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.BatchActions.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.FieldHelp.js', FRAMEWORK_ADMIN_DIR . '/javascript/LeftAndMain.TreeDropdownField.js'), Requirements::add_i18n_javascript(FRAMEWORK_DIR . '/javascript/lang', true, true), Requirements::add_i18n_javascript(FRAMEWORK_ADMIN_DIR . '/javascript/lang', true, true)))); // TODO Confuses jQuery.ondemand through document.write() if (Director::isDev()) { Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/src/jquery.entwine.inspector.js'); } Requirements::css(FRAMEWORK_ADMIN_DIR . '/thirdparty/jquery-notice/jquery.notice.css'); Requirements::css(THIRDPARTY_DIR . '/jquery-ui-themes/smoothness/jquery-ui.css'); Requirements::css(FRAMEWORK_ADMIN_DIR . '/thirdparty/chosen/chosen/chosen.css'); Requirements::css(THIRDPARTY_DIR . '/jstree/themes/apple/style.css'); Requirements::css(FRAMEWORK_DIR . '/css/TreeDropdownField.css'); Requirements::css(FRAMEWORK_ADMIN_DIR . '/css/screen.css'); Requirements::css(FRAMEWORK_DIR . '/css/GridField.css'); // Browser-specific requirements $ie = isset($_SERVER['HTTP_USER_AGENT']) ? strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') : false; if ($ie) { $version = substr($_SERVER['HTTP_USER_AGENT'], $ie + 5, 3); if ($version == 7) { Requirements::css(FRAMEWORK_ADMIN_DIR . '/css/ie7.css'); } else { if ($version == 8) { Requirements::css(FRAMEWORK_ADMIN_DIR . '/css/ie8.css'); } } } // Custom requirements foreach (self::$extra_requirements['javascript'] as $file) { Requirements::javascript($file[0]); } foreach (self::$extra_requirements['css'] as $file) { Requirements::css($file[0], $file[1]); } foreach (self::$extra_requirements['themedcss'] as $file) { Requirements::themedCSS($file[0], $file[1]); } $dummy = null; $this->extend('init', $dummy); // The user's theme shouldn't affect the CMS, if, for example, they have replaced // TableListField.ss or Form.ss. SSViewer::set_theme(null); }
function setUp() { // Mark test as being run $this->originalIsRunningTest = self::$is_running_test; self::$is_running_test = true; // i18n needs to be set to the defaults or tests fail i18n::set_locale(i18n::default_locale()); i18n::set_date_format(null); i18n::set_time_format(null); // Remove password validation $this->originalMemberPasswordValidator = Member::password_validator(); $this->originalRequirements = Requirements::backend(); Member::set_password_validator(null); Cookie::set_report_errors(false); RootURLController::reset(); Translatable::reset(); Versioned::reset(); DataObject::reset(); SiteTree::reset(); Hierarchy::reset(); if (Controller::has_curr()) { Controller::curr()->setSession(new Session(array())); } $this->originalTheme = SSViewer::current_theme(); // Save nested_urls state, so we can restore it later $this->originalNestedURLsState = SiteTree::nested_urls(); $className = get_class($this); $fixtureFile = eval("return {$className}::\$fixture_file;"); $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_'; // Set up fixture if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) { if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) { //echo "Re-creating temp database... "; self::create_temp_db(); //echo "done.\n"; } singleton('DataObject')->flushCache(); self::empty_temp_db(); foreach ($this->requireDefaultRecordsFrom as $className) { $instance = singleton($className); if (method_exists($instance, 'requireDefaultRecords')) { $instance->requireDefaultRecords(); } if (method_exists($instance, 'augmentDefaultRecords')) { $instance->augmentDefaultRecords(); } } if ($fixtureFile) { $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile); $i = 0; foreach ($fixtureFiles as $fixtureFilePath) { $fixture = new YamlFixture($fixtureFilePath); $fixture->saveIntoDatabase(); $this->fixtures[] = $fixture; // backwards compatibility: Load first fixture into $this->fixture if ($i == 0) { $this->fixture = $fixture; } $i++; } } $this->logInWithPermission("ADMIN"); } // Set up email $this->originalMailer = Email::mailer(); $this->mailer = new TestMailer(); Email::set_mailer($this->mailer); Email::send_all_emails_to(null); // Preserve memory settings $this->originalMemoryLimit = ini_get('memory_limit'); }
/** * @uses LeftAndMainDecorator->init() * @uses LeftAndMainDecorator->accessedCMS() * @uses CMSMenu */ function init() { parent::init(); SSViewer::setOption('rewriteHashlinks', false); // set language $member = Member::currentUser(); if (!empty($member->Locale)) { i18n::set_locale($member->Locale); } if (!empty($member->DateFormat)) { i18n::set_date_format($member->DateFormat); } if (!empty($member->TimeFormat)) { i18n::set_time_format($member->TimeFormat); } // can't be done in cms/_config.php as locale is not set yet CMSMenu::add_link('Help', _t('LeftAndMain.HELP', 'Help', PR_HIGH, 'Menu title'), self::$help_link); // set reading lang if (Object::has_extension('SiteTree', 'Translatable') && !$this->isAjax()) { Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree'))); } // Allow customisation of the access check by a decorator // Also all the canView() check to execute Director::redirect() if (!$this->canView() && !$this->response->isFinished()) { // When access /admin/, we should try a redirect to another part of the admin rather than be locked out $menu = $this->MainMenu(); foreach ($menu as $candidate) { if ($candidate->Link && $candidate->Link != $this->Link() && $candidate->MenuItem->controller && singleton($candidate->MenuItem->controller)->canView()) { return Director::redirect($candidate->Link); } } if (Member::currentUser()) { Session::set("BackURL", null); } // if no alternate menu items have matched, return a permission error $messageSet = array('default' => _t('LeftAndMain.PERMDEFAULT', "Please choose an authentication method and enter your credentials to access the CMS."), 'alreadyLoggedIn' => _t('LeftAndMain.PERMALREADY', "I'm sorry, but you can't access that part of the CMS. If you want to log in as someone else, do so below"), 'logInAgain' => _t('LeftAndMain.PERMAGAIN', "You have been logged out of the CMS. If you would like to log in again, enter a username and password below.")); return Security::permissionFailure($this, $messageSet); } // Don't continue if there's already been a redirection request. if (Director::redirected_to()) { return; } // Audit logging hook if (empty($_REQUEST['executeForm']) && !$this->isAjax()) { $this->extend('accessedCMS'); } // Set the members html editor config HtmlEditorConfig::set_active(Member::currentUser()->getHtmlEditorConfigForCMS()); // Set default values in the config if missing. These things can't be defined in the config // file because insufficient information exists when that is being processed $htmlEditorConfig = HtmlEditorConfig::get_active(); $htmlEditorConfig->setOption('language', i18n::get_tinymce_lang()); if (!$htmlEditorConfig->getOption('content_css')) { $cssFiles = 'cms/css/editor.css'; // Use theme from the site config if (($config = SiteConfig::current_site_config()) && $config->Theme) { $theme = $config->Theme; } elseif (SSViewer::current_theme()) { $theme = SSViewer::current_theme(); } else { $theme = false; } if ($theme) { $cssFiles .= ',' . THEMES_DIR . "/{$theme}/css/editor.css"; } else { if (project()) { $cssFiles .= ',' . project() . '/css/editor.css'; } } $htmlEditorConfig->setOption('content_css', $cssFiles); } Requirements::css(CMS_DIR . '/css/typography.css'); Requirements::css(CMS_DIR . '/css/layout.css'); Requirements::css(CMS_DIR . '/css/cms_left.css'); Requirements::css(CMS_DIR . '/css/cms_right.css'); Requirements::css(SAPPHIRE_DIR . '/css/Form.css'); if (isset($_REQUEST['debug_firebug'])) { // Firebug is a useful console for debugging javascript // Its available as a Firefox extension or a javascript library // for easy inclusion in other browsers (just append ?debug_firebug=1 to the URL) Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/firebug-lite/firebug.js'); } else { // By default, we include fake-objects for all firebug calls // to avoid javascript errors when referencing console.log() etc in javascript code Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/firebug-lite/firebugx.js'); } Requirements::javascript(SAPPHIRE_DIR . '/javascript/prototypefix/intro.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/prototype/prototype.js'); Requirements::javascript(SAPPHIRE_DIR . '/javascript/prototypefix/outro.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery/jquery.js'); Requirements::javascript(SAPPHIRE_DIR . '/javascript/jquery_improvements.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-ui/jquery-ui.js'); //import all of jquery ui Requirements::javascript(CMS_DIR . '/thirdparty/jquery-layout/jquery.layout.js'); Requirements::javascript(CMS_DIR . '/thirdparty/jquery-layout/jquery.layout.state.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/json-js/json2.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-metadata/jquery.metadata.js'); Requirements::javascript(CMS_DIR . '/javascript/jquery-fitheighttoparent/jquery.fitheighttoparent.js'); Requirements::javascript(CMS_DIR . '/javascript/ssui.core.js'); // @todo Load separately so the CSS files can be inlined Requirements::css(SAPPHIRE_DIR . '/thirdparty/jquery-ui-themes/smoothness/jquery.ui.all.css'); // entwine Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-entwine/dist/jquery.entwine-dist.js'); // Required for TreeTools panel above tree Requirements::javascript(SAPPHIRE_DIR . '/javascript/TabSet.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/behaviour/behaviour.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-cookie/jquery.cookie.js'); Requirements::javascript(CMS_DIR . '/thirdparty/jquery-notice/jquery.notice.js'); Requirements::javascript(SAPPHIRE_DIR . '/javascript/jquery-ondemand/jquery.ondemand.js'); Requirements::javascript(CMS_DIR . '/javascript/jquery-changetracker/lib/jquery.changetracker.js'); Requirements::add_i18n_javascript(SAPPHIRE_DIR . '/javascript/lang'); Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/scriptaculous/effects.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/scriptaculous/dragdrop.js'); Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/scriptaculous/controls.js'); Requirements::javascript(THIRDPARTY_DIR . '/tree/tree.js'); Requirements::css(THIRDPARTY_DIR . '/tree/tree.css'); Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.js'); Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.Tree.js'); Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.EditForm.js'); Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.AddForm.js'); Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.BatchActions.js'); // navigator Requirements::css(SAPPHIRE_DIR . '/css/SilverStripeNavigator.css'); Requirements::javascript(SAPPHIRE_DIR . '/javascript/SilverStripeNavigator.js'); Requirements::themedCSS('typography'); foreach (self::$extra_requirements['javascript'] as $file) { Requirements::javascript($file[0]); } foreach (self::$extra_requirements['css'] as $file) { Requirements::css($file[0], $file[1]); } foreach (self::$extra_requirements['themedcss'] as $file) { Requirements::themedCSS($file[0], $file[1]); } Requirements::css(CMS_DIR . '/css/unjquery.css'); // Javascript combined files Requirements::combine_files('base.js', array('sapphire/thirdparty/prototype/prototype.js', 'sapphire/thirdparty/behaviour/behaviour.js', 'sapphire/thirdparty/jquery/jquery.js', 'sapphire/thirdparty/jquery-livequery/jquery.livequery.js', 'sapphire/javascript/jquery-ondemand/jquery.ondemand.js', 'sapphire/thirdparty/jquery-ui/jquery-ui.js', 'sapphire/thirdparty/firebug-lite/firebug.js', 'sapphire/thirdparty/firebug-lite/firebugx.js', 'sapphire/javascript/i18n.js')); Requirements::combine_files('leftandmain.js', array('sapphire/thirdparty/scriptaculous/effects.js', 'sapphire/thirdparty/scriptaculous/dragdrop.js', 'sapphire/thirdparty/scriptaculous/controls.js', 'cms/javascript/LeftAndMain.js', 'sapphire/javascript/tree/tree.js', 'sapphire/javascript/TreeSelectorField.js', 'cms/javascript/ThumbnailStripField.js')); $dummy = null; $this->extend('init', $dummy); // The user's theme shouldn't affect the CMS, if, for example, they have replaced // TableListField.ss or Form.ss. SSViewer::set_theme(null); }
/** * Installs the current locale into i18n * * @param boolean $persist Attempt to persist any detected locale within session / cookies */ public static function install_locale($persist = true) { // Ensure the locale is set correctly given the designated parameters $locale = self::current_locale($persist); if (empty($locale)) { return; } i18n::set_locale($locale); // LC_NUMERIC causes SQL errors for some locales (comma as decimal indicator) so skip foreach (array(LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_TIME) as $category) { setlocale($category, "{$locale}.UTF-8", $locale); } // Get date/time formats from Zend require_once 'Zend/Date.php'; i18n::config()->date_format = Zend_Locale_Format::getDateFormat($locale); i18n::config()->time_format = Zend_Locale_Format::getTimeFormat($locale); }
public function testURLSegmentAutoUpdateLocalized() { $oldLocale = i18n::get_locale(); i18n::set_locale('de_DE'); $sitetree = new SiteTree(); $sitetree->Title = _t('CMSMain.NEWPAGE', array('pagetype' => $sitetree->i18n_singular_name())); $sitetree->write(); $this->assertEquals($sitetree->URLSegment, 'neue-seite', 'Sets based on default title on first save'); $sitetree->Title = 'Changed'; $sitetree->write(); $this->assertEquals($sitetree->URLSegment, 'changed', 'Auto-updates when set to default title'); $sitetree->Title = 'Changed again'; $sitetree->write(); $this->assertEquals($sitetree->URLSegment, 'changed', 'Does not auto-update once title has been changed'); i18n::set_locale($oldLocale); }