/**
  * Alter file path to generated a static (static) error page file to handle error page template on different sub-sites 
  *
  * @see Error::get_filepath_for_errorcode()
  *
  * FIXME since {@link Subsite::currentSubsite()} partly relies on Session, viewing other sub-site (including main site) between 
  * opening ErrorPage in the CMS and publish ErrorPage causes static error page to get generated incorrectly. 
  */
 function alternateFilepathForErrorcode($statusCode, $locale = null)
 {
     $static_filepath = Object::get_static($this->owner->ClassName, 'static_filepath');
     $subdomainPart = "";
     // Try to get current subsite from session
     $subsite = Subsite::currentSubsite(false);
     // since this function is called from Page class before the controller is created, we have to get subsite from domain instead
     if (!$subsite) {
         $subsiteID = Subsite::getSubsiteIDForDomain();
         if ($subsiteID != 0) {
             $subsite = DataObject::get_by_id("Subsite", $subsiteID);
         } else {
             $subsite = null;
         }
     }
     if ($subsite) {
         $subdomain = $subsite->domain();
         $subdomainPart = "-{$subdomain}";
     }
     if (singleton('SiteTree')->hasExtension('Translatable') && $locale && $locale != Translatable::default_locale()) {
         $filepath = $static_filepath . "/error-{$statusCode}-{$locale}{$subdomainPart}.html";
     } else {
         $filepath = $static_filepath . "/error-{$statusCode}{$subdomainPart}.html";
     }
     return $filepath;
 }
 public function setUp()
 {
     parent::setUp();
     //Remap translation group for home pages
     Translatable::disable_locale_filter();
     $default = $this->objFromFixture('Page', 'home');
     $defaultFR = $this->objFromFixture('Page', 'home_fr');
     $defaultFR->addTranslationGroup($default->ID, true);
     Translatable::enable_locale_filter();
     $this->origLocaleRoutingEnabled = Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL');
     Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', false);
     $this->origDashLocaleEnabled = Config::inst()->get('MultilingualRootURLController', 'UseDashLocale');
     Config::inst()->update('MultilingualRootURLController', 'UseDashLocale', false);
     $this->origAcceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en-US,en;q=0.5';
     $this->origCookieLocale = Cookie::get('language');
     Cookie::force_expiry('language');
     $this->origCurrentLocale = Translatable::get_current_locale();
     Translatable::set_current_locale('en_US');
     $this->origLocale = Translatable::default_locale();
     Translatable::set_default_locale('en_US');
     $this->origi18nLocale = i18n::get_locale();
     i18n::set_locale('en_US');
     $this->origAllowedLocales = Translatable::get_allowed_locales();
     Translatable::set_allowed_locales(array('en_US', 'fr_FR'));
     MultilingualRootURLController::reset();
 }
