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();
 }
 public function handleBatchAction($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') && SiteTree::has_extension('Translatable')) {
             Translatable::disable_locale_filter();
         }
         $recordClass = $this->recordClass;
         $pages = DataObject::get($recordClass)->byIDs($ids);
         if (class_exists('Translatable') && SiteTree::has_extension('Translatable')) {
             Translatable::enable_locale_filter();
         }
         $record_class = $this->recordClass;
         if ($record_class::has_extension('Versioned')) {
             // If we didn't query all the pages, then find the rest on the live site
             if (!$pages || $pages->Count() < sizeof($ids)) {
                 $idsFromLive = array();
                 foreach ($ids as $id) {
                     $idsFromLive[$id] = true;
                 }
                 if ($pages) {
                     foreach ($pages as $page) {
                         unset($idsFromLive[$page->ID]);
                     }
                 }
                 $idsFromLive = array_keys($idsFromLive);
                 $livePages = Versioned::get_by_stage($this->recordClass, 'Live')->byIDs($idsFromLive);
                 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);
 }
 /**
  * If there are multiple @link NewsHolderPage available, add the field for multiples.
  * This includes translation options
  */
 private function multipleNewsHolderPages()
 {
     $enabled = false;
     // If we have translations, disable translation filter to get all pages.
     if (class_exists('Translatable')) {
         $enabled = Translatable::disable_locale_filter();
     }
     $pages = Versioned::get_by_stage('NewsHolderPage', 'Live');
     // Only add the page-selection if there are multiple. Otherwise handled by onBeforeWrite();
     if ($pages->count() > 1) {
         $pagelist = array();
         if (class_exists('Translatable')) {
             foreach ($pages as $page) {
                 $pagelist['Root.Main'][$page->ID] = $page->Title . ' ' . $page->Locale;
             }
         } else {
             $pagelist = $pages->map('ID', 'Title')->toArray();
         }
         $this->field_list['Root.Main'][1] = ListboxField::create('NewsHolderPages', $this->owner->fieldLabel('NewsHolderPages'), $pagelist);
         $this->field_list['Root.Main'][1]->setMultiple(true);
     }
     if ($enabled) {
         Translatable::enable_locale_filter();
     }
 }
 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();
 }
 /**
  * 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 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;
    }
Пример #7
0
 function handleAction($request)
 {
     // This method can't be called without ajax.
     if (!$this->parentController->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 = 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) {
                     $pages->merge($livePages);
                 } else {
                     $pages = $livePages;
                 }
             }
         }
     } else {
         $pages = new ArrayList();
     }
     return $actionHandler->run($pages);
 }
 /**
  * Specific controller action for displaying a particular list of links
  * for a class
  *
  * @return mixed
  */
 public function sitemap()
 {
     if ($this->request->param('ID') == 'SiteTree') {
         //Disable the locale filter
         Translatable::disable_locale_filter();
         $items = parent::sitemap();
         //Re-enable the locale filter
         Translatable::enable_locale_filter();
         return $items;
     } else {
         return parent::sitemap();
     }
 }
 /**
  * Returns the state of other modules before compatibility mode is started.
  *
  * @return array
  */
 public static function start()
 {
     $compatibility = array(self::SUBSITES => null, self::TRANSLATABLE => null);
     if (ClassInfo::exists("Subsite")) {
         $compatibility[self::SUBSITES] = Subsite::$disable_subsite_filter;
         Subsite::disable_subsite_filter(true);
     }
     if (ClassInfo::exists("Translatable")) {
         $compatibility[self::TRANSLATABLE] = Translatable::locale_filter_enabled();
         Translatable::disable_locale_filter();
     }
     return $compatibility;
 }
 /**
  * @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
     Translatable::disable_locale_filter();
     $sitetree = DataObject::get_one('SiteTree', sprintf('"URLSegment" = \'%s\' %s', Convert::raw2sql($URLSegment), SiteTree::nested_urls() ? 'AND "ParentID" = 0' : null));
     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 = self::find_old_page($URLSegment)) {
             $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;
         }
         $ctrl = new Paste_Controller();
         $ctrl->request = $request;
         $paste = $ctrl->getCurrentPaste();
         if ($paste) {
             if (is_string($paste) || is_object($paste) && is_a($paste, 'SS_HTTPResponse')) {
                 return $paste;
             }
             $ctrl->init($paste);
             $response = $ctrl->handleRequest($request);
             return $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 ($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'));
 }
 /**
  * Check catalogue URL's before we get to the CMS (if it exists)
  * 
  * @param SS_HTTPRequest $request
  * @param DataModel|null $model
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     $this->request = $request;
     $this->setDataModel($model);
     $catalogue_enabled = Catalogue::config()->enable_frontend;
     $this->pushCurrent();
     // Create a response just in case init() decides to redirect
     $this->response = new SS_HTTPResponse();
     $this->init();
     // If we had a redirection or something, halt processing.
     if ($this->response->isFinished()) {
         $this->popCurrent();
         return $this->response;
     }
     // If DB is not present, build
     if (!DB::isActive() || !ClassInfo::hasTable('CatalogueProduct') || !ClassInfo::hasTable('CatalogueCategory')) {
         return $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
     }
     $urlsegment = $request->param('URLSegment');
     $this->extend('onBeforeInit');
     $this->init();
     $this->extend('onAfterInit');
     // Find link, regardless of current locale settings
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     $filter = array('URLSegment' => $urlsegment, 'Disabled' => 0);
     if ($catalogue_enabled && ($object = CatalogueProduct::get()->filter($filter)->first())) {
         $controller = $this->controller_for($object);
     } elseif ($catalogue_enabled && ($object = CatalogueCategory::get()->filter($filter)->first())) {
         $controller = $this->controller_for($object);
     } elseif (class_exists('ModelAsController')) {
         // If CMS installed
         $controller = ModelAsController::create();
     } else {
         $controller = Controller::create();
     }
     if (class_exists('Translatable')) {
         Translatable::enable_locale_filter();
     }
     $result = $controller->handleRequest($request, $model);
     $this->popCurrent();
     return $result;
 }
 public static function Fetch($echo = false)
 {
     $since_id = (int) SocialMediaSettings::getValue('TwitterIndex');
     if ($since_id == 0) {
         $since_id = 1;
     }
     //Twitter gives an error message if since_id is zero. This happens when tweets are fetched the first time.
     $tweets = self::Connection()->get('statuses/user_timeline', array('since_id' => $since_id, 'count' => 200, 'include_rts' => true, 'exclude_replies' => true, 'screen_name' => self::config()->username));
     if (self::Error()) {
         user_error("Twitter error: " . self::ErrorMessage($tweets));
         return false;
     }
     $updates = array();
     $max_id = (int) SocialMediaSettings::getValue('TwitterIndex');
     $skipped = 0;
     $translatable_locale_filter = Translatable::disable_locale_filter();
     //ID filtering does not work well if locale filtering is on.
     foreach ($tweets as $tweet) {
         if (!DataObject::get('BlogPost')->filter('TwitterID', $tweet->id)->exists()) {
             //Do not supply the tweet if a DataObject with the same Twitter ID already exists.
             //However, $max_id can still be updated with the already existing ID number. This will
             //Ensure we do not have to loop over this tweet again.
             $updates[] = self::tweet_to_array($tweet);
         } else {
             $skipped++;
         }
         $max_id = max($max_id, (int) $tweet->id);
     }
     Translatable::enable_locale_filter($translatable_locale_filter);
     if ($echo and $skipped > 0) {
         echo "Twitter: Skipped {$skipped} existing records. This is normal if its only a few records occasionally, but if it happens every time and the number is constant or raises, then the Twitter's 'since_id' parameter is not working correctly. If the count reaches 200, it might be that you won't get any new records at all, because Twitter's maximum count for returned records per query is 200 at the moment when writing this (January 2016). Also constant skipping might affect performance.<br />";
     }
     if ($echo) {
         echo "Twitter: since_id was {$since_id} and is now {$max_id}.<br />";
     }
     SocialMediaSettings::setValue('TwitterIndex', $max_id);
     //Keep track of where we left, so we don't get the same tweets next time.
     return $updates;
 }
 /**
  * Constructs the list of data to include in the rendered feed. Links
  * can include pages from the website, dataobjects (such as forum posts)
  * as well as custom registered paths.
  *
  * @param string
  * @param int
  *
  * @return ArrayList
  */
 public static function get_items()
 {
     $output = new ArrayList();
     $search_filter = Config::inst()->get('GoogleShoppingFeed', 'use_show_in_search');
     $disabled_filter = Config::inst()->get('GoogleShoppingFeed', 'use_disabled');
     $filter = array();
     // todo migrate to extension hook or DI point for other modules to
     // modify state filters
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     foreach (self::$dataobjects as $class) {
         if ($class == "SiteTree") {
             $search_filter = $search_filter ? "\"ShowInSearch\" = 1" : "";
             $instances = Versioned::get_by_stage('SiteTree', 'Live', $search_filter);
         } elseif ($class == "Product") {
             $instances = $class::get();
             if ($disabled_filter) {
                 $instances->filter("Disabled", 0);
             }
         } else {
             $instances = new DataList($class);
         }
         if ($instances) {
             foreach ($instances as $obj) {
                 if ($obj->canIncludeInGoogleShoppingFeed()) {
                     $output->push($obj);
                 }
             }
         }
     }
     return $output;
 }
 /**
  * Overrides ModelAsController->getNestedController to find the nested controller
  * on a per-site basis
  **/
 public function getNestedController()
 {
     $request = $this->request;
     $segment = $request->param('URLSegment');
     $site = Multisites::inst()->getCurrentSiteId();
     if (!$site) {
         return $this->httpError(404);
     }
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     $page = SiteTree::get()->filter(array('ParentID' => $site, 'URLSegment' => rawurlencode($segment)));
     $page = $page->first();
     if (class_exists('Translatable')) {
         Translatable::enable_locale_filter();
     }
     if (!$page) {
         // Check to see if linkmapping module is installed and if so, if there a map for this request.
         if (class_exists('LinkMapping')) {
             if ($request->requestVars()) {
                 $queryString = '?';
                 foreach ($request->requestVars() as $key => $value) {
                     if ($key != 'url') {
                         $queryString .= $key . '=' . $value . '&';
                     }
                 }
                 $queryString = rtrim($queryString, '&');
             }
             $link = $queryString != '?' ? $request->getURL() . $queryString : $request->getURL();
             $link = trim(Director::makeRelative($link));
             $map = LinkMapping::get()->filter('MappedLink', $link)->first();
             if ($map) {
                 $this->response = new SS_HTTPResponse();
                 $this->response->redirect($map->getLink(), 301);
                 return $this->response;
             }
         }
         // use OldPageRedirector if it exists, to find old page
         if (class_exists('OldPageRedirector')) {
             if ($redirect = OldPageRedirector::find_old_page(array($segment), Multisites::inst()->getCurrentSite())) {
                 $redirect = SiteTree::get_by_link($redirect);
             }
         } else {
             $redirect = self::find_old_page($segment, $site);
         }
         if ($redirect) {
             $getVars = $request->getVars();
             //remove the url var as it confuses the routing
             unset($getVars['url']);
             $url = Controller::join_links($redirect->Link(Controller::join_links($request->param('Action'), $request->param('ID'), $request->param('OtherID'))));
             if (!empty($getVars)) {
                 $url .= '?' . http_build_query($getVars);
             }
             $this->response->redirect($url, 301);
             return $this->response;
         }
         return $this->httpError(404);
     }
     if (class_exists('Translatable') && $page->Locale) {
         Translatable::set_current_locale($page->Locale);
     }
     return self::controller_for($page, $request->param('Action'));
 }
 /**
  * Get the locale for an object that has the Translatable extension.
  * 
  * @return locale
  */
 public function getLocaleForObject()
 {
     $id = (int) $this->getRequest()->requestVar('id');
     $class = Convert::raw2sql($this->getRequest()->requestVar('class'));
     $locale = Translatable::get_current_locale();
     if ($id && $class && class_exists($class) && $class::has_extension('Translatable')) {
         // temporarily disable locale filter so that we won't filter out the object
         Translatable::disable_locale_filter();
         $object = DataObject::get_by_id($class, $id);
         Translatable::enable_locale_filter();
         if ($object) {
             $locale = $object->Locale;
         }
     }
     return $locale;
 }
 /**
  * 
  * @return DataList
  */
 protected function getAllLivePages()
 {
     ini_set('memory_limit', '512M');
     $oldMode = Versioned::get_reading_mode();
     if (class_exists('Subsite')) {
         Subsite::disable_subsite_filter(true);
     }
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     Versioned::reading_stage('Live');
     $pages = DataObject::get("SiteTree");
     Versioned::set_reading_mode($oldMode);
     return $pages;
 }
