<?php

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

require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/BeanFactory.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/Enum.class.php';
require_once USER_TRUST_PATH . '/admin/class/installer/UserInstallUtils.class.php';
require_once USER_TRUST_PATH . '/class/UserUtils.class.php';

/**
 * User_Installer
**/
class User_Installer
{
    /**
     * @brief   Legacy_ModuleInstallLog
    **/
    public $mLog = null;

    /**
     * @brief   bool
    **/
    private $_mForceMode = false;

    /**
     * @brief   XoopsModule
    **/
    private $_mXoopsModule = null;

    /**
     * __construct
     * 
     * @param   void
     * 
     * @return  void
    **/
    public function __construct()
    {
        $this->mLog = new Legacy_ModuleInstallLog();
    }

    /**
     * setCurrentXoopsModule
     * 
     * @param   XoopsModule  &$xoopsModule
     * 
     * @return  void
    **/
    public function setCurrentXoopsModule(/*** XoopsModule ***/ &$xoopsModule)
    {
        $this->_mXoopsModule =& $xoopsModule;
    }

    /**
     * setForceMode
     * 
     * @param   bool  $isForceMode
     * 
     * @return  void
    **/
    public function setForceMode(/*** bool ***/ $isForceMode)
    {
        $this->_mForceMode = $isForceMode;
    }

    /**
     * _installTables
     * 
     * @param   void
     * 
     * @return  bool
    **/
    private function _installTables()
    {
        if (!User_InstallUtils::installSQLAutomatically($this->_mXoopsModule, $this->mLog)) {
			return false;
		}
        if (!User_InstallUtils::installDataAutomatically($this->_mXoopsModule, $this->mLog)) {
			return false;
		}
		return true;
    }

    /**
     * _installModule
     * 
     * @param   void
     * 
     * @return  bool
    **/
    private function _installModule()
    {
        $moduleHandler =& UserUtils::getXoopsHandler('module');
        if(!$moduleHandler->insert($this->_mXoopsModule))
        {
            $this->mLog->addError(_MI_USER_INSTALL_ERROR_MODULE_INSTALLED);
            return false;
        }
    
        $gpermHandler =& UserUtils::getXoopsHandler('groupperm');
    
        if($this->_mXoopsModule->getInfo('hasAdmin'))
        {
            $adminPerm =& $this->_createPermission(XOOPS_GROUP_ADMIN);
            $adminPerm->setVar('gperm_name','module_admin');
            if(!$gpermHandler->insert($adminPerm))
            {
                $this->mLog->addError(_MI_USER_INSTALL_ERROR_PERM_ADMIN_SET);
            }
        }

        if($this->_mXoopsModule->getInfo('read_any'))
        {
            $memberHandler =& UserUtils::getXoopsHandler('member');
            $groupObjects =& $memberHandler->getGroups();
            foreach($groupObjects as $group)
            {
                $readPerm =& $this->_createPermission($group->getVar('groupid'));
                $readPerm->setVar('gperm_name','module_read');
                if(!$gpermHandler->insert($readPerm))
                {
                    $this->mLog->addError(_MI_USER_INSTALL_ERROR_PERM_READ_SET);
                }
            }
        }
        else
        {
            $root =& XCube_Root::getSingleton();
            $groups = $root->mContext->mXoopsUser->getGroups();
            foreach($groups as $group)
            {
                $readPerm =& $this->_createPermission($group);
                $readPerm->setVar('gperm_name','module_read');
                if(!$gpermHandler->insert($readPerm))
                {
                    $this->mLog->addError(_MI_USER_INSTALL_ERROR_PERM_READ_SET);
                }
            }
        }
        
        return true;
    }

    /**
     * &_createPermission
     * 
     * @param   int  $group
     * 
     * @return  XoopsGroupPerm
    **/
    private function &_createPermission(/*** int ***/ $group)
    {
        $gpermHandler =& UserUtils::getXoopsHandler('groupperm');
        $perm =& $gpermHandler->create();
        $perm->setVar('gperm_groupid',$group);
        $perm->setVar('gperm_itemid',$this->_mXoopsModule->getVar('mid'));
        $perm->setVar('gperm_modid',1);
    
        return $perm;
    }

