<?php

if (!defined('XOOPS_ROOT_PATH')) exit();

define("LEGACY_CONTROLLER_STATE_PUBLIC",1);
define("LEGACY_CONTROLLER_STATE_ADMIN",2);

/**
 * This class is a virtual controller that has the compatibility with XOOPS 2.0.x.
 * 
 * [NOTICE]
 * XOOPS 2.0.x can switch to public mode and control panel mode. This controller
 * emulates its process with using STATE. But, we may lose flexible setup by this
 * implement. Now, we are investigating the influence.
 *
 * [TODO]
 * XCube_Controller keeps a process that set up instances of some legacy classes,
 * yet. We should move its process to this controller.
 */
class Legacy_Controller extends XCube_Controller
{
	var $mXoopsUser;

	var $_mAdminModeFlag=false;
	var $_mControllerState=null;
	
	var $mDialogMode=false;
	
	function Legacy_Controller()
	{
		set_magic_quotes_runtime(0);	// ^^;
		
		//
		// Decide status. [TEST]
		//
		$urlInfo=$this->_parseUrl();
		$adminStateFlag=false;

		if(count($urlInfo)>=3) {
			if(strtolower($urlInfo[0])=="modules" && strtolower($urlInfo[2])=="admin"){
				$adminStateFlag=true;
			}
			elseif($urlInfo[0] == "modules" && $urlInfo[1] == "system" && substr($urlInfo[2], 0, 9) == "admin.php") {
				$adminStateFlag=true;
			}
		}
		elseif(substr($urlInfo[0], 0, 9) == "admin.php") {
			$adminStateFlag=true;
		}

		$this->_mControllerState= $adminStateFlag ?  new BaseControllerAdminState() : new BaseControllerPublicState();
	}

	function _setupLogger()
	{
		require_once XOOPS_ROOT_PATH.'/class/logger.php';
		$this->mLogger=&XoopsLogger::instance();
		$this->mLogger->startTime();

		$GLOBALS['xoopsLogger']=&$this->mLogger;
	}

	function _setupEnvironment()
	{
		parent::_setupEnvironment();
		require_once XOOPS_ROOT_PATH."/include/version.php";
		
		require_once XOOPS_ROOT_PATH."/settings/definition.inc.php";
		define("XOOPS_BASE_PATH",XOOPS_MODULE_PATH."/".XOOPS_BASE_PROC_NAME);

		require_once XOOPS_ROOT_PATH.'/include/functions.php';

		require_once XOOPS_ROOT_PATH.'/kernel/object.php';
		require_once XOOPS_ROOT_PATH.'/class/criteria.php';
		require_once XOOPS_ROOT_PATH.'/class/token.php';
		require_once XOOPS_ROOT_PATH."/class/module.textsanitizer.php";

		require_once XOOPS_BASE_PATH."/kernel/object.php";				// ToDo (here?)
		require_once XOOPS_BASE_PATH."/kernel/handler.php";				// ToDo
		require_once XOOPS_ROOT_PATH."/class/XCube_Utils.class.php";	// ToDo

		require_once XOOPS_ROOT_PATH.'/class/xoopssecurity.php';
		$_GLOBALS['xoopsSecurity'] = new XoopsSecurity();

		require_once XOOPS_ROOT_PATH."/include/version.php";
	}

