/**
  * Get the locale of the Member, or if we're not logged in or don't have a locale, use the default one
  * @return string
  */
 protected function locale()
 {
     if (($member = Member::currentUser()) && $member->Locale) {
         return $member->Locale;
     }
     return i18n::get_locale();
 }
 public function tearDown()
 {
     parent::tearDown();
     i18n::set_locale($this->originalLocale);
     Config::inst()->remove('SilverStripe\\Forms\\TimeField', 'default_config');
     Config::inst()->update('SilverStripe\\Forms\\TimeField', 'default_config', $this->origTimeConfig);
 }
 public function __construct($name, $title = null, $value = "")
 {
     if (!$this->locale) {
         $this->locale = i18n::get_locale();
     }
     $this->config = $this->config()->default_config;
     if (!$this->getConfig('timeformat')) {
         $this->setConfig('timeformat', i18n::config()->get('time_format'));
     }
     parent::__construct($name, $title, $value);
 }
 /**
  * Write a Money object to the database, then re-read it to ensure it
  * is re-read properly.
  */
 public function testGettingWrittenDataObject()
 {
     $local = i18n::get_locale();
     //make sure that the $ amount is not prefixed by US$, as it would be in non-US locale
     i18n::set_locale('en_US');
     $obj = new MoneyTest_DataObject();
     $m = new DBMoney();
     $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 testRepeatedLoginAttemptsLockingPeopleOut()
 {
     $local = i18n::get_locale();
     i18n::set_locale('en_US');
     Member::config()->lock_out_after_incorrect_logins = 5;
     Member::config()->lock_out_delay_mins = 15;
     // Login with a wrong password for more than the defined threshold
     for ($i = 1; $i <= Member::config()->lock_out_after_incorrect_logins + 1; $i++) {
         $this->doTestLoginForm('*****@*****.**', 'incorrectpassword');
         $member = DataObject::get_by_id("SilverStripe\\Security\\Member", $this->idFromFixture('SilverStripe\\Security\\Member', 'test'));
         if ($i < Member::config()->lock_out_after_incorrect_logins) {
             $this->assertNull($member->LockedOutUntil, 'User does not have a lockout time set if under threshold for failed attempts');
             $this->assertContains($this->loginErrorMessage(), Convert::raw2xml(_t('Member.ERRORWRONGCRED')));
         } else {
             // Fuzzy matching for time to avoid side effects from slow running tests
             $this->assertGreaterThan(time() + 14 * 60, strtotime($member->LockedOutUntil), 'User has a lockout time set after too many failed attempts');
         }
         $msg = _t('Member.ERRORLOCKEDOUT2', 'Your account has been temporarily disabled because of too many failed attempts at ' . 'logging in. Please try again in {count} minutes.', null, array('count' => Member::config()->lock_out_delay_mins));
         if ($i > Member::config()->lock_out_after_incorrect_logins) {
             $this->assertContains($msg, $this->loginErrorMessage());
         }
     }
     $this->doTestLoginForm('*****@*****.**', '1nitialPassword');
     $this->assertNull($this->session()->inst_get('loggedInAs'), 'The user can\'t log in after being locked out, even with the right password');
     // (We fake this by re-setting LockedOutUntil)
     $member = DataObject::get_by_id("SilverStripe\\Security\\Member", $this->idFromFixture('SilverStripe\\Security\\Member', 'test'));
     $member->LockedOutUntil = date('Y-m-d H:i:s', time() - 30);
     $member->write();
     $this->doTestLoginForm('*****@*****.**', '1nitialPassword');
     $this->assertEquals($this->session()->inst_get('loggedInAs'), $member->ID, 'After lockout expires, the user can login again');
     // Log the user out
     $this->session()->inst_set('loggedInAs', null);
     // Login again with wrong password, but less attempts than threshold
     for ($i = 1; $i < Member::config()->lock_out_after_incorrect_logins; $i++) {
         $this->doTestLoginForm('*****@*****.**', 'incorrectpassword');
     }
     $this->assertNull($this->session()->inst_get('loggedInAs'));
     $this->assertContains($this->loginErrorMessage(), Convert::raw2xml(_t('Member.ERRORWRONGCRED')), 'The user can retry with a wrong password after the lockout expires');
     $this->doTestLoginForm('*****@*****.**', '1nitialPassword');
     $this->assertEquals($this->session()->inst_get('loggedInAs'), $member->ID, 'The user can login successfully after lockout expires, if staying below the threshold');
     i18n::set_locale($local);
 }
 /**
  * Given a partial class name, attempt to determine the best module to assign strings to.
  *
  * @param string $class Either a FQN class name, or a non-qualified class name.
  * @return string Name of module
  */
 protected function findModuleForClass($class)
 {
     if (ClassInfo::exists($class)) {
         return i18n::get_owner_module($class);
     }
     // If we can't find a class, see if it needs to be fully qualified
     if (strpos($class, '\\') !== false) {
         return null;
     }
     // Find FQN that ends with $class
     $classes = preg_grep('/' . preg_quote("\\{$class}", '\\/') . '$/i', ClassLoader::instance()->getManifest()->getClassNames());
     // Find all modules for candidate classes
     $modules = array_unique(array_map(function ($class) {
         return i18n::get_owner_module($class);
     }, $classes));
     if (count($modules) === 1) {
         return reset($modules);
     }
     // Couldn't find it! Exists in none, or multiple modules.
     return null;
 }
 /**
  * Returns the localized name based on the field's value.
  * Example: "de_DE" returns "Deutsch".
  *
  * @return String
  */
 public function getNativeName()
 {
     $common_names = i18n::get_common_locales(true);
     return isset($common_names[$this->value]) ? $common_names[$this->value] : false;
 }
 /**
  * Gets summary of items in changeset
  *
  * @return string
  */
 public function getDescription()
 {
     // Initialise list of items to count
     $counted = [];
     $countedOther = 0;
     foreach ($this->config()->important_classes as $type) {
         if (class_exists($type)) {
             $counted[$type] = 0;
         }
     }
     // Check each change item
     /** @var ChangeSetItem $change */
     foreach ($this->Changes() as $change) {
         $found = false;
         foreach ($counted as $class => $num) {
             if (is_a($change->ObjectClass, $class, true)) {
                 $counted[$class]++;
                 $found = true;
                 break;
             }
         }
         if (!$found) {
             $countedOther++;
         }
     }
     // Describe set based on this output
     $counted = array_filter($counted);
     // Empty state
     if (empty($counted) && empty($countedOther)) {
         return '';
     }
     // Put all parts together
     $parts = [];
     foreach ($counted as $class => $count) {
         $parts[] = DataObject::singleton($class)->i18n_pluralise($count);
     }
     // Describe non-important items
     if ($countedOther) {
         if ($counted) {
             $parts[] = i18n::pluralise(_t('ChangeSet.DESCRIPTION_OTHER_ITEM', 'other item'), _t('ChangeSet.DESCRIPTION_OTHER_ITEMS', 'other items'), $countedOther);
         } else {
             $parts[] = i18n::pluralise(_t('ChangeSet.DESCRIPTION_ITEM', 'item'), _t('ChangeSet.DESCRIPTION_ITEMS', 'items'), $countedOther);
         }
     }
     // Figure out how to join everything together
     if (empty($parts)) {
         return '';
     }
     if (count($parts) === 1) {
         return $parts[0];
     }
     // Non-comma list
     if (count($parts) === 2) {
         return _t('ChangeSet.DESCRIPTION_AND', '{first} and {second}', ['first' => $parts[0], 'second' => $parts[1]]);
     }
     // First item
     $string = _t('ChangeSet.DESCRIPTION_LIST_FIRST', '{item}', ['item' => $parts[0]]);
     // Middle items
     for ($i = 1; $i < count($parts) - 1; $i++) {
         $string = _t('ChangeSet.DESCRIPTION_LIST_MID', '{list}, {item}', ['list' => $string, 'item' => $parts[$i]]);
     }
     // Oxford comma
     $string = _t('ChangeSet.DESCRIPTION_LIST_LAST', '{list}, and {item}', ['list' => $string, 'item' => end($parts)]);
     return $string;
 }
 public function testMemberWithNoDateFormatFallsbackToGlobalLocaleDefaultFormat()
 {
     i18n::config()->update('date_format', 'yyyy-MM-dd')->update('time_format', 'H:mm');
     $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'noformatmember');
     $this->assertEquals('yyyy-MM-dd', $member->DateFormat);
     $this->assertEquals('H:mm', $member->TimeFormat);
 }
 public function __construct($name, $title = null, $value = null)
 {
     if (!$this->locale) {
         $this->locale = i18n::get_locale();
     }
     $this->config = $this->config()->default_config;
     if (!$this->getConfig('dateformat')) {
         $this->setConfig('dateformat', i18n::config()->get('date_format'));
     }
     foreach ($this->config()->default_config as $defaultK => $defaultV) {
         if ($defaultV) {
             if ($defaultK == 'locale') {
                 $this->locale = $defaultV;
             } else {
                 $this->setConfig($defaultK, $defaultV);
             }
         }
     }
     parent::__construct($name, $title, $value);
 }
 /**
  * Gets the current locale this field is set to.
  *
  * @return string
  */
 public function getLocale()
 {
     if ($this->locale) {
         return $this->locale;
     }
     return i18n::get_locale();
 }
