<?php

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

require_once XOOPS_LEGACY_PATH."/admin/class/AbstractModuleInstaller.class.php";

/**
 * This class extends a base class for the process of install module. This is added
 * some private functions.
 */
class Legacy_ModuleInstaller extends Legacy_AbstractModuleInstaller
{
    var $mAgree = false;
	
	function Legacy_ModuleInstaller($dirname)
	{
		parent::Legacy_AbstractModuleInstaller($dirname);
		
		$this->mProcessScript->register('Legacy_ModuleInstaller.ProcessScript');
		$this->mProcessScript->add('Legacy_ModuleInstaller::_processScript');
		
		$this->mInstallTable->register('Legacy_ModuleInstaller.InstallTable');
		$this->mInstallTable->add('Legacy_ModuleUtils::installTable');
		
		$this->mInstallTemplate->register('Legacy_ModuleInstaller.InstallTemplate');
		$this->mInstallTemplate->add('Legacy_ModuleInstaller::_installTemplate');
	}

    /**
     * Load xoops module object that isn't installed and return it.
     * @static
     * @access public
     * @param $dirname string
     * @return XoopsModule
     */
    function &loadModuleObject($dirname)
    {
        $ret = null;

        $moduleHandler =& xoops_gethandler('module');
        $module =& $moduleHandler->getByDirname($dirname);

        if (is_object($module))
            return $ret;

        $module =& $moduleHandler->create();
        $module->setVar('weight', 1);
        $module->loadInfoAsVar($this->mDirname);
        
        if ($module->get('dirname') == null) {
            return $ret;
        }
        
        if ($module->get('dirname') == 'system') {
            $module->setVar('mid', 1);
        }
        
        if (isset($module->modinfo['installer']) && isset($module->modinfo['installer']['licence']) ) {
            $this->mAgree = true;
        }
        
        return $module;
    }
    
    function _installModule()
    {
        if (parent::_installModule()) {
            $gpermHandler =& xoops_gethandler('groupperm');

            //
            // Add a permission which administrators can manage.
            //
            if ($this->mModule->getInfo('hasAdmin')) {
                $adminPerm =& $this->_createPermission(XOOPS_GROUP_ADMIN);
                $adminPerm->setVar('gperm_name', 'module_admin');

                if (!$gpermHandler->insert($adminPerm)) {
                    $log->addError(_AD_LEGACY_ERROR_COULD_NOT_SET_ADMIN_PERMISSION);
                }
            }

            //
            // Add a permission which administrators can manage. (Special for Legacy System Module)
            //
            if ($this->mModule->getVar('dirname') == 'system') {
				$root =& XCube_Root::getSingleton();
				$root->mLanguageManager->loadModuleAdminMessageCatalog('system');

                require_once XOOPS_ROOT_PATH . "/modules/system/constants.php";
				
                $fileHandler = opendir(XOOPS_ROOT_PATH . "/modules/system/admin");
                while ($file = readdir($fileHandler)) {
                    $infoFile = XOOPS_ROOT_PATH . "/modules/system/admin/" . $file . "/xoops_version.php";
                    if (file_exists($infoFile)) {
                        require_once $infoFile;
                        if (!empty($modversion['category'])) {
                            $sysAdminPerm  =& $this->_createPermission(XOOPS_GROUP_ADMIN);
                            $adminPerm->setVar('gperm_itemid', $modversion['category']);
                            $adminPerm->setVar('gperm_name', 'system_admin');
                            if (!$gpermHandler->insert($adminPerm)) {
                                $log->addError(_AD_LEGACY_ERROR_COULD_NOT_SET_SYSTEM_PERMISSION);
                            }
                            unset($sysAdminPerm);
                        }
                        unset($modversion);
                    }
                }
            }
            
            if ($this->mModule->getInfo('hasMain')) {
                $read_any = $this->mModule->getInfo('read_any');
                if ($read_any) {
                    $memberHandler =& xoops_gethandler('member');
                    $groupObjects =& $memberHandler->getGroups();
                    //
                    // Add a permission all group members and guest can read.
                    //
                    foreach($groupObjects as $group) {
                        $readPerm =& $this->_createPermission($group->getVar('groupid'));
                        $readPerm->setVar('gperm_name', 'module_read');

                        if (!$gpermHandler->insert($readPerm)) {
                            $log->addError(_AD_LEGACY_ERROR_COULD_NOT_SET_READ_PERMISSION);
                        }
                    }
                } else {
                    //
                    // Add a permission which administrators can read.
                    //
                    $root =& XCube_Root::getSingleton();
                    $groups = $root->mContext->mXoopsUser->getGroups();
                    foreach($groups as $mygroup) {
                        $readPerm =& $this->_createPermission($mygroup);
                        $readPerm->setVar('gperm_name', 'module_read');

                        if (!$gpermHandler->insert($readPerm)) {
                            $log->addError(_AD_LEGACY_ERROR_COULD_NOT_SET_READ_PERMISSION);
                        }
                    }
                }
            }
        }
    }

    /**
     * Create a permission object which has been initialized for admin.
     * For flexibility, creation only and not save it.
     * @access private
     * @param $group
     */
    function &_createPermission($group)
    {
        $gpermHandler =& xoops_gethandler('groupperm');

        $perm =& $gpermHandler->create();

        $perm->setVar('gperm_groupid', $group);
        $perm->setVar('gperm_itemid', $this->mModule->getVar('mid'));
        $perm->setVar('gperm_modid', 1);
        
        return $perm;
    }

	/**
	 * @static
	 */
	function _installTemplate(&$module, &$log)
	{
        $templates = $module->getInfo('templates');
        if ($templates != false) {
            foreach ($templates as $template) {
                Legacy_ModuleUtils::installTemplate($module, $template, $log);
            }
        }
	}

    function _installBlock()
    {
        $definedBlocks = $this->mModule->getInfo('blocks');
        if($definedBlocks == false)
            return true;

        $blockHandler =& xoops_gethandler('block');

        $func_num=0;
        foreach ($definedBlocks as $block) {
            $func_num++;
            $newBlock =& Legacy_ModuleUtils::createBlockByInfo($this->mModule, $block);
            $newBlock->setVar('func_num', $func_num);

            Legacy_ModuleUtils::installBlock($this->mModule, $newBlock, $block, $this->mLog);
        }
    }

	function _installNotification()
	{
	}
	
    function _installPreference()
    {
        Legacy_ModuleUtils::insertAllConfigs($this->mModule, $this->mLog);
    }
    
    function _processScript(&$module, &$log)
    {
        $installScript = trim($module->getInfo('onInstall'));
        if ($installScript != false) {
            require_once XOOPS_MODULE_PATH . "/" . $module->getVar('dirname') . "/" . $installScript;
            $funcName = 'xoops_module_install_' . $module->getVar('dirname');
            if (function_exists($funcName)) {
                if (!call_user_func($funcName, $module)) {
                    $log->addError(XCUbe_Utils::formatMessage(_AD_LEGACY_ERROR_FAILED_TO_EXECUTE_CALLBACK, $funcName));
                }
            }
        }
    }
	
	function _processReport()
	{
		if (!$this->mLog->hasError()) {
			$this->mLog->add(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_INSTALLATION_MODULE_SUCCESSFUL, $this->mModule->get('name')));
		}
		else {
			if (is_object($this->mModule)) {
				$this->mLog->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_INSTALLATION_MODULE_FAILURE, $this->mModule->get('name')));
			}
			else {
				$this->mLog->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_INSTALLATION_MODULE_FAILURE, $this->mDirname));
			}
		}
	}

    function hasAgree()
    {
        return $this->mAgree;
    }
}

?>