Example #1
0
 private function merge(\Gettext_Translations $current, Translatable $parent, $locale)
 {
     $parent_loader = $parent->loadExisting($locale);
     $comment = "Copied from {$parent->id}/{$locale}";
     foreach ($current->entries as $entry_id => &$entry) {
         if (isset($parent_loader->entries[$entry_id]) && (empty($entry->translations) || $entry->translator_comments == $comment)) {
             if ($translations = $parent_loader->entries[$entry_id]->translations) {
                 $entry->translator_comments = $comment;
                 $entry->translations = $translations;
             }
         }
     }
 }
 /**
  * Create a new LanguageDropdownField
  * @param string $name
  * @param string $title
  * @param array $dontInclude list of languages 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
  */
 function __construct($name, $title, $dontInclude = array(), $translatingClass = 'SiteTree', $list = 'Common-English')
 {
     $usedlangs = array_diff(i18n::get_existing_content_languages($translatingClass), $dontInclude);
     // we accept in dontInclude both language codes and names, so another diff is required
     $usedlangs = array_diff($usedlangs, array_flip($dontInclude));
     if (isset($usedlangs[Translatable::default_lang()])) {
         unset($usedlangs[Translatable::default_lang()]);
     }
     if ('Common-English' == $list) {
         $languageList = i18n::get_common_languages();
     } else {
         if ('Common-Native' == $list) {
             $languageList = i18n::get_common_languages(true);
         } else {
             $languageList = i18n::get_locale_list();
         }
     }
     $alllangs = array_diff($languageList, (array) $usedlangs, $dontInclude);
     $alllangs = array_flip(array_diff(array_flip($alllangs), $dontInclude));
     if (isset($alllangs[Translatable::default_lang()])) {
         unset($alllangs[Translatable::default_lang()]);
     }
     asort($alllangs);
     if (count($usedlangs)) {
         asort($usedlangs);
         $labelAvail = _t('Form.LANGAVAIL', "Available languages");
         $labelOther = _t('Form.LANGAOTHER', "Other languages");
         parent::__construct($name, $title, array($labelAvail => $usedlangs, $labelOther => $alllangs), reset($usedlangs));
     } else {
         parent::__construct($name, $title, $alllangs);
     }
 }
 /**
  * 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;
 }
 /**
  * Initiate the standard Metadata catalogue search form. The 
  * additional parameter $defaults defines the default values for the form.
  * 
  * @param Controller $controller The parent controller, necessary to create the appropriate form action tag.
  * @param String $name The method on the controller that will return this form object.
  * @param FieldSet $fields All of the fields in the form - a {@link FieldSet} of {@link FormField} objects.
  * @param FieldSet $actions All of the action buttons in the form - a {@link FieldSet} of {@link FormAction} objects
  * @param Validator $validator Override the default validator instance (Default: {@link RequiredFields})
  * @param Array $defaults Override the default values of the form.		 
  */
 function __construct($controller, $name, FieldSet $fields = null, FieldSet $actions = null, $validator = null, $defaults = null)
 {
     $format = $defaults['format'];
     $searchTerm = $defaults['searchTerm'];
     $bboxUpper = $bboxLower = null;
     if (isset($defaults['bboxUpper']) && isset($defaults['bboxLower'])) {
         $bboxUpper = $defaults['bboxUpper'];
         $bboxLower = $defaults['bboxLower'];
     }
     $values = CataloguePage_Controller::get_standard_names();
     $upperField = new HiddenField('bboxUpper', _t('SearchForm.SEARCH', 'bboxUpper'), $bboxUpper);
     $upperField->addExtraClass('upper');
     $lowerField = new HiddenField('bboxLower', _t('SearchForm.SEARCH', 'bboxLower'), $bboxLower);
     $lowerField->addExtraClass('lower');
     if (!$fields) {
         $fields = new FieldSet(new TextField('searchTerm', _t('SearchForm.SEARCH', 'Search'), $searchTerm), $upperField, $lowerField, new OptionsetField('format', _t('SearchForm.MetadataStandard', 'Metadata Standard'), $values, $format));
     }
     if (singleton('SiteTree')->hasExtension('Translatable')) {
         $fields->push(new HiddenField('locale', 'locale', Translatable::get_current_locale()));
     }
     if (!$actions) {
         $actions = new FieldSet(new FormAction("submit", _t('SearchForm.Search', 'Search')));
     }
     parent::__construct($controller, $name, $fields, $actions);
     $this->setFormMethod('get');
 }
 public function init()
 {
     // set reading lang
     if (SiteTree::has_extension('Translatable') && !$this->getRequest()->isAjax()) {
         Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree')));
     }
     parent::init();
     Versioned::reading_stage("Stage");
     Requirements::css(CMS_DIR . '/css/screen.css');
     Requirements::customCSS($this->generatePageIconsCss());
     Requirements::combine_files('cmsmain.js', array_merge(array(CMS_DIR . '/javascript/CMSMain.js', CMS_DIR . '/javascript/CMSMain.EditForm.js', CMS_DIR . '/javascript/CMSMain.AddForm.js', CMS_DIR . '/javascript/CMSPageHistoryController.js', CMS_DIR . '/javascript/CMSMain.Tree.js', CMS_DIR . '/javascript/SilverStripeNavigator.js', CMS_DIR . '/javascript/SiteTreeURLSegmentField.js'), Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang', true, true)));
     CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish');
     CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish');
     // Check legacy actions
     $legacy = $this->config()->enabled_legacy_actions;
     // Delete from live is unnecessary since we have unpublish which does the same thing
     if (in_array('CMSBatchAction_DeleteFromLive', $legacy)) {
         Deprecation::notice('4.0', 'Delete From Live is deprecated. Use Un-publish instead');
         CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive');
     }
     // Delete action
     if (in_array('CMSBatchAction_Delete', $legacy)) {
         Deprecation::notice('4.0', 'Delete from Stage is deprecated. Use Archive instead.');
         CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete');
     } else {
         CMSBatchActionHandler::register('archive', 'CMSBatchAction_Archive');
         CMSBatchActionHandler::register('restore', 'CMSBatchAction_Restore');
     }
 }
 /**
  * Returns a DataList containing Pages.
  * The provided links point to their translated pages.
  * You can use it in templates like this:
  *
  * <% loop LanguageChooser %>
  *   $Title, $Current, and any other vars in your page instance
  * <% end_loop %>
  *
  * @return DataList
  */
 public function LanguageChooser()
 {
     if (!Controller::curr()) {
         return;
     }
     if ($langs = Translatable::get_allowed_locales()) {
         $data = ArrayList::create();
         foreach ($langs as $key => $code) {
             if ($code == Translatable::get_current_locale()) {
                 $this->owner->Current = 'current';
                 $data->push($this->owner);
             } else {
                 $translation = $this->owner->getTranslation($code);
                 if ($translation) {
                     $data->push($translation);
                 } else {
                     $page = Translatable::get_one_by_locale("SiteTree", $code, "URLSegment LIKE 'home%'");
                     if ($page) {
                         $data->push($page);
                     }
                 }
             }
         }
         return $data;
     }
     return false;
 }
 function run(SS_List $pages)
 {
     $status = array('translated' => array(), 'error' => array());
     foreach ($pages as $page) {
         $id = $page->ID;
         foreach (Translatable::get_allowed_locales() as $locale) {
             if ($page->Locale == $locale) {
                 continue;
             }
             if (!$page->hasTranslation($locale)) {
                 try {
                     $translation = $page->createTranslation($locale);
                     $successMessage = $this->duplicateRelations($page, $translation);
                     $status['translated'][$translation->ID] = array('TreeTitle' => $translation->TreeTitle);
                     $translation->destroy();
                     unset($translation);
                 } catch (Exception $e) {
                     // no permission - fail gracefully
                     $status['error'][$page->ID] = true;
                 }
             }
         }
         $page->destroy();
         unset($page);
     }
     return $this->response(_t('CMSBatchActions.TRANSLATED_PAGES', 'Translated %d pages to draft site, %d failures'), $status);
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
Example #10
0
	public function init() {
		// set reading lang
		if(Object::has_extension('SiteTree', 'Translatable') && !$this->request->isAjax()) {
			Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree')));
		}
		
		parent::init();
		
		Requirements::css(CMS_DIR . '/css/screen.css');
		
		Requirements::combine_files(
			'cmsmain.js',
			array_merge(
				array(
					CMS_DIR . '/javascript/CMSMain.js',
					CMS_DIR . '/javascript/CMSMain.EditForm.js',
					CMS_DIR . '/javascript/CMSMain.AddForm.js',
					CMS_DIR . '/javascript/CMSPageHistoryController.js',
					CMS_DIR . '/javascript/CMSMain.Tree.js',
					CMS_DIR . '/javascript/SilverStripeNavigator.js'
				),
				Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang', true, true)
			)
		);

		CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish');
		CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish');
		CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete');
		CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive');
	}
	function testUpdateCMSFieldsOnSiteTree() {
		$pageOrigLang = $this->objFromFixture('Page', 'home');
		
		// first test with default language
		$fields = $pageOrigLang->getCMSFields();
		$this->assertType(
			'TextField', 
			$fields->dataFieldByName('Title'),
			'Translatable doesnt modify fields if called in default language (e.g. "non-translation mode")'
		);
		$this->assertNull( 
			$fields->dataFieldByName('Title_original'),
			'Translatable doesnt modify fields if called in default language (e.g. "non-translation mode")'
		);
		
		// then in "translation mode"
		$pageTranslated = Translatable::get_one_by_lang('Page',"fr", "ID = $pageOrigLang->ID");
		$fields = $pageTranslated->getCMSFields();
		$this->assertType(
			'TextField', 
			$fields->dataFieldByName('Title'),
			'Translatable leaves original formfield intact in "translation mode"'
		);
		$readonlyField = $fields->dataFieldByName('Title')->performReadonlyTransformation();
		$this->assertType(
			$readonlyField->class, 
			$fields->dataFieldByName('Title_original'),
			'Translatable adds the original value as a ReadonlyField in "translation mode"'
		);
		
	}
 public function output()
 {
     // TODO: Refactor into a content-type option
     if (\Director::is_ajax()) {
         return $this->friendlyErrorMessage;
     } else {
         // TODO: Refactor this into CMS
         if (class_exists('ErrorPage')) {
             $errorFilePath = \ErrorPage::get_filepath_for_errorcode($this->statusCode, class_exists('Translatable') ? \Translatable::get_current_locale() : null);
             if (file_exists($errorFilePath)) {
                 $content = file_get_contents($errorFilePath);
                 if (!headers_sent()) {
                     header('Content-Type: text/html');
                 }
                 // $BaseURL is left dynamic in error-###.html, so that multi-domain sites don't get broken
                 return str_replace('$BaseURL', \Director::absoluteBaseURL(), $content);
             }
         }
         $renderer = \Debug::create_debug_view();
         $output = $renderer->renderHeader();
         $output .= $renderer->renderInfo("Website Error", $this->friendlyErrorMessage, $this->friendlyErrorDetail);
         if (\Email::config()->admin_email) {
             $mailto = \Email::obfuscate(\Email::config()->admin_email);
             $output .= $renderer->renderParagraph('Contact an administrator: ' . $mailto . '');
         }
         $output .= $renderer->renderFooter();
         return $output;
     }
 }
Example #13
0
 public function getNestedController()
 {
     if ($this->urlParams['URLSegment']) {
         $SQL_URLSegment = Convert::raw2sql($this->urlParams['URLSegment']);
         if (Translatable::is_enabled()) {
             $child = Translatable::get_one("SiteTree", "URLSegment = '{$SQL_URLSegment}'");
         } else {
             $child = DataObject::get_one("SiteTree", "URLSegment = '{$SQL_URLSegment}'");
         }
         if (!$child) {
             $child = $this->get404Page();
         }
         if ($child) {
             if (isset($_REQUEST['debug'])) {
                 Debug::message("Using record #{$child->ID} of type {$child->class} with URL {$this->urlParams['URLSegment']}");
             }
             $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;
             }
             $controller->setURLParams($this->urlParams);
             return $controller;
         } else {
             die("The requested page couldn't be found.");
         }
     } else {
         user_error("ModelAsController not geting a URLSegment.  It looks like the site isn't redirecting to home", E_USER_ERROR);
     }
 }
 /**
  * We need to disable Translatable before retreiving the DataObjects or 
  * Pages for the sitemap, because otherwise only pages in the default 
  * language are found.
  * 
  * Next we need to add the alternatives for each Translatable Object 
  * included in the sitemap: basically these are the Translations plus 
  * the current object itself
  * 
  * @return Array
  */
 public function sitemap()
 {
     Translatable::disable_locale_filter();
     $sitemap = parent::sitemap();
     Translatable::enable_locale_filter();
     $updatedItems = new ArrayList();
     foreach ($sitemap as $items) {
         foreach ($items as $item) {
             if ($item->hasExtension('Translatable')) {
                 $translations = $item->getTranslations();
                 if ($translations) {
                     $alternatives = new ArrayList();
                     foreach ($translations as $translation) {
                         $translation->GoogleLocale = $this->getGoogleLocale($translation->Locale);
                         $alternatives->push($translation);
                     }
                     $item->GoogleLocale = $this->getGoogleLocale($item->Locale);
                     $alternatives->push($item);
                     $item->Alternatives = $alternatives;
                 }
                 $updatedItems->push($item);
             }
         }
     }
     if (!empty($updatedItems)) {
         return array('Items' => $updatedItems);
     } else {
         return $sitemap;
     }
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     if (!$this->owner->Locale) {
         $this->owner->Locale = Translatable::get_current_locale();
     }
 }
 /**
  * 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;
 }
 function updateLinkForm(&$form)
 {
     $field = new LanguageDropdownField('Language', _t('CMSMain.LANGUAGEDROPDOWNLABEL', 'Language'));
     $field->setValue(Translatable::get_current_locale());
     $field->setForm($form);
     $form->Fields()->insertBefore($field, 'internal');
     Requirements::javascript('translatable/javascript/HtmlEditorField.Translatable.js');
 }
 /**
  * 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');
 }
 /**
  * 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;
 }
 /**
  * Creates a form object with a free configurable markup.
  * Adds the current locale to the custom params.
  *
  * @param ContentController $controller  the calling controller instance
  * @param array             $params      optional parameters
  * @param array             $preferences optional preferences
  * @param bool              $barebone    defines if a form should only be instanciated or be used too
  *
  * @return CustomHtmlForm
  * 
  * @author Sebastian Diel <*****@*****.**>
  * @since 26.06.2013
  */
 public function __construct($controller, $params = null, $preferences = null, $barebone = false)
 {
     if (is_null($params)) {
         $params = array();
     }
     $params['locale'] = Translatable::get_current_locale();
     parent::__construct($controller, $params, $preferences, $barebone);
 }
 function handleAction($request)
 {
     // This method can't be called without ajax.
     if (!$request->isAjax()) {
         $this->parentController->redirectBack();
         return;
     }
     // Protect against CSRF on destructive action
     if (!SecurityToken::inst()->checkRequest($request)) {
         return $this->httpError(400);
     }
     $actions = $this->batchActions();
     $actionClass = $actions[$request->param('BatchAction')]['class'];
     $actionHandler = new $actionClass();
     // Sanitise ID list and query the database for apges
     $ids = preg_split('/ *, */', trim($request->requestVar('csvIDs')));
     foreach ($ids as $k => $v) {
         if (!is_numeric($v)) {
             unset($ids[$k]);
         }
     }
     if ($ids) {
         if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable')) {
             Translatable::disable_locale_filter();
         }
         $pages = DataObject::get($this->recordClass, sprintf('"%s"."ID" IN (%s)', ClassInfo::baseDataClass($this->recordClass), implode(", ", $ids)));
         if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable')) {
             Translatable::enable_locale_filter();
         }
         if (Object::has_extension($this->recordClass, 'Versioned')) {
             // If we didn't query all the pages, then find the rest on the live site
             if (!$pages || $pages->Count() < sizeof($ids)) {
                 foreach ($ids as $id) {
                     $idsFromLive[$id] = true;
                 }
                 if ($pages) {
                     foreach ($pages as $page) {
                         unset($idsFromLive[$page->ID]);
                     }
                 }
                 $idsFromLive = array_keys($idsFromLive);
                 $sql = sprintf('"%s"."ID" IN (%s)', $this->recordClass, implode(", ", $idsFromLive));
                 $livePages = Versioned::get_by_stage($this->recordClass, 'Live', $sql);
                 if ($pages) {
                     // Can't merge into a DataList, need to condense into an actual list first
                     // (which will retrieve all records as objects, so its an expensive operation)
                     $pages = new ArrayList($pages->toArray());
                     $pages->merge($livePages);
                 } else {
                     $pages = $livePages;
                 }
             }
         }
     } else {
         $pages = new ArrayList();
     }
     return $actionHandler->run($pages);
 }
    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;
    }
    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 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');
 }
 /**
  * @param array $compatibility
  */
 public static function done(array $compatibility)
 {
     if (class_exists("Subsite")) {
         Subsite::$disable_subsite_filter = $compatibility[self::SUBSITES];
     }
     if (class_exists("Translatable")) {
         Translatable::enable_locale_filter($compatibility[self::TRANSLATABLE]);
     }
 }
 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();
 }
 /**
  * @return mixed
  */
 public function getLanguageField()
 {
     $locale = Translatable::get_current_locale();
     if ($member = Member::currentUser()) {
         if (Permission::checkMember($member, 'VIEW_LANGS')) {
             return $this->getLanguageDropdownField($locale);
         }
     }
     return LiteralField::create('Locale', i18n::get_locale_name($locale));
 }
 static function tear_down_once()
 {
     if (!self::$origTranslatableSettings['has_extension']) {
         Object::remove_extension('SiteTree', 'Translatable');
     }
     Translatable::set_default_locale(self::$origTranslatableSettings['default_locale']);
     self::kill_temp_db();
     self::create_temp_db();
     parent::tear_down_once();
 }
 /**
  * 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;
 }