<?php

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

if (class_exists('User_InstallUtils'))
{
    return;
}

/**
 * User_InstallUtils
**/
class User_InstallUtils
{
    /**
     * installSQLAutomatically
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function installSQLAutomatically(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {

        $sqlFileInfo =& $module->getInfo('sqlfile');
        if(!isset($sqlFileInfo[XOOPS_DB_TYPE]))
        {
            return true;
        }
        $sqlFile = $sqlFileInfo[XOOPS_DB_TYPE];

        $dirname = $module->getVar('dirname');
        $sqlFilePath = sprintf('%s/%s/%s',XOOPS_MODULE_PATH,$dirname,$sqlFile);
        if(!file_exists($sqlFilePath))
        {
            $sqlFilePath = sprintf(
                '%s/modules/%s/%s',
                XOOPS_TRUST_PATH,
                $module->modinfo['trust_dirname'],
                $sqlFile
            );
        }

        require_once XOOPS_MODULE_PATH . '/legacy/admin/class/Legacy_SQLScanner.class.php';    // TODO will be use other class?
        $scanner = new Legacy_SQLScanner();
        $scanner->setDB_PREFIX(XOOPS_DB_PREFIX);
        $scanner->setDirname($dirname);
        if(!$scanner->loadFile($sqlFilePath))
        {
            $log->addError(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_ERROR_SQL_FILE_NOT_FOUND,
                    $sqlFile
                )
            );
            return false;
        }

        $scanner->parse();
        $root =& XCube_Root::getSingleton();
        $db =& $root->mController->getDB();

        foreach($scanner->getSQL() as $sql)
        {
            if(!$db->query($sql))
            {
                $log->addError($db->error());
                return false;
            }
        }
        $log->addReport(_MI_USER_INSTALL_MSG_DB_SETUP_FINISHED);
        return true;
    }

    /**
     * DBquery
     *
     * @param   string  $query
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function DBquery(/*** string ***/ $query,/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        require_once XOOPS_MODULE_PATH . '/legacy/admin/class/Legacy_SQLScanner.class.php';    // TODO will be use other class?
        $scanner = new Legacy_SQLScanner();
        $scanner->setDB_PREFIX(XOOPS_DB_PREFIX);
        $scanner->setDirname($module->get('dirname'));
        $scanner->setBuffer($query);
        $scanner->parse();
        $sqls = $scanner->getSQL();

        $root =& XCube_Root::getSingleton();