Example #3
0
 public function init()
 {
     parent::init();
     // Locale" attribute is either explicitly added by LeftAndMain Javascript logic,
     // or implied on a translated record (see {@link Translatable->updateCMSFields()}).
     // $Lang serves as a "context" which can be inspected by Translatable - hence it
     // has the same name as the database property on Translatable.
     if ($this->getRequest()->requestVar("Locale")) {
         $this->Locale = $this->getRequest()->requestVar("Locale");
     } elseif ($this->getRequest()->requestVar("locale")) {
         $this->Locale = $this->getRequest()->requestVar("locale");
     } else {
         $this->Locale = Translatable::default_locale();
     }
     Translatable::set_current_locale($this->Locale);
     // collect languages for TinyMCE spellchecker plugin.
     // see http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker
     $langName = i18n::get_locale_name($this->Locale);
     HtmlEditorConfig::get('cms')->setOption('spellchecker_languages', "+{$langName}={$this->Locale}");
     Requirements::javascript(CMS_DIR . '/javascript/CMSMain.js');
     Requirements::javascript(CMS_DIR . '/javascript/CMSMain.Tree.js');
     Requirements::javascript(CMS_DIR . '/javascript/CMSMain.EditForm.js');
     Requirements::javascript(CMS_DIR . '/javascript/CMSMain.Translatable.js');
     Requirements::css(CMS_DIR . '/css/CMSMain.css');
     CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish');
     CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish');
     CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete');
     CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive');
 }
 /**
  * Convenience method to use within a locale context.
  * Eg. by specifying the edit fields with the UploadField.
  * <code>
  * $imageUpload = UploadField::create('Image');
  * $imageUpload->setFileEditFields('getUploadEditorFields');
  * </code>
  * @return FieldList
  */
 public function getUploadEditorFields()
 {
     /** @var FieldList $fields */
     $fields = FieldList::create();
     $translatedFields = TranslatableDataObject::get_localized_class_fields($this->owner->class);
     $transformation = null;
     $defaultLocale = Translatable::default_locale();
     if ($defaultLocale != Translatable::get_current_locale()) {
         /** @var TranslatableFormFieldTransformation $transformation */
         $transformation = TranslatableFormFieldTransformation::create($this->owner);
     }
     foreach ($translatedFields as $fieldName) {
         // create the field in the default locale
         /** @var FormField $field */
         $field = $this->owner->getLocalizedFormField($fieldName, $defaultLocale);
         // use translated title if available
         $field->setTitle(_t('File.' . $fieldName, $fieldName));
         // if not in the default locale, we apply the form field transformation to the field
         if ($transformation) {
             $field = $transformation->transformFormField($field);
         }
         $fields->push($field);
     }
     return $fields;
 }
 /**
  * Helper method to get content languages from the live DB table.
  * Most of the code is borrowed from the Translatable::get_live_content_languages method.
  * This method operates on "SiteTree" and makes a distinction between Live and Stage.
  * @return array
  */
 public static function get_content_languages()
 {
     $table = Versioned::current_stage() == 'Live' ? 'SiteTree_Live' : 'SiteTree';
     if (class_exists('SQLSelect')) {
         $query = new SQLSelect("Distinct \"Locale\"", "\"{$table}\"");
     } else {
         // SS 3.1 compat
         $query = new SQLQuery("Distinct \"Locale\"", array("\"{$table}\""));
     }
     $query = $query->setGroupBy('"Locale"');
     $dbLangs = $query->execute()->column();
     $langlist = array_merge((array) Translatable::default_locale(), (array) $dbLangs);
     $returnMap = array();
     $allCodes = array_merge(Config::inst()->get('i18n', 'all_locales'), Config::inst()->get('i18n', 'common_locales'));
     foreach ($langlist as $langCode) {
         if ($langCode && isset($allCodes[$langCode])) {
             if (is_array($allCodes[$langCode])) {
                 $returnMap[$langCode] = $allCodes[$langCode]['name'];
             } else {
                 $returnMap[$langCode] = $allCodes[$langCode];
             }
         }
     }
     return $returnMap;
 }