Пример #17
0
 /**
  * Link to this product.
  * The link is in context of the current controller. If the current 
  * controller does not match some related product criteria (mirrored product 
  * group, translation of a mirrored product group or translation of main
  * group) the main group will be used as context.
  *
  * @return string URL of $this
  *
  * @author Sebastian Diel <*****@*****.**>,
  *         Roland Lehmann <*****@*****.**>,
  *         Ramon Kupper <*****@*****.**>
  * @since 03.03.2015
  */
 public function Link()
 {
     $link = '';
     if (Controller::curr() instanceof SilvercartProductGroupPage_Controller && !Controller::curr() instanceof SilvercartSearchResultsPage_Controller && $this->SilvercartProductGroupMirrorPages()->find('ID', Controller::curr()->data()->ID)) {
         $link = $this->buildLink(Controller::curr(), $this->title2urlSegment());
     } elseif (Controller::curr() instanceof SilvercartProductGroupPage_Controller && Translatable::get_current_locale() != SilvercartConfig::DefaultLanguage()) {
         Translatable::disable_locale_filter();
         if ($this->SilvercartProductGroupMirrorPages()->find('ID', Controller::curr()->getTranslation(SilvercartConfig::DefaultLanguage())->ID)) {
             $link = $this->buildLink(Controller::curr(), $this->title2urlSegment());
         }
         Translatable::enable_locale_filter();
     }
     if (empty($link) && $this->SilvercartProductGroup()) {
         $link = $this->buildLink($this->SilvercartProductGroup(), $this->title2urlSegment());
     }
     return $link;
 }