	/**
	 * [NOTICE]
	 * We set up only filters that are decided to register by us. This is not
	 * flexible. This is not the style fixed.
	 *
	 * [MEMO]
	 * For test, you can use automatic loading plug-in with writing a setting
	 * in site_custom.ini.php.
	 * 
	 * site_custom.ini.php:
	 *  [Legacy]
	 *  AutoPreload = 1
	 *
	 */
	function _setupFilterChain()
	{
		require_once XOOPS_ROOT_PATH."/modules/base/preload/protectorLE/protectorLE.class.php";
		$protector=new protectorLE_Filter($this);
		$this->addActionFilter($protector);

		require_once XOOPS_ROOT_PATH."/modules/base/preload/IPbanning/IPbanning.class.php";
		$ipban=new IPbanning_Filter($this);
		$this->addActionFilter($ipban);

		require_once XOOPS_ROOT_PATH."/modules/base/preload/SiteClose/SiteClose.class.php";
		$siteclose = new SiteClose_Filter($this);
		$this->addActionFilter($siteclose);

		require_once XOOPS_ROOT_PATH."/modules/base/preload/ThemeSelect/ThemeSelect.class.php";
		$themeselect = new ThemeSelect_Filter($this);
		$this->addActionFilter($themeselect);

		//
		// Auto pre-loading.
		//
		if($this->mRoot->getSiteConfig('Legacy','AutoPreload')==1) {
			$dir=XOOPS_ROOT_PATH."/preload/";
			if(is_dir($dir)) {
				if($handler=opendir($dir)) {
					while(($file=readdir($handler))!==false) {
						if(preg_match("/(\w+)\.class\.php$/",$file,$matches)) {
							require_once $dir.$file;
							$className=$matches[1];
							if(class_exists($className)) {
								$instance =& new $className($this);
								$this->addActionFilter($instance);
							}
						}
					}
					closedir($handler);
				}
			}
		}
	}

	function _setupBlock()
	{
		$this->_mControllerState->setupBlock($this);
	}

	function _processBlock()
	{
		$i=0;
		
		$blockTarget=new XCube_RenderTarget();
		$blockTarget->setType(XCUBE_RENDER_TARGET_TYPE_BLOCK);
		
		$cache =& $this->mRoot->getCacheSystem();

		foreach($this->mBlockChain as $blockProcedure) {
			$cache->reset();
			$blockTarget->reset();

			$cache->setResourceName("block" . $blockProcedure->getId());
			if ($cache->isCache($blockProcedure->getCacheTime())) {
				$content = $cache->load();
				if ($content) {
					$this->mRenderSystem->mBlockContents[$blockProcedure->getEntryIndex()][] = array(
							'title'   => $blockProcedure->getTitle(),
							'content' => $cache->load(),
							'weight'  => $blockProcedure->getWeight()
					);
				}
			}
			else {
				$blockProcedure->execute($this,$this->getXoopsUser());

				if (!$blockProcedure->hasResult()) {
					continue;
				}
					
				$blockTarget->setAttribute("mid",$blockProcedure->getId());

				if ($blockProcedure->getTemplateName() == null) {
					$this->mRenderSystem->mBlockShowFlags[$blockProcedure->getEntryIndex()] = true;
					$result = $blockProcedure->getResult();
					
					$blockTarget->setTemplateName('system_dummy.html');
					$blockTarget->setAttribute('dummy_content', $result['content']);
				}
				else {
					$blockTarget->setTemplateName($blockProcedure->getTemplateName());
					$blockTarget->setAttribute("block",$blockProcedure->getResult());
				}

				$this->mRenderSystem->renderBlock($blockTarget);
				
				$content = $blockTarget->getResult();
				
				if ($content) {
					$this->mRenderSystem->mBlockShowFlags[$blockProcedure->getEntryIndex()] = true;
					$this->mRenderSystem->mBlockContents[$blockProcedure->getEntryIndex()][] = array(
							'title'=>$blockProcedure->getTitle(),
							'content'=>$blockTarget->getResult(),
							'weight'=>$blockProcedure->getWeight()
					);
				}

				if ($blockProcedure->getCacheTime() > 0) {
					$cache->save($blockTarget);
				}
			}

			unset($blockProcedure);
		}
	}

	function _parseUrl()
	{
		$ret = array();
		
		$nakedRootPath=substr(strstr(XOOPS_URL,$_SERVER['HTTP_HOST']),strlen($_SERVER['HTTP_HOST'])) . "/";
		$subPath=substr($_SERVER['REQUEST_URI'],strlen($nakedRootPath));

		return explode("/",$subPath);
	}

	function _setupModuleController()
	{
		$this->_mControllerState->setupModuleController($this);
	}

	function _processModuleController()
	{
		if(parent::_processModuleController()) {
			$GLOBALS['xoopsModule']=&$this->mModuleController->mModuleObject;			// TODO
			$GLOBALS['xoopsModuleConfig']=$this->mModuleController->getConfig();
		}
	}

