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

 /**
  * This is an abstract class which has interfaces to connect with the
  * controller about the module process. Legacy controller has a instance of
  * the sub-class of this class. So module developers may define their
  * sub-classes.
  * 
  * @see Legacy_Utils::createModule()
  * @see XoopsModule
  */
class Legacy_AbstractModule
{
	/**
	 * Hash used free for this module.
	 * @var Array
	 */
	var $mAttributes = array();
	
	/**
	 * @access public
	 * @var XoopsModule
	 */
	var $mXoopsModule = null;
	
	/**
	 * @access public
	 * @var array
	 */
	var $mModuleConfig = array();
	
	/**
	 * @var Legacy_AbstractCacheInformation
	 */
	var $mCacheInfo = null;
	
	/**
	 * [READ ONLY] The render target instance for this module.
	 * @access public
	 * @var XCube_RenderTarget
	 * @see Legacy_Module::getRenderBuffer()
	 */
	var $mRender = null;
	
	/**
	 * 
	 */
	function Legacy_AbstractModule(&$module)
	{
		$this->setXoopsModule($module);
		
		if ($module->get('hasconfig') == 1 || $module->get('hascomments') == 1) {
			$handler =& xoops_gethandler('config');
			$this->setModuleConfig($handler->getConfigsByCat(0, $module->get('mid')));
		}
	}

	/**
	 * Sets $value with $key to attributes. Use direct access to $mAttributes
	 * if references are must, because PHP4 can't handle reference in the
	 * signature of this member function.
	 * 
	 * @param string $key
	 * @param mixed $value
	 */
	function setAttribute($key, $value)
	{
		$this->mAttributes[$key] = $value;
	}

	/**
	 * Gets a value indicating whether the value specified by $key exists.
	 * 
	 * @param string $key
	 * @return mixed
	 */	
	function hasAttribute($key)
	{
		return isset($this->mAttributes[$key]);
	}
	
	/**
	 * Gets a value of attributes with $key. If the value specified by $key
	 * doesn't exist in attributes, gets null.
	 * 
	 * @param string $key
	 * @return mixed
	 */	
	function getAttribute($key)
	{
		return isset($this->mAttributes[$key]) ? $this->mAttributes[$key] : null;
	}

	/**
	 * Sets a instance of XoopsModule to the property.
	 * @param XoopsModule $xoopsModule
	 */	
	function setXoopsModule(&$xoopsModule)
	{
		$this->mXoopsModule =& $xoopsModule;
	}
	
	/**
	 * Gets a instance of XoopsModule.
	 * @return XoopsModule
	 */
	function &getXoopsModule()
	{
		return $this->mXoopsModule;
	}
	
	/**
	 * Sets array of xoops module config to the property.
	 * @param Array $config
	 */
	function setModuleConfig($config)
	{
		$this->mModuleConfig = $config;
	}

	/**
	 * Gets a value form xoops module config with $key. If $key is specified
	 * null, returns array.
	 * @param string $key
	 * @return mixed
	 */
	function getModuleConfig($key = null)
	{
		if ($key == null) {
			return $this->mModuleConfig;
		}
		
		return isset($this->mModuleConfig[$key]) ? $this->mModuleConfig[$key] : null;
	}

	/**
	 * Gets the cache information instance.
	 * @return Legacy_ModuleCaceInformation
	 * @see Legacy_Module::_createChaceInfo()
	 */	
	function &getCacheInfo()
	{
		if (!is_object($this->mCacheInfo)) {
			$this->_createCacheInfo();
		}
		
		return $this->mCacheInfo;
	}
	
	/**
	 * Creates a cache information instance and returns it. This member
	 * function sets the created instance to mCacheInfo because this instance
	 * has to keep the instance for many callbacks.
	 * @access protected
	 * @return Legacy_ModuleCacheInformation
	 * @see Legacy_Module::getCacheInfo()
	 */
	function _createCacheInfo()
	{
		$this->mCacheInfo =& new Legacy_ModuleCacheInformation();
		$this->mCacheInfo->mURL = xoops_getenv('REQUEST_URI');
		$this->mCacheInfo->setModule($this->mXoopsModule);
	}
	
	/**
	 * Gets the render target instance.
	 * @access public
	 * @return XCube_RenderTarget
	 * @see Legacy_Module::_createRenderBuffer()
	 */
	function &getRenderBuffer()
	{
		if ($this->mRender == null) {
			$this->_createRenderBuffer();
		}
		
		return $this->mRender;
	}

	/**
	 * Creates a render target instance and returns it. This member function
	 * sets the created instance to mRender because this instance has to keep
	 * the instance for many callbacks.
	 * @access protected
	 * @return XCube_RenderTarget
	 * @see Legacy_Module::getRenderBuffer()
	 */	
	function _createRenderBuffer()
	{
		$root =& XCube_Root::getSingleton();
		$renderSystem =& $root->getRenderSystem($this->getRenderSystemName());
		
		$this->mRender =& $renderSystem->createRenderTarget('main');
		if ($this->mXoopsModule != null) {
			$this->mRender->setAttribute('legacy_module', $this->mXoopsModule->get('dirname'));
		}
	}
	
