/**
  * 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;
 }
 /**
  * Injects some custom javascript to provide instant loading of DataObject
  * tables.
  *
  * @return void
  *
  * @author Sebastian Diel <*****@*****.**>
  * @since 13.01.2011
  */
 public function onAfterInit()
 {
     Translatable::set_current_locale(i18n::get_locale());
     if (Director::is_ajax()) {
         return true;
     }
     Requirements::css('silvercart/admin/css/SilvercartMain.css');
 }
    public function getResults($pageLength = null, $data = null)
    {
        // legacy usage: $data was defaulting to $_REQUEST, parameter not passed in doc.silverstripe.org tutorials
        if (!isset($data) || !is_array($data)) {
            $data = $_REQUEST;
        }
        // set language (if present)
        if (class_exists('Translatable') && singleton('SiteTree')->hasExtension('Translatable') && isset($data['locale'])) {
            $origLocale = Translatable::get_current_locale();
            Translatable::set_current_locale($data['locale']);
        }
        $keywords = $data['Search'];
        $andProcessor = create_function('$matches', '
	 		return " +" . $matches[2] . " +" . $matches[4] . " ";
	 	');
        $notProcessor = create_function('$matches', '
	 		return " -" . $matches[3];
	 	');
        $keywords = preg_replace_callback('/()("[^()"]+")( and )("[^"()]+")()/i', $andProcessor, $keywords);
        $keywords = preg_replace_callback('/(^| )([^() ]+)( and )([^ ()]+)( |$)/i', $andProcessor, $keywords);
        $keywords = preg_replace_callback('/(^| )(not )("[^"()]+")/i', $notProcessor, $keywords);
        $keywords = preg_replace_callback('/(^| )(not )([^() ]+)( |$)/i', $notProcessor, $keywords);
        $keywords = $this->addStarsToKeywords($keywords);
        if (!$pageLength) {
            $pageLength = $this->pageLength;
        }
        $start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
        $siteFilter = '';
        $fileFilter = "ID != 0";
        $site = Multisites::inst()->getCurrentSite();
        $siteFilter = 'SiteID = ' . $site->ID;
        if ($this->config()->restrict_files_by_site) {
            if ($site->FolderID) {
                $prefix = $site->Folder()->Filename;
                if (strlen($prefix)) {
                    $fileFilter .= ' AND "Filename" LIKE \'' . Convert::raw2sql($prefix) . '%\'';
                }
            }
        }
        if (strpos($keywords, '"') !== false || strpos($keywords, '+') !== false || strpos($keywords, '-') !== false || strpos($keywords, '*') !== false) {
            $results = DB::getConn()->searchEngine($this->classesToSearch, $keywords, $start, $pageLength, "\"Relevance\" DESC", $siteFilter, true, $fileFilter);
        } else {
            $results = DB::getConn()->searchEngine($this->classesToSearch, $keywords, $start, $pageLength, '', $siteFilter, false, $fileFilter);
        }
        // filter by permission
        if ($results) {
            foreach ($results as $result) {
                if (!$result->canView()) {
                    $results->remove($result);
                }
            }
        }
        // reset locale
        if (class_exists('Translatable') && singleton('SiteTree')->hasExtension('Translatable') && isset($data['locale'])) {
            Translatable::set_current_locale($origLocale);
        }
        return $results;
    }
    public function getExtendedResults($pageLength = null, $sort = 'Relevance DESC', $filter = '', $data = null)
    {
        // legacy usage: $data was defaulting to $_REQUEST, parameter not passed in doc.silverstripe.org tutorials
        if (!isset($data) || !is_array($data)) {
            $data = $_REQUEST;
        }
        // set language (if present)
        if (class_exists('Translatable')) {
            if (singleton('SiteTree')->hasExtension('Translatable') && isset($data['searchlocale'])) {
                if ($data['searchlocale'] == "ALL") {
                    Translatable::disable_locale_filter();
                } else {
                    $origLocale = Translatable::get_current_locale();
                    Translatable::set_current_locale($data['searchlocale']);
                }
            }
        }
        $keywords = $data['Search'];
        $andProcessor = create_function('$matches', '
	 		return " +" . $matches[2] . " +" . $matches[4] . " ";
	 	');
        $notProcessor = create_function('$matches', '
	 		return " -" . $matches[3];
	 	');
        $keywords = preg_replace_callback('/()("[^()"]+")( and )("[^"()]+")()/i', $andProcessor, $keywords);
        $keywords = preg_replace_callback('/(^| )([^() ]+)( and )([^ ()]+)( |$)/i', $andProcessor, $keywords);
        $keywords = preg_replace_callback('/(^| )(not )("[^"()]+")/i', $notProcessor, $keywords);
        $keywords = preg_replace_callback('/(^| )(not )([^() ]+)( |$)/i', $notProcessor, $keywords);
        $keywords = $this->addStarsToKeywords($keywords);
        if (!$pageLength) {
            $pageLength = $this->owner->pageLength;
        }
        $start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
        if (strpos($keywords, '"') !== false || strpos($keywords, '+') !== false || strpos($keywords, '-') !== false || strpos($keywords, '*') !== false) {
            $results = DB::getConn()->searchEngine($this->owner->classesToSearch, $keywords, $start, $pageLength, $sort, $filter, true);
        } else {
            $results = DB::getConn()->searchEngine($this->owner->classesToSearch, $keywords, $start, $pageLength);
        }
        // filter by permission
        if ($results) {
            foreach ($results as $result) {
                if (!$result->canView()) {
                    $results->remove($result);
                }
            }
        }
        // reset locale
        if (class_exists('Translatable')) {
            if (singleton('SiteTree')->hasExtension('Translatable') && isset($data['searchlocale'])) {
                if ($data['searchlocale'] == "ALL") {
                    Translatable::enable_locale_filter();
                } else {
                    Translatable::set_current_locale($origLocale);
                }
            }
        }
        return $results;
    }
 /**
  * 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 updateEditForm(Form $form)
 {
     $locale = isset($_REQUEST['locale']) ? $_REQUEST['locale'] : $_REQUEST['Locale'];
     if (!empty($locale) && i18n::validate_locale($locale) && singleton('SiteConfig')->has_extension('Translatable') && (Translatable::get_allowed_locales() === null || in_array($locale, (array) Translatable::get_allowed_locales(), false)) && $locale != Translatable::get_current_locale()) {
         $orig = Translatable::get_current_locale();
         Translatable::set_current_locale($locale);
         $formAction = $form->FormAction();
         $form->setFormAction($formAction);
         Translatable::set_current_locale($orig);
     }
 }
 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');
 }
 static function tear_down_once()
 {
     if (self::$origTranslatableSettings['has_extension']) {
         Object::add_extension('SiteTree', 'Translatable');
         Object::add_extension('SiteConfig', 'Translatable');
     }
     Translatable::set_default_locale(self::$origTranslatableSettings['default_locale']);
     Translatable::set_current_locale(self::$origTranslatableSettings['default_locale']);
     self::kill_temp_db();
     self::create_temp_db();
     parent::tear_down_once();
 }
Example #9
0
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $boxes = array();
     if ($this->hasExtension('Translatable')) {
         $fields->removeByName('Locale');
         $fields->insertBefore(new LanguageDropdownField('Locale', _t('CMSMain.LANGUAGEDROPDOWNLABEL', 'Language'), array(), 'SiteTree', 'Locale-English', singleton('SiteTree')), 'Title');
         $fields->removeByName('Translations');
         Translatable::set_current_locale($this->Locale);
     }
     foreach (ClassInfo::getValidSubClasses('PromoBox') as $boxClass) {
         if ($boxClass != 'PromoBox') {
             $instance = singleton($boxClass);
             $boxes[$boxClass] = $instance->i18n_singular_name();
         }
     }
     $fields->addFieldToTab('Root.Main', new DropdownField('ClassName', 'Type (save after changing this to see fields)', $boxes, 'ImagePromoBox'));
     $fields->removeByName('Pages');
     return $fields;
 }
 public function getNestedController()
 {
     if ($this->urlParams['URLSegment']) {
         $SQL_URLSegment = Convert::raw2sql($this->urlParams['URLSegment']);
         $child = SiteTree::get_by_url($SQL_URLSegment);
         if (!$child) {
             if ($child = $this->findOldPage($SQL_URLSegment)) {
                 $url = Controller::join_links(Director::baseURL(), $child->URLSegment, isset($this->urlParams['Action']) ? $this->urlParams['Action'] : null, isset($this->urlParams['ID']) ? $this->urlParams['ID'] : null, isset($this->urlParams['OtherID']) ? $this->urlParams['OtherID'] : null);
                 $response = new HTTPResponse();
                 $response->redirect($url, 301);
                 return $response;
             }
             $child = $this->get404Page();
         }
         if ($child) {
             if (isset($_REQUEST['debug'])) {
                 Debug::message("Using record #{$child->ID} of type {$child->class} with URL {$this->urlParams['URLSegment']}");
             }
             // set language
             if ($child->Locale) {
                 Translatable::set_current_locale($child->Locale);
             }
             $controllerClass = "{$child->class}_Controller";
             if ($this->urlParams['Action'] && ClassInfo::exists($controllerClass . '_' . $this->urlParams['Action'])) {
                 $controllerClass = $controllerClass . '_' . $this->urlParams['Action'];
             }
             if (ClassInfo::exists($controllerClass)) {
                 $controller = new $controllerClass($child);
             } else {
                 $controller = $child;
             }
             return $controller;
         } else {
             return new HTTPResponse("The requested page couldn't be found.", 404);
         }
     } else {
         user_error("ModelAsController not geting a URLSegment.  It looks like the site isn't redirecting to home", E_USER_ERROR);
     }
 }
 /**
  * Create a new translation from an existing item, switch to this language and reload the tree.
  */
 function createtranslation($data, $form)
 {
     $request = $this->owner->getRequest();
     // Protect against CSRF on destructive action
     if (!SecurityToken::inst()->checkRequest($request)) {
         return $this->owner->httpError(400);
     }
     $langCode = Convert::raw2sql($request->postVar('NewTransLang'));
     $record = $this->owner->getRecord($request->postVar('ID'));
     if (!$record) {
         return $this->httpError(404);
     }
     $this->owner->Locale = $langCode;
     Translatable::set_current_locale($langCode);
     // Create a new record in the database - this is different
     // to the usual "create page" pattern of storing the record
     // in-memory until a "save" is performed by the user, mainly
     // to simplify things a bit.
     // @todo Allow in-memory creation of translations that don't persist in the database before the user requests it
     $translatedRecord = $record->createTranslation($langCode);
     $url = sprintf("%s/%d/?locale=%s", singleton('CMSPageEditController')->Link('show'), $translatedRecord->ID, $langCode);
     return $this->owner->redirect($url);
 }
 /**
  * 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);
 }
Example #13
0
 function testSavePageInCMS()
 {
     $adminUser = $this->objFromFixture('Member', 'admin');
     $enPage = $this->objFromFixture('Page', 'testpage_en');
     $group = new Group();
     $group->Title = 'Example Group';
     $group->write();
     $frPage = $enPage->createTranslation('fr_FR');
     $frPage->write();
     $adminUser->logIn();
     $cmsMain = new CMSMain();
     $origLocale = Translatable::get_current_locale();
     Translatable::set_current_locale('fr_FR');
     $form = $cmsMain->getEditForm($frPage->ID);
     $form->loadDataFrom(array('Title' => 'Translated', 'ViewerGroups' => $group->ID));
     $form->saveInto($frPage);
     $frPage->write();
     $this->assertEquals('Translated', $frPage->Title);
     $this->assertEquals(array($group->ID), $frPage->ViewerGroups()->column('ID'));
     $adminUser->logOut();
     Translatable::set_current_locale($origLocale);
 }
 public function onBeforeHandleAction(SS_HTTPRequest $request, $action)
 {
     if ($locale = $request->getVar('Locale')) {
         Translatable::set_current_locale($locale);
     }
 }
 /**
  * Create a new translation from an existing item, switch to this language and reload the tree.
  */
 function createtranslation($data, $form)
 {
     $request = $this->owner->getRequest();
     // Protect against CSRF on destructive action
     if (!SecurityToken::inst()->checkRequest($request)) {
         return $this->owner->httpError(400);
     }
     $langCode = Convert::raw2sql($request->postVar('NewTransLang'));
     $record = $this->owner->getRecord($request->postVar('ID'));
     if (!$record) {
         return $this->owner->httpError(404);
     }
     $this->owner->Locale = $langCode;
     Translatable::set_current_locale($langCode);
     // Create a new record in the database - this is different
     // to the usual "create page" pattern of storing the record
     // in-memory until a "save" is performed by the user, mainly
     // to simplify things a bit.
     // @todo Allow in-memory creation of translations that don't
     // persist in the database before the user requests it
     $translatedRecord = $record->createTranslation($langCode);
     $url = Controller::join_links($this->owner->Link('show'), $translatedRecord->ID);
     // set the X-Pjax header to Content, so that the whole admin panel will be refreshed
     $this->owner->getResponse()->addHeader('X-Pjax', 'Content');
     return $this->owner->redirect($url);
 }
Example #16
0
 /**
  * Get a singleton instance of a class in the given language.
  * @param string $class The name of the class.
  * @param string $locale  The name of the language.
  * @param string $filter A filter to be inserted into the WHERE clause.
  * @param boolean $cache Use caching (default: false)
  * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
  * @return DataObject
  */
 static function get_one_by_locale($class, $locale, $filter = '', $cache = false, $orderby = "")
 {
     if ($locale && !i18n::validate_locale($locale)) {
         throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
     }
     $orig = Translatable::get_current_locale();
     Translatable::set_current_locale($locale);
     $do = DataObject::get_one($class, $filter, $cache, $orderby);
     Translatable::set_current_locale($orig);
     return $do;
 }
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = null)
 {
     self::$is_at_root = true;
     $this->setDataModel($model);
     $this->pushCurrent();
     $this->init();
     if ($language = $request->param('Language')) {
         if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) {
             if (Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) {
                 //Language is missing a dash 404
                 if (strpos($language, '-') === false) {
                     //Locale not found 404
                     if ($response = ErrorPage::response_for(404)) {
                         return $response;
                     } else {
                         $this->httpError(404, 'The requested page could not be found.');
                     }
                     return $this->response;
                 }
                 $locale = explode('-', $language);
                 $locale[1] = strtoupper($locale[1]);
                 //Make sure that the language is all lowercase
                 if ($language == implode('-', $locale)) {
                     //Locale not found 404
                     if ($response = ErrorPage::response_for(404)) {
                         return $response;
                     } else {
                         $this->httpError(404, 'The requested page could not be found.');
                     }
                     return $this->response;
                 }
                 $locale = implode('_', $locale);
             } else {
                 $locale = $language;
             }
         } else {
             if (strpos($request->param('Language'), '_') !== false) {
                 //Locale not found 404
                 if ($response = ErrorPage::response_for(404)) {
                     return $response;
                 } else {
                     $this->httpError(404, 'The requested page could not be found.');
                 }
                 return $this->response;
             } else {
                 $locale = i18n::get_locale_from_lang($language);
             }
         }
         if (in_array($locale, Translatable::get_allowed_locales())) {
             Cookie::set('language', $language);
             Translatable::set_current_locale($locale);
             i18n::set_locale($locale);
             if (!DB::isActive() || !ClassInfo::hasTable('SiteTree')) {
                 $this->response = new SS_HTTPResponse();
                 $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
                 return $this->response;
             }
             $request->setUrl($language . '/' . self::get_homepage_link() . '/');
             $request->match('$Language/$URLSegment//$Action', true);
             $controller = new MultilingualModelAsController();
             $result = $controller->handleRequest($request, $model);
             $this->popCurrent();
             return $result;
         } else {
             //URL Param Locale is not allowed so redirect to default
             $this->redirect(Controller::join_links(Director::baseURL(), Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL') ? Translatable::default_locale() : Translatable::default_lang()) . '/', 301);
             $this->popCurrent();
             return $this->response;
         }
     }
     //No Locale Param so detect browser language and redirect
     if ($locale = self::detect_browser_locale()) {
         if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) {
             if (Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) {
                 $language = str_replace('_', '-', strtolower($locale));
             } else {
                 $language = $locale;
             }
         } else {
             $language = i18n::get_lang_from_locale($locale);
         }
         Cookie::set('language', $language);
         $this->redirect(Controller::join_links(Director::baseURL(), $language) . '/', 301);
         $this->popCurrent();
         return $this->response;
     }
     if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) {
         if (Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) {
             $language = str_replace('_', '-', strtolower(Translatable::default_locale()));
         } else {
             $language = Translatable::default_locale();
         }
     } else {
         $language = Translatable::default_lang();
     }
     $this->redirect(Controller::join_links(Director::baseURL(), $language . '/'), 301);
     $this->popCurrent();
     return $this->response;
 }
 /**
  * Create a new translation from an existing item, switch to this language and reload the tree.
  */
 function createtranslation($request)
 {
     $langCode = Convert::raw2sql($request->getVar('newlang'));
     $originalLangID = (int) $request->getVar('ID');
     $record = $this->getRecord($originalLangID);
     $this->Locale = $langCode;
     Translatable::set_current_locale($langCode);
     // Create a new record in the database - this is different
     // to the usual "create page" pattern of storing the record
     // in-memory until a "save" is performed by the user, mainly
     // to simplify things a bit.
     // @todo Allow in-memory creation of translations that don't persist in the database before the user requests it
     $translatedRecord = $record->createTranslation($langCode);
     $url = sprintf("%s/%d/?locale=%s", $this->Link('show'), $translatedRecord->ID, $langCode);
     return Director::redirect($url);
 }
 /**
  * @return ContentController
  */
 public function getNestedController()
 {
     $request = $this->request;
     if (!($URLSegment = $request->param('URLSegment'))) {
         throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.');
     }
     // Find page by link, regardless of current locale settings
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     $sitetree = DataObject::get_one('SiteTree', sprintf('"SiteTree"."URLSegment" = \'%s\' %s', Convert::raw2sql(rawurlencode($URLSegment)), SiteTree::config()->nested_urls ? 'AND "SiteTree"."ParentID" = 0' : null));
     if (class_exists('Translatable')) {
         Translatable::enable_locale_filter();
     }
     if (!$sitetree) {
         $response = ErrorPage::response_for(404);
         $this->httpError(404, $response ? $response : 'The requested page could not be found.');
     }
     // Enforce current locale setting to the loaded SiteTree object
     if (class_exists('Translatable') && $sitetree->Locale) {
         Translatable::set_current_locale($sitetree->Locale);
     }
     if (isset($_REQUEST['debug'])) {
         Debug::message("Using record #{$sitetree->ID} of type {$sitetree->class} with link {$sitetree->Link()}");
     }
     return self::controller_for($sitetree, $this->request->param('Action'));
 }
 /**
  * @return ContentController
  */
 public function getNestedController()
 {
     $request = $this->request;
     if (!($URLSegment = $request->param('URLSegment'))) {
         throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.');
     }
     // Find page by link, regardless of current locale settings
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     $sitetree = DataObject::get_one('SiteTree', sprintf('"URLSegment" = \'%s\' %s', Convert::raw2sql(rawurlencode($URLSegment)), SiteTree::nested_urls() ? 'AND "ParentID" = 0' : null));
     if (class_exists('Translatable')) {
         Translatable::enable_locale_filter();
     }
     if (!$sitetree) {
         // If a root page has been renamed, redirect to the new location.
         // See ContentController->handleRequest() for similiar logic.
         $redirect = self::find_old_page($URLSegment);
         if ($redirect) {
             $params = $request->getVars();
             if (isset($params['url'])) {
                 unset($params['url']);
             }
             $this->response = new SS_HTTPResponse();
             $this->response->redirect(Controller::join_links($redirect->Link(Controller::join_links($request->param('Action'), $request->param('ID'), $request->param('OtherID'))), $params ? '?' . http_build_query($params) : null), 301);
             return $this->response;
         }
         if ($response = ErrorPage::response_for(404)) {
             return $response;
         } else {
             $this->httpError(404, 'The requested page could not be found.');
         }
     }
     // Enforce current locale setting to the loaded SiteTree object
     if (class_exists('Translatable') && $sitetree->Locale) {
         Translatable::set_current_locale($sitetree->Locale);
     }
     if (isset($_REQUEST['debug'])) {
         Debug::message("Using record #{$sitetree->ID} of type {$sitetree->class} with link {$sitetree->Link()}");
     }
     return self::controller_for($sitetree, $this->request->param('Action'));
 }
 /**
  * Create a new translation from an existing item, switch to this language and reload the tree.
  */
 function createtranslation($request)
 {
     // Protect against CSRF on destructive action
     if (!SecurityToken::inst()->checkRequest($request)) {
         return $this->httpError(400);
     }
     $langCode = Convert::raw2sql($_REQUEST['newlang']);
     $originalLangID = (int) $_REQUEST['ID'];
     $record = $this->getRecord($originalLangID);
     $this->Locale = $langCode;
     Translatable::set_current_locale($langCode);
     // Create a new record in the database - this is different
     // to the usual "create page" pattern of storing the record
     // in-memory until a "save" is performed by the user, mainly
     // to simplify things a bit.
     // @todo Allow in-memory creation of translations that don't persist in the database before the user requests it
     $translatedRecord = $record->createTranslation($langCode);
     $url = sprintf("%s/%d/?locale=%s", $this->Link('show'), $translatedRecord->ID, $langCode);
     FormResponse::add(sprintf('window.location.href = "%s";', $url));
     return FormResponse::respond();
 }
 /**
  * Verifies the correct home page is detected for the french locale
  */
 public function testFrenchGetHomepageLink()
 {
     //Set accept language to french
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr-FR,fr;q=0.5';
     Translatable::set_default_locale('fr_FR');
     Translatable::set_current_locale('fr_FR');
     i18n::set_locale('fr_FR');
     $this->assertEquals('maison', MultilingualRootURLController::get_homepage_link());
 }
 /**
  * Tests to see if the controller responds correctly if the language is in the url
  */
 public function testAutoDetectLanguage()
 {
     //Set accept language to french
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr-FR,fr;q=0.5';
     Translatable::set_default_locale('fr_FR');
     Translatable::set_current_locale('fr_FR');
     i18n::set_locale('fr_FR');
     //Perform Request
     $response = $this->get('MultilingualTestController');
     //Ensure a 200 response
     $this->assertEquals(200, $response->getStatusCode());
     //Verify the response matches what is expected
     $this->assertEquals('i18n: fr_FR|Translatable: fr_FR', $response->getBody());
 }
 public function testAlternateGetByLink()
 {
     $parent = $this->objFromFixture('Page', 'parent');
     $child = $this->objFromFixture('Page', 'child1');
     $grandchild = $this->objFromFixture('Page', 'grandchild1');
     $parentTranslation = $parent->createTranslation('en_AU');
     $parentTranslation->write();
     $childTranslation = $child->createTranslation('en_AU');
     $childTranslation->write();
     $grandchildTranslation = $grandchild->createTranslation('en_AU');
     $grandchildTranslation->write();
     Translatable::set_current_locale('en_AU');
     $this->assertEquals($parentTranslation->ID, Sitetree::get_by_link($parentTranslation->Link())->ID, 'Top level pages can be found.');
     $this->assertEquals($childTranslation->ID, SiteTree::get_by_link($childTranslation->Link())->ID, 'Child pages can be found.');
     $this->assertEquals($grandchildTranslation->ID, SiteTree::get_by_link($grandchildTranslation->Link())->ID, 'Grandchild pages can be found.');
     // TODO Re-enable test after clarifying with ajshort (see r88503).
     // Its unclear if this is valid behaviour, and/or necessary for translated nested URLs
     // to work properly
     //
     // $this->assertEquals (
     // 	$child->ID,
     // 	SiteTree::get_by_link($parentTranslation->Link($child->URLSegment))->ID,
     // 	'Links can be made up of multiple languages'
     // );
 }
 /**
  * Tests to see if the french home page is the root url and the english home page is not for french browsers
  */
 public function testFrenchShouldBeRoot()
 {
     //Set accept language to french
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr-FR,fr;q=0.5';
     Translatable::set_default_locale('fr_FR');
     Translatable::set_current_locale('fr_FR');
     i18n::set_locale('fr_FR');
     $default = $this->objFromFixture('Page', 'home');
     $defaultFR = $this->objFromFixture('Page', 'home_fr');
     $this->assertEquals(false, MultilingualRootURLController::should_be_on_root($default));
     $this->assertEquals(true, MultilingualRootURLController::should_be_on_root($defaultFR));
 }
 /**
  * Get a singleton instance of a class in the given language.
  * @param string $class The name of the class.
  * @param string $locale  The name of the language.
  * @param string $filter A filter to be inserted into the WHERE clause.
  * @param boolean $cache Use caching (default: false)
  * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
  * @return DataObject
  */
 public static function get_one_by_locale($class, $locale, $filter = '', $cache = false, $orderby = "")
 {
     if ($locale && !i18n::validate_locale($locale)) {
         throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
     }
     $orig = Translatable::get_current_locale();
     Translatable::set_current_locale($locale);
     $do = $class::get()->where($filter)->where(sprintf('"Locale" = \'%s\'', Convert::raw2sql($locale)))->sort($orderby)->First();
     Translatable::set_current_locale($orig);
     return $do;
 }
 function run($request)
 {
     $ids = array();
     echo "#################################\n";
     echo "# Adding translation groups to existing records" . "\n";
     echo "#################################\n";
     $allSiteTreeIDs = DB::query('SELECT `ID` FROM `SiteTree`')->column();
     if ($allSiteTreeIDs) {
         foreach ($allSiteTreeIDs as $id) {
             $original = DataObject::get_by_id('SiteTree', $id);
             $existingGroupID = $original->getTranslationGroup();
             if (!$existingGroupID) {
                 $original->addTranslationGroup($original->ID);
             }
             $original->destroy();
             unset($original);
         }
     }
     DataObject::flush_and_destroy_cache();
     echo sprintf("Created translation groups for %d records\n", count($allSiteTreeIDs));
     foreach (array('Stage', 'Live') as $stage) {
         echo "\n\n#################################\n";
         echo "# Migrating stage {$stage}" . "\n";
         echo "#################################\n";
         $suffix = $stage == 'Live' ? '_Live' : '';
         // First get all entries in SiteTree_lang
         // This should be all translated pages
         $trans = DB::query(sprintf('SELECT * FROM `_obsolete_SiteTree_lang%s`', $suffix));
         // Iterate over each translated pages
         foreach ($trans as $oldtrans) {
             $newLocale = i18n::get_locale_from_lang($oldtrans['Lang']);
             echo sprintf("Migrating from %s to %s translation of '%s' (#%d)\n", $oldtrans['Lang'], $newLocale, Convert::raw2xml($oldtrans['Title']), $oldtrans['OriginalLangID']);
             // Get the untranslated page
             $original = Versioned::get_one_by_stage($oldtrans['ClassName'], $stage, '`SiteTree`.`ID` = ' . $oldtrans['OriginalLangID']);
             if (!$original) {
                 echo sprintf("Couldn't find original for #%d", $oldtrans['OriginalLangID']);
                 continue;
             }
             // write locale to $original
             $original->Locale = i18n::get_locale_from_lang(Translatable::default_lang());
             $original->writeToStage($stage);
             // Clone the original, and set it up as a translation
             $existingTrans = $original->getTranslation($newLocale, $stage);
             if ($existingTrans) {
                 echo sprintf("Found existing new-style translation for #%d. Already merged? Skipping.\n", $oldtrans['OriginalLangID']);
                 continue;
             }
             // Doesn't work with stage/live split
             //$newtrans = $original->createTranslation($newLocale);
             $newtrans = $original->duplicate(false);
             $newtrans->OriginalID = $original->ID;
             // we have to "guess" a locale based on the language
             $newtrans->Locale = $newLocale;
             if ($stage == 'Live' && array_key_exists($original->ID, $ids)) {
                 $newtrans->ID = $ids[$original->ID];
             }
             // Look at each class in the ancestry, and see if there is a _lang table for it
             foreach (ClassInfo::ancestry($oldtrans['ClassName']) as $classname) {
                 $oldtransitem = false;
                 // If the class is SiteTree, we already have the DB record, else check for the table and get the record
                 if ($classname == 'SiteTree') {
                     $oldtransitem = $oldtrans;
                 } elseif (in_array(strtolower($classname) . '_lang', DB::tableList())) {
                     $oldtransitem = DB::query(sprintf('SELECT * FROM `_obsolete_%s_lang%s` WHERE `OriginalLangID` = %d AND `Lang` = \'%s\'', $classname, $suffix, $original->ID, $oldtrans['Lang']))->first();
                 }
                 // Copy each translated field into the new translation
                 if ($oldtransitem) {
                     foreach ($oldtransitem as $key => $value) {
                         if (!in_array($key, array('ID', 'OriginalLangID'))) {
                             $newtrans->{$key} = $value;
                         }
                     }
                 }
             }
             // Write the new translation to the database
             $sitelang = Translatable::get_current_locale();
             Translatable::set_current_locale($newtrans->Locale);
             $newtrans->writeToStage($stage);
             Translatable::set_current_locale($sitelang);
             $newtrans->addTranslationGroup($original->getTranslationGroup(), true);
             if ($stage == 'Stage') {
                 $ids[$original->ID] = $newtrans->ID;
             }
         }
     }
     echo "\n\n#################################\n";
     echo "Done!\n";
 }
 /**
  * Test conversion of a url's locale to a TLD
  * (make sure a german page shows with a .de extension)
  */
 function testConvertURLLocaleToTLD()
 {
     $orig_locale = Translatable::get_current_locale();
     Translatable::set_current_locale('en_US');
     $url = "http://www.mysite.co.uk:8888/home/";
     $expectedResult = "mysite.com";
     $newURL = TranslatableDomains::setDomainByPageLocale($url);
     $newURLTLD = TranslatableDomains::getTLD($newURL);
     $this->assertTrue($newURLTLD == $expectedResult, "Failed converting {$url} to {$expectedResult}");
     Translatable::set_current_locale('de_DE');
     $url = "http://mysite.com/home-de/";
     $expectedResult = "another.de";
     $newURL = TranslatableDomains::setDomainByPageLocale($url);
     $newURLTLD = TranslatableDomains::getTLD($newURL);
     $this->assertTrue($newURLTLD == $expectedResult, "Failed converting {$url} to {$expectedResult}");
     Translatable::set_current_locale('en_GB');
     $url = "http://sub.sub.mysite.com/home-gb/";
     $expectedResult = "mysite.co.uk";
     $newURL = TranslatableDomains::setDomainByPageLocale($url);
     $newURLTLD = TranslatableDomains::getTLD($newURL);
     $this->assertTrue($newURLTLD == $expectedResult, "Failed converting {$url} to {$expectedResult}");
     Translatable::set_current_locale('fr_FR');
     $url = "http://sub.localhost-jp/home-fr/";
     $expectedResult = "localhost-fr";
     $newURL = TranslatableDomains::setDomainByPageLocale($url);
     $newURLTLD = TranslatableDomains::getTLD($newURL);
     $this->assertTrue($newURLTLD == $expectedResult, "Failed converting {$url} to {$expectedResult}");
     Translatable::set_current_locale('ja_JP');
     $url = "http://localhost-jp:8888/home-jp/";
     $expectedResult = "localhost-jp";
     $newURL = TranslatableDomains::setDomainByPageLocale($url);
     $newURLTLD = TranslatableDomains::getTLD($newURL);
     $this->assertTrue($newURLTLD == $expectedResult, "Failed converting {$url} to {$expectedResult}");
     Translatable::set_current_locale($orig_locale);
 }
 /**
  * @return ContentController
  * @throws Exception If URLSegment not passed in as a request parameter.
  */
 public function getNestedController()
 {
     $request = $this->getRequest();
     if (!($URLSegment = $request->param('URLSegment'))) {
         throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.');
     }
     // Find page by link, regardless of current locale settings
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     // Select child page
     $conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
     if (SiteTree::config()->nested_urls) {
         $conditions[] = array('"SiteTree"."ParentID"' => 0);
     }
     $sitetree = DataObject::get_one('SiteTree', $conditions);
     // Check translation module
     // @todo Refactor out module specific code
     if (class_exists('Translatable')) {
         Translatable::enable_locale_filter();
     }
     if (!$sitetree) {
         $response = ErrorPage::response_for(404);
         $this->httpError(404, $response ? $response : 'The requested page could not be found.');
     }
     // Enforce current locale setting to the loaded SiteTree object
     if (class_exists('Translatable') && $sitetree->Locale) {
         Translatable::set_current_locale($sitetree->Locale);
     }
     if (isset($_REQUEST['debug'])) {
         Debug::message("Using record #{$sitetree->ID} of type {$sitetree->class} with link {$sitetree->Link()}");
     }
     return self::controller_for($sitetree, $this->getRequest()->param('Action'));
 }
Example #30
0
 /**
  * Get a singleton instance of a class in the given language.
  * @param string $class The name of the class.
  * @param string $locale  The name of the language.
  * @param string $filter A filter to be inserted into the WHERE clause.
  * @param boolean $cache Use caching (default: false)
  * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
  * @return DataObject
  */
 static function get_one_by_locale($class, $locale, $filter = '', $cache = false, $orderby = "")
 {
     $orig = Translatable::get_current_locale();
     Translatable::set_current_locale($locale);
     $do = DataObject::get_one($class, $filter, $cache, $orderby);
     Translatable::set_current_locale($orig);
     return $do;
 }