    /**
     * _installTemplates
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _installTemplates()
    {
        User_InstallUtils::installAllOfModuleTemplates(
            $this->_mXoopsModule,
            $this->mLog
        );
        User_InstallUtils::installCommonTemplates(
            $this->_mXoopsModule,
            $this->mLog
        );
    }

    /**
     * _installBlocks
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _installBlocks()
    {
        User_InstallUtils::installAllOfBlocks(
            $this->_mXoopsModule,
            $this->mLog
        );
    }

    /**
     * _installPreferences
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _installPreferences()
    {
        User_InstallUtils::installAllOfConfigs(
            $this->_mXoopsModule,
            $this->mLog
        );
    }

    /**
     * _processReport
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _processReport()
    {
        if(!$this->mLog->hasError())
        {
            $this->mLog->add(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_MSG_MODULE_INSTALLED,
                    $this->_mXoopsModule->getInfo('name')
                )
            );
        }
        else if(is_object($this->_mXoopsModule))
        {
            $this->mLog->addError(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_ERROR_MODULE_INSTALLED,
                    $this->_mXoopsModule->getInfo('name')
                )
            );
        }
        else
        {
            $this->mLog->addError(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_ERROR_MODULE_INSTALLED,
                    'something'
                )
            );
        }
    }
    
	function _processScript()
    {
    	$uid = $GLOBALS['xoopsUser']->getVar('uid', 'n');
    	$mid = $this->_mXoopsModule->getVar('mid');

    	// define groups
		$member_handler =& xoops_gethandler('member');
		$gids = array_keys($member_handler->getGroupList());
		$ogids = array_diff($gids, array(XOOPS_GROUP_ADMIN, XOOPS_GROUP_USERS, XOOPS_GROUP_ANONYMOUS));
    	
    	// set block parameters (read permissions and positions)
		// php-indent: disable
		$block_params = array(
			'b_user_login_show' => array(
				'rights' => array(true, true, false),
				'positions' => array(true, 0, 10, true)
			),
		);
		// php-indent: enable
		foreach ($block_params as $show_func => $block_param) {
			$bids = User_InstallUtils::getBlockIds($mid, $show_func);
			foreach ($bids as $bid) {
				// - rights
				$rights = $block_param['rights'];
				list($uright, $gright, $oright) = $block_param['rights'];
				User_InstallUtils::setBlockReadRight($bid, XOOPS_GROUP_USERS, $uright);
				User_InstallUtils::setBlockReadRight($bid, XOOPS_GROUP_ANONYMOUS, $gright);
				foreach ($ogids as $gid) {
					User_InstallUtils::setBlockReadRight($bid, $gid, $oright);
				}
				// - positions
				list($visible, $side, $weight, $allpage) = $block_param['positions'];
				User_InstallUtils::setBlockPosition($bid, $visible, $side, $weight);
				User_InstallUtils::setBlockShowPage($bid, 0, $allpage);
				if ($allpage) {
					// unset top page
					User_InstallUtils::setBlockShowPage($bid, - 1, false);
				} else {
					User_InstallUtils::setBlockShowPage($bid, - 1, true);
				}
			}
		}

        $uploadDir = XOOPS_ROOT_PATH . '/uploads/user';
    	if (!is_dir($uploadDir)) {
			mkdir($uploadDir);
		}
        if (!is_dir($uploadDir . '/group')) {
			mkdir($uploadDir . '/group');
		}

		// set notifications
		$member_handler =& xoops_gethandler('member');
		$uids = array_keys($member_handler->getUsers(null, true));
		// php-indent: disable
		$info = $this->_mXoopsModule->getInfo('notification');
		$notifications = array();
		foreach ($info['category'] as $category) {
			$events = array();
			foreach ($info['event'] as $event) {
				if ($event['category'] == $category['name']) {
					$events[] = $event['name'];
				}
			}
			$notifications[$category['name']] = $events;
		}
		// php-indent: enable
		foreach ($notifications as $category => $events) {
			foreach ($events as $event) {
				// enable event
				User_InstallUtils::enableNotification($mid, $category, $event);
				// subscribe all notifications to all users
				foreach ($uids as $uid) {
					User_InstallUtils::subscribeNotification($mid, $uid, $category, $event);
				}
			}
		}

		$usersBean = Xoonips_BeanFactory::getBean('UsersBean', XCUBE_CORE_USER_MODULE_NAME);
        $userInfo = $usersBean->getUserBasicInfo($uid);
        if ($userInfo == false) {
            return false;
        }		
        $userInfo['activate'] = Xoonips_Enum::USER_CERTIFIED;
        if (!$usersBean->pickupUser($userInfo)) {
            return false;
        }             	
    }

    /**
     * executeInstall
     * 
     * @param   void
     * 
     * @return  bool
    **/
    public function executeInstall()
    {
    	set_time_limit(120);
        $this->_installTables();
        if(!$this->_mForceMode && $this->mLog->hasError())
        {
            $this->_processReport();
            return false;
        }
    
        $this->_installModule();
        if(!$this->_mForceMode && $this->mLog->hasError())
        {
            $this->_processReport();
            return false;
        }
    
        $this->_installTemplates();
        if(!$this->_mForceMode && $this->mLog->hasError())
        {
            $this->_processReport();
            return false;
        }
    
        $this->_installBlocks();
        if(!$this->_mForceMode && $this->mLog->hasError())
        {
            $this->_processReport();
            return false;
        }
    
        $this->_installPreferences();
        if(!$this->_mForceMode && $this->mLog->hasError())
        {
            $this->_processReport();
            return false;
        }
        
    	$this->_processScript();
		if (!$this->_mForceMode && $this->mLog->hasError()) {
			$this->_processReport();
			return false;
		}
    
        $this->_processReport();
        return true;
    }
}