	/**
	 * Gets a name of the dependency render system.
	 * @return string
	 */
	function getRenderSystemName()
	{
		$root =& XCube_Root::getSingleton();
		return $root->mContext->mBaseRenderSystemName;
	}
	
	/**
	 * Gets a value indicating whether this modules is an active.
	 * @return bool
	 */
	function isActive()
	{
		if (!is_object($this->mXoopsModule)) {	//< FIXME
			return false;
		}
		
		return $this->mXoopsModule->get('isactive') ? true : false;
	}
	
	/**
	 * Gets a value indicating whether the current module has a option of
	 * configurations to use the cache system.
	 * @return bool
	 */
	function isEnableCache()
	{
		if (xoops_getenv('REQUEST_METHOD') == 'POST') {
			return false;
		}
		
		$root =& XCube_Root::getSingleton();
		
		return is_object($this->mXoopsModule) && !empty($root->mContext->mXoopsConfig['module_cache'][$this->mXoopsModule->get('mid')]);
	}
	
	/**
	 * Initializes a cache information object, and returns it.
	 * @return Legacy_ModuleCacheInformation
	 */
	function &createCacheInfo()
	{
		$this->mCacheInfo =& new Legacy_ModuleCacheInformation();
		$this->mCacheInfo->mURL = xoops_getenv('REQUEST_URI');
		$this->mCacheInfo->setModule($xoopsModule);
		
		return $this->mCacheInfo;
	}

	/**
	 * This method is called by the controller strategy, if this module is the
	 * current module.
	 */	
	function startup()
	{
	}
	
	/**
	 * This method is called back by the action search feature in the control
	 * panel.
	 * 
	 * @param Legacy_ActionSearchArgs $searchArgs
	 * @see Legacy_ActionSearchArgs
	 */
	function doActionSearch(&$searchArgs)
	{
	}
	
	/**
	 * This method is called back by the xoops global search feature.
	 * 
	 * @param Legacy_ActionSearchArgs $searchArgs
	 * @see Legacy_ActionSearchArgs
	 */
	function doLegacyGlobalSearch($queries, $andor, $max_hit, $start, $uid)
	{
	}
	
	/**
	 * Gets a value indicating whether this module has the page controller in
	 * the control panel side.
	 * 
	 * @return bool
	 * @note Side menu blocks may not display the admin menu if this member
	 * function returns false.
	 */
	function hasAdminIndex()
	{
		return false;
	}
	
	/**
	 * Gets an absolute URL indicating the top page of this module for the
	 * control panel side.
	 * @return string
	 */
	function getAdminIndex()
	{
		return null;
	}
	
	/**
	 * Gets an array having menus for the side menu of the control panel.
	 * @return array
	 * @see /modules/legacy/admin/templates/blocks/legacy_admin_block_sidemenu.html
	 */
	function getAdminMenu()
	{
	}
}

/**
 * This is an adapter class which imitates XOOPS2 responses.
 */
class Legacy_ModuleAdapter extends Legacy_AbstractModule
{
	var $_mAdminMenuLoadedFlag = false;
	var $mAdminMenu = null;
	
	function doActionSearch(&$searchArgs)
	{
		if(!is_object($searchArgs)) {
			return;
		}

		$this->mXoopsModule->loadAdminMenu();
		if(count($this->mXoopsModule->adminmenu) == 0 && !isset($this->mXoopsModule->modinfo['config']) ) {
			return;
		}
			
		//
		// Search preference
		//
		if(isset($this->mXoopsModule->modinfo['config'])&&count($this->mXoopsModule->modinfo['config'])>0) {
			$configInfos=array();
			foreach($this->mXoopsModule->modinfo['config'] as $config) {
				if(isset($config['title']))
					$configInfos[]=@constant($config['title']);
				if(isset($config['description']))
					$configInfos[]=@constant($config['description']);
				if(isset($config['options'])&&count($config['options'])>0) {
					foreach($config['options'] as $key=>$val) {
						$configInfos[]=$key;
					}
				}
			}

			$findFlag=true;
			foreach($searchArgs->getKeywords() as $word) {
				$findFlag&=(stristr(implode(" ",$configInfos),$word)!==false);
			}
				
			if($findFlag) {
				$searchArgs->addRecord($this->mXoopsModule->getVar('name'),
				                  XOOPS_URL.'/modules/legacy/admin/index.php?action=PreferenceEdit&amp;confmod_id='.$this->mXoopsModule->getVar('mid'),
				                  _PREFERENCES );
			}
		}
		
		//
		// Search AdminMenu
		//
		if(count($this->mXoopsModule->adminmenu)>0) {
			foreach($this->mXoopsModule->adminmenu as $menu) {
				$findFlag=true;
				foreach($searchArgs->getKeywords() as $word) {
					$tmpFlag=false;
					$tmpFlag|=(stristr($menu['title'],$word)!==false);

					// Search keyword
					if(isset($menu['keywords'])) {
						$keyword=is_array($menu['keywords']) ? implode(" ",$menu['keywords']) : $menu['keywords'];
						$tmpFlag|=(stristr($keyword,$word)!==false);
					}

					$findFlag&=$tmpFlag;
				}

				if($findFlag) {
					//
					// Create url string with absolute information.
					//
					$url="";
					if(isset($menu['absolute'])&&$menu['absolute']) {
						$url=$menu['link'];
					}
					else {
						$url=XOOPS_URL."/modules/".$this->mXoopsModule->getVar('dirname')."/".$menu['link'];
					}

					//
					// Add record
					//
					$searchArgs->addRecord($this->mXoopsModule->getVar('name'),$url,$menu['title']);
				}
			}
		}
		
		//
		// Search help
		//
		if ($this->mXoopsModule->hasHelp()) {
			$root =& XCube_Root::getSingleton();
			$language = $root->mContext->getXoopsConfig('language');
			$helpfile = $this->mXoopsModule->getHelp();
			$dir = XOOPS_MODULE_PATH . "/" . $this->mXoopsModule->getVar('dirname') . "/language/" . $language;

			if (!file_exists($dir . "/" . $helpfile)) {
				$dir = XOOPS_MODULE_PATH . "/" . $this->mXoopsModule->getVar('dirname') . "/language/" . $language;
					if (!file_exists($dir . "/" . $helpfile)) {
						return;
					}
			}
			$lines = file($dir . "/" . $helpfile);
			foreach ($lines as $line) {
				foreach($searchArgs->getKeywords() as $word) {
					if (stristr($line, $word) !== false) {
						$url = XOOPS_MODULE_URL . "/legacy/admin/index.php?action=Help&amp;dirname=" . $this->mXoopsModule->getVar('dirname');
						$searchArgs->addRecord($this->mXoopsModule->getVar('name'), $url, _HELP);
						return;
					}
				}
			}
		}
	}