Пример #18
0
 /**
  *
  * @return DataObject (Any type of Data Object that is buyable)
  * @param Boolean $current - is this a current one, or an older VERSION ?
  **/
 function Buyable($current = false)
 {
     if (!$this->BuyableID) {
         return null;
     }
     //start hack
     if (!$this->BuyableClassName) {
         $this->BuyableClassName = str_replace("_OrderItem", "", $this->ClassName);
     }
     $turnTranslatableBackOn = false;
     if (Object::has_extension($this->BuyableClassName, 'Translatable')) {
         Translatable::disable_locale_filter();
         $turnTranslatableBackOn = true;
     }
     //end hack!
     $obj = null;
     if ($current) {
         $obj = DataObject::get_by_id($this->BuyableClassName, $this->BuyableID);
     }
     //run if current not available or current = false
     if (!$obj && $this->Version) {
         /* @TODO: check if the version exists?? - see sample below
         			$versionTable = $this->BuyableClassName."_versions";
         			$dbConnection = DB::getConn();
         			if($dbConnection && $dbConnection instanceOf MySQLDatabase && $dbConnection->hasTable($versionTable)) {
         				$result = DB::query("
         					SELECT COUNT(\"ID\")
         					FROM \"$versionTable\"
         					WHERE
         						\"RecordID\" = ".intval($this->BuyableID)."
         						AND \"Version\" = ".intval($this->Version)."
         				");
         				if($result->value()) {
         			 */
         $obj = OrderItem::get_version($this->BuyableClassName, $this->BuyableID, $this->Version);
     }
     //our last resort
     if (!$obj) {
         $obj = Versioned::get_latest_version($this->BuyableClassName, $this->BuyableID);
     }
     if ($turnTranslatableBackOn) {
         Translatable::enable_locale_filter();
     }
     return $obj;
 }
 /**
  * This acts the same as {@link Controller::handleRequest()}, but if an action cannot be found this will attempt to
  * fall over to a child controller in order to provide functionality for nested URLs.
  *
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request)
 {
     $child = null;
     $action = $request->param('Action');
     // If nested URLs are enabled, and there is no action handler for the current request then attempt to pass
     // control to a child controller. This allows for the creation of chains of controllers which correspond to a
     // nested URL.
     if ($action && SiteTree::nested_urls() && !$this->hasAction($action)) {
         // See ModelAdController->getNestedController() for similar logic
         Translatable::disable_locale_filter();
         // look for a page with this URLSegment
         $child = DataObject::get_one('SiteTree', sprintf("\"ParentID\" = %s AND \"URLSegment\" = '%s'", $this->ID, Convert::raw2sql($action)));
         Translatable::enable_locale_filter();
         // if we can't find a page with this URLSegment try to find one that used to have
         // that URLSegment but changed. See ModelAsController->getNestedController() for similiar logic.
         if (!$child) {
             $child = ModelAsController::find_old_page($action, $this->ID);
             if ($child) {
                 $response = new SS_HTTPResponse();
                 $params = $request->getVars();
                 if (isset($params['url'])) {
                     unset($params['url']);
                 }
                 $response->redirect(Controller::join_links($child->Link(Controller::join_links($request->param('ID'), $request->param('OtherID'))), $params ? '?' . http_build_query($params) : null), 301);
                 return $response;
             }
         }
     }
     // we found a page with this URLSegment.
     if ($child) {
         $request->shiftAllParams();
         $request->shift();
         $response = ModelAsController::controller_for($child)->handleRequest($request);
     } else {
         // If a specific locale is requested, and it doesn't match the page found by URLSegment,
         // look for a translation and redirect (see #5001). Only happens on the last child in
         // a potentially nested URL chain.
         if ($request->getVar('locale') && $this->dataRecord && $this->dataRecord->Locale != $request->getVar('locale')) {
             $translation = $this->dataRecord->getTranslation($request->getVar('locale'));
             if ($translation) {
                 $response = new SS_HTTPResponse();
                 $response->redirect($translation->Link(), 301);
                 throw new SS_HTTPResponse_Exception($response);
             }
         }
         Director::set_current_page($this->data());
         $response = parent::handleRequest($request);
         Director::set_current_page(null);
     }
     return $response;
 }
 /**
  * When the SiteConfig object is automatically instantiated, we should ensure that
  * 1. All SiteConfig objects belong to the same group
  * 2. Defaults are correctly initiated from the base object
  * 3. The creation mechanism uses the createTranslation function in order to be consistent
  * This function ensures that any already created "vanilla" SiteConfig object is populated 
  * correctly with translated values.
  * This function DOES populate the ID field with the newly created object ID
  * @see SiteConfig
  */
 protected function populateSiteConfigDefaults()
 {
     // Work-around for population of defaults during database initialisation.
     // When the database is being setup singleton('SiteConfig') is called.
     if (!DB::getConn()->hasTable($this->owner->class)) {
         return;
     }
     if (!DB::getConn()->hasField($this->owner->class, 'Locale')) {
         return;
     }
     if (DB::getConn()->isSchemaUpdating()) {
         return;
     }
     // Find the best base translation for SiteConfig
     $enabled = Translatable::locale_filter_enabled();
     Translatable::disable_locale_filter();
     $existingConfig = SiteConfig::get()->filter(array('Locale' => Translatable::default_locale()))->first();
     if (!$existingConfig) {
         $existingConfig = SiteConfig::get()->first();
     }
     if ($enabled) {
         Translatable::enable_locale_filter();
     }
     // Stage this SiteConfig and copy into the current object
     if ($existingConfig && !$existingConfig->getTranslation(Translatable::get_current_locale()) && $existingConfig->canTranslate(null, Translatable::get_current_locale())) {
         // Create an unsaved "staging" translated object using the correct createTranslation mechanism
         $stagingConfig = $existingConfig->createTranslation(Translatable::get_current_locale(), false);
         $this->owner->update($stagingConfig->toMap());
     }
     // Maintain single translation group for SiteConfig
     if ($existingConfig) {
         $this->owner->_TranslationGroupID = $existingConfig->getTranslationGroup();
     }
     $this->owner->Locale = Translatable::get_current_locale();
 }
 /**
  * Safely query and return all pages queried
  *
  * @param array $ids
  * @return SS_List
  */
 protected function getPages($ids)
 {
     // Check empty set
     if (empty($ids)) {
         return new ArrayList();
     }
     $recordClass = $this->recordClass;
     // Bypass translatable filter
     if (class_exists('Translatable') && $recordClass::has_extension('Translatable')) {
         Translatable::disable_locale_filter();
     }
     // Bypass versioned filter
     if ($recordClass::has_extension('Versioned')) {
         // Workaround for get_including_deleted not supporting byIDs filter very well
         // Ensure we select both stage / live records
         $pages = Versioned::get_including_deleted($recordClass, array('"RecordID" IN (' . DB::placeholders($ids) . ')' => $ids));
     } else {
         $pages = DataObject::get($recordClass)->byIDs($ids);
     }
     if (class_exists('Translatable') && $recordClass::has_extension('Translatable')) {
         Translatable::enable_locale_filter();
     }
     return $pages;
 }
 function testLocaleFilteringEnabledAndDisabled()
 {
     $this->assertTrue(Translatable::locale_filter_enabled());
     // get our base page to use for testing
     $origPage = $this->objFromFixture('Page', 'testpage_en');
     $origPage->MenuTitle = 'unique-key-used-in-my-query';
     $origPage->write();
     $origPage->publish('Stage', 'Live');
     // create a translation of it so that we can see if translations are filtered
     $translatedPage = $origPage->createTranslation('de_DE');
     $translatedPage->MenuTitle = $origPage->MenuTitle;
     $translatedPage->write();
     $translatedPage->publish('Stage', 'Live');
     $where = sprintf("\"MenuTitle\" = '%s'", Convert::raw2sql($origPage->MenuTitle));
     // make sure that our query was filtered
     $this->assertEquals(1, Page::get()->where($where)->count());
     // test no filtering with disabled locale filter
     Translatable::disable_locale_filter();
     $this->assertEquals(2, Page::get()->where($where)->count());
     Translatable::enable_locale_filter();
     // make sure that our query was filtered after re-enabling the filter
     $this->assertEquals(1, Page::get()->where($where)->count());
     // test effectiveness of disabling locale filter with 3.x delayed querying
     // see https://github.com/silverstripe/silverstripe-translatable/issues/113
     Translatable::disable_locale_filter();
     // create the DataList while the locale filter is disabled
     $dataList = Page::get()->where($where);
     Translatable::enable_locale_filter();
     // but don't use it until later - after the filter is re-enabled
     $this->assertEquals(2, $dataList->count());
 }
 /**
  * The google site map is broken down into multiple smaller files to 
  * prevent overbearing a server. By default separate {@link DataObject}
  * records are keep in separate files and broken down into chunks.
  *
  * @return ArrayList
  */
 public function getSitemaps()
 {
     $countPerFile = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap');
     $sitemaps = new ArrayList();
     $filter = Config::inst()->get('GoogleSitemap', 'use_show_in_search');
     if (class_exists('SiteTree')) {
         // move to extension hook. At the moment moduleexists config hook
         // does not work.
         if (class_exists('Translatable')) {
             Translatable::disable_locale_filter();
         }
         $filter = $filter ? "\"ShowInSearch\" = 1" : "";
         $class = 'SiteTree';
         $instances = Versioned::get_by_stage($class, 'Live', $filter);
         $this->extend("alterDataList", $instances, $class);
         $count = $instances->count();
         $neededForPage = ceil($count / $countPerFile);
         for ($i = 1; $i <= $neededForPage; $i++) {
             $lastEdited = $instances->limit($countPerFile, ($i - 1) * $countPerFile)->sort(array())->max('LastEdited');
             $lastModified = $lastEdited ? date('Y-m-d', strtotime($lastEdited)) : date('Y-m-d');
             $sitemaps->push(new ArrayData(array('ClassName' => 'SiteTree', 'LastModified' => $lastModified, 'Page' => $i)));
         }
     }
     if (count(self::$dataobjects) > 0) {
         foreach (self::$dataobjects as $class => $config) {
             $list = new DataList($class);
             $list = $list->sort('LastEdited ASC');
             $this->extend("alterDataList", $list, $class);
             $neededForClass = ceil($list->count() / $countPerFile);
             for ($i = 1; $i <= $neededForClass; $i++) {
                 // determine the last modified date for this slice
                 $sliced = $list->limit($countPerFile, ($i - 1) * $countPerFile)->last();
                 $lastModified = $sliced ? $sliced->dbObject('LastEdited')->Format('Y-m-d') : date('Y-m-d');
                 $sitemaps->push(new ArrayData(array('ClassName' => $class, 'Page' => $i, 'LastModified' => $lastModified)));
             }
         }
     }
     if (count(self::$routes) > 0) {
         $needed = ceil(count(self::$routes) / $countPerFile);
         for ($i = 1; $i <= $needed; $i++) {
             $sitemaps->push(new ArrayData(array('ClassName' => 'GoogleSitemapRoute', 'Page' => $i)));
         }
     }
     return $sitemaps;
 }
 /**
  * This acts the same as {@link Controller::handleRequest()}, but if an action cannot be found this will attempt to
  * fall over to a child controller in order to provide functionality for nested URLs.
  *
  * @param SS_HTTPRequest $request
  * @param DataModel $model
  * @return SS_HTTPResponse
  * @throws SS_HTTPResponse_Exception
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = null)
 {
     $child = null;
     $action = $request->param('Action');
     $this->setDataModel($model);
     // If nested URLs are enabled, and there is no action handler for the current request then attempt to pass
     // control to a child controller. This allows for the creation of chains of controllers which correspond to a
     // nested URL.
     if ($action && SiteTree::config()->nested_urls && !$this->hasAction($action)) {
         // See ModelAdController->getNestedController() for similar logic
         if (class_exists('Translatable')) {
             Translatable::disable_locale_filter();
         }
         // look for a page with this URLSegment
         $child = $this->model->SiteTree->filter(array('ParentID' => $this->ID, 'URLSegment' => rawurlencode($action)))->first();
         if (class_exists('Translatable')) {
             Translatable::enable_locale_filter();
         }
     }
     // we found a page with this URLSegment.
     if ($child) {
         $request->shiftAllParams();
         $request->shift();
         $response = ModelAsController::controller_for($child)->handleRequest($request, $model);
     } else {
         // If a specific locale is requested, and it doesn't match the page found by URLSegment,
         // look for a translation and redirect (see #5001). Only happens on the last child in
         // a potentially nested URL chain.
         if (class_exists('Translatable')) {
             if ($request->getVar('locale') && $this->dataRecord && $this->dataRecord->Locale != $request->getVar('locale')) {
                 $translation = $this->dataRecord->getTranslation($request->getVar('locale'));
                 if ($translation) {
                     $response = new SS_HTTPResponse();
                     $response->redirect($translation->Link(), 301);
                     throw new SS_HTTPResponse_Exception($response);
                 }
             }
         }
         Director::set_current_page($this->data());
         try {
             $response = parent::handleRequest($request, $model);
             Director::set_current_page(null);
         } catch (SS_HTTPResponse_Exception $e) {
             $this->popCurrent();
             Director::set_current_page(null);
             throw $e;
         }
     }
     return $response;
 }
Пример #25
0
 /**
  * The holder-page ID should be set if translatable, otherwise, we just select the first available one.
  * The NewsHolderPage should NEVER be doubled.
  */
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     /** Check if we have translatable and a NewsHolderPage. If no HolderPage available, skip (Create an orphan) */
     if (!$this->NewsHolderPages()->count()) {
         if (!class_exists('Translatable') && ($page = NewsHolderPage::get()->first())) {
             $this->NewsHolderPages()->add($page);
         } elseif (class_exists('Translatable')) {
             Translatable::disable_locale_filter();
             $page = NewsHolderPage::get()->first();
             $this->NewsHolderPages()->add($page);
             Translatable::enable_locale_filter();
         }
     }
     if (!$this->Type || $this->Type === '') {
         $this->Type = 'news';
     }
     /** Set PublishFrom to today to prevent errors with sorting. New since 2.0, backward compatible. */
     if (!$this->PublishFrom) {
         $this->PublishFrom = SS_Datetime::now()->Rfc2822();
     }
     /**
      * Make sure the link is valid.
      */
     if (substr($this->External, 0, 4) !== 'http' && $this->External != '') {
         $this->External = 'http://' . $this->External;
     }
     $this->setURLValue();
     $this->setAuthorData();
 }
 /**
  * Will publish all pages of the SiteTree for the defined translationLocale
  *
  * @param int $parentID ID of the parent to get pages for
  * 
  * @return void
  *
  * @author Sebastian Diel <*****@*****.**>
  * @since 03.05.2012
  */
 public function publishSiteTree($parentID = 0)
 {
     $translationLocale = $this->getTranslationLocale();
     Translatable::disable_locale_filter();
     Versioned::set_reading_mode('Stage.Stage');
     $pages = SiteTree::get()->filter(array("ParentID" => $parentID, "Locale" => $translationLocale));
     if ($pages->exists()) {
         foreach ($pages as $page) {
             $page->publish("Stage", "Live");
             $this->publishSiteTree($page->ID);
         }
     }
 }
 /**
  *
  * @param Boolean $current - is this a current one, or an older VERSION ?
  * @return DataObject (Any type of Data Object that is buyable)
  **/
 function Buyable($current = false)
 {
     $tempBuyableStoreType = $current ? "current" : "version";
     if (!isset($this->tempBuyableStore[$tempBuyableStoreType])) {
         if (!$this->BuyableID) {
             user_error("There was an error retrieving the product", E_USER_NOTICE);
             return null;
         }
         //start hack
         if (!$this->BuyableClassName) {
             $this->BuyableClassName = str_replace("_OrderItem", "", $this->ClassName);
         }
         $turnTranslatableBackOn = false;
         $className = $this->BuyableClassName;
         if ($className::has_extension($this->class, 'Translatable')) {
             Translatable::disable_locale_filter();
             $turnTranslatableBackOn = true;
         }
         //end hack!
         $obj = null;
         if ($current) {
             $obj = $className::get()->byID($this->BuyableID);
         }
         //run if current not available or current = false
         if (!$obj || !$current) {
             if ((!$obj || !$obj->exists()) && $this->Version) {
                 /* @TODO: check if the version exists?? - see sample below
                 			$versionTable = $this->BuyableClassName."_versions";
                 			$dbConnection = DB::getConn();
                 			if($dbConnection && $dbConnection instanceOf MySQLDatabase && $dbConnection->hasTable($versionTable)) {
                 				$result = DB::query("
                 					SELECT COUNT(\"ID\")
                 					FROM \"$versionTable\"
                 					WHERE
                 						\"RecordID\" = ".intval($this->BuyableID)."
                 						AND \"Version\" = ".intval($this->Version)."
                 				");
                 				if($result->value()) {
                 			 */
                 $obj = OrderItem::get_version($this->BuyableClassName, $this->BuyableID, $this->Version);
             }
             //our second to last resort
             if (!$obj || !$obj->exists()) {
                 $obj = Versioned::get_latest_version($this->BuyableClassName, $this->BuyableID);
             }
         }
         //our final backup
         if (!$obj || !$obj->exists()) {
             $obj = $className::get()->byID($this->BuyableID);
         }
         if ($turnTranslatableBackOn) {
             Translatable::enable_locale_filter();
         }
         $this->tempBuyableStore[$tempBuyableStoreType] = $obj;
     }
     return $this->tempBuyableStore[$tempBuyableStoreType];
 }
 public function Entries()
 {
     $member = Member::currentUser();
     if ($member) {
         $member->logOut();
     }
     $list = new ArrayList();
     //first check registered_data objects
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     foreach ($this->data_objects as $class_name => $template) {
         if ($class_name == 'SiteTree' || is_subclass_of($class_name, 'SiteTree')) {
             $objects = Versioned::get_by_stage($class_name, 'Live', "CanViewType = 'Anyone' || CanViewType = 'Inherit'");
         } else {
             if ($template->hasFetchFunction()) {
                 $objects = $template->fetch();
             } else {
                 $objects = $class_name::get();
             }
         }
         foreach ($objects as $obj) {
             if ($obj instanceof ErrorPage) {
                 continue;
             }
             if ($obj instanceof SiteTree && (!$obj->canIncludeInGoogleSiteMap() || !$obj->canView())) {
                 continue;
             }
             $url = $template->buildUrl($obj);
             if (!$url) {
                 continue;
             }
             $change_freq = $obj->hasMethod('getChangeFrequency') ? $obj->getChangeFrequency() : false;
             if (!$change_freq) {
                 $change_freq = $template->change_freq;
             }
             $priority = $obj->hasMethod('getGooglePriority') ? $obj->getGooglePriority() : false;
             if (!$priority) {
                 $priority = $template->priority;
             }
             $list->add(new GoogleSiteMapEntry($url, $change_freq, $priority));
         }
     }
     //then plain urls...
     foreach ($this->plain_urls as $key => $entry) {
         $list->add($entry);
     }
     return $list;
 }
 /**
  * @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'));
 }
Пример #30
0
 /**
  * @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'));
 }