        $successFlag = true;
        foreach($sqls as $sql)
        {
            if($root->mController->mDB->query($sql))
            {
                $log->addReport(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_MSG_SQL_SUCCESS,
                        $sql
                    )
                );
            }
            else
            {
                $log->addReport(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_MSG_SQL_ERROR,
                        $sql
                    )
                );
                $successFlag = false;
            }
        }
        return $successFlag;
    }

    /**
     * replaceDirname
     *
     * @param   string  $from
     * @param   string  $dirname
     * @param   string  $trustDirname
     *
     * @return  {string 'public',string 'trust'}
    **/
    public static function replaceDirname(/*** string ***/ $from,/*** string ***/ $dirname,/*** string ***/ $trustDirname = null)
    {
        return array(
            'public' => str_replace('{dirname}',$dirname,$from),
            'trust' => ($trustDirname != null) ? str_replace('{dirname}',$trustDirname,$from) : null
        );
    }

    /**
     * readTemplateFile
     *
     * @param   string  $dirname
     * @param   string  $trustDirname
     * @param   string  $filename
     * @param   bool  $isBlock
     *
     * @return  string
    **/
    public static function readTemplateFile(/*** string ***/ $dirname,/*** string ***/ $trustDirname,/*** string ***/ $filename,/*** bool ***/ $isBlock = false)
    {
        $filePath = sprintf(
            '%s/%s/templates/%s%s',
            XOOPS_MODULE_PATH,
            $dirname,
            ($isBlock ? 'blocks/' : ''),
            $filename
        );

        if(!file_exists($filePath))
        {
            $filePath = sprintf(
                '%s/modules/%s/templates/%s%s',
                XOOPS_TRUST_PATH,
                $trustDirname,
                ($isBlock ? 'blocks/' : ''),
                $filename
            );
            if(!file_exists($filePath))
            {
                return false;
            }
        }

        if(!($lines = file($filePath)))
        {
            return false;
        }

        $tplData = '';
        foreach($lines as $line)
        {
            $tplData .= str_replace("\n","\r\n",str_replace("\r\n","\n",$line));
        }

        return $tplData;
    }

    /**
     * installAllOfModuleTemplates
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  void
    **/
    public static function installAllOfModuleTemplates(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $templates =& $module->getInfo('templates');
        if(is_array($templates) && count($templates) > 0)
        {
            foreach($templates as $template)
            {
                User_InstallUtils::installModuleTemplate($module,$template,$log);
            }
        }
    }

    /**
     * installModuleTemplate
     *
     * @param   XoopsModule  &$module
     * @param   string[]  $template
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function installModuleTemplate(/*** XoopsModule ***/ &$module,/*** string[] ***/ $template,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $dirname = $module->getVar('dirname');
        $trustDirname =& $module->getInfo('trust_dirname');
        $tplHandler =& UserUtils::getXoopsHandler('tplfile');
        $filename   =  User_InstallUtils::replaceDirname(trim($template['file']),$dirname,$trustDirname);
        $tplData    =  User_InstallUtils::readTemplateFile($dirname,$trustDirname,$filename['trust']);

        if($tplData == false)
        {
            return false;
        }

        $tplFile =& $tplHandler->create();
        $tplFile->setVar('tpl_refid'       ,$module->getVar('mid'));
        $tplFile->setVar('tpl_lastimported',0);
        $tplFile->setVar('tpl_lastmodified',time());
        $tplFile->setVar('tpl_type'        ,(substr($filename['trust'],-4) == '.css') ? 'css' : 'module');
        $tplFile->setVar('tpl_source'      ,$tplData,true);
        $tplFile->setVar('tpl_module'      ,$module->getVar('dirname'));
        $tplFile->setVar('tpl_tplset'      ,'default');
        $tplFile->setVar('tpl_file'        ,$filename['public'],true);
        $tplFile->setVar('tpl_desc'        ,isset($template['desctiption']) ? $template['description'] : '',true);

        if($tplHandler->insert($tplFile))
        {
            $log->addReport(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_MSG_TPL_INSTALLED,
                    $filename['public']
                )
            );
        }
        else
        {
            $log->addError(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_ERROR_TPL_INSTALLED,
                    $filename['public']
                )
            );
            return false;
        }
        return true;
    }

    public static function installCommonTemplates(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log){
    	$dirname = $module->getVar('dirname');
    	$tplfile_handler =& xoops_gethandler('tplfile');
		$tpl_path = XOOPS_TRUST_PATH . '/libs/xoonips/templates';
		if( $handler = @opendir( $tpl_path . '/' ) ) {
			while( ( $file = readdir( $handler ) ) !== false ) {
				if( substr( $file , 0 , 1 ) == '.' ) continue ;
				$file_path = $tpl_path . '/' . $file ;
				if( is_file( $file_path ) ) {
					$mtime = intval( @filemtime( $file_path ) ) ;
					$tplfile =& $tplfile_handler->create() ;
					$tplfile->setVar( 'tpl_source' , file_get_contents( $file_path ) , true ) ;
					$tplfile->setVar( 'tpl_refid' , $module->getVar('mid') ) ;
					$tplfile->setVar( 'tpl_tplset' , 'default' ) ;
					$tplfile->setVar( 'tpl_file' , $dirname . '_' . $file ) ;
					$tplfile->setVar( 'tpl_desc' , '' , true ) ;
					$tplfile->setVar( 'tpl_module' , $dirname ) ;
					$tplfile->setVar( 'tpl_lastmodified' , $mtime ) ;
					$tplfile->setVar( 'tpl_lastimported' , 0 ) ;
					$tplfile->setVar( 'tpl_type' , 'module' ) ;
					if($tplfile_handler->insert($tplfile))
			        {
			            $log->addReport(
			                XCube_Utils::formatString(
			                    _MI_USER_INSTALL_MSG_TPL_INSTALLED,
			                    $dirname . '_' . $file
			                )
			            );
			        }
			        else
			        {
			            $log->addError(
			                XCube_Utils::formatString(
			                    _MI_USER_INSTALL_ERROR_TPL_INSTALLED,
			                    $dirname . '_' . $file
			                )
			            );
			            return false;
			        }
				}
			}
			closedir( $handler ) ;
		}
		return true;
    }

    /**
     * uninstallAllOfModuleTemplates
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     * @param   bool  $defaultOnly
     *
     * @return  void
    **/
    public static function uninstallAllOfModuleTemplates(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log,/*** bool ***/ $defaultOnly = true)
    {
        $tplHandler   =& UserUtils::getXoopsHandler('tplfile');

        $delTemplates =& $tplHandler->find($defaultOnly ? 'default' : null,'module',$module->get('mid'));

        if(is_array($delTemplates) && count($delTemplates) > 0)
        {
            $xoopsTpl = new XoopsTpl();
            $xoopsTpl->clear_cache(null,'mod_' . $module->get('dirname'));
            foreach($delTemplates as $tpl)
            {
                if(!$tplHandler->delete($tpl))
                {
                    $log->addError(
                        XCube_Utils::formatString(
                            _MI_USER_INSTALL_ERROR_TPL_UNINSTALLED,
                            $tpl->get('tpl_file')
                        )
                    );
                }
            }
        }

        $delTemplates =& $tplHandler->find($defaultOnly ? 'default' : null,'css',$module->get('mid'));

        if(is_array($delTemplates) && count($delTemplates) > 0)
        {
            $xoopsTpl = new XoopsTpl();
            $xoopsTpl->clear_cache(null,'css_' . $module->get('dirname'));
            foreach($delTemplates as $tpl)
            {
                if(!$tplHandler->delete($tpl))
                {
                    $log->addError(
                        XCube_Utils::formatString(
                            _MI_USER_INSTALL_ERROR_TPL_UNINSTALLED,
                            $tpl->get('tpl_file')
                        )
                    );
                }
            }
        }
    }

    /**
     * installAllOfBlocks
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function installAllOfBlocks(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $blocks =& $module->getInfo('blocks');
        if(is_array($blocks) && count($blocks) > 0)
        {
            foreach($blocks as $idx => $block)
            {
            	$block['func_num'] = $idx;
                $newBlock =& User_InstallUtils::createBlockByInfo($module,$block);
                User_InstallUtils::installBlock($module,$newBlock,$block,$log);
            }
        }
        return true;
    }

    /**
     * &createBlockByInfo
     *
     * @param   XoopsModule  &$module
     * @param   string[]  $block
     *
     * @return  XoopsBlock
    **/
    public static function &createBlockByInfo(/*** XoopsModule ***/ &$module,/*** string[] ***/ $block)
    {
    	$edit_func = isset($block['edit_func']) ? $block['edit_func'] : null;
        $visible = isset($block['visible']) ?
            $block['visible'] :
            (isset($block['visible_any']) ? $block['visible_any'] : 0);
        $filename = isset($block['template']) ?
            User_InstallUtils::replaceDirname($block['template'],$module->get('dirname')) :
            null;

        $blockHandler =& UserUtils::getXoopsHandler('block');
        $blockObj =& $blockHandler->create();

        $blockObj->set('mid',$module->getVar('mid'));
        $blockObj->set('options',isset($block['options']) ? $block['options'] : null);
        $blockObj->set('name',$block['name']);
        $blockObj->set('title',$block['name']);
        $blockObj->set('block_type','M');
        $blockObj->set('c_type','1');
        $blockObj->set('isactive',1);
        $blockObj->set('dirname',$module->getVar('dirname'));
        $blockObj->set('func_file',$block['file']);
    	//
		// IMPORTANT CONVENTION
		//
		$show_func = "";
		if (isset($block['class'])) {
			$show_func = "cl::" . $block['class'];
		}
		else {
			$show_func = $block['show_func'];
		}
		$blockObj->set('show_func', $show_func);
		$blockObj->set('edit_func', $edit_func);
        $blockObj->set('template',$filename['public']);
        $blockObj->set('last_modified',time());
        $blockObj->set('visible',$visible);
        $blockObj->set('func_num',intval($block['func_num']));
        return $blockObj;
    }

    /**
     * installBlock
     *
     * @param   XoopsModule  &$module
     * @param   XoopsBlock  &$blockObj
     * @param   string[]  &$block
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function installBlock(/*** XoopsModule ***/ &$module,/*** XoopsBlock ***/ &$blockObj,/*** string[] ***/ &$block,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $isNew = $blockObj->isNew();
        $blockHandler =& UserUtils::getXoopsHandler('block');
        $autoLink = isset($block['show_all_module']) ? $block['show_all_module'] : false;

        if(!$blockHandler->insert($blockObj,$autoLink))
        {
            $log->addError(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_ERROR_BLOCK_INSTALLED,
                    $blockObj->getVar('name')
                )
            );
            return false;
        }

        $log->addReport(
            XCube_Utils::formatString(
                _MI_USER_INSTALL_MSG_BLOCK_INSTALLED,
                $blockObj->getVar('name')
            )
        );

        User_InstallUtils::installBlockTemplate($blockObj,$module,$log);

        if(!$isNew)
        {
            return true;
        }

        if($autoLink)
        {
            $sql = sprintf(
                'insert into `%s` set (`block_id`,`module_id`) values (%d,0);',
                $blockHandler->db->prefix('block_module_link'),
                $blockObj->getVar('bid')
            );
            if(!$blockHandler->db->query($sql))
            {
                $log->addWarning(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_ERROR_BLOCK_COULD_NOT_LINK,
                        $blockObj->getVar('name')
                    )
                );
            }
        }

        $gpermHandler =& UserUtils::getXoopsHandler('groupperm');
        $perm =& $gpermHandler->create();
        $perm->setVar('gperm_itemid',$blockObj->getVar('bid'));
        $perm->setVar('gperm_name','block_read');
        $perm->setVar('gperm_modid',1);
        if(isset($block['visible_any']) && $block['visible_any'])
        {
            $memberHandler =& UserUtils::getXoopsHandler('member');
            $groups =& $memberHandler->getGroups();
            foreach($groups as $group)
            {
                $perm->setVar('gperm_groupid',$group->getVar('groupid'));
                $perm->setNew();
                if(!$gpermHandler->insert($perm))
                {
                    $log->addWarning(
                        XCube_Utils::formatString(
                            _MI_USER_INSTALL_ERROR_PERM_COULD_NOT_SET,
                            $blockObj->getVar('name')
                        )
                    );
                }
            }
        }
        else
        {
            $root =& XCube_Root::getSingleton();
            $groups = $root->mContext->mXoopsUser->getGroups();
            foreach($groups as $group)
            {
                $perm->setVar('gperm_groupid',$group);
                $perm->setNew();
                if(!$gpermHandler->insert($perm))
                {
                    $log->addWarning(
                        XCube_Utils::formatString(
                            _MI_USER_INSTALL_ERROR_BLOCK_PERM_SET,
                            $blockObj->getVar('name')
                        )
                    );
                }
            }
        }

        return true;
    }

    /**
     * installBlockTemplate
     *
     * @param   XoopsBlock  &$block
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function installBlockTemplate(/*** XoopsBlock ***/ &$block,/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        if($block->get('template') == null)
        {
            return true;
        }

        $info =& $module->getInfo('blocks');
        $filename = User_InstallUtils::replaceDirname(
            $info[$block->get('func_num')]['template'],
            $module->get('dirname'),
            $module->getInfo('trust_dirname')
        );
        $tplHandler =& UserUtils::getXoopsHandler('tplfile');

        $cri = new CriteriaCompo();
        $cri->add(new Criteria('tpl_type','block'));
        $cri->add(new Criteria('tpl_tplset','default'));
        $cri->add(new Criteria('tpl_module',$module->get('dirname')));
        $cri->add(new Criteria('tpl_file',$filename['public']));

        $tpls =& $tplHandler->getObjects($cri);

        if(count($tpls) > 0)
        {
            $tplFile =& $tpls[0];
        }
        else
        {
            $tplFile =& $tplHandler->create();
            $tplFile->set('tpl_refid',$block->get('bid'));
            $tplFile->set('tpl_tplset','default');
            $tplFile->set('tpl_file',$filename['public']);
            $tplFile->set('tpl_module',$module->get('dirname'));
            $tplFile->set('tpl_type','block');
            $tplFile->set('tpl_lastimported',0);
        }

        $tplSource = User_InstallUtils::readTemplateFile(
            $module->get('dirname'),
            $module->getInfo('trust_dirname'),
            $filename['trust'],
            true
        );

        $tplFile->set('tpl_source',$tplSource);
        $tplFile->set('tpl_lastmodified',time());
        if($tplHandler->insert($tplFile))
        {
            $log->addReport(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_MSG_BLOCK_TPL_INSTALLED,
                    $filename['public']
                )
            );
            return true;
        }

        $log->addError(
            XCube_Utils::formatString(
                _MI_USER_INSTALL_ERROR_BLOCK_TPL_INSTALLED,
                $filename['public']
            )
        );
        return false;
    }

    /**
     * uninstallAllOfBlocks
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function uninstallAllOfBlocks(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $successFlag = true;

        $blockHandler =& UserUtils::getXoopsHandler('block');
        $gpermHandler =& UserUtils::getXoopsHandler('groupperm');
        $cri = new Criteria('mid',$module->get('mid'));
        $blocks =& $blockHandler->getObjectsDirectly($cri);

        foreach($blocks as $block)
        {
            if($blockHandler->delete($block))
            {
                $log->addReport(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_MSG_BLOCK_UNINSTALLED,
                        $block->get('name')
                    )
                );
            }
            else
            {
                $log->addWarning(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_ERROR_BLOCK_UNINSTALLED,
                        $block->get('name')
                    )
                );
                $successFlag = false;
            }

            $cri = new CriteriaCompo();
            $cri->add(new Criteria('gperm_name','block_read'));
            $cri->add(new Criteria('gperm_itemid',$block->get('bid')));
            $cri->add(new Criteria('gperm_modid',1));
            if(!$gpermHandler->deleteAll($cri))
            {
                $log->addWarning(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_ERROR_BLOCK_PERM_DELETE,
                        $block->get('name')
                    )
                );
                $successFlag = false;
            }
        }

        return $successFlag;
    }

    /**
     * smartUpdateAllOfBlocks
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  void
    **/
    public static function smartUpdateAllOfBlocks(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $dirname = $module->get('dirname');

        $fileReader = new Legacy_ModinfoX2FileReader($dirname);
        $dbReader = new Legacy_ModinfoX2DBReader($dirname);

        $blocks =& $dbReader->loadBlockInformations();
        $blocks->update($fileReader->loadBlockInformations());

        foreach($blocks->mBlocks as $block)
        {
            switch($block->mStatus)
            {
                case LEGACY_INSTALLINFO_STATUS_LOADED:
                    User_InstallUtils::updateBlockTemplateByInfo($block,$module,$log);
                    break;
                case LEGACY_INSTALLINFO_STATUS_UPDATED:
                    User_InstallUtils::updateBlockByInfo($block,$module,$log);
                    break;
                case LEGACY_INSTALLINFO_STATUS_NEW:
                    User_InstallUtils::installBlockByInfo($block,$module,$log);
                    break;
                case LEGACY_INSTALLINFO_STATUS_DELETED:
                    User_InstallUtils::uninstallBlockByFuncNum($block->mFuncNum,$module,$log);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * updateBlockTemplateByInfo
     *
     * @param   Legacy_BlockInformation  &$info
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  void
    **/
    public static function updateBlockTemplateByInfo(/*** Legacy_BlockInformation ***/ &$info,/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $blockHandler =& UserUtils::getModuleHandler('newblocks','legacy');
        $cri = new CriteriaCompo();
        $cri->add(new Criteria('dirname',$module->get('dirname')));
        $cri->add(new Criteria('func_num',$info->mFuncNum));
        $blocks =& $blockHandler->getObjects($cri);

        foreach($blocks as $block)
        {
            User_InstallUtils::uninstallBlockTemplate($block,$module,$log,true);
            User_InstallUtils::installBlockTemplate($block,$module,$log);
        }
    }

    /**
     * updateBlockByInfo
     *
     * @param   Legacy_BlockInformation  &$info
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  void
    **/
    public static function updateBlockByInfo(/*** Legacy_BlockInformation ***/ &$info,/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $blockHandler =& UserUtils::getModuleHandler('newblocks','legacy');
        $cri = new CriteriaCompo();
        $cri->add(new Criteria('dirname',$module->get('dirname')));
        $cri->add(new Criteria('func_num',$info->mFuncNum));
        $blocks =& $blockHandler->getObjects($cri);

        foreach($blocks as $block)
        {
            $filename = User_InstallUtils::replaceDirname(
                $info->mTemplate,
                $module->get('dirname'),
                $module->getInfo('trust_dirname')
            );
            $block->set('options',$info->mOptions);
            $block->set('name',$info->mName);
            $block->set('func_file',$info->mFuncFile);
            $block->set('show_func',$info->mShowFunc);
            $block->set('template',$filename['public']);
            if($blockHandler->insert($block))
            {
                $log->addReport(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_MSG_BLOCK_UPDATED,
                        $block->get('name')
                    )
                );
            }
            else
            {
                $log->addError(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_ERROR_BLOCK_UPDATED,
                        $block->get('name')
                    )
                );
            }
            User_InstallUtils::uninstallBlockTemplate($block,$module,$log,true);
            User_InstallUtils::installBlockTemplate($block,$module,$log);
        }
    }

    /**
     * installBlockByInfo
     *
     * @param   Legacy_BlockInformation  &$info
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function installBlockByInfo(/*** Legacy_BlockInformation ***/ &$info,/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $filename = User_InstallUtils::replaceDirname(
            $info->mTemplate,
            $module->get('dirname'),
            $module->getInfo('trust_dirname')
        );

        $blockHandler =& UserUtils::getXoopsHandler('block');

        $block =& $blockHandler->create();
        $block->set('mid',$module->get('mid'));
        $block->set('func_num',$info->mFuncNum);
        $block->set('options',$info->mOptions);
        $block->set('name',$info->mName);
        $block->set('title',$info->mName);
        $block->set('dirname',$module->get('dirname'));
        $block->set('func_file',$info->mFuncFile);
        $block->set('show_func',$info->mShowFunc);
        $block->set('template',$filename['public']);
        $block->set('block_type','M');
        $block->set('c_type',1);

        if(!$blockHandler->insert($block))
        {
            $log->addError(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_ERROR_BLOCK_INSTALLED,
                    $block->get('name')
                )
            );
            return false;
        }

        $log->addReport(
            XCube_Utils::formatString(
                _MI_USER_INSTALL_MSG_BLOCK_INSTALLED,
                $block->get('name')
            )
        );

        User_InstallUtils::installBlockTemplate($block,$module,$log);
        return true;
    }

    /**
     * uninstallBlockByFuncNum
     *
     * @param   int  $func_num
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function uninstallBlockByFuncNum(/*** int ***/ $func_num,/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        $blockHandler =& UserUtils::getModuleHandler('newblocks','legacy');
        $cri = new CriteriaCompo();
        $cri->add(new Criteria('dirname',$module->get('dirname')));
        $cri->add(new Criteria('func_num',$func_num));
        $blocks =& $blockHandler->getObjects($cri);

        $successFlag = true;
        foreach($blocks as $block)
        {
            if($blockHandler->delete($block))
            {
                $log->addReport(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_MSG_BLOCK_UNINSTALLED,
                        $block->get('name')
                    )
                );
            }
            else
            {
                $log->addError(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_ERROR_BLOCK_UNINSTALLED,
                        $block->get('name')
                    )
                );
                $successFlag = false;
            }
        }
        return $successFlag;
    }

    /**
     * uninstallBlockTemplate
     *
     * @param   XoopsBlock  &$block
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     * @param   bool  $defaultOnly
     *
     * @return  bool
    **/
    public static function uninstallBlockTemplate(/*** XoopsBlock ***/ &$block,/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log,/*** bool ***/ $defaultOnly = false)
    {
        $tplHandler =& UserUtils::getXoopsHandler('tplfile');
        $delTemplates =& $tplHandler->find($defaultOnly ? 'default' : null,'block',$module->get('mid'),$module->get('dirname'),$block->get('template'));

        if(is_array($delTemplates) && count($delTemplates) > 0)
        {
            foreach($delTemplates as $tpl)
            {
                if(!$tplHandler->delete($tpl))
                {
                    $log->addError(
                        XCube_Utils::formatString(
                            _MI_USER_INSTALL_ERROR_TPL_UNINSTALLED,
                            $tpl->get('tpl_file')
                        )
                    );
                }
            }
        }

        $log->addReport(
            XCube_Utils::formatString(
                _MI_USER_INSTALL_MSG_BLOCK_TPL_UNINSTALLED,
                $block->get('template')
            )
        );
        return true;
    }

    /**
     * installAllOfConfigs
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function installAllOfConfigs(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
 	    Legacy_ModuleInstallUtils::installAllOfConfigs($module,$log);
        /*$successFlag = true;
        $configHandler =& UserUtils::getXoopsHandler('config');
        $fileReader = new Legacy_ModinfoX2FileReader($module->get('dirname'));    // TODO will be use other class?
        $preferences =& $fileReader->loadPreferenceInformations();

        foreach($preferences->mPreferences as $info)
        {
            $config =& $configHandler->createConfig();
            $config->set('conf_modid',$module->get('mid'));
            $config->set('conf_catid',0);
            $config->set('conf_name',$info->mName);
            $config->set('conf_title',$info->mTitle);
            $config->set('conf_desc',$info->mDescription);
            $config->set('conf_formtype',$info->mFormType);
            $config->set('conf_valuetype',$info->mValueType);
            $config->setConfValueForInput($info->mDefault);
            $config->set('conf_order',$info->mOrder);

            if(count($info->mOption->mOptions) > 0)
            {
                foreach($info->mOption->mOptions as $opt)
                {
                    $option = $configHandler->createConfigOption();
                    $option->set('confop_name',$opt->mName);
                    $option->set('confop_value',$opt->mValue);
                    $config->setConfOptions($option);
                    unset($option);
                }
            }

            if($configHandler->insertConfig($config))
            {
                $log->addReport(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_MSG_CONFIG_ADDED,
                        $config->get('conf_name')
                    )
                );
            }
            else
            {
                $log->addError(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_ERROR_CONFIG_ADDED,
                        $config->get('conf_name')
                    )
                );
                $successFlag = false;
            }
        }

        return $successFlag;*/
    }

    /**
     * uninstallAllOfConfigs
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public static function uninstallAllOfConfigs(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
        if($module->get('hasconfig') == 0)
        {
            return true;
        }

        $configHandler =& UserUtils::getXoopsHandler('config');
        $configs =& $configHandler->getConfigs(new Criteria('conf_modid',$module->get('mid')));

        if(count($configs) == 0)
        {
            return true;
        }

        $sucessFlag = true;
        foreach($configs as $config)
        {
            if($configHandler->deleteConfig($config))
            {
                $log->addReport(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_MSG_CONFIG_DELETED,
                        $config->getVar('conf_name')
                    )
                );
            }
            else
            {
                $log->addWarning(
                    XCube_Utils::formatString(
                        _MI_USER_INSTALL_ERROR_CONFIG_DELETED,
                        $config->getVar('conf_name')
                    )
                );
                $sucessFlag = false;
            }
        }
        return $sucessFlag;
    }


    /**
     * smartUpdateAllOfConfigs
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  void
    **/    
    public static function smartUpdateAllOfConfigs(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {
      Legacy_ModuleInstallUtils::smartUpdateAllOfPreferences($module,$log);
     }

   /**
   	* set block read right
   	*
   	* @access public
   	* @param int $bid block id
   	* @param int $gid group id
   	* @param int $right has read right ?
   	* @return bool false if failure
   	*/
  	public static function setBlockReadRight( $bid, $gid, $right ) {
    	return self::setReadRight( false, $bid, $gid, $right );
  	}

	/**
   	* set xoops module/block read right
   	*
   	* @access private
   	* @param bool $is_module true is module, false is block
   	* @param int $iid module id or block id
   	* @param int $gid group id
   	* @param bool $right has read right?
   	* @return bool false if failure
   	*/
  	private static function setReadRight( $is_module, $iid, $gid, $right ) {
    	$name = $is_module ? 'module_read' : 'block_read';
    	$criteria = new CriteriaCompo( new Criteria( 'gperm_name', $name ) );
    	$criteria->add( new Criteria( 'gperm_groupid', $gid ) );
    	$criteria->add( new Criteria( 'gperm_itemid', $iid ) );
    	$criteria->add( new Criteria( 'gperm_modid', 1 ) );
    	$gperm_handler =& xoops_gethandler( 'groupperm' );
    	$gperm_objs =& $gperm_handler->getObjects( $criteria );
    	if ( count( $gperm_objs ) > 0 ) {
      		// already exists
      		$gperm_obj = $gperm_objs[0];
      		if ( ! $right ) {
        		$gperm_handler->delete( $gperm_obj );
      		}
    	} else {
      		// not found
      		if ( $right ) {
        		$gperm_handler->addRight( $name, $iid, $gid );
      		}
    	}
    	return true;
  	}

	/**
   	* get module block ids
   	*
   	* @access public
   	* @param int $mid block id
   	* @param int $show_func show function name
   	* @return array block ids
   	*/
  	public static function getBlockIds( $mid, $show_func ) {
    	global $xoopsDB;
    	$table = $xoopsDB->prefix( 'newblocks' );
    	$sql = sprintf( 'SELECT bid FROM `%s` WHERE `mid`=%u AND `show_func`=\'%s\'', $table, $mid, addslashes( $show_func ) );
    	$result = $xoopsDB->query( $sql );
    	if ( ! $result ) {
      		return false;
    	}
    	$ret = array();
    	while( $myrow = $xoopsDB->fetchArray( $result ) ) {
      		$ret[] = $myrow['bid'];
    	}
    	$xoopsDB->freeRecordSet( $result );
    	return $ret;
  	}

	/**
   	* set block position
   	*
   	* @access public
   	* @param int $bid block id
   	* @param bool $visible visible flag
   	* @param int $side
   	*        0: sideblock - left
   	*        1: sideblock - right
   	*        2: sideblock - left and right
   	*        3: centerblock - left
   	*        4: centerblock - right
   	*        5: centerblock - center
   	*        6: centerblock - left, right, center
   	* @param int $weight weight
   	* @return bool false if failure
   	*/
  	public static function setBlockPosition( $bid, $visible, $side, $weight ) {
    	$block = new XoopsBlock();
    	$block->load( $bid );
    	if ( ! is_null( $visible ) ) {
      		$block->setVar( 'visible', $visible ? 1 : 0, true ); // not gpc
    	}
    	if ( ! is_null( $side ) ) {
      		$block->setVar( 'side', $side, true ); // not gpc
    	}
    	if ( ! is_null( $weight ) ) {
      		$block->setVar( 'weight', $weight, true ); // not gpc
    	}
    	return $block->store();
  	}

  	/**
   	* set block show page
   	*
   	* @access public
   	* @param int $bid block id
   	* @param int $mid
   	*     -1 : top page
   	*      0 : all pages
  	*    >=1 : module id
   	* @param bool $is_show
   	* @return bool false if failure
   	*/
  	public static function setBlockShowPage( $bid, $mid, $is_show ) {
    	global $xoopsDB;
    	$table = $xoopsDB->prefix( 'block_module_link' );
    	// check current status
    	$sql = sprintf( 'SELECT `block_id`,`module_id` FROM `%s` WHERE `block_id`=%u AND `module_id`=%d', $table, $bid, $mid );
    	if ( ! $result = $xoopsDB->query( $sql ) ) {
      		return false;
    	}
    	$count = $xoopsDB->getRowsNum( $result );
    	$xoopsDB->freeRecordSet( $result );
    	if ( $count == 0 ) {
      		// not exists
      		if ( $is_show ) {
        		$sql = sprintf( 'INSERT INTO `%s` (`block_id`,`module_id`) VALUES ( %u, %d )', $table, $bid, $mid );
        		if ( ! $result = $xoopsDB->query( $sql ) ) {
          			return false;
        		}
      		}
    	} else {
      		// already exists
      		if ( ! $is_show ) {
        		$sql = sprintf( 'DELETE FROM `%s` WHERE `block_id`=%u AND `module_id`=%d', $table, $bid, $mid );
        		if ( ! $result = $xoopsDB->query( $sql ) ) {
          			return false;
        		}
      		}
    	}
    	return true;
  	}

  	/**
   	* enable xoops notificaiton
   	*
  	* @access public
   	* @param string $mid module id
   	* @param string $category
   	* @param string $event
   	* @return bool false if failure
   	*/
  	function enableNotification( $mid, $category, $event ) {
    	global $xoopsDB;
    	$config_handler =& xoops_gethandler( 'config' );
    	$criteria = new CriteriaCompo();
    	$criteria->add( new Criteria( 'conf_name', 'notification_events' ) );
    	$criteria->add( new Criteria( 'conf_modid', $mid ) );
    	$criteria->add( new Criteria( 'conf_catid', 0 ) );
    	$config_items = $config_handler->getConfigs( $criteria );
    	if ( count( $config_items ) != 1 ) {
      		return false;
    	} else {
      		$config_item = $config_items[0];
      		$option_value = $category.'-'.$event;
      		$option_values = $config_item->getConfValueForOutput();
      		if ( ! in_array( $option_value, $option_values ) ){
        		$option_values[] = $option_value;
        		$config_item->setConfValueForInput( $option_values );
        		$config_item_handler = new XoopsConfigItemHandler( $xoopsDB );
        		$config_item_handler->insert( $config_item );
      		}
    	}
    	return true;
  	}

  	/**
   	* subscribe user to xoops notificaiton
   	*
   	* @access public
   	* @param string $mid module id
   	* @param string $uid user id
   	* @param string $category
   	* @param string $event
   	* @return bool false if failure
   	*/
  	function subscribeNotification( $mid, $uid, $category, $event ) {
    	$notification_handler =& xoops_gethandler( 'notification' );
    	$notification_handler->subscribe( $category, 0, $event, null, $mid, $uid );
    	return true;
  	}

    public static function installDataAutomatically(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log) {
		$dirname = $module->getVar('dirname');
		$trustDirname = $module->modinfo['trust_dirname'];
		if (self::installDataAndViewType($dirname, $trustDirname)) {
			$log->addReport(XCube_Utils::formatString(_MI_USER_INSTALL_MSG_DATA_INSTALLED, $dirname . '_view_type,' . $dirname . '_data_type'));
		} else {
			$log->addError(XCube_Utils::formatString(_MI_USER_INSTALL_ERROR_DATAL_INSTALLED, $dirname . '_view_type,' . $dirname . '_data_type'));
			return false;
		}
		if (self::installComplement($dirname, $trustDirname)) {
			$log->addReport(XCube_Utils::formatString(_MI_USER_INSTALL_MSG_DATA_INSTALLED, $dirname . '_complement'));
		} else {
			$log->addError(XCube_Utils::formatString(_MI_USER_INSTALL_ERROR_DATAL_INSTALLED, $dirname . '_complement'));
			return false;
		}
		if (self::installUserFieldValue($dirname, $trustDirname)) {
			$log->addReport(XCube_Utils::formatString(_MI_USER_INSTALL_MSG_DATA_INSTALLED, $dirname . '_item_field_value_set'));
		} else {
			$log->addError(XCube_Utils::formatString(_MI_USER_INSTALL_ERROR_DATAL_INSTALLED, $dirname . '_item_field_value_set'));
			return false;
		}
		if (self::installUserFieldAndGroup($dirname, $trustDirname)) {
			$log->addReport(XCube_Utils::formatString(_MI_USER_INSTALL_MSG_DATA_INSTALLED, $dirname . '_item_field_group,' . $dirname . '_item_field_detail'));
		} else {
			$log->addError(XCube_Utils::formatString(_MI_USER_INSTALL_ERROR_DATAL_INSTALLED, $dirname . '_item_field_group,' . $dirname . '_item_field_detail'));
			return false;
		}
	}

    private static function installDataAndViewType($dirname, $trustDirname) {
    	$datatypelist = array(
    		array('name' => 'int', 'module' => 'DataTypeInt'),
			array('name' => 'float', 'module' => 'DataTypeFloat'),
			array('name' => 'double', 'module' => 'DataTypeDouble'),
			array('name' => 'char', 'module' => 'DataTypeChar'),
			array('name' => 'varchar', 'module' => 'DataTypeVarchar'),
			array('name' => 'text', 'module' => 'DataTypeText'),
			array('name' => 'date', 'module' => 'DataTypeDate'),
			array('name' => 'datetime', 'module' => 'DataTypeDatetime'),
			array('name' => 'blob', 'module' => 'DataTypeBlob')
		);
		$viewtypelist = array(
			array('preselect' => 0, 'multi' => 1, 'name' => 'hidden', 'module' => 'ViewTypeHidden'),
			array('preselect' => 0, 'multi' => 1, 'name' => 'text', 'module' => 'ViewTypeText'),
			array('preselect' => 0, 'multi' => 1, 'name' => 'textarea', 'module' => 'ViewTypeTextArea'),
			array('preselect' => 0, 'multi' => 1, 'name' => 'radio', 'module' => 'ViewTypeRadioBox'),
			array('preselect' => 0, 'multi' => 1, 'name' => 'checkbox', 'module' => 'ViewTypeCheckBox'),
			array('preselect' => 0, 'multi' => 1, 'name' => 'select', 'module' => 'ViewTypeComboBox'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'user name', 'module' => 'ViewTypeUserName'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'email', 'module' => 'ViewTypeEmail'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'password', 'module' => 'ViewTypePassword'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'member since', 'module' => 'ViewTypeMemberSince'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'last login', 'module' => 'ViewTypeLastLogin'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'timezone', 'module' => 'ViewTypeTimeZone'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'avatar', 'module' => 'ViewTypeAvatar'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'group name', 'module' => 'ViewTypeGroupName'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'email notice', 'module' => 'ViewTypeEmailNotice'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'posts', 'module' => 'ViewTypePosts'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'level', 'module' => 'ViewTypeLevel'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'theme', 'module' => 'ViewTypeTheme'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'signature', 'module' => 'ViewTypeSignature'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'comment mode', 'module' => 'ViewTypeCommentMode'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'comment order', 'module' => 'ViewTypeCommentOrder'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'rank', 'module' => 'ViewTypeRank'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'notify method', 'module' => 'ViewTypeNotifyMethod'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'notify mode', 'module' => 'ViewTypeNotifyMode'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'view email', 'module' => 'ViewTypeViewEmail'),
			//array('preselect' => 1, 'multi' => 0, 'name' => 'Mbyte', 'module' => 'ViewTypeMbyte'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'maximum items', 'module' => 'ViewTypeMaximumItems'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'maximum indexes', 'module' => 'ViewTypeMaximumIndexes'),
			array('preselect' => 1, 'multi' => 0, 'name' => 'maximum space', 'module' => 'ViewTypeMaximumSpace')
    	);
		$relationlist = array(
			array('view_type_id' => 'hidden', 'data_type_id' => 'int', 'data_length' => 11, 'data_decimal_places' => -1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'float', 'data_length' => 24, 'data_decimal_places' => 1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'double', 'data_length' => 53, 'data_decimal_places' => 1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'char', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'text', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'date', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'datetime', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'hidden', 'data_type_id' => 'blob', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'text', 'data_type_id' => 'int', 'data_length' => 11, 'data_decimal_places' => -1),
			array('view_type_id' => 'text', 'data_type_id' => 'float', 'data_length' => 24, 'data_decimal_places' => 1),
			array('view_type_id' => 'text', 'data_type_id' => 'double', 'data_length' => 53, 'data_decimal_places' => 1),
			array('view_type_id' => 'text', 'data_type_id' => 'char', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1),
			array('view_type_id' => 'text', 'data_type_id' => 'text', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'text', 'data_type_id' => 'date', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'text', 'data_type_id' => 'datetime', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'text', 'data_type_id' => 'blob', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'textarea', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1),
			array('view_type_id' => 'textarea', 'data_type_id' => 'text', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'radio', 'data_type_id' => 'int', 'data_length' => 11, 'data_decimal_places' => -1),
			array('view_type_id' => 'radio', 'data_type_id' => 'float', 'data_length' => 24, 'data_decimal_places' => 1),
			array('view_type_id' => 'radio', 'data_type_id' => 'double', 'data_length' => 53, 'data_decimal_places' => 1),
			array('view_type_id' => 'radio', 'data_type_id' => 'char', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'radio', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1),
			array('view_type_id' => 'checkbox', 'data_type_id' => 'int', 'data_length' => 11, 'data_decimal_places' => -1),
			array('view_type_id' => 'checkbox', 'data_type_id' => 'float', 'data_length' => 24, 'data_decimal_places' => 1),
			array('view_type_id' => 'checkbox', 'data_type_id' => 'double', 'data_length' => 53, 'data_decimal_places' => 1),
			array('view_type_id' => 'checkbox', 'data_type_id' => 'char', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'checkbox', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1),
			array('view_type_id' => 'select', 'data_type_id' => 'int', 'data_length' => 11, 'data_decimal_places' => -1),
			array('view_type_id' => 'select', 'data_type_id' => 'float', 'data_length' => 24, 'data_decimal_places' => 1),
			array('view_type_id' => 'select', 'data_type_id' => 'double', 'data_length' => 53, 'data_decimal_places' => 1),
			array('view_type_id' => 'select', 'data_type_id' => 'char', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'select', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1),
			array('view_type_id' => 'user name', 'data_type_id' => 'varchar', 'data_length' => 25, 'data_decimal_places' => -1),
			array('view_type_id' => 'email', 'data_type_id' => 'varchar', 'data_length' => 60, 'data_decimal_places' => -1),
			array('view_type_id' => 'password', 'data_type_id' => 'varchar', 'data_length' => 32, 'data_decimal_places' => -1),
			array('view_type_id' => 'member since', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'last login', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'timezone', 'data_type_id' => 'float', 'data_length' => 3, 'data_decimal_places' => 1),
			array('view_type_id' => 'avatar', 'data_type_id' => 'varchar', 'data_length' => 30, 'data_decimal_places' => -1),
			array('view_type_id' => 'group name', 'data_type_id' => 'int', 'data_length' => 5, 'data_decimal_places' => -1),
			array('view_type_id' => 'email notice', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1),
			array('view_type_id' => 'posts', 'data_type_id' => 'int', 'data_length' => 8, 'data_decimal_places' => -1),
			array('view_type_id' => 'level', 'data_type_id' => 'int', 'data_length' => 3, 'data_decimal_places' => -1),
			array('view_type_id' => 'theme', 'data_type_id' => 'varchar', 'data_length' => 100, 'data_decimal_places' => -1),
			array('view_type_id' => 'signature', 'data_type_id' => 'text', 'data_length' => -1, 'data_decimal_places' => -1),
			array('view_type_id' => 'comment mode', 'data_type_id' => 'varchar', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'comment order', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1),
			array('view_type_id' => 'rank', 'data_type_id' => 'int', 'data_length' => 5, 'data_decimal_places' => -1),
			array('view_type_id' => 'notify method', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1),
			array('view_type_id' => 'notify mode', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1),
			array('view_type_id' => 'view email', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1),
			array('view_type_id' => 'maximum items', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'maximum indexes', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1),
			array('view_type_id' => 'maximum space', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1)
		);
    	$dataTypeBean = Xoonips_BeanFactory::getBean('DataTypeBean', $dirname, $trustDirname);
    	$viewTypeBean = Xoonips_BeanFactory::getBean('ViewTypeBean', $dirname, $trustDirname);
		$datatypeid = array();
    	foreach ($datatypelist as $datatype) {
    		$id = '';
    		if (!$dataTypeBean->insert($datatype, $id)) {
    			return false;
    		}
    		$datatypeid[$datatype['name']] = $id;
    	}
		$viewtypeid = array();
    	foreach ($viewtypelist as $viewtype) {
    		$id = '';
    		if (!$viewTypeBean->insert($viewtype, $id)) {
    			return false;
    		}
    		$viewtypeid[$viewtype['name']] = $id;
    	}
		foreach ($relationlist as $relation) {
			$relation['view_type_id'] = $viewtypeid[$relation['view_type_id']];
			$relation['data_type_id'] = $datatypeid[$relation['data_type_id']];
    		if (!$dataTypeBean->insertRelation($relation)) {
    			return false;
    		}
    	}
    	return true;
    }

    private static function installComplement($dirname, $trustDirname) {
    	$viewTypeBean = Xoonips_BeanFactory::getBean('ViewTypeBean', $dirname, $trustDirname);
    	$viewtypelist = $viewTypeBean->getViewtypeList();
		$viewtypeid = array();
    	foreach ($viewtypelist as $viewtype) {
    		$viewtypeid[$viewtype['name']] = $viewtype['view_type_id'];
    	}

    	$complementlist = array(
    		array('view_type_id' => $viewtypeid['view email'], 'title' => 'Email', 'module' => NULL),
    		array('view_type_id' => $viewtypeid['signature'], 'title' => 'Signature', 'module' => NULL),
    	);

    	$detaillist = array(
    		array('complement_id' => 'Email', 'code' => 'email', 'title' => _MI_USER_INSTALL_COMPLEMENT_EMAIL),
    		array('complement_id' => 'Signature', 'code' => 'signature', 'title' => _MI_USER_INSTALL_COMPLEMENT_SIGNATURE),
    	);

    	$complementBean = Xoonips_BeanFactory::getBean('ComplementBean', $dirname, $trustDirname);
    	$complementid = array();
    	foreach ($complementlist as $complement) {
    		$id = '';
    		if (!$complementBean->insert($complement, $id)) {
    			return false;
    		}
    		$complementid[$complement['title']] = $id;
    	}
	   	foreach ($detaillist as $detail) {
    		$id = '';
    		$detail['complement_id'] = $complementid[$detail['complement_id']];
    		if (!$complementBean->insertDetail($detail, $id)) {
    			return false;
    		}
    	}
    	return true;
    }

    private function installUserFieldValue($dirname, $trustDirname) {
        $valueList = array(
        	array('select_name' => 'Position', 'title_id' => '1', 'title' => _MI_USER_INSTALL_POSITION_PROFESSOR, 'weight' => 10),
        	array('select_name' => 'Position', 'title_id' => '2', 'title' => _MI_USER_INSTALL_POSITION_ASSOCIATE_PROFESSOR, 'weight' => 20),
        	array('select_name' => 'Position', 'title_id' => '3', 'title' => _MI_USER_INSTALL_POSITION_ASSISTANT_PROFESSOR, 'weight' => 30),
        	array('select_name' => 'Position', 'title_id' => '4', 'title' => _MI_USER_INSTALL_POSITION_LECTURE, 'weight' => 40),
        	array('select_name' => 'Position', 'title_id' => '5', 'title' => _MI_USER_INSTALL_POSITION_INSTRUCTOR, 'weight' => 50),
        	array('select_name' => 'Position', 'title_id' => '6', 'title' => _MI_USER_INSTALL_POSITION_RESEARCH_ASSOCIATE, 'weight' => 60),
        	array('select_name' => 'Position', 'title_id' => '7', 'title' => _MI_USER_INSTALL_POSITION_RESEARCH_ASSISTANT, 'weight' => 70),
        	array('select_name' => 'Position', 'title_id' => '8', 'title' => _MI_USER_INSTALL_POSITION_ASSISTANT, 'weight' => 80),
        	array('select_name' => 'Position', 'title_id' => '9', 'title' => _MI_USER_INSTALL_POSITION_SECRETARY, 'weight' => 90),
        	array('select_name' => 'Position', 'title_id' => '10', 'title' => _MI_USER_INSTALL_POSITION_OTHERS, 'weight' => 100),
        	array('select_name' => 'Position', 'title_id' => '11', 'title' => _MI_USER_INSTALL_POSITION_MODERATOR, 'weight' => 500),
        	array('select_name' => 'Position', 'title_id' => '12', 'title' => _MI_USER_INSTALL_POSITION_REGISTERED_USERS, 'weight' => 510),
		);
		$valueSetBean = Xoonips_BeanFactory::getBean('UserFieldValueSetBean', $dirname, $trustDirname);
    	foreach ($valueList as $value) {
    		if (!$valueSetBean->insertValue($value)) {
    			return false;
    		}
    	}
    	return true;
    }

    private function installUserFieldAndGroup($dirname, $trustDirname) {
    	$groupObj = array(
    		array('name' => _MI_USER_INSTALL_FIELD_USER_NAME, 'xml' => 'uname', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_REAL_NAME, 'xml' => 'name', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_EMAIL, 'xml' => 'emails', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_WEBSITE, 'xml' => 'url', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_AVATAR, 'xml' => 'user_avatar', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_ICQ, 'xml' => 'user_icq', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_AIM, 'xml' => 'user_aim', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_YIM, 'xml' => 'user_yim', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_MSNM, 'xml' => 'user_msnm', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_PASSWORD, 'xml' => 'pass', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_POSITION, 'xml' => 'position', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_DIVISION, 'xml' => 'division', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_INSTITUTE, 'xml' => 'company', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_PHONE, 'xml' => 'tel', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_FAX, 'xml' => 'fax', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_ADDRESS, 'xml' => 'address', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_COUNTRY, 'xml' => 'country', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_ZIP_CODE, 'xml' => 'zipcode', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_TIMEZONE, 'xml' => 'timezone_offset', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_MEMBER_SINCE, 'xml' => 'user_regdate', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_LAST_LOGIN, 'xml' => 'last_login', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_RECIEVE_EMAIL, 'xml' => 'user_mailok', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_POSTS, 'xml' => 'posts', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_LEVEL, 'xml' => 'level', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_THEME, 'xml' => 'theme', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_GROUP, 'xml' => 'group_name', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_OCCUPATION, 'xml' => 'user_occ', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_EXTRA, 'xml' => 'bio', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_INTEREST, 'xml' => 'user_intrest', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_DESCRIPTION, 'xml' => 'decription', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_SIGNATURE, 'xml' => 'user_sig', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_ACTIVATE, 'xml' => 'activate', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_INDEX, 'xml' => 'index_id', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_MAXIMUM_ITEMS, 'xml' => 'item_number_limit', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_MAXIMUM_INDEXES, 'xml' => 'index_number_limit', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_MAXIMUM_SPACE, 'xml' => 'item_storage_limit', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_COMMENTS_MODE, 'xml' => 'umode', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_COMMENTS_ORDER, 'xml' => 'uorder', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_RANK, 'xml' => 'rank', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_NOTIFICATION_METHOD, 'xml' => 'notify_method', 'occurrence' => 0),
    		array('name' => _MI_USER_INSTALL_FIELD_NOTIFICATION_MODE, 'xml' => 'notify_mode', 'occurrence' => 0),
    	);

    	$detailObj = array(
			array('table_name' => 'users', 'column_name' => 'uname', 'group_id' => 'uname', 'name' => _MI_USER_INSTALL_FIELD_USER_NAME,
				'xml' => 'uname', 'view_type_id' => 'user name', 'data_type_id' => 'varchar', 'data_length' => 25, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 1, 'list_display' => 1, 'list_sort_key' => 1, 'list_width' => 20, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 0, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'name', 'group_id' => 'name', 'name' => _MI_USER_INSTALL_FIELD_REAL_NAME,
				'xml' => 'name', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 60, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 1, 'list_sort_key' => 1, 'list_width' => 30, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'email', 'group_id' => 'emails', 'name' => _MI_USER_INSTALL_FIELD_EMAIL,
				'xml' => 'email', 'view_type_id' => 'email', 'data_type_id' => 'varchar', 'data_length' => 60, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 1, 'list_display' => 1, 'list_sort_key' => 1, 'list_width' => 30, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_viewemail', 'group_id' => 'emails', 'name' => _MI_USER_INSTALL_FIELD_ALLOW_EMAIL,
				'xml' => 'user_viewemail', 'view_type_id' => 'view email', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 0,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'url', 'group_id' => 'url', 'name' => _MI_USER_INSTALL_FIELD_URL,
				'xml' => 'url', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 100, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_avatar', 'group_id' => 'user_avatar', 'name' => _MI_USER_INSTALL_FIELD_AVATAR,
				'xml' => 'user_avatar', 'view_type_id' => 'avatar', 'data_type_id' => 'varchar', 'data_length' => 30, 'data_decimal_places' => -1,
				'default_value' => 'blank.gif', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_icq', 'group_id' => 'user_icq', 'name' => _MI_USER_INSTALL_FIELD_ICQ,
				'xml' => 'user_icq', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 15, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_aim', 'group_id' => 'user_aim', 'name' => _MI_USER_INSTALL_FIELD_AIM,
				'xml' => 'user_aim', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 18, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_yim', 'group_id' => 'user_yim', 'name' => _MI_USER_INSTALL_FIELD_YIM,
				'xml' => 'user_yim', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 25, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_msnm', 'group_id' => 'user_msnm', 'name' => _MI_USER_INSTALL_FIELD_MSNM,
				'xml' => 'user_msnm', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 100, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'pass', 'group_id' => 'pass', 'name' => _MI_USER_INSTALL_FIELD_PASSWORD,
				'xml' => 'pass', 'view_type_id' => 'password', 'data_type_id' => 'varchar', 'data_length' => 32, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 1, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 0,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'position', 'name' => _MI_USER_INSTALL_FIELD_POSITION,
				'xml' => 'position', 'view_type_id' => 'select', 'data_type_id' => 'varchar', 'data_length' => 30, 'data_decimal_places' => -1,
				'list' => 'Position', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'division', 'name' => _MI_USER_INSTALL_FIELD_DIVISION,
				'xml' => 'division', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'company', 'name' => _MI_USER_INSTALL_FIELD_INSTITUTE,
				'xml' => 'company', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'tel', 'name' => _MI_USER_INSTALL_FIELD_PHONE,
				'xml' => 'tel', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 32, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'fax', 'name' => _MI_USER_INSTALL_FIELD_FAX,
				'xml' => 'fax', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 32, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_from', 'group_id' => 'address', 'name' => _MI_USER_INSTALL_FIELD_ADDRESS,
				'xml' => 'address', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 100, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'country', 'name' => _MI_USER_INSTALL_FIELD_COUNTRY,
				'xml' => 'country', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 255, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'zipcode', 'name' => _MI_USER_INSTALL_FIELD_ZIP_CODE,
				'xml' => 'zipcode', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 32, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 1, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'timezone_offset', 'group_id' => 'timezone_offset', 'name' => _MI_USER_INSTALL_FIELD_TIMEZONE,
				'xml' => 'timezone_offset', 'view_type_id' => 'timezone', 'data_type_id' => 'float', 'data_length' => 3, 'data_decimal_places' => 1,
				'default_value' => 0.0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_regdate', 'group_id' => 'user_regdate', 'name' => _MI_USER_INSTALL_FIELD_MEMBER_SINCE,
				'xml' => 'user_regdate', 'view_type_id' => 'member since', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 1, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'last_login', 'group_id' => 'last_login', 'name' => _MI_USER_INSTALL_FIELD_LAST_LOGIN,
				'xml' => 'last_login', 'view_type_id' => 'last login', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 1, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_mailok', 'group_id' => 'user_mailok', 'name' => _MI_USER_INSTALL_FIELD_RECIEVE_EMAIL,
				'xml' => 'user_mailok', 'view_type_id' => 'email notice', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'posts', 'group_id' => 'posts', 'name' => _MI_USER_INSTALL_FIELD_POSTS,
				'xml' => 'posts', 'view_type_id' => 'posts', 'data_type_id' => 'int', 'data_length' => 8, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 1, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'level', 'group_id' => 'level', 'name' => _MI_USER_INSTALL_FIELD_LEVEL,
				'xml' => 'level', 'view_type_id' => 'level', 'data_type_id' => 'int', 'data_length' => 3, 'data_decimal_places' => -1,
				'default_value' => 1, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 1,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'theme', 'group_id' => 'theme', 'name' => _MI_USER_INSTALL_FIELD_THEME,
				'xml' => 'theme', 'view_type_id' => 'theme', 'data_type_id' => 'varchar', 'data_length' => 100, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 1,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 1),
			array('table_name' => 'groups_users_link', 'column_name' => 'groupid', 'group_id' => 'group_name', 'name' => _MI_USER_INSTALL_FIELD_GROUP,
				'xml' => 'group_name', 'view_type_id' => 'group name', 'data_type_id' => 'int', 'data_length' => 5, 'data_decimal_places' => -1,
				'default_value' => 2, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 1,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_occ', 'group_id' => 'user_occ', 'name' => _MI_USER_INSTALL_FIELD_OCCUPATION,
				'xml' => 'user_occ', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 100, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'bio', 'group_id' => 'bio', 'name' => _MI_USER_INSTALL_FIELD_EXTRA,
				'xml' => 'bio', 'view_type_id' => 'textarea', 'data_type_id' => 'text', 'data_length' => -1, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_intrest', 'group_id' => 'user_intrest', 'name' => _MI_USER_INSTALL_FIELD_INTEREST,
				'xml' => 'user_intrest', 'view_type_id' => 'text', 'data_type_id' => 'varchar', 'data_length' => 150, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'decription', 'name' => _MI_USER_INSTALL_FIELD_DESCRIPTION,
				'xml' => 'decription', 'view_type_id' => 'textarea', 'data_type_id' => 'text', 'data_length' => -1, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 3,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'user_sig', 'group_id' => 'user_sig', 'name' => _MI_USER_INSTALL_FIELD_SIGNATURE,
				'xml' => 'user_sig', 'view_type_id' => 'signature', 'data_type_id' => 'text', 'data_length' => -1, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'attachsig', 'group_id' => 'user_sig', 'name' => _MI_USER_INSTALL_FIELD_ATTACH_SIGNATURE,
				'xml' => 'attachsig', 'view_type_id' => 'checkbox', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'activate', 'name' => _MI_USER_INSTALL_FIELD_ACTIVATE,
				'xml' => 'activate', 'view_type_id' => 'text', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1,
				'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 0,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 1),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'index_id', 'name' => _MI_USER_INSTALL_FIELD_INDEX,
				'xml' => 'index_id', 'view_type_id' => 'text', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 0,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 1),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'item_number_limit', 'name' => _MI_USER_INSTALL_FIELD_MAXIMUM_ITEMS,
				'xml' => 'item_number_limit', 'view_type_id' => 'maximum items', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 1,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'index_number_limit', 'name' => _MI_USER_INSTALL_FIELD_MAXIMUM_INDEXES,
				'xml' => 'index_number_limit', 'view_type_id' => 'maximum indexes', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 1,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => $dirname. '_extend', 'column_name' => 'value', 'group_id' => 'item_storage_limit', 'name' => _MI_USER_INSTALL_FIELD_MAXIMUM_SPACE,
				'xml' => 'item_storage_limit', 'view_type_id' => 'maximum space', 'data_type_id' => 'int', 'data_length' => 10, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 1,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'umode', 'group_id' => 'umode', 'name' => _MI_USER_INSTALL_FIELD_COMMENTS_MODE,
				'xml' => 'umode', 'view_type_id' => 'comment mode', 'data_type_id' => 'varchar', 'data_length' => 10, 'data_decimal_places' => -1,
				'default_value' => '', 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'uorder', 'group_id' => 'uorder', 'name' => _MI_USER_INSTALL_FIELD_COMMENTS_ORDER,
				'xml' => 'uorder', 'view_type_id' => 'comment order', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'rank', 'group_id' => 'rank', 'name' => _MI_USER_INSTALL_FIELD_RANK,
				'xml' => 'rank', 'view_type_id' => 'rank', 'data_type_id' => 'int', 'data_length' => 5, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 0, 'edit_user' => 0, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'notify_method', 'group_id' => 'notify_method', 'name' => _MI_USER_INSTALL_FIELD_NOTIFICATION_METHOD,
				'xml' => 'notify_method', 'view_type_id' => 'notify method', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1,
				'default_value' => 1, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
			array('table_name' => 'users', 'column_name' => 'notify_mode', 'group_id' => 'notify_mode', 'name' => _MI_USER_INSTALL_FIELD_NOTIFICATION_MODE,
				'xml' => 'notify_mode', 'view_type_id' => 'notify mode', 'data_type_id' => 'int', 'data_length' => 1, 'data_decimal_places' => -1,
				'default_value' => 0, 'essential' => 0, 'list_display' => 0, 'list_sort_key' => 0, 'list_width' => 0, 'detail_display' => 2,
				'registry_user' => 1, 'edit_user' => 1, 'target_user' => 0, 'scope_search' => 0, 'nondisplay' => 0),
		);

		$complementObj = array(
			array('complement_id' => 'Email', 'base_user_detail_id' => 'emails:user_viewemail', 'complement_detail_id' => 'email', 'user_detail_id' => 'emails:email'),
			array('complement_id' => 'Signature', 'base_user_detail_id' => 'user_sig:attachsig', 'complement_detail_id' => 'signature', 'user_detail_id' => 'user_sig:user_sig'),
		);

    	$weight = 1;
		$groupid = array();
    	foreach ($groupObj as &$obj) {
			$obj['preselect'] = 1;
			$obj['released'] = 1;
    		$obj['group_id'] = $obj['xml'];
			$obj['weight'] = $weight;
			$weight = $weight + 1;
    	}

       $viewTypeBean = Xoonips_BeanFactory::getBean('ViewTypeBean', $dirname, $trustDirname);
    	$viewtypelist = $viewTypeBean->getViewtypeList();
		$viewtypeid = array();
    	foreach ($viewtypelist as $viewtype) {
    		$viewtypeid[$viewtype['name']] = $viewtype['view_type_id'];
    	}
    	$dataTypeBean = Xoonips_BeanFactory::getBean('DataTypeBean', $dirname, $trustDirname);
    	$datatypelist = $dataTypeBean->getDatatypeList();
		$datatypeid = array();
    	foreach ($datatypelist as $datatype) {
    		$datatypeid[$datatype['name']] = $datatype['data_type_id'];
    	}
		$group_id = '';
        foreach ($detailObj as &$obj) {
			$obj['preselect'] = 1;
			$obj['released'] = 1;
			if (!isset($obj['default_value'])) {
				$obj['default_value'] = NULL;
			}
			if (!isset($obj['list'])) {
				$obj['list'] = NULL;
			}
			$obj['user_detail_id'] = $obj['group_id'] . ':' . $obj['xml'];
    		$obj['view_type_id'] = $viewtypeid[$obj['view_type_id']];
			$obj['data_type_id'] = $datatypeid[$obj['data_type_id']];
    		if ($group_id != $obj['group_id']) {
    			$weight = 1;
    			$group_id = $obj['group_id'];
    		} else {
    			$weight = $weight + 1;
    		}
    		$obj['weight'] = $weight;

    	}

		$complementBean = Xoonips_BeanFactory::getBean('ComplementBean', $dirname, $trustDirname);
		$complementlist = $complementBean->getComplementInfo();
		$complementid = array();
		$complementtitle = array();
		foreach ($complementlist as $complement) {
			$complementid[$complement['title']] = $complement['complement_id'];
			$complementtitle[$complement['complement_id']] = $complement['title'];
		}
		$complementdetaillist = $complementBean->getComplementDetailInfo();
		$complementdetailid = array();
		foreach ($complementdetaillist as $complementdetail) {
			$complementdetailid[($complementtitle[$complementdetail['complement_id']] . ':' . $complementdetail['code'])] = $complementdetail['complement_detail_id'];
		}
		foreach ($complementObj as &$obj) {
			$obj['released'] = 1;
			$obj['complement_detail_id'] = $complementdetailid[$obj['complement_id']. ':' . $obj['complement_detail_id']];
			$obj['complement_id'] = $complementid[$obj['complement_id']];
		}

    	$map = array();
		$groupBean = Xoonips_BeanFactory::getBean('FieldGroupBean', $dirname, $trustDirname);
		if (!$groupBean->copyByObj($groupObj, $map, false, true)) {
			return false;
		}

		$detailBean = Xoonips_BeanFactory::getBean('FieldDetailBean', $dirname, $trustDirname);
		if (!$detailBean->copyByObj($detailObj, $map, false, true)) {
			return false;
		}

		foreach ($detailObj as $detail) {
			$link = array('group_id' => $map['group'][$detail['group_id']]
    		,'user_detail_id' => $map['detail'][$detail['user_detail_id']]
    		,'weight' => $detail['weight']
    		,'edit' => 1
    		,'edit_weight' => $detail['weight']
    		,'released' => 1);

    		$link_info = $groupBean->getGroupDetailById($link['group_id'], $link['user_detail_id']);
			if (count($link_info) == 0) {
	    		if (!$groupBean->insertLink($link, $lid)) {
    				return false;
    			}
			}
		}

		$linkBean = Xoonips_BeanFactory::getBean('FieldDetailComplementLinkBean', $dirname, $trustDirname);
		if (!$linkBean->copyByObj($complementObj, $map, false, true)) {
			return false;
		}

		// create extend table
		$detailObj = $detailBean->getReleasedDetail();
		if (!$detailBean->createExtendTable($detailObj)) {
			return false;
		}

		return true;
    }

}