	function _processHostAbstractLayer()
	{
		if ( !isset($_SERVER['PATH_TRANSLATED']) && isset($_SERVER['SCRIPT_FILENAME']) ) {
			// There is this setting for CGI mode. @todo We have to confirm this.
			$_SERVER['PATH_TRANSLATED'] =& $_SERVER['SCRIPT_FILENAME'];
		} elseif ( isset($_SERVER['PATH_TRANSLATED']) && !isset($_SERVER['SCRIPT_FILENAME']) ) {
			// There is this setting for IIS Win2K. Really?
			$_SERVER['SCRIPT_FILENAME'] =& $_SERVER['PATH_TRANSLATED'];
		}

		// IIS does not set REQUEST_URI. This system defines it. But...
		if (empty($_SERVER['REQUEST_URI'])) {
			if ( !( $_SERVER[ 'REQUEST_URI' ] = @$_SERVER['PHP_SELF'] ) ) {
				$_SERVER[ 'REQUEST_URI' ] = $_SERVER['SCRIPT_NAME'];
			}
			if ( isset( $_SERVER[ 'QUERY_STRING' ] ) ) {
				$_SERVER[ 'REQUEST_URI' ] .= '?' . $_SERVER[ 'QUERY_STRING' ];
			}
		    
			// Guard for XSS string of PHP_SELF
			// @todo I must move this logic to preload plugin.
			if(preg_match("/[\<\>\"\'\(\)]/",$_SERVER['REQUEST_URI']))
				die();
		}

		// What is this!? But, old system depends this setting. We have to confirm it and modify!
		$GLOBALS['xoopsRequestUri'] = $_SERVER[ 'REQUEST_URI' ];
	}

	function _setupUser()
	{
		$eventManager=&$this->mRoot->getEventManager();
		if($eventManager!=null) {
			$eventArgs= new LoginEventArgs();
			$eventManager->raiseEvent("Site.Login",$this,$eventArgs);

			if($eventArgs->hasXoopsUser())
				$this->mXoopsUser=&$eventArgs->getXoopsUser();
		}

		// Set instance to global variable for compatiblity with XOOPS 2.0.x
		$GLOBALS['xoopsUser']=&$this->mXoopsUser;
		$GLOBALS['xoopsUserIsAdmin'] = is_object($this->mXoopsUser) ? $this->mXoopsUser->isAdmin(1) : false;	//@todo Remove '1'

		//
		// Set member handler to global variables for compatibility with XOOPS 2.0.x.
		//		
		$GLOBALS['xoopsMemberHandler'] =& xoops_gethandler('member');
		$GLOBALS['member_handler'] =& $GLOBALS['xoopsMemberHandler'];
	}
	
	function _setupErrorHandler()
	{
	}

	/**
	 * Create the instance of DataBase class, and set it to member property.
	 * @access protected
	 */
	function _setupDB()
	{
		if(!defined('XOOPS_XMLRPC'))
			define('XOOPS_DB_CHKREF', 1);
		else
			define('XOOPS_DB_CHKREF', 0);

		require_once XOOPS_ROOT_PATH.'/class/database/databasefactory.php';

		if ($_SERVER['REQUEST_METHOD'] != 'POST' || !xoops_refcheck(XOOPS_DB_CHKREF)) {
			define('XOOPS_DB_PROXY', 1);
		}

		$this->mDB =& XoopsDatabaseFactory::getDatabaseConnection();

		$GLOBALS['xoopsDB']=&$this->mDB;
	}
	
	function _setupConfig()
	{
		$configHandler=&xoops_gethandler('config');
		$this->mConfig=&$configHandler->getConfigsByCat(XOOPS_CONF);

		$this->mRoot->setThemeName($this->mConfig['theme_set']);

		$GLOBALS['xoopsConfig']=&$this->mConfig;
		
		$this->mRoot->setThemeName($this->mConfig['theme_set']);
	}