	function doLegacyGlobalSearch($queries, $andor, $max_hit, $start, $uid)
	{
		$ret = array();
		$results = $this->mXoopsModule->search($queries, $andor, $max_hit, $start, $uid);
		
		if (is_array($results) && count($results) > 0) {
			foreach ($results as $result) {
				$item = array();
				if (isset($result['image']) && strlen($result['image']) > 0) {
					$item['image'] = XOOPS_URL . '/modules/' . $this->mXoopsModule->get('dirname') . '/' . $result['image'];
				}
				else {
					$item['image'] = XOOPS_URL . '/images/icons/posticon2.gif';
				}
						
				$item['link'] = XOOPS_URL . '/modules/' . $this->mXoopsModule->get('dirname') . '/' . $result['link'];
				$item['title'] = $result['title'];
				$item['uid'] = $result['uid'];
						
				//
				// TODO If this service will come to web service, we should
				// change format from unixtime to string by timeoffset.
				//
				$item['time'] = isset($result['time']) ? $result['time'] : 0;
				
				$ret[] = $item;
			}
		}
		
		return $ret;
	}
	
	function hasAdminIndex()
	{
		$dmy =& $this->mXoopsModule->getInfo();
		return isset($this->mXoopsModule->modinfo['adminindex']) && $this->mXoopsModule->modinfo['adminindex'] != null;
	}
	
	function getAdminIndex()
	{
		$dmy =& $this->mXoopsModule->getInfo();
		return XOOPS_MODULE_URL . '/' . $this->mXoopsModule->get('dirname') . '/' . $this->mXoopsModule->modinfo['adminindex'];
	}
	
	function getAdminMenu()
	{
		if ($this->_mAdminMenuLoadedFlag) {
			return $this->mAdminMenu;
		}
		
		$dmy =& $this->mXoopsModule->getInfo();
		$root =& XCube_Root::getSingleton();

		//
		// Load admin menu, and add preference menu by own judge.
		//
		$this->mXoopsModule->loadAdminMenu();
		if ($this->mXoopsModule->get('hasnotification')
		    || ($this->mXoopsModule->getInfo('config') && is_array($this->mXoopsModule->getInfo('config')))
		    || ($this->mXoopsModule->getInfo('comments') && is_array($this->mXoopsModule->getInfo('comments')))) {
				$this->mXoopsModule->adminmenu[] = array(
					'link' => $root->mController->getPreferenceEditUrl($this->mXoopsModule),
					'title' => _PREFERENCES,
					'absolute' => true);
		}
			
		if ($this->mXoopsModule->hasHelp()) {
			$this->mXoopsModule->adminmenu[] = array('link' =>  $root->mController->getHelpViewUrl($this->mXoopsModule),
			                              'title' => _HELP,
			                              'absolute' => true);
		}
		
		$this->_mAdminMenuLoadedFlag = true;
		
		if ($this->mXoopsModule->adminmenu) {
			foreach ($this->mXoopsModule->adminmenu as $menu) {
				if (!(isset($menu['absolute']) && isset($menu['absolute']) == true)) {
					$menu['link'] = XOOPS_MODULE_URL . '/' . $this->mXoopsModule->get('dirname') . '/' . $menu['link'];
				}
				$this->mAdminMenu[] = $menu;
			}
		}
		
		return $this->mAdminMenu;
	}
}

?>