From 74ef9dd1bcdddf3cea2be12453bf5cd89b16233f Mon Sep 17 00:00:00 2001 From: helpfulrobot Date: Sat, 26 Dec 2015 10:59:47 +1300 Subject: [PATCH] Converted to PSR-2 --- code/control/MultilingualGoogleSitemap.php | 31 +-- .../control/MultilingualModelAsController.php | 143 +++++------ .../control/MultilingualRootURLController.php | 227 +++++++++--------- .../MultilingualControllerExtension.php | 44 ++-- .../MultilingualOldPageRedirector.php | 166 ++++++------- .../MultilingualSiteTreeExtension.php | 12 +- tests/MultilingualControllerTest.php | 50 ++-- tests/MultilingualModelAsControllerTest.php | 30 ++- tests/MultilingualRootURLControllerTest.php | 42 ++-- tests/pre-up/travis_setup.php | 11 +- 10 files changed, 397 insertions(+), 359 deletions(-) diff --git a/code/control/MultilingualGoogleSitemap.php b/code/control/MultilingualGoogleSitemap.php index 5ec8685..b4df3e4 100644 --- a/code/control/MultilingualGoogleSitemap.php +++ b/code/control/MultilingualGoogleSitemap.php @@ -1,21 +1,23 @@ request->param('ID')=='SiteTree') { + /** + * 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(); @@ -24,9 +26,8 @@ public function sitemap() { return $items; - }else { + } else { return parent::sitemap(); - } + } } } -?> \ No newline at end of file diff --git a/code/control/MultilingualModelAsController.php b/code/control/MultilingualModelAsController.php index c3753d0..7c70e7c 100644 --- a/code/control/MultilingualModelAsController.php +++ b/code/control/MultilingualModelAsController.php @@ -1,26 +1,28 @@ request=$request; - $this->setDataModel($model); - - $this->pushCurrent(); + /** + * @uses ModelAsController::getNestedController() + * @return SS_HTTPResponse + */ + public function handleRequest(SS_HTTPRequest $request, DataModel $model) + { + $this->request=$request; + $this->setDataModel($model); + + $this->pushCurrent(); //Get the local from the language param - if(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { - if(Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) { + if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { + if (Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) { //Language is missing a dash 404 - if(strpos($request->param('Language'), '-')===false) { + if (strpos($request->param('Language'), '-')===false) { //Locale not found 404 - if($response=ErrorPage::response_for(404)) { + if ($response=ErrorPage::response_for(404)) { return $response; - }else { + } else { $this->httpError(404, 'The requested page could not be found.'); } @@ -31,11 +33,11 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { $locale[1]=strtoupper($locale[1]); //Make sure that the language is all lowercase - if($request->param('Language')==implode('-', $locale)) { + if ($request->param('Language')==implode('-', $locale)) { //Locale not found 404 - if($response=ErrorPage::response_for(404)) { + if ($response=ErrorPage::response_for(404)) { return $response; - }else { + } else { $this->httpError(404, 'The requested page could not be found.'); } @@ -43,33 +45,33 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { } $locale=implode('_', $locale); - }else { + } else { $locale=$request->param('Language'); } - }else if(strpos($request->param('Language'), '_')!==false) { + } elseif (strpos($request->param('Language'), '_')!==false) { //Locale not found 404 - if($response=ErrorPage::response_for(404)) { + if ($response=ErrorPage::response_for(404)) { return $response; - }else { + } else { $this->httpError(404, 'The requested page could not be found.'); } return $this->response; - }else { + } else { $locale=i18n::get_locale_from_lang($request->param('Language')); } - - if(in_array($locale, Translatable::get_allowed_locales())) { + + if (in_array($locale, Translatable::get_allowed_locales())) { //Set the current locale and remember it Cookie::set('language', $request->param('Language')); Translatable::set_current_locale($locale); i18n::set_locale($locale); - }else { + } else { //Locale not found 404 - if($response=ErrorPage::response_for(404)) { + if ($response=ErrorPage::response_for(404)) { return $response; - }else { + } else { $this->httpError(404, 'The requested page could not be found.'); } @@ -79,7 +81,7 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { //Handle the home page for the language $urlSegment=$request->param('URLSegment'); - if(empty($urlSegment)) { + if (empty($urlSegment)) { $controller=new MultilingualRootURLController(); $response=$controller->handleRequest($request, $model); @@ -89,55 +91,56 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { } - //Normal page request so handle that + //Normal page request so handle that $response=parent::handleRequest($request, $model); - + $this->popCurrent(); return $response; } - + /** - * Overrides the default getNestedController() to maintain the language restrictions - * @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 - $sitetree = DataObject::get_one( - 'SiteTree', - sprintf( - '"URLSegment" = \'%s\' %s', - Convert::raw2sql(rawurlencode($URLSegment)), - (SiteTree::nested_urls() ? 'AND "ParentID" = 0' : null) - ) - ); - - if(!$sitetree) { + * Overrides the default getNestedController() to maintain the language restrictions + * @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 + $sitetree = DataObject::get_one( + 'SiteTree', + sprintf( + '"URLSegment" = \'%s\' %s', + Convert::raw2sql(rawurlencode($URLSegment)), + (SiteTree::nested_urls() ? 'AND "ParentID" = 0' : null) + ) + ); + + if (!$sitetree) { $response = ErrorPage::response_for(404); - $this->httpError(404, $response ? $response : 'The requested page could not be found.'); - } - - // Enforce current language setting to the loaded SiteTree object - if(class_exists('Translatable') && $sitetree->Locale) { - if(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { + $this->httpError(404, $response ? $response : 'The requested page could not be found.'); + } + + // Enforce current language setting to the loaded SiteTree object + if (class_exists('Translatable') && $sitetree->Locale) { + if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { Cookie::set('language', $sitetree->Locale); - }else { + } else { Cookie::set('language', i18n::get_lang_from_locale($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')); + } + + 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')); } /** @@ -147,13 +150,13 @@ public function getNestedController() { * @param int $parentID The ID of the parent of the page the URLSegment belongs to. * @return SiteTree */ - public static function find_old_page($URLSegment, $parent = null, $ignoreNestedURLs = false) { + public static function find_old_page($URLSegment, $parent = null, $ignoreNestedURLs = false) + { Deprecation::notice('3.2', 'Use MultilingualOldPageRedirector::find_old_page instead'); if ($parent) { - $parent = SiteTree::get()->byId($parent); + $parent = SiteTree::get()->byId($parent); } $url = MultilingualOldPageRedirector::find_old_page(array($URLSegment), $parent); return SiteTree::get_by_link($url); } } -?> \ No newline at end of file diff --git a/code/control/MultilingualRootURLController.php b/code/control/MultilingualRootURLController.php index b10036d..276a3ee 100644 --- a/code/control/MultilingualRootURLController.php +++ b/code/control/MultilingualRootURLController.php @@ -1,5 +1,6 @@ setDataModel($model); - - $this->pushCurrent(); + + $this->pushCurrent(); $this->init(); - if($language=$request->param('Language')) { - if(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { - if(Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) { + 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) { + if (strpos($language, '-')===false) { //Locale not found 404 - if($response=ErrorPage::response_for(404)) { + if ($response=ErrorPage::response_for(404)) { return $response; - }else { + } else { $this->httpError(404, 'The requested page could not be found.'); } @@ -40,11 +42,11 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model=null) { $locale[1]=strtoupper($locale[1]); //Make sure that the language is all lowercase - if($language==implode('-', $locale)) { + if ($language==implode('-', $locale)) { //Locale not found 404 - if($response=ErrorPage::response_for(404)) { + if ($response=ErrorPage::response_for(404)) { return $response; - }else { + } else { $this->httpError(404, 'The requested page could not be found.'); } @@ -52,82 +54,82 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model=null) { } $locale=implode('_', $locale); - }else { + } else { $locale=$language; } - }else if(strpos($request->param('Language'), '_')!==false) { + } elseif (strpos($request->param('Language'), '_')!==false) { //Locale not found 404 - if($response=ErrorPage::response_for(404)) { + if ($response=ErrorPage::response_for(404)) { return $response; - }else { + } else { $this->httpError(404, 'The requested page could not be found.'); } return $this->response; - }else { + } else { $locale=i18n::get_locale_from_lang($language); } - if(in_array($locale, Translatable::get_allowed_locales())) { + 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().'/'); + + 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(); + + $controller=new MultilingualModelAsController(); + $result=$controller->handleRequest($request, $model); + + $this->popCurrent(); return $result; - }else { + } 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')) { + if ($locale=self::detect_browser_locale()) { + if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { + if (Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) { $language=str_replace('_', '-', strtolower($locale)); - }else { + } else { $language=$locale; } - }else { + } else { $language=i18n::get_lang_from_locale($locale); } Cookie::set('language', $language); - + $this->redirect(Controller::join_links(Director::baseURL(), $language).'/', 301); - $this->popCurrent(); + $this->popCurrent(); return $this->response; } - if(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { - if(Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) { + if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { + if (Config::inst()->get('MultilingualRootURLController', 'UseDashLocale')) { $language=str_replace('_', '-', strtolower(Translatable::default_locale())); - }else { + } else { $language=Translatable::default_locale(); } - }else { + } else { $language=Translatable::default_lang(); } @@ -137,81 +139,83 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model=null) { return $this->response; } - /** - * Determines the locale best matching the given list of browser locales - * @return {string} The matching locale, or null if none could be determined - */ - public static function detect_browser_locale() { - if($language=Cookie::get('language')) { - if(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { + /** + * Determines the locale best matching the given list of browser locales + * @return {string} The matching locale, or null if none could be determined + */ + public static function detect_browser_locale() + { + if ($language=Cookie::get('language')) { + if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { $locale=$language; - }else { + } else { $locale=i18n::get_locale_from_lang($language); } - if(in_array($locale, Translatable::get_allowed_locales())) { + if (in_array($locale, Translatable::get_allowed_locales())) { return $locale; - }else { + } else { Cookie::force_expiry('language'); } } - // Given multiple canditates, narrow down the final result using the client's preferred languages - $inputLocales=(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER) ? $_SERVER['HTTP_ACCEPT_LANGUAGE']:null); - if(empty($inputLocales)) { + // Given multiple canditates, narrow down the final result using the client's preferred languages + $inputLocales=(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER) ? $_SERVER['HTTP_ACCEPT_LANGUAGE']:null); + if (empty($inputLocales)) { return null; - } - - // Generate mapping of priority => list of languages at this priority - // break up string into pieces (languages and q factors) - preg_match_all('/(?[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?1|0\.[0-9]+))?/i', $inputLocales, $parsedLocales); - - $prioritisedLocales=array(); - if(count($parsedLocales['code'])) { - // create a list like "en" => 0.8 - $parsedLocales=array_combine($parsedLocales['code'], $parsedLocales['priority']); - - // Generate nested list of priorities => [languages] - foreach ($parsedLocales as $language => $priority) { - $priority=(empty($priority) ? 1.0:floatval($priority)); - if(empty($prioritisedLocales[$priority])) { - $prioritisedLocales[$priority] = array(); + } + + // Generate mapping of priority => list of languages at this priority + // break up string into pieces (languages and q factors) + preg_match_all('/(?[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?1|0\.[0-9]+))?/i', $inputLocales, $parsedLocales); + + $prioritisedLocales=array(); + if (count($parsedLocales['code'])) { + // create a list like "en" => 0.8 + $parsedLocales=array_combine($parsedLocales['code'], $parsedLocales['priority']); + + // Generate nested list of priorities => [languages] + foreach ($parsedLocales as $language => $priority) { + $priority=(empty($priority) ? 1.0:floatval($priority)); + if (empty($prioritisedLocales[$priority])) { + $prioritisedLocales[$priority] = array(); } - - $prioritisedLocales[$priority][]=$language; - } - - // sort list based on value - krsort($prioritisedLocales, SORT_NUMERIC); - } - - // Check each requested language against loaded languages - foreach ($prioritisedLocales as $priority=>$parsedLocales) { - foreach($parsedLocales as $browserLocale) { - foreach(Translatable::get_allowed_locales() as $language) { - if(stripos(preg_replace('/_/', '-', $language), $browserLocale)===0) { - return $language; - } - } - } - } - - return null; + + $prioritisedLocales[$priority][]=$language; + } + + // sort list based on value + krsort($prioritisedLocales, SORT_NUMERIC); + } + + // Check each requested language against loaded languages + foreach ($prioritisedLocales as $priority=>$parsedLocales) { + foreach ($parsedLocales as $browserLocale) { + foreach (Translatable::get_allowed_locales() as $language) { + if (stripos(preg_replace('/_/', '-', $language), $browserLocale)===0) { + return $language; + } + } + } + } + + return null; } - - - /** - * 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 true; - } - - return false; + + + /** + * 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 true; + } + + return false; } /** @@ -220,7 +224,8 @@ public static function should_be_on_root(SiteTree $page) { * * @deprecated 3.2 Use the "MultilingualRootURLController.UseLocaleURL" config setting instead */ - public static function set_use_locale_url($value) { + public static function set_use_locale_url($value) + { Deprecation::notice('3.2', 'Use the "MultilingualRootURLController.UseLocaleURL" config setting instead'); Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', $value); } @@ -231,9 +236,9 @@ public static function set_use_locale_url($value) { * * @deprecated 3.2 Use the "MultilingualRootURLController.UseLocaleURL" config setting instead */ - public static function get_use_locale_url() { + public static function get_use_locale_url() + { Deprecation::notice('3.2', 'Use the "MultilingualRootURLController.UseLocaleURL" config setting instead'); return Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL'); } } -?> \ No newline at end of file diff --git a/code/extensions/MultilingualControllerExtension.php b/code/extensions/MultilingualControllerExtension.php index 3b6aeeb..bd0f55a 100644 --- a/code/extensions/MultilingualControllerExtension.php +++ b/code/extensions/MultilingualControllerExtension.php @@ -1,48 +1,50 @@ owner instanceof MultilingualRootURLController || $this->owner instanceof MultilingualModelAsController || $this->owner instanceof LeftAndMain || $this->owner instanceof DevelopmentAdmin || $this->owner instanceof TestRunner) { + 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) { + 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')) { + if ($request && $request->param('Language')) { $language=$request->param('Language'); - if(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { - $locale=$language; - }else if(strpos($request->param('Language'), '_')!==false) { + if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { + $locale=$language; + } elseif (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())) { + } 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); + //Set the various locales + Translatable::set_current_locale($locale); i18n::set_locale($locale); - }else { + } else { //Unknown language so redirect to the default $url=$request->getURL(true); $default=(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL') ? Translatable::default_locale():Translatable::default_lang()); @@ -55,10 +57,10 @@ public function onBeforeInit() { //Detect the locale - if($locale=MultilingualRootURLController::detect_browser_locale()) { - if(Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { + if ($locale=MultilingualRootURLController::detect_browser_locale()) { + if (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL')) { $language=$locale; - }else { + } else { $language=i18n::get_lang_from_locale($locale); } @@ -78,8 +80,8 @@ public function onBeforeInit() { * @return {string} Multilingual link to this controller * @see Controller::Link() */ - public function MultilingualLink() { + public function MultilingualLink() + { return Controller::join_links((Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL') ? i18n::get_locale():i18n::get_lang_from_locale(i18n::get_locale())), get_class($this->owner)).'/'; } } -?> \ No newline at end of file diff --git a/code/extensions/MultilingualOldPageRedirector.php b/code/extensions/MultilingualOldPageRedirector.php index 27f298f..1c88337 100644 --- a/code/extensions/MultilingualOldPageRedirector.php +++ b/code/extensions/MultilingualOldPageRedirector.php @@ -1,95 +1,97 @@ allParams()), function($v) { return ($v !== NULL); }); +class MultilingualOldPageRedirector extends Extension +{ + /** + * On every URL that generates a 404, we'll capture it here and see if we can + * find an old URL that it should be redirecting to. + * + * @param SS_HTTPResponse $request The request object + */ + public function onBeforeHTTPError404($request) + { + // Build up the request parameters + $params=array_filter(array_values($request->allParams()), function ($v) { return ($v !== null); }); unset($params[0]); //Remove the locale from the url - - $getvars=$request->getVars(); + + $getvars=$request->getVars(); unset($getvars['url']); - + $page=self::find_old_page($params); - - if($page) { - $res=new SS_HTTPResponse(); - $res->redirect( - Controller::join_links( - $page, - ($getvars) ? '?' . http_build_query($getvars) : null + + if ($page) { + $res=new SS_HTTPResponse(); + $res->redirect( + Controller::join_links( + $page, + ($getvars) ? '?' . http_build_query($getvars) : null ), 301); - - throw new SS_HTTPResponse_Exception($res); - } + + throw new SS_HTTPResponse_Exception($res); + } } - /** - * Attempt to find an old/renamed page from some given the URL as an array - * - * @param array $params The array of URL, e.g. /foo/bar as array('foo', 'bar') - * @param SiteTree $parent The current parent in the recursive flow - * @param boolean $redirect Whether we've found an old page worthy of a redirect - * - * @return string|boolean False, or the new URL - */ - public static function find_old_page($params, $parent = null, $redirect = false) { - $URL=Convert::raw2sql(array_shift($params)); - if (empty($URL)) { - return false; + /** + * Attempt to find an old/renamed page from some given the URL as an array + * + * @param array $params The array of URL, e.g. /foo/bar as array('foo', 'bar') + * @param SiteTree $parent The current parent in the recursive flow + * @param boolean $redirect Whether we've found an old page worthy of a redirect + * + * @return string|boolean False, or the new URL + */ + public static function find_old_page($params, $parent = null, $redirect = false) + { + $URL=Convert::raw2sql(array_shift($params)); + if (empty($URL)) { + return false; + } + + if ($parent) { + $page=SiteTree::get()->filter(array('ParentID' => $parent->ID, 'URLSegment' => $URL))->First(); + } else { + $page=SiteTree::get()->filter(array('URLSegment' => $URL))->First(); } - - if($parent) { - $page=SiteTree::get()->filter(array('ParentID' => $parent->ID, 'URLSegment' => $URL))->First(); - }else { - $page=SiteTree::get()->filter(array('URLSegment' => $URL))->First(); - } - - if(!$page) { - // If we haven't found a candidate, lets resort to finding an old page with this URL segment - // TODO: Rewrite using ORM syntax - $query=new SQLQuery ( - '"RecordID"', - '"SiteTree_versions"', - "\"URLSegment\" = '$URL' AND \"WasPublished\" = 1 AND \"Locale\"='".Translatable::get_current_locale()."'". ($parent ? ' AND "ParentID" = ' . $parent->ID : ''), - '"LastEdited" DESC', - null, - null, - 1 + + if (!$page) { + // If we haven't found a candidate, lets resort to finding an old page with this URL segment + // TODO: Rewrite using ORM syntax + $query=new SQLQuery( + '"RecordID"', + '"SiteTree_versions"', + "\"URLSegment\" = '$URL' AND \"WasPublished\" = 1 AND \"Locale\"='".Translatable::get_current_locale()."'". ($parent ? ' AND "ParentID" = ' . $parent->ID : ''), + '"LastEdited" DESC', + null, + null, + 1 ); - $record=$query->execute()->first(); - if($record) { - $page=SiteTree::get()->byID($record['RecordID']); - $redirect=true; - } - } - - if ($page && $page->canView()) { - if (count($params)) { + $record=$query->execute()->first(); + if ($record) { + $page=SiteTree::get()->byID($record['RecordID']); + $redirect=true; + } + } + + if ($page && $page->canView()) { + if (count($params)) { // We have to go deeper! - $ret = self::find_old_page($params, $page, $redirect); - if ($ret) { - // A valid child page was found! We can return it - return $ret; - } else { - // No valid page found. - if ($redirect) { - // If we had some redirect to be done, lets do it. imagine /foo/action -> /bar/action, we still want this redirect to happen if action isn't a page - return $page->Link() . implode('/', $params); - } - } - } else { - // We've found the final, end all, page. - return $page->Link(); - } - } - - return false; + $ret = self::find_old_page($params, $page, $redirect); + if ($ret) { + // A valid child page was found! We can return it + return $ret; + } else { + // No valid page found. + if ($redirect) { + // If we had some redirect to be done, lets do it. imagine /foo/action -> /bar/action, we still want this redirect to happen if action isn't a page + return $page->Link() . implode('/', $params); + } + } + } else { + // We've found the final, end all, page. + return $page->Link(); + } + } + + return false; } } -?> \ No newline at end of file diff --git a/code/extensions/MultilingualSiteTreeExtension.php b/code/extensions/MultilingualSiteTreeExtension.php index 2ffb4ae..b063578 100644 --- a/code/extensions/MultilingualSiteTreeExtension.php +++ b/code/extensions/MultilingualSiteTreeExtension.php @@ -1,12 +1,14 @@ dataFieldByName('URLSegment'); - if($urlSegmentField) { + if ($urlSegmentField) { $baseLink=Controller::join_links( Director::absoluteBaseURL(), (Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL') ? $this->owner->Locale:i18n::get_lang_from_locale($this->owner->Locale)).'/', @@ -22,8 +24,8 @@ public function updateCMSFields(FieldList $fields) { * Gets the RFC 1766 version of the input locale * @return {string} RFC 1766 version of the locale (i.e en-US) */ - public function getRFC1766Locale() { + public function getRFC1766Locale() + { return i18n::convert_rfc1766($this->owner->Locale); } } -?> \ No newline at end of file diff --git a/tests/MultilingualControllerTest.php b/tests/MultilingualControllerTest.php index 0469673..92d5e86 100644 --- a/tests/MultilingualControllerTest.php +++ b/tests/MultilingualControllerTest.php @@ -1,5 +1,6 @@ origLocaleRoutingEnabled=Config::inst()->get('MultilingualRootURLController', 'UseLocaleURL'); @@ -47,7 +49,8 @@ public function setUp() { MultilingualRootURLController::reset(); } - public function tearDown() { + public function tearDown() + { MultilingualRootURLController::set_use_locale_url($this->origLocaleRoutingEnabled); Translatable::set_current_locale($this->origCurrentLocale); @@ -58,7 +61,7 @@ public function tearDown() { Cookie::force_expiry('language'); - if($this->origCookieLocale) { + if ($this->origCookieLocale) { Cookie::set('language', $this->origCookieLocale); } @@ -72,7 +75,8 @@ public function tearDown() { /** * Tests to see if the controller responds correctly if the language is in the url */ - public function testLanguageInURL() { + public function testLanguageInURL() + { //Perform Request $response=$this->get('fr/multilingual-test-controller/'); @@ -81,21 +85,22 @@ public function testLanguageInURL() { $this->assertEquals(200, $response->getStatusCode()); - //Verify the response matches what is expected + //Verify the response matches what is expected $this->assertEquals('i18n: fr_FR|Translatable: fr_FR', $response->getBody()); } /** * Tests to see if the controller responds correctly if the locale is in the url */ - public function testLocaleInURL() { - //Enable locale urls - Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', true); - - //Set accept language to french - $_SERVER['HTTP_ACCEPT_LANGUAGE']='fr-FR,fr;q=0.5'; - - //Get the root url + public function testLocaleInURL() + { + //Enable locale urls + Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', true); + + //Set accept language to french + $_SERVER['HTTP_ACCEPT_LANGUAGE']='fr-FR,fr;q=0.5'; + + //Get the root url $response=$this->get('fr_FR/multilingual-test-controller/'); @@ -104,13 +109,14 @@ public function testLocaleInURL() { //Verify the response matches what is expected - $this->assertEquals('i18n: fr_FR|Translatable: fr_FR', $response->getBody()); + $this->assertEquals('i18n: fr_FR|Translatable: fr_FR', $response->getBody()); } /** * Tests to see if the controller responds correctly if the language is in the url */ - public function testAutoDetectLanguage() { + public function testAutoDetectLanguage() + { //Set accept language to french $_SERVER['HTTP_ACCEPT_LANGUAGE']='fr-FR,fr;q=0.5'; Translatable::set_default_locale('fr_FR'); @@ -133,7 +139,8 @@ public function testAutoDetectLanguage() { /** * Tests to see if the controller responds correctly if the language is in the url */ - public function testInvalidLanguageURL() { + public function testInvalidLanguageURL() + { //Perform Request $response=$this->get('es/multilingual-test-controller/'); @@ -147,13 +154,14 @@ public function testInvalidLanguageURL() { } } -class MultilingualTestController extends Controller implements TestOnly { +class MultilingualTestController extends Controller implements TestOnly +{ private static $extensions=array( 'MultilingualControllerExtension' ); - public function index() { - return 'i18n: '.i18n::get_locale().'|Translatable: '.Translatable::get_current_locale(); + public function index() + { + return 'i18n: '.i18n::get_locale().'|Translatable: '.Translatable::get_current_locale(); } } -?> \ No newline at end of file diff --git a/tests/MultilingualModelAsControllerTest.php b/tests/MultilingualModelAsControllerTest.php index f787b90..7f99a4a 100644 --- a/tests/MultilingualModelAsControllerTest.php +++ b/tests/MultilingualModelAsControllerTest.php @@ -1,5 +1,6 @@ filter('Locale', 'en_US'); - foreach($pages as $page) { + 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) { + foreach ($pagesFR as $index=>$page) { $page->addTranslationGroup($pages->offsetGet($index)->ID, true); $page->publish('Stage', 'Live'); } @@ -63,7 +65,8 @@ public function setUp() { MultilingualRootURLController::reset(); } - public function tearDown() { + public function tearDown() + { Config::inst()->update('MultilingualRootURLController', 'UseDashLocale', $this->origLocaleRoutingEnabled); Config::inst()->update('MultilingualRootURLController', 'UseDashLocale', $this->origDashLocaleEnabled); @@ -75,7 +78,7 @@ public function tearDown() { Cookie::force_expiry('language'); - if($this->origCookieLocale) { + if ($this->origCookieLocale) { Cookie::set('language', $this->origCookieLocale); } @@ -89,7 +92,8 @@ public function tearDown() { /** * Verifies that the language/locale is required on the url */ - public function testMultilingualRequired() { + public function testMultilingualRequired() + { $page=$this->objFromFixture('Page', 'page1'); $response=$this->get($page->URLSegment); @@ -99,10 +103,11 @@ public function testMultilingualRequired() { $this->assertEquals(200, $response->getStatusCode()); } - /** + /** * Tests to ensure that loading a page not on the current language returns a page not found when accessing it via the wrong url */ - public function testCrossLangNotFound() { + public function testCrossLangNotFound() + { $page=$this->objFromFixture('Page', 'page1_fr'); $response=$this->get('en/'.$page->URLSegment.'/'); @@ -112,7 +117,8 @@ public function testCrossLangNotFound() { /** * Tests to see if the english home page is the root url and the french home page is not for english browsers */ - public function testEnglishShouldBeRoot() { + public function testEnglishShouldBeRoot() + { $default=$this->objFromFixture('Page', 'home'); $defaultFR=$this->objFromFixture('Page', 'home_fr'); @@ -123,7 +129,8 @@ public function testEnglishShouldBeRoot() { /** * 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() { + public function testFrenchShouldBeRoot() + { //Set accept language to french $_SERVER['HTTP_ACCEPT_LANGUAGE']='fr-FR,fr;q=0.5'; Translatable::set_default_locale('fr_FR'); @@ -137,4 +144,3 @@ public function testFrenchShouldBeRoot() { $this->assertEquals(true, MultilingualRootURLController::should_be_on_root($defaultFR)); } } -?> \ No newline at end of file diff --git a/tests/MultilingualRootURLControllerTest.php b/tests/MultilingualRootURLControllerTest.php index 4a31c73..1128989 100644 --- a/tests/MultilingualRootURLControllerTest.php +++ b/tests/MultilingualRootURLControllerTest.php @@ -1,5 +1,6 @@ update('MultilingualRootURLController', 'UseLocaleURL', $this->origLocaleRoutingEnabled); Config::inst()->update('MultilingualRootURLController', 'UseDashLocale', $this->origDashLocaleEnabled); @@ -66,7 +69,7 @@ public function tearDown() { Cookie::force_expiry('language'); - if($this->origCookieLocale) { + if ($this->origCookieLocale) { Cookie::set('language', $this->origCookieLocale); } @@ -80,7 +83,8 @@ public function tearDown() { /** * Tests to ensure that the site redirects to the default language root url when the user hits the site root */ - public function testEnglishLangRootRouting() { + public function testEnglishLangRootRouting() + { //Get the root url $response=$this->get(''); @@ -97,7 +101,8 @@ public function testEnglishLangRootRouting() { /** * Tests to ensure that the site redirects to the french language root url when the user hits the site root and the users accept language is french first */ - public function testFrenchLangRootRouting() { + public function testFrenchLangRootRouting() + { //Set accept language to french $_SERVER['HTTP_ACCEPT_LANGUAGE']='fr-FR,fr;q=0.5'; @@ -113,11 +118,12 @@ public function testFrenchLangRootRouting() { $response->getHeader('Location') ); } - - /** - * Tests to ensure that the site redirects to the default locale root url when the user hits the site root and the MultilingualRootURLController.UseLocaleURL is set to true + + /** + * Tests to ensure that the site redirects to the default locale root url when the user hits the site root and the MultilingualRootURLController.UseLocaleURL is set to true */ - public function testEnglishLocaleRootRouting() { + public function testEnglishLocaleRootRouting() + { //Enable locale urls Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', true); @@ -137,7 +143,8 @@ public function testEnglishLocaleRootRouting() { /** * Tests to ensure that the site redirects to the french locale root url when the user hits the site root and the users accept language is french first with the MultilingualRootURLController.UseLocaleURL is set to true */ - public function testFrenchLocaleRootRouting() { + public function testFrenchLocaleRootRouting() + { //Enable locale urls Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', true); @@ -160,7 +167,8 @@ public function testFrenchLocaleRootRouting() { /** * Tests to ensure that the site redirects to the default locale root url when the user hits the site root and the MultilingualRootURLController.UseLocaleURL is set to true and MultilingualRootURLController.UseDashLocale is set to true */ - public function testEnglishDashLocaleRootRouting() { + public function testEnglishDashLocaleRootRouting() + { //Enable locale urls Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', true); Config::inst()->update('MultilingualRootURLController', 'UseDashLocale', true); @@ -189,7 +197,8 @@ public function testEnglishDashLocaleRootRouting() { /** * Tests to ensure that the site redirects to the french locale root url when the user hits the site root and the users accept language is french first with the MultilingualRootURLController.UseLocaleURL is set to true and MultilingualRootURLController.UseDashLocale is set to true */ - public function testFrenchDashLocaleRootRouting() { + public function testFrenchDashLocaleRootRouting() + { //Enable locale urls Config::inst()->update('MultilingualRootURLController', 'UseLocaleURL', true); Config::inst()->update('MultilingualRootURLController', 'UseDashLocale', true); @@ -221,14 +230,16 @@ public function testFrenchDashLocaleRootRouting() { /** * Verifies the correct home page is detected */ - public function testEnglishGetHomepageLink() { + public function testEnglishGetHomepageLink() + { $this->assertEquals('home', MultilingualRootURLController::get_homepage_link()); } /** * Verifies the correct home page is detected for the french locale */ - public function testFrenchGetHomepageLink() { + public function testFrenchGetHomepageLink() + { //Set accept language to french $_SERVER['HTTP_ACCEPT_LANGUAGE']='fr-FR,fr;q=0.5'; Translatable::set_default_locale('fr_FR'); @@ -238,4 +249,3 @@ public function testFrenchGetHomepageLink() { $this->assertEquals('maison', MultilingualRootURLController::get_homepage_link()); } } -?> \ No newline at end of file diff --git a/tests/pre-up/travis_setup.php b/tests/pre-up/travis_setup.php index 137866e..4192b3d 100644 --- a/tests/pre-up/travis_setup.php +++ b/tests/pre-up/travis_setup.php @@ -5,17 +5,17 @@ } $opts = getopt('', array( - 'target:', // required + 'target:', // required )); // Sanity checks -if(!$opts || !isset($opts['target'])) { - echo "Invalid arguments specified\n"; - exit(1); +if (!$opts || !isset($opts['target'])) { + echo "Invalid arguments specified\n"; + exit(1); } $targetPath=$opts['target']; -if(!file_exists("$targetPath/mysite/code/Page.php")) { +if (!file_exists("$targetPath/mysite/code/Page.php")) { echo "Cannot find Page class in mysite\n"; exit(1); } @@ -65,4 +65,3 @@ class Page_'; $f=fopen("$targetPath/mysite/code/Page.php", 'w'); fwrite($f, $pageContents); fclose($f); -?> \ No newline at end of file