	/**
	 * Set debbuger object to member property.
	 * @return void
	 */
	function _setupDebugger()
	{
		error_reporting(0);

		require_once XOOPS_BASE_PATH."/class/debug/XoopsDebugManager.class.php";
		
		$debug_mode = $this->mConfig['debug_mode'];
		if(defined("OH_MY_GOD_HELP_ME"))
			$debug_mode = XOOPS_DEBUG_PHP;

		$this->mDebugger=&XoopsDebuggerManager::getInstance($debug_mode);
		$this->mDebugger->setup();

		$GLOBALS['xoopsDebugger']=&$this->mDebugger;
	}

	function _processPreBlockFilter()
    {
		//
		// Auto pre-loading for Module.
		//
		if($this->mRoot->getSiteConfig('Legacy','AutoPreload')==1) {
            $moduleHandler =& xoops_gethandler('module');
            $moduleObjects =& $moduleHandler->getObjects();
            foreach($moduleObjects as $moduleObject) {
                $mod_dir = $moduleObject->getVar('dirname');
                $dir = XOOPS_ROOT_PATH.'/modules/'.$mod_dir.'/class/';
    			if(is_dir($dir)) {
    			    $files = glob($dir.'modulePreload*.class.php');
    			    if (is_array($files)) {
						foreach($files as $file) {
							require_once $file;
							$className=preg_replace('/^modulePreload(\w*)\.class\.php/', $mod_dir.'ModulePreload\1', basename($file));
							if(class_exists($className)) {
								$instance =& new $className($this);
								$this->addActionFilter($instance);
							}
						}
    			    }
    			}
            }
        }
        parent::_processPreBlockFilter();
    }

	function _setupSession()
	{
		global $xoopsDB;

		$sessionHandler=&xoops_gethandler('session');
		
		session_set_save_handler( 
			array(&$sessionHandler,"open"),
			array(&$sessionHandler,"close"),
			array(&$sessionHandler, 'read'),
			array(&$sessionHandler, 'write'),
			array(&$sessionHandler, 'destroy'),
			array(&$sessionHandler, 'gc'));
		
		session_start();
	}

	function &_createLanguageManager()
	{
		global $xoopsOption;

		require_once XOOPS_BASE_PATH."/kernel/Legacy_LanguageManager.class.php";
		
		$languageManager =& new Legacy_LanguageManager($this->mConfig['language']);
		$languageManager->loadMainLanguage();
		
		// If you use special page, load message catalog for it.
		if (isset($xoopsOption['pagetype']))
			$languageManager->loadSpecialTypeLanguage($xoopsOption['pagetype']);

		return $languageManager;
	}

	/**
	 * @deprecated
	 */	
	function _setupRenderSystem()
	{
		// TODO remove this method.
	}
	
	function executeHeader()
	{
		parent::executeHeader();

		//
		//  We changed a render-system class in a pure drawing system. Therefore
		// a controller should not ask him for careful work for compatibility.
		//

		//
		// The following comment-outed line is old version process.
		//
		// $this->mRenderSystem->_processStartPage();

		require_once XOOPS_ROOT_PATH.'/include/old_theme_functions.php';
		$GLOBALS['xoopsTheme']['thename'] = $GLOBALS['xoopsConfig']['theme_set'];

		//
		// cache check
		//
		$cacheSystem =& $this->mRoot->getCacheSystem();
		$xoopsModule =& $this->mModuleController->getXoopsModule();
		
		$renderTarget=new Legacy_RenderTargetMain();

		if ($this->_isModuleCache($xoopsModule)) {
			$url = xoops_getenv('REQUEST_URI');
			$cacheSystem->setResourceName($url);
			
			if ($cacheSystem->isCache($this->_getModuleCacheTime($xoopsModule))) {
				$renderTarget =& new Legacy_RenderTargetMain();
				$renderTarget->setResult($cacheSystem->load());

				$this->_executeViewTheme($renderTarget);

				exit(0);
			}
		}

		ob_start();

		$this->mRenderSystem->setRenderTarget($renderTarget);
	}
	
	/**
	 * @return bool
	 */
	function _isModuleCache($xoopsModule)
	{
		return (xoops_getenv('REQUEST_METHOD') != 'POST' && is_object($xoopsModule) && !empty($this->mConfig['module_cache'][$xoopsModule->getVar('mid')]));
	}
	