Ejemplo n.º 12
0
 /**
  * Provide menu titles to the i18n entity provider
  */
 public function provideI18nEntities()
 {
     $cmsClasses = self::get_cms_classes();
     $entities = array();
     foreach ($cmsClasses as $cmsClass) {
         $defaultTitle = LeftAndMain::menu_title($cmsClass, false);
         $ownerModule = i18n::get_owner_module($cmsClass);
         $entities["{$cmsClass}.MENUTITLE"] = array($defaultTitle, 'Menu title', $ownerModule);
     }
     return $entities;
 }
Ejemplo n.º 13
0
 /**
  * Includes all available language files for a certain defined locale.
  *
  * @param string $locale All resources from any module in locale $locale will be loaded
  * @param Boolean $clean Clean old caches?
  */
 public static function include_by_locale($locale, $clean = false)
 {
     if ($clean) {
         self::flush();
     }
     // Get list of module => path pairs, and then just the names
     $modules = ClassLoader::instance()->getManifest()->getModules();
     $moduleNames = array_keys($modules);
     // Remove the "project" module from the list - we'll add it back specially later if needed
     global $project;
     if (($idx = array_search($project, $moduleNames)) !== false) {
         array_splice($moduleNames, $idx, 1);
     }
     // Get the order from the config syste,
     $order = i18n::config()->get('module_priority');
     // Find all modules that don't have their order specified by the config system
     $unspecified = array_diff($moduleNames, $order);
     // If the placeholder "other_modules" exists in the order array, replace it by the unspecified modules
     if (($idx = array_search('other_modules', $order)) !== false) {
         array_splice($order, $idx, 1, $unspecified);
     } else {
         // Otherwise just jam them on the front
         array_splice($order, 0, 0, $unspecified);
     }
     // Put the project module back in at the begining if it wasn't specified by the config system
     if (!in_array($project, $order)) {
         array_unshift($order, $project);
     }
     $sortedModules = array();
     foreach ($order as $module) {
         if (isset($modules[$module])) {
             $sortedModules[$module] = $modules[$module];
         }
     }
     $sortedModules = array_reverse($sortedModules, true);
     // Loop in reverse order, meaning the translator with the highest priority goes first
     $translatorsByPrio = array_reverse(self::get_translators(), true);
     foreach ($translatorsByPrio as $priority => $translators) {
         /** @var Zend_Translate $translator */
         foreach ($translators as $name => $translator) {
             /** @var i18nTranslateAdapterInterface|Zend_Translate_Adapter $adapter */
             $adapter = $translator->getAdapter();
             // Load translations from modules
             foreach ($sortedModules as $module) {
                 $filename = $adapter->getFilenameForLocale($locale);
                 $filepath = "{$module}/lang/" . $filename;
                 if ($filename && !file_exists($filepath)) {
                     continue;
                 }
                 $adapter->addTranslation(array('content' => $filepath, 'locale' => $locale));
             }
             // 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, Config::inst()->get('SilverStripe\\View\\SSViewer', 'theme')) === 0 && file_exists("{$themesBase}/{$theme}/lang/")) {
                         $filename = $adapter->getFilenameForLocale($locale);
                         $filepath = "{$themesBase}/{$theme}/lang/" . $filename;
                         if ($filename && !file_exists($filepath)) {
                             continue;
                         }
                         $adapter->addTranslation(array('content' => $filepath, 'locale' => $locale));
                     }
                 }
             }
             // 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.
             $adapter->addTranslation(array('content' => array($locale => $locale), 'locale' => $locale, 'usetranslateadapter' => true));
         }
     }
 }
