<?php
/**
 * @package Legacy
 * @version $Id$
 */

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

/**
 * Theme select mechanism is that base knows the method to change themes
 * without RenderSystem. So this class uses delegate to check whether the
 * specified theme is selectable. Functions should be added to this delegate in
 * constructor, because the delegate is called in preBlockFilter().
 */
class Legacy_ThemeSelect extends XCube_ActionFilter
{
	/**
	 * @var XCube_Delegate
	 */
	var $mIsSelectableTheme = null;
	
	function Legacy_ThemeSelect(&$controller)
	{
		//
		// TODO remove
		//
		parent::XCube_ActionFilter($controller);
		$this->mIsSelectableTheme =& new XCube_Delegate();
		$this->mIsSelectableTheme->register('Legacy_ThemeSelect.IsSelectableTheme');
		
		$controller->mSetupUser->add(array(&$this, 'doChangeTheme'));
	}
	
	function preBlockFilter()
	{
		$this->mController->mRoot->mDelegateManager->add("Site.CheckLogin.Success", "Legacy_ThemeSelect::callbackCheckLoginSuccess");
	}
	
	/**
	 * Because this process needs sessions, this functions is added to
	 * SiteLogin event.
	 * 
	 * @param XoopsUser $xoopsUser Must parameter, because this is added to login event.
	 */
	function doChangeTheme(&$principal, &$controller, &$context)
	{
		if (!empty($_POST['xoops_theme_select']) && $this->_isSelectableTheme($_POST['xoops_theme_select'])) {
			$this->mRoot->mContext->setThemeName($_POST['xoops_theme_select']);
			$_SESSION['xoopsUserTheme'] = $_POST['xoops_theme_select'];
		} elseif (!empty($_SESSION['xoopsUserTheme']) && $this->_isSelectableTheme($_SESSION['xoopsUserTheme'])) {
			$this->mRoot->mContext->setThemeName($_SESSION['xoopsUserTheme']);
		}
	}

	function callbackCheckLoginSuccess(&$xoopsUser)
	{
		//
		// Check Theme and set it to session.
		//
		$userTheme = $xoopsUser->get('theme');
		if (is_array($userTheme) && in_array($userTheme, $this->mRoot->mContext->getXoopsConfig('theme_set_allowed'))) {
			$_SESSION['xoopsUserTheme'] = $userTheme;
		}
	}
	
	function _isSelectableTheme($theme_name)
	{
		return in_array($theme_name, $this->mRoot->mContext->getXoopsConfig('theme_set_allowed'));
	}
}

?>