<?php
class TranslatedModelAsController extends ModelAsController {
private $locale;
private $page;
public function init() {
if(isset($_REQUEST["stage"])) {
$_SESSION["currentStage"] = $_REQUEST["stage"];
} else {
$_SESSION["currentStage"] = "Live";
Versioned::reading_stage("Live");
}
$this->checkUrl();
}
public function setPage($page) {
$this->page = $page;
}
public function setLocale($locale) {
$this->locale = $this->checkLocale($locale);
Translatable::set_current_locale($this->locale);
}
public static function getLocale() {
return self::$locale;
}
public function checkUrl() {
if(empty($this->URLParams['URLSegment1']) && empty($this->URLParams['URLSegment2'])) {
$this->setLocale($this->getProbableLocale());
$this->setPage("home");
}
if(!empty($this->URLParams['URLSegment1']) && !empty($this->URLParams['URLSegment2'])) {
$this->setLocale($this->URLParams['URLSegment1']);
$this->setPage($this->URLParams['URLSegment2']);
}
}
public function checkLocale($str) {
if(preg_match('/(^[a-z]{2})_([A-Z]{2})$/', $str, $matches)) {
return $str;
}
if(preg_match('/(^[a-zA-Z]{2})-([a-zA-Z]{2})$/', $str, $matches)) {
return strtolower($matches[1])."_".strtoupper($matches[2]);
}
return $this->getProbableLocale();
}
public function getProbableLocale() {
return Translatable::default_locale();
}
public function getNestedController() {
if($this->page) {
$SQL_URLSegment = Convert::raw2sql($this->page);
$child = SiteTree::get_by_url($SQL_URLSegment);
if(!$child) {
$child = $this->findOldPage($SQL_URLSegment);
if($child) {
$url = Controller::join_links(
Director::baseURL(),
$this->locale,
$this->page,
(isset($this->urlParams['Action'])) ? $this->urlParams['Action'] : null,
(isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null,
(isset($this->urlParams['OtherID'])) ? $this->urlParams['OtherID'] : null
);
$response = new HTTPResponse();
$response->redirect($url, 301);
return $response;
}
$child = $this->get404Page();
}
if($child) {
if(isset($_REQUEST['debug'])) Debug::message("Using record #$child->ID of type $child->class with URL {$this->urlParams['URLSegment']}");
if($child->Locale) Translatable::set_current_locale($child->Locale);
$controllerClass = "{$child->class}_Controller";
if($this->urlParams['Action'] && ClassInfo::exists($controllerClass.'_'.$this->urlParams['Action'])) {
$controllerClass = $controllerClass.'_'.$this->urlParams['Action'];
}
if(ClassInfo::exists($controllerClass)) {
$controller = new $controllerClass($child);
} else {
$controller = $child;
}
$controller->setLocale($this->locale);
return $controller;
} else {
return new HTTPResponse("The requested page couldn't be found.",404);
}
}
else {
user_error("ModelAsController not geting a URLSegment. It looks like the site isn't redirecting to home", E_USER_ERROR);
}
}
}
?>