	/**
	 * @return int
	 */
	function _getModuleCacheTime($xoopsModule)
	{
		return $this->mConfig['module_cache'][$xoopsModule->getVar('mid')];
	}
	
	function executeView()
	{
		//
		//  Buffering handling of standard output for main render target is responsibility
		// of a controller. Of course all controllers do not have to implement this.
		// The following lines are movement for compatibility and the feature of
		// this controller.
		//
		if(!$this->mRenderSystem->mTemplateName)
			$this->mRenderSystem->mTemplateName = isset($GLOBALS['xoopsOption']['template_main']) ? $GLOBALS['xoopsOption']['template_main'] : null;
		
		$renderTarget=&$this->mRenderSystem->getRenderTarget();


		// Wmm...
		if($renderTarget->getTemplateName()==null) {
			$renderTarget->setTemplateName($this->mRenderSystem->mTemplateName);
			if ($this->mModuleController->isModuleProcess()) {
				$renderTarget->setModuleName($this->mModuleController->getDirname());
			}
		}

		$renderTarget->setAttribute("stdout_buffer",ob_get_contents());
		ob_end_clean();
		
//		$this->mRenderSystem->mRenderTarget->copyAttributes($mainRenderTarget);

		$this->mRenderSystem->renderWithTarget($renderTarget);

		//
		// Cache Control
		//
		$xoopsModule =& $this->mModuleController->getXoopsModule();
		if ($this->_isModuleCache($xoopsModule)) {
			$url = xoops_getenv('REQUEST_URI');
			$cacheSystem =& $this->mRoot->getCacheSystem();
			$cacheSystem->setResourceName($url);
			$cacheSystem->save($renderTarget);
		}
		
		$this->_executeViewTheme($renderTarget);
	}
	
	/**
	 * $resultRenderTarget object The render target of content's result.
	 */
	function _executeViewTheme(&$resultRenderTarget)
	{
		//
		// Theme Control
		//
		$screenTarget=$this->mDialogMode ? new Legacy_DialogRenderTarget() : new Legacy_ThemeRenderTarget();
		$screenTarget->setTemplateName($this->mRoot->getThemeName());
		
		$screenTarget->setAttribute('xoops_contents',$resultRenderTarget->getResult());

		$this->mRenderSystem->renderWithTarget($screenTarget);

		$isAdmin=false;
		if(is_object($this->mXoopsUser)) {
			if($this->mModuleController->isModuleProcess() && $this->mModuleController->isActive()) {
				// @todo I depend on Legacy Module Controller.
				$mid=$this->mModuleController->mModuleObject->getVar('mid');
			}
			else
				$mid=1;	///< @todo Do not use literal directly!

			$isAdmin = $this->mXoopsUser->isAdmin($mid);
		}

		// Debug Process
		if ($this->mConfig['debug_mode'] == XOOPS_DEBUG_MYSQL && $isAdmin) {
			$xoopsDebugger->displayLog();
		}
	}

	function &_createEventManager()
	{
		$manager=&parent::_createEventManager();

		//
		// TODO We should stop hard-cording in the following lines.
		//

		require_once XOOPS_ROOT_PATH."/modules/user/kernel/UserEventProxyRegister.class.php";
		$manager->addProxyRegister(new UserEventProxyRegister());
		$manager->add("Site.Login",new XCube_Delegate("UserCommonEventFunction","Login"));	// TODO

		require_once XOOPS_ROOT_PATH."/modules/pm/kernel/PmEventProxyRegister.class.php";
		$manager->addProxyRegister(new PmEventProxyRegister());

		require_once XOOPS_ROOT_PATH."/modules/base/kernel/MiscEventFunctions.class.php";
		$manager->setAnchorDelegate("Legacypage.Misc.Access", new XCube_Delegate("Legacy_MiscEventFunction","AccessToMisc"));

		//
		// We write the following lines for test here.
		//
//		require_once XOOPS_ROOT_PATH."/modules/comment/event/CommentEventProxyRegister.class.php";
//		$manager->addProxyRegister(new CommentEventProxyRegister());

		$manager->setAnchorDelegate("Site.CheckLogin",new XCube_InstanceDelegate($this,"eventCheckLogin"));
		$manager->setAnchorDelegate("Site.Logout",new XCube_InstanceDelegate($this,"eventLogout"));

		return $manager;
	}