Ejemplo n.º 14
0
/**
 * @see i18n::_t()
 *
 * @param string $entity
 * @param string $string
 * @param string $context
 * @param array $injection
 * @return string
 */
function _t($entity, $string = "", $context = "", $injection = null)
{
    return i18n::_t($entity, $string, $context, $injection);
}
Ejemplo n.º 15
0
 /**
  * Return a {@link FieldList} of fields that would appropriate for editing
  * this member.
  *
  * @return FieldList Return a FieldList of fields that would appropriate for
  *                   editing this member.
  */
 public function getCMSFields()
 {
     require_once 'Zend/Date.php';
     $self = $this;
     $this->beforeUpdateCMSFields(function (FieldList $fields) use($self) {
         /** @var FieldList $mainFields */
         $mainFields = $fields->fieldByName("Root")->fieldByName("Main")->getChildren();
         // Build change password field
         $mainFields->replaceField('Password', $self->getMemberPasswordField());
         $mainFields->replaceField('Locale', new DropdownField("Locale", _t('Member.INTERFACELANG', "Interface Language", 'Language of the CMS'), i18n::get_existing_translations()));
         $mainFields->removeByName($self->config()->hidden_fields);
         if (!$self->config()->lock_out_after_incorrect_logins) {
             $mainFields->removeByName('FailedLoginCount');
         }
         // Groups relation will get us into logical conflicts because
         // Members are displayed within  group edit form in SecurityAdmin
         $fields->removeByName('Groups');
         // Members shouldn't be able to directly view/edit logged passwords
         $fields->removeByName('LoggedPasswords');
         $fields->removeByName('RememberLoginHashes');
         if (Permission::check('EDIT_PERMISSIONS')) {
             $groupsMap = array();
             foreach (Group::get() as $group) {
                 // Listboxfield values are escaped, use ASCII char instead of &raquo;
                 $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
             }
             asort($groupsMap);
             $fields->addFieldToTab('Root.Main', ListboxField::create('DirectGroups', singleton('SilverStripe\\Security\\Group')->i18n_plural_name())->setSource($groupsMap)->setAttribute('data-placeholder', _t('Member.ADDGROUP', 'Add group', 'Placeholder text for a dropdown')));
             // Add permission field (readonly to avoid complicated group assignment logic).
             // This should only be available for existing records, as new records start
             // with no permissions until they have a group assignment anyway.
             if ($self->ID) {
                 $permissionsField = new PermissionCheckboxSetField_Readonly('Permissions', false, 'SilverStripe\\Security\\Permission', 'GroupID', $self->getManyManyComponents('Groups'));
                 $fields->findOrMakeTab('Root.Permissions', singleton('SilverStripe\\Security\\Permission')->i18n_plural_name());
                 $fields->addFieldToTab('Root.Permissions', $permissionsField);
             }
         }
         $permissionsTab = $fields->fieldByName("Root")->fieldByName('Permissions');
         if ($permissionsTab) {
             $permissionsTab->addExtraClass('readonly');
         }
         $defaultDateFormat = Zend_Locale_Format::getDateFormat(new Zend_Locale($self->Locale));
         $dateFormatMap = array('MMM d, yyyy' => Zend_Date::now()->toString('MMM d, yyyy'), 'yyyy/MM/dd' => Zend_Date::now()->toString('yyyy/MM/dd'), 'MM/dd/yyyy' => Zend_Date::now()->toString('MM/dd/yyyy'), 'dd/MM/yyyy' => Zend_Date::now()->toString('dd/MM/yyyy'));
         $dateFormatMap[$defaultDateFormat] = Zend_Date::now()->toString($defaultDateFormat) . sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
         $mainFields->push($dateFormatField = new MemberDatetimeOptionsetField('DateFormat', $self->fieldLabel('DateFormat'), $dateFormatMap));
         $formatClass = get_class($dateFormatField);
         $dateFormatField->setValue($self->DateFormat);
         $dateTemplate = SSViewer::get_templates_by_class($formatClass, '_description_date', $formatClass);
         $dateFormatField->setDescriptionTemplate($dateTemplate);
         $defaultTimeFormat = Zend_Locale_Format::getTimeFormat(new Zend_Locale($self->Locale));
         $timeFormatMap = array('h:mm a' => Zend_Date::now()->toString('h:mm a'), 'H:mm' => Zend_Date::now()->toString('H:mm'));
         $timeFormatMap[$defaultTimeFormat] = Zend_Date::now()->toString($defaultTimeFormat) . sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
         $mainFields->push($timeFormatField = new MemberDatetimeOptionsetField('TimeFormat', $self->fieldLabel('TimeFormat'), $timeFormatMap));
         $timeFormatField->setValue($self->TimeFormat);
         $timeTemplate = SSViewer::get_templates_by_class($formatClass, '_description_time', $formatClass);
         $timeFormatField->setDescriptionTemplate($timeTemplate);
     });
     return parent::getCMSFields();
 }
 public function setUp()
 {
     //nest config and injector for each test so they are effectively sandboxed per test
     Config::nest();
     Injector::nest();
     $this->originalReadingMode = Versioned::get_reading_mode();
     // We cannot run the tests on this abstract class.
     if (get_class($this) == __CLASS__) {
         $this->markTestSkipped(sprintf('Skipping %s ', get_class($this)));
         return;
     }
     // 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::config()->get('default_locale'));
     i18n::config()->date_format = null;
     i18n::config()->time_format = null;
     // Set default timezone consistently to avoid NZ-specific dependencies
     date_default_timezone_set('UTC');
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Cookie::config()->update('report_errors', false);
     if (class_exists('SilverStripe\\CMS\\Controllers\\RootURLController')) {
         RootURLController::reset();
     }
     if (class_exists('Translatable')) {
         Translatable::reset();
     }
     Versioned::reset();
     DataObject::reset();
     if (class_exists('SilverStripe\\CMS\\Model\\SiteTree')) {
         SiteTree::reset();
     }
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(Session::create(array()));
     }
     Security::$database_is_ready = null;
     // Add controller-name auto-routing
     // @todo Fix to work with namespaced controllers
     Director::config()->update('rules', array('$Controller//$Action/$ID/$OtherID' => '*'));
     $fixtureFiles = $this->getFixturePaths();
     // Todo: this could be a special test model
     $this->model = DataModel::inst();
     // Set up fixture
     if ($fixtureFiles || $this->usesDatabase) {
         if (!self::using_temp_db()) {
             self::create_temp_db();
         }
         DataObject::singleton()->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();
             }
         }
         foreach ($fixtureFiles as $fixtureFilePath) {
             $fixture = YamlFixture::create($fixtureFilePath);
             $fixture->writeInto($this->getFixtureFactory());
         }
         $this->logInWithPermission("ADMIN");
     }
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
     // turn off template debugging
     SSViewer::config()->update('source_file_comments', false);
     // Clear requirements
     Requirements::clear();
     // Set up email
     $this->mailer = new TestMailer();
     Injector::inst()->registerService($this->mailer, 'SilverStripe\\Control\\Email\\Mailer');
     Email::config()->remove('send_all_emails_to');
 }
 public function testCoreGlobalVariableCalls()
 {
     $this->assertEquals(Director::absoluteBaseURL(), $this->render('{$absoluteBaseURL}'), 'Director::absoluteBaseURL can be called from within template');
     $this->assertEquals(Director::absoluteBaseURL(), $this->render('{$AbsoluteBaseURL}'), 'Upper-case %AbsoluteBaseURL can be called from within template');
     $this->assertEquals(Director::is_ajax(), $this->render('{$isAjax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(Director::is_ajax(), $this->render('{$IsAjax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(Director::is_ajax(), $this->render('{$is_ajax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(Director::is_ajax(), $this->render('{$Is_ajax}'), 'All variations of is_ajax result in the correct call');
     $this->assertEquals(i18n::get_locale(), $this->render('{$i18nLocale}'), 'i18n template functions result correct result');
     $this->assertEquals(i18n::get_locale(), $this->render('{$get_locale}'), 'i18n template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$CurrentMember}'), 'Member template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$CurrentUser}'), 'Member template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$currentMember}'), 'Member template functions result correct result');
     $this->assertEquals((string) Member::currentUser(), $this->render('{$currentUser}'), 'Member template functions result correct result');
     $this->assertEquals(SecurityToken::getSecurityID(), $this->render('{$getSecurityID}'), 'SecurityToken template functions result correct result');
     $this->assertEquals(SecurityToken::getSecurityID(), $this->render('{$SecurityID}'), 'SecurityToken template functions result correct result');
     $this->assertEquals(Permission::check("ADMIN"), (bool) $this->render('{$HasPerm(\'ADMIN\')}'), 'Permissions template functions result correct result');
     $this->assertEquals(Permission::check("ADMIN"), (bool) $this->render('{$hasPerm(\'ADMIN\')}'), 'Permissions template functions result correct result');
 }
 /**
  * @return String
  */
 public function Locale()
 {
     return DBField::create_field('Locale', i18n::get_locale());
 }
 public function testCollectFromFilesystemAndWriteMasterTables()
 {
     $local = i18n::get_locale();
     i18n::set_locale('en_US');
     //set the locale to the US locale expected in the asserts
     i18n::config()->update('default_locale', 'en_US');
     $c = new i18nTextCollector();
     $c->setWriter(new i18nTextCollector_Writer_RailsYaml());
     $c->basePath = $this->alternateBasePath;
     $c->baseSavePath = $this->alternateBaseSavePath;
     $c->run();
     // i18ntestmodule
     $moduleLangFile = "{$this->alternateBaseSavePath}/i18ntestmodule/lang/" . $c->getDefaultLocale() . '.yml';
     $this->assertTrue(file_exists($moduleLangFile), 'Master language file can be written to modules /lang folder');
     $moduleLangFileContent = file_get_contents($moduleLangFile);
     $this->assertContains("    ADDITION: Addition\n", $moduleLangFileContent);
     $this->assertContains("    ENTITY: 'Entity with \"Double Quotes\"'\n", $moduleLangFileContent);
     $this->assertContains("    MAINTEMPLATE: 'Main Template'\n", $moduleLangFileContent);
     $this->assertContains("    OTHERENTITY: 'Other Entity'\n", $moduleLangFileContent);
     $this->assertContains("    WITHNAMESPACE: 'Include Entity with Namespace'\n", $moduleLangFileContent);
     $this->assertContains("    NONAMESPACE: 'Include Entity without Namespace'\n", $moduleLangFileContent);
     // i18nothermodule
     $otherModuleLangFile = "{$this->alternateBaseSavePath}/i18nothermodule/lang/" . $c->getDefaultLocale() . '.yml';
     $this->assertTrue(file_exists($otherModuleLangFile), 'Master language file can be written to modules /lang folder');
     $otherModuleLangFileContent = file_get_contents($otherModuleLangFile);
     $this->assertContains("    ENTITY: 'Other Module Entity'\n", $otherModuleLangFileContent);
     $this->assertContains("    MAINTEMPLATE: 'Main Template Other Module'\n", $otherModuleLangFileContent);
     // testtheme1
     $theme1LangFile = "{$this->alternateBaseSavePath}/themes/testtheme1/lang/" . $c->getDefaultLocale() . '.yml';
     $this->assertTrue(file_exists($theme1LangFile), 'Master theme language file can be written to themes/testtheme1 /lang folder');
     $theme1LangFileContent = file_get_contents($theme1LangFile);
     $this->assertContains("    MAINTEMPLATE: 'Theme1 Main Template'\n", $theme1LangFileContent);
     $this->assertContains("    LAYOUTTEMPLATE: 'Theme1 Layout Template'\n", $theme1LangFileContent);
     $this->assertContains("    SPRINTFNAMESPACE: 'Theme1 My replacement: %s'\n", $theme1LangFileContent);
     $this->assertContains("    LAYOUTTEMPLATENONAMESPACE: 'Theme1 Layout Template no namespace'\n", $theme1LangFileContent);
     $this->assertContains("    SPRINTFNONAMESPACE: 'Theme1 My replacement no namespace: %s'\n", $theme1LangFileContent);
     $this->assertContains("    SPRINTFINCLUDENAMESPACE: 'Theme1 My include replacement: %s'\n", $theme1LangFileContent);
     $this->assertContains("    WITHNAMESPACE: 'Theme1 Include Entity with Namespace'\n", $theme1LangFileContent);
     $this->assertContains("    NONAMESPACE: 'Theme1 Include Entity without Namespace'\n", $theme1LangFileContent);
     $this->assertContains("    SPRINTFINCLUDENONAMESPACE: 'Theme1 My include replacement no namespace: %s'\n", $theme1LangFileContent);
     // testtheme2
     $theme2LangFile = "{$this->alternateBaseSavePath}/themes/testtheme2/lang/" . $c->getDefaultLocale() . '.yml';
     $this->assertTrue(file_exists($theme2LangFile), 'Master theme language file can be written to themes/testtheme2 /lang folder');
     $theme2LangFileContent = file_get_contents($theme2LangFile);
     $this->assertContains("    MAINTEMPLATE: 'Theme2 Main Template'\n", $theme2LangFileContent);
     i18n::set_locale($local);
     //set the locale to the US locale expected in the asserts
 }
 /**
  * Pluralise this item given a specific count.
  *
  * E.g. "0 Pages", "1 File", "3 Images"
  *
  * @param string $count
  * @param bool $prependNumber Include number in result. Defaults to true.
  * @return string
  */
 public function i18n_pluralise($count, $prependNumber = true)
 {
     return i18n::pluralise($this->i18n_singular_name(), $this->i18n_plural_name(), $count, $prependNumber);
 }
 /**
  * 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();
     $map = $this->config()->locale_map;
     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, $map)) {
             // Specialized mapping for combined lang properties
             $lang = $map[$locale];
         } else {
             // Fall back to default lang (meaning "en_US" turns into "en")
             $lang = i18n::get_lang_from_locale($locale);
         }
     }
     return $lang;
 }
 public function testReadonly()
 {
     i18n::set_locale('en_US');
     $field = new NumericField('Number');
     $this->assertRegExp("#<span[^>]+>\\s*0\\s*<\\/span>#", "" . $field->performReadonlyTransformation()->Field() . "");
 }
Ejemplo n.º 23
0
 /**
  * @return string
  */
 public function getLocale()
 {
     return $this->locale ? $this->locale : i18n::get_locale();
 }