Example #6
0
	static function set_up_once() {
		// needs to recreate the database schema with language properties
		self::kill_temp_db();

		// store old defaults	
		if(class_exists('Translatable')) {
			self::$origTranslatableSettings['has_extension'] = singleton('SiteTree')->hasExtension('Translatable');
			self::$origTranslatableSettings['default_locale'] = Translatable::default_locale();
			
			// overwrite locale
			Translatable::set_default_locale("en_US");

			// refresh the extended statics - different fields in $db with Translatable enabled
			if(self::$origTranslatableSettings['has_extension']) {
				Object::remove_extension('SiteTree', 'Translatable');
				Object::remove_extension('SiteConfig', 'Translatable');
			}
		}

		// recreate database with new settings
		$dbname = self::create_temp_db();
		DB::set_alternative_database_name($dbname);

		parent::set_up_once();
	}
 public function setUp()
 {
     parent::setUp();
     Translatable::disable_locale_filter();
     //Publish all english pages
     $pages = Page::get()->filter('Locale', 'en_US');
     foreach ($pages as $page) {
         $page->publish('Stage', 'Live');
     }
     //Rewrite the french translation groups and publish french pages
     $pagesFR = Page::get()->filter('Locale', 'fr_FR');
     foreach ($pagesFR as $index => $page) {
         $page->addTranslationGroup($pages->offsetGet($index)->ID, true);
         $page->publish('Stage', 'Live');
     }
     Translatable::enable_locale_filter();
     $this->origLocaleRoutingEnabled = Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL');
     Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', false);
     $this->origDashLocaleEnabled = Config::inst()->get('MultilingualRootURLController', 'UseDashLocale');
     Config::inst()->update('MultilingualRootURLController', 'UseDashLocale', false);
     $this->origAcceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en-US,en;q=0.5';
     $this->origCookieLocale = Cookie::get('language');
     Cookie::force_expiry('language');
     Cookie::set('language', 'en');
     $this->origCurrentLocale = Translatable::get_current_locale();
     Translatable::set_current_locale('en_US');
     $this->origLocale = Translatable::default_locale();
     Translatable::set_default_locale('en_US');
     $this->origi18nLocale = i18n::get_locale();
     i18n::set_locale('en_US');
     $this->origAllowedLocales = Translatable::get_allowed_locales();
     Translatable::set_allowed_locales(array('en_US', 'fr_FR'));
     MultilingualRootURLController::reset();
 }
 /**
  * Returns TRUE if a request to a certain page should be redirected to the site root (i.e. if the page acts as the
  * home page).
  *
  * @param SiteTree $page
  * @return bool
  */
 public static function should_be_on_root(SiteTree $page)
 {
     if (!self::$is_at_root && self::get_homepage_link() == trim($page->RelativeLink(true), '/')) {
         return !(class_exists('Translatable') && $page->hasExtension('Translatable') && $page->Locale && $page->Locale != Translatable::default_locale());
     }
     return false;
 }
 function init()
 {
     $req = $this->owner->getRequest();
     // Ignore being called on LeftAndMain base class,
     // which is the case when requests are first routed through AdminRootController
     // as an intermediary rather than the endpoint controller
     if (!$this->owner->stat('tree_class')) {
         return;
     }
     // Locale" attribute is either explicitly added by LeftAndMain Javascript logic,
     // or implied on a translated record (see {@link Translatable->updateCMSFields()}).
     // $Lang serves as a "context" which can be inspected by Translatable - hence it
     // has the same name as the database property on Translatable.
     $id = $req->param('ID');
     if ($req->requestVar("Locale")) {
         $this->owner->Locale = $req->requestVar("Locale");
     } else {
         if ($id && is_numeric($id)) {
             $record = DataObject::get_by_id($this->owner->stat('tree_class'), $id);
             if ($record && $record->Locale) {
                 $this->owner->Locale = $record->Locale;
             }
         } else {
             $this->owner->Locale = Translatable::default_locale();
             if ($this->owner->class == 'CMSPagesController') {
                 // the CMSPagesController always needs to have the locale set,
                 // otherwise page editing will cause an extra
                 // ajax request which looks weird due to multiple "loading"-flashes
                 $getVars = $req->getVars();
                 if (isset($getVars['url'])) {
                     unset($getVars['url']);
                 }
                 return $this->owner->redirect(Controller::join_links($this->owner->Link(), $req->param('Action'), $req->param('ID'), $req->param('OtherID'), ($query = http_build_query($getVars)) ? "?{$query}" : null));
             }
         }
     }
     Translatable::set_current_locale($this->owner->Locale);
     // If a locale is set, it needs to match to the current record
     $requestLocale = $req->requestVar("Locale");
     $page = $this->owner->currentPage();
     if ($req->httpMethod() == 'GET' && $requestLocale && $page && $page->hasExtension('Translatable') && $page->Locale != $requestLocale && $req->latestParam('Action') != 'EditorToolbar') {
         $transPage = $page->getTranslation($requestLocale);
         if ($transPage) {
             Translatable::set_current_locale($transPage->Locale);
             return $this->owner->redirect(Controller::join_links($this->owner->Link('show'), $transPage->ID));
         } else {
             if ($this->owner->class != 'CMSPagesController') {
                 // If the record is not translated, redirect to pages overview
                 return $this->owner->redirect(Controller::join_links(singleton('CMSPagesController')->Link(), '?Locale=' . $requestLocale));
             }
         }
     }
     // collect languages for TinyMCE spellchecker plugin.
     // see http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker
     $langName = i18n::get_locale_name($this->owner->Locale);
     HtmlEditorConfig::get('cms')->setOption('spellchecker_languages', "+{$langName}={$this->owner->Locale}");
     Requirements::javascript('translatable/javascript/CMSMain.Translatable.js');
     Requirements::css('translatable/css/CMSMain.Translatable.css');
 }
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     DB::query(sprintf('UPDATE "ContentModule" SET "Locale" = \'%s\' WHERE "Locale" = \'\' OR "Locale" IS NULL', Translatable::default_locale()));
     DB::query(sprintf('UPDATE "ContentModule_Live" SET "Locale" = \'%s\' WHERE "Locale" = \'\' OR "Locale" IS NULL', Translatable::default_locale()));
     DB::query(sprintf('UPDATE "ContentModule_versions" SET "Locale" = \'%s\' WHERE "Locale" = \'\' OR "Locale" IS NULL', Translatable::default_locale()));
     DB::alteration_message('Updated ContentModule for Translatable', 'changed');
 }
 /**
  * PageByDefaultLocale
  * gets a page in the default locale
  *
  * @param string $pageURL url of a page in the default locale
  * @return DataObject requested page in the current locale, null if none exists.
  */
 function PageByDefaultLocale($pageURL)
 {
     $defLoc = Translatable::default_locale();
     if ($pg = Translatable::get_one_by_locale('Page', $defLoc, "URLSegment = '{$pageURL}'")) {
         return $pg;
     }
     return null;
 }
 function setUp()
 {
     parent::setUp();
     // whenever a translation is created, canTranslate() is checked
     $cmseditor = $this->objFromFixture('Member', 'cmseditor');
     $cmseditor->logIn();
     $this->origLocale = Translatable::default_locale();
     Translatable::set_default_locale("en_US");
 }
 public function SortedImages()
 {
     //Debug::dump($this->Images()->Sort('SortOrder')->toArray());
     $obj = $this;
     if (class_exists('Translatable') && $this->Locale != Translatable::default_locale()) {
         $obj = $this->getTranslation(Translatable::default_locale());
     }
     return $obj->Images()->Sort('SortOrder');
 }
 public function tMaxPhotos()
 {
     if (class_exists("Translatable") && $this->owner->Locale != Translatable::default_locale() && !$this->owner->MaxPhotos()->exists()) {
         $tPage = $this->owner->getTranslation(Translatable::default_locale());
         if ($tPage) {
             return $tPage->MaxPhotos();
         }
     }
     return $this->owner->MaxPhotos();
 }
 /**
  * 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);
     }
 }
 function testHomepageForDomain()
 {
     $originalHost = $_SERVER['HTTP_HOST'];
     // Tests matching an HTTP_HOST value to URLSegment homepage values
     $tests = array('page.co.nz' => 'page1', 'www.page.co.nz' => 'page1', 'help.com' => 'page1', 'www.help.com' => 'page1', 'something.com' => 'page1', 'www.something.com' => 'page1', 'other.co.nz' => 'page2', 'www.other.co.nz' => 'page2', 'right' => 'page2', 'www. right' => 'page2', 'only.com' => 'page3', 'www.only.com' => 'page3', 'www.somethingelse.com' => 'home', 'somethingelse.com' => 'home', 'alternate.only.com' => 'home', 'www.alternate.only.com' => 'home', 'alternate.something.com' => 'home');
     foreach ($tests as $domain => $urlSegment) {
         $_SERVER['HTTP_HOST'] = $domain;
         $this->assertEquals($urlSegment, RootURLController::get_homepage_urlsegment(Translatable::default_locale()), "Testing {$domain} matches {$urlSegment}");
     }
     $_SERVER['HTTP_HOST'] = $originalHost;
 }
 public function run($request)
 {
     $locale = Translatable::default_locale();
     $pages = SiteTree::get()->where("Locale='{$locale}'");
     foreach ($pages as $page) {
         $translated = $page->createTranslation("en_GB");
         $translated->doPublish();
         // $page->doUnpublish();
         // $page->delete();
     }
 }
 /**
  * Create a new LanguageDropdownField
  * @param string $name
  * @param string $title
  * @param array $excludeLocales List of locales that won't be included
  * @param string $translatingClass Name of the class with translated instances where to look for used languages
  * @param string $list Indicates the source language list. Can be either Common-English, Common-Native, Locale-English, Locale-Native
  */
 function __construct($name, $title, $excludeLocales = array(), $translatingClass = 'SiteTree', $list = 'Common-English', $instance = null)
 {
     $usedLocalesWithTitle = Translatable::get_existing_content_languages($translatingClass);
     $usedLocalesWithTitle = array_diff_key($usedLocalesWithTitle, $excludeLocales);
     if ('Common-English' == $list) {
         $allLocalesWithTitle = i18n::get_common_languages();
     } else {
         if ('Common-Native' == $list) {
             $allLocalesWithTitle = i18n::get_common_languages(true);
         } else {
             if ('Locale-English' == $list) {
                 $allLocalesWithTitle = i18n::get_common_locales();
             } else {
                 if ('Locale-Native' == $list) {
                     $allLocalesWithTitle = i18n::get_common_locales(true);
                 } else {
                     $allLocalesWithTitle = i18n::get_locale_list();
                 }
             }
         }
     }
     if (isset($allLocales[Translatable::default_locale()])) {
         unset($allLocales[Translatable::default_locale()]);
     }
     // Limit to allowed locales if defined
     // Check for canTranslate() if an $instance is given
     $allowedLocales = Translatable::get_allowed_locales();
     foreach ($allLocalesWithTitle as $locale => $localeTitle) {
         if ($allowedLocales && !in_array($locale, $allowedLocales) || $excludeLocales && in_array($locale, $excludeLocales) || $usedLocalesWithTitle && array_key_exists($locale, $usedLocalesWithTitle)) {
             unset($allLocalesWithTitle[$locale]);
         }
     }
     // instance specific permissions
     foreach ($allLocalesWithTitle as $locale => $localeTitle) {
         if ($instance && !$instance->canTranslate(null, $locale)) {
             unset($allLocalesWithTitle[$locale]);
         }
     }
     foreach ($usedLocalesWithTitle as $locale => $localeTitle) {
         if ($instance && !$instance->canTranslate(null, $locale)) {
             unset($usedLocalesWithTitle[$locale]);
         }
     }
     // Sort by title (array value)
     asort($allLocalesWithTitle);
     if (count($usedLocalesWithTitle)) {
         asort($usedLocalesWithTitle);
         $source = array(_t('Form.LANGAVAIL', "Available languages") => $usedLocalesWithTitle, _t('Form.LANGAOTHER', "Other languages") => $allLocalesWithTitle);
     } else {
         $source = $allLocalesWithTitle;
     }
     parent::__construct($name, $title, $source);
 }
 function testCurrentCreatesDefaultForLocale()
 {
     Translatable::set_current_locale(Translatable::default_locale());
     $configEn = SiteConfig::current_site_config();
     Translatable::set_current_locale('fr_FR');
     $configFr = SiteConfig::current_site_config();
     Translatable::set_current_locale(Translatable::default_locale());
     $this->assertInstanceOf('SiteConfig', $configFr);
     $this->assertEquals($configFr->Locale, 'fr_FR');
     $this->assertEquals($configFr->Title, $configEn->Title, 'Copies title from existing config');
     $this->assertEquals($configFr->getTranslationGroup(), $configEn->getTranslationGroup(), 'Created in the same translation group');
 }
 public function alternateFilepathForErrorcode($code, $locale)
 {
     $path = ErrorPage::get_static_filepath();
     $parts = array();
     if ($site = Multisites::inst()->getActiveSite()) {
         $parts[] = $site->Host;
     }
     $parts[] = $code;
     if ($locale && $this->owner->hasExtension('Translatable') && $locale != Translatable::default_locale()) {
         $parts[] = $locale;
     }
     return sprintf("%s/error-%s.html", $path, implode('-', $parts));
 }
 /**
  * Returns true if we're currently on the root page and should be redirecting to the root
  * Doesn't take into account actions, post vars, or get vars.
  *
  * @param SiteTree $currentPage
  * @return boolean
  */
 static function should_be_on_root(SiteTree $currentPage)
 {
     if (self::$is_at_root) {
         return false;
     }
     $matchesHomepageSegment = self::get_homepage_urlsegment() == $currentPage->URLSegment;
     // Don't redirect translated homepage segments,
     // as the redirection target '/' will show the default locale
     // instead of the translation.
     $isTranslatedHomepage = singleton('SiteTree')->hasExtension('Translatable') && $currentPage->Locale && $currentPage->Locale != Translatable::default_locale();
     if ($matchesHomepageSegment && !$isTranslatedHomepage) {
         return true;
     }
     return false;
 }
 public function onTranslatableCreate($saveTranslation)
 {
     if ($saveTranslation) {
         //create new modules
         if ($original = $this->owner->getTranslation(Translatable::default_locale())) {
             foreach ($original->ContentModules() as $module) {
                 //create new module
                 $newModule = Object::create(get_class($module));
                 $newModule->Title = $module->Title . ' - ' . Translatable::get_current_locale();
                 $newModule->Locale = Translatable::get_current_locale();
                 $newModule->OriginalID = $original->ID;
                 $newModule->write();
                 $this->owner->ContentModules()->add($newModule);
             }
         }
     }
 }
 /**
  * Creates a folder for a page as a subfolder of the parent page
  * You can exclude page types by setting $ignored_classes in config
  *
  * Doesn't create folders for translated pages by default.
  *
  * @TODO doesn't check if page is moved to another parent
  */
 function checkFolder()
 {
     $ignoredPageTypes = Config::inst()->get($this->class, 'ignored_classes');
     foreach ($ignoredPageTypes as $pagetype) {
         if (is_a($this->owner, $pagetype)) {
             return;
         }
     }
     if (class_exists('Translatable') && $this->owner->Locale !== Translatable::default_locale() && !Config::inst()->get($this->class, 'create_folder_for_translations')) {
         return;
     }
     if (!$this->owner->RootFolderID) {
         $this->createRootFolder();
     } else {
         $this->updateRootFolder();
     }
 }
 /**
  * @param FieldList $fields
  */
 public function updateCMSFields(FieldList $fields)
 {
     //adding upload field - if item has already been saved
     //AssetsFolderID is set by the uploaddirrules module
     if ($this->owner->ID && $this->owner->AssetsFolderID != 0) {
         //this is the default, for non multi-language sites
         if (!class_exists('Translatable') || $this->owner->Locale == Translatable::default_locale()) {
             //The upload directory is expected to have been set in {@see UploadDirRules},
             //This should be handled on the object that uses this extension!
             $imageField = SortableUploadField::create('Images', '')->setAllowedFileCategories('image');
             $fields->addFieldToTab('Root.Images', $imageField);
         } else {
             //Note that images are administered in the original language
             $orig = $this->owner->getTranslation(Translatable::default_locale());
             $html = sprintf('<a href="%s">%s</a>', Controller::join_links($orig->CMSEditLink(), '?locale=' . $orig->Locale), 'Images are administered through ' . i18n::get_locale_name($orig->Locale));
             $fields->addFieldToTab('Root.Images', LiteralField::create('ImagesDesc', $html));
         }
     }
 }
 function init()
 {
     // Locale" attribute is either explicitly added by LeftAndMain Javascript logic,
     // or implied on a translated record (see {@link Translatable->updateCMSFields()}).
     // $Lang serves as a "context" which can be inspected by Translatable - hence it
     // has the same name as the database property on Translatable.
     $req = $this->owner->getRequest();
     $id = $req->param('ID');
     if ($req->requestVar("Locale")) {
         $this->owner->Locale = $req->requestVar("Locale");
     } elseif ($req->requestVar("locale")) {
         $this->owner->Locale = $req->requestVar("locale");
     } else {
         if ($id && is_numeric($id)) {
             $record = DataObject::get_by_id($this->owner->stat('tree_class'), $id);
             if ($record && $record->Locale) {
                 $this->owner->Locale = $record->Locale;
             }
         } else {
             $this->owner->Locale = Translatable::default_locale();
         }
     }
     Translatable::set_current_locale($this->owner->Locale);
     // if a locale is set, it needs to match to the current record
     $requestLocale = $req->requestVar("Locale") ? $req->requestVar("Locale") : $req->requestVar("locale");
     $page = $this->owner->currentPage();
     if ($requestLocale && $page && $page->Locale != $requestLocale) {
         $transPage = $page->getTranslation($requestLocale);
         if ($transPage) {
             Translatable::set_current_locale($transPage->Locale);
             return $this->owner->redirect(Controller::join_links($this->owner->Link('show'), $transPage->ID));
         } else {
             // If the record is not translated, redirect to pages overview
             return $this->owner->redirect(Controller::join_links(singleton('CMSPagesController')->Link(), '?locale=' . $requestLocale));
         }
     }
     // collect languages for TinyMCE spellchecker plugin.
     // see http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker
     $langName = i18n::get_locale_name($this->owner->Locale);
     HtmlEditorConfig::get('cms')->setOption('spellchecker_languages', "+{$langName}={$this->owner->Locale}");
     Requirements::javascript('translatable/javascript/CMSMain.Translatable.js');
     Requirements::css('translatable/css/CMSMain.Translatable.css');
 }