	function &_createServiceManager()
	{
		$manager=&parent::_createServiceManager();
		
		//
		// TODO : Now, we register services we specified. However, this process should be customized by user.
		//
		require_once XOOPS_ROOT_PATH."/modules/pm/service/LegacyPmService.class.php";
		$service=new LegacyPmService();
		$manager->addXCubeService("PrivateMessage",$service);
		unset($service);

		require_once XOOPS_ROOT_PATH."/modules/base/service/LegacySearchService.class.php";
		$service=new LegacySearchService();
		$manager->addXCubeService("LegacySearch",$service);
		unset($service);

		return $manager;
	}

	function eventCheckLogin(&$sender,&$eventArgs)
	{
		if($eventArgs->isSuccess()) {
			// RMV-NOTIFY
			// Perform some maintenance of notification records
			// $notification_handler =& xoops_gethandler('notification');
			// $notification_handler->doLoginMaintenance($user->getVar('uid'));

			$successEventArgs=array();
			$successEventArgs['user']=&$eventArgs->getUser();
			$successEventArgs['xoopsUser']=&$eventArgs->getXoopsUser();

			$this->mRoot->mEventManager->raiseEvent("Site.CheckLogin.Success",$this,$successEventArgs);

			$xoopsUser=&$eventArgs->getXoopsUser();
			if($xoopsUser!=null) {
				$message=sprintf(_US_LOGGINGU,$xoopsUser->getVar('uname'));
			}
			XCube_Utils::redirectHeader($eventArgs->getRedirectUrl(),1,$message);
		}
		else {
			XCube_Utils::redirectHeader($eventArgs->getRedirectUrl(),1,$eventArgs->getRedirectMessage());
		}
	}
	
	function eventLogout(&$sender,&$eventArgs)
	{
		if($eventArgs['successFlag']) {
			//
			// TODO : We depends on a message catalog of user module, yet.
			//
			XCube_Utils::redirectHeader(XOOPS_URL,1,_US_LOGGEDOUT.'<br />'._US_THANKYOUFORVISIT);
		}
	}

	/**
	 * CAUTION!!
	 * This method has a special mission.
	 * Because this method changes state after executeCommon, this resets now property.
	 * It depends on XCube_Controller steps.
	 *
	 * @param $state BaseControllerState*
	 */
	function switchStateCompulsory($state)
	{
		if($state->mStatusFlag != $this->_mControllerState->mStatusFlag) {
			unset($this->mRenderSystem);
			$this->_mControllerState=&$state;
			
			//
			// The following line depends on XCube_Controller process of executeCommon.
			// But, There is no other method.
			//
			$this->_setupModuleController();
			$this->_setupRenderSystem();
			$this->_processModuleController();
		}
	}

	function &getXoopsUser()
	{
		return $this->mXoopsUser;
	}

	/**
	 * Set bool flag to dialog mode flag.
	 * If you set true, executeView() will use Legacy_DialogRenderTarget class as
	 * render target.
	 * @param $flag bool
	 */
	function setDialogMode($flag)
	{
		$this->mDialogMode = $flag;
	}

	/**
	 * Return dialog mode flag.
	 * @return bool
	 */
	function getDialogMode()
	{
		return $this->mDialogMode;
	}
	
	/**
	 *  Return current module object. But, it's decided by the rules of the state.
	 *  Preferences page, Help page and some pages returns the specified module by
	 * dirname. It's useful for controlling a theme. 
	 * 
	 * @return XoopsModule
	 */
	function &getVirtualCurrentModule()
	{
		return $this->_mControllerState->getVirtualCurrentModule($this);
	}
}

/**
 * @abstract
 */
class BaseControllerState
{
	var $mStatusFlag;

	function setupModuleController(&$controller)
	{
	}

	function setupRenderSystem(&$controller)
	{
	}
	
	function setupBlock(&$controller)
	{
	}

	/**
	 * @return XoopsModule
	 * @see Legacy_Controller::getVirtualCurrentModule()
	 */	
	function &getVirtualCurrentModule(&$controller)
	{
		$ret = null;
		return $ret;
	}
}