Example #26
0
 static function set_up_once()
 {
     // needs to recreate the database schema with language properties
     self::kill_temp_db();
     // store old defaults
     self::$origTranslatableSettings['has_extension'] = singleton('SiteTree')->hasExtension('Translatable');
     self::$origTranslatableSettings['default_locale'] = Translatable::default_locale();
     // overwrite locale
     Translatable::set_default_locale("en_US");
     // refresh the decorated statics - different fields in $db with Translatable enabled
     if (!self::$origTranslatableSettings['has_extension']) {
         Object::add_extension('SiteTree', 'Translatable');
     }
     Object::add_extension('TranslatableTest_DataObject', 'Translatable');
     // clear singletons, they're caching old extension info which is used in DatabaseAdmin->doBuild()
     global $_SINGLETONS;
     $_SINGLETONS = array();
     // recreate database with new settings
     $dbname = self::create_temp_db();
     DB::set_alternative_database_name($dbname);
     parent::set_up_once();
 }
 public function setUp()
 {
     parent::setUp();
     $this->origLocaleRoutingEnabled = Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL');
     Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', false);
     $this->origAcceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en-US,en;q=0.5';
     $this->origCookieLocale = Cookie::get('language');
     Cookie::force_expiry('language');
     Cookie::set('language', 'en');
     $this->origCurrentLocale = Translatable::get_current_locale();
     Translatable::set_current_locale('en_US');
     $this->origLocale = Translatable::default_locale();
     Translatable::set_default_locale('en_US');
     $this->origi18nLocale = i18n::get_locale();
     i18n::set_locale('en_US');
     $this->origAllowedLocales = Translatable::get_allowed_locales();
     Translatable::set_allowed_locales(array('en_US', 'fr_FR'));
     MultilingualTestController::add_extension('MultilingualControllerExtension');
     Config::inst()->update('Director', 'rules', array('$Language/multilingual-test-controller//$Action/$ID/$OtherID' => 'MultilingualTestController'));
     MultilingualRootURLController::reset();
 }