class BaseControllerPublicState extends BaseControllerState
{
	var $mStatusFlag=LEGACY_CONTROLLER_STATE_PUBLIC;
	
	function BaseControllerPublicState()
	{
		@define("LEGACY_DEPENDENCE_RENDERER", "Legacy_RenderSystem");
	}

	function setupModuleController(&$controller)
	{
		require_once XOOPS_BASE_PATH."/kernel/Legacy_ModuleController.class.php";
		$controller->mModuleController=new Legacy_ModuleController($controller);
	}

	function setupRenderSystem(&$controller)
	{
		// TODO remove this method.
	}
	
	function setupBlock(&$controller)
	{
		$showFlag =0;
		$mid=0;

		if($controller->mModuleController->isModuleProcess()) {
			$showFlag = (preg_match("/index\.php$/i", xoops_getenv('PHP_SELF')) && $controller->mConfig['startpage'] == $controller->mModuleController->mModuleObject->getVar('dirname'));
			$mid=$controller->mModuleController->mModuleObject->getVar('mid');
		}
		else {
			//
			// If you does not have module_contoller, this request is to toppage.
			//
			$mid = -1;
		}

        $blockHandler =& xoops_gethandler('block');
		$showCenterFlag = (SHOW_CENTERBLOCK_LEFT | SHOW_CENTERBLOCK_CENTER | SHOW_CENTERBLOCK_RIGHT);
		$showRightFlag = SHOW_SIDEBLOCK_RIGHT;
		$showFlag = SHOW_SIDEBLOCK_LEFT | $showRightFlag | $showCenterFlag;
		$groups = is_object($controller->mXoopsUser) ? $controller->mXoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;

		$blockObjects=&$blockHandler->getBlocks($groups, $mid, $showFlag);
		foreach($blockObjects as $blockObject) {
			$controller->mBlockChain[]=new XCube_LegacyAdaptBlockProcedure($blockObject);
			unset($blockObject);
		}
	}
}

class BaseControllerAdminState extends BaseControllerState
{
	var $mStatusFlag=LEGACY_CONTROLLER_STATE_ADMIN;
	
	/**
	 *  If this array includes current action, getVirtualCurrentModule() returns
	 * the module object that specified by dirname.
	 * 
	 * @access private
	 */
	var $_mSpecialActions = array("Help", "CommentList");

	function BaseControllerAdminState()
	{
		//
		// TODO We have to develop complated-switching-controller-mechanizm.
		//
		@define("LEGACY_DEPENDENCE_RENDERER", "Legacy_AdminRenderSystem");
	}

	function setupModuleController(&$controller)
	{
		require_once XOOPS_BASE_PATH."/class/Legacy_AdminModuleController.class.php";
		$controller->mModuleController=new Legacy_AdminModuleController($controller);
	}

	function setupRenderSystem(&$controller)
	{
		// TODO remove this method.

		//
		// [TODO]
		// Controller or Root should have factory-method so that we create a 
		// instance by a site config.
		//
		$renderSystem =& $this->mRoot->getRenderSystem("Legacy_AdminRenderSystem");
		$controller->mRenderSystem->prepare();
	}
	
	function setupBlock(&$controller)
	{
		require_once XOOPS_BASE_PATH."/admin/blocks/AdminActionSearch.class.php";
		require_once XOOPS_BASE_PATH."/admin/blocks/AdminSideMenu.class.php";
		$controller->mBlockChain[] =& new Legacy_AdminActionSearch();
		$controller->mBlockChain[] =& new Legacy_AdminSideMenu();
	}

	function &getVirtualCurrentModule(&$controller)
	{
		$module = null;
		
		if ($controller->mModuleController->isModuleProcess()) {
			$module =& $controller->mModuleController->getXoopsModule();
			
			if ($module->get('dirname') == "base" && isset($_REQUEST['dirname'])) {
				if (in_array(xoops_getrequest('action'), $this->_mSpecialActions)) {
					$handler =& xoops_gethandler('module');
					$module =& $handler->getByDirname(xoops_getrequest('dirname'));
				}
			}
		}

		return $module;
	}
}

?>