Example #28
0
 /**
  * Returns an absolute filesystem path to a static error file
  * which is generated through {@link publish()}.
  * 
  * @param int $statusCode A HTTP Statuscode, mostly 404 or 500
  * @param String $locale A locale, e.g. 'de_DE' (Optional)
  *
  * @return string
  */
 public static function get_filepath_for_errorcode($statusCode, $locale = null)
 {
     if (singleton('ErrorPage')->hasMethod('alternateFilepathForErrorcode')) {
         return singleton('ErrorPage')->alternateFilepathForErrorcode($statusCode, $locale);
     }
     if (class_exists('Translatable') && singleton('SiteTree')->hasExtension('Translatable') && $locale && $locale != Translatable::default_locale()) {
         return self::config()->static_filepath . "/error-{$statusCode}-{$locale}.html";
     } else {
         return self::config()->static_filepath . "/error-{$statusCode}.html";
     }
 }
	public function setUp() {
		parent::setUp();
		$this->translatableDefaultLocale = Translatable::default_locale();
		Translatable::set_default_locale('en_US');
	}
 /**
  * Collect all additional database fields of the given class.
  * @param string $class
  * @return array fieldnames that should be added
  */
 protected static function collectDBFields($class)
 {
     if (isset(self::$collectorCache[$class])) {
         return self::$collectorCache[$class];
     }
     if (isset(self::$collectorLock[$class]) && self::$collectorLock[$class]) {
         return null;
     }
     self::$collectorLock[$class] = true;
     // Get all DB Fields
     $fields = array();
     Config::inst()->get($class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $fields);
     // Get all arguments
     $arguments = self::get_arguments($class);
     $locales = self::get_target_locales();
     // remove the default locale
     if (($index = array_search(Translatable::default_locale(), $locales)) !== false) {
         array_splice($locales, $index, 1);
     }
     // fields that should be translated
     $fieldsToTranslate = array();
     // validate the arguments
     if ($arguments) {
         foreach ($arguments as $field) {
             // only allow fields that are actually in our field list
             if (array_key_exists($field, $fields)) {
                 $fieldsToTranslate[] = $field;
             }
         }
     } else {
         // check for the given default field types and add all fields of that type
         foreach ($fields as $field => $type) {
             $typeClean = ($p = strpos($type, '(')) !== false ? substr($type, 0, $p) : $type;
             $defaultFields = self::config()->default_field_types;
             if (is_array($defaultFields) && in_array($typeClean, $defaultFields)) {
                 $fieldsToTranslate[] = $field;
             }
         }
     }
     // gather all the DB fields
     $additionalFields = array();
     self::$localizedFields[$class] = array();
     foreach ($fieldsToTranslate as $field) {
         self::$localizedFields[$class][$field] = array();
         foreach ($locales as $locale) {
             $localizedName = self::localized_field($field, $locale);
             self::$localizedFields[$class][$field][] = $localizedName;
             $additionalFields[$localizedName] = $fields[$field];
         }
     }
     self::$collectorCache[$class] = $additionalFields;
     self::$collectorLock[$class] = false;
     return $additionalFields;
 }