<?php	
/* $Id: step_6.inc.php,v 1.41 2003/11/19 15:53:46 k-fish Exp $ */
if(!defined("SETUP_RUNNING")) die('Use index.php for running setup!');

/* define temporary rootpath (loge)
 * we must do this cause i use it in phpxd.php which will be included
 */
$appconf["rootpath"] = ROOTPATH;

include("../include/adodb/adodb.inc.php");
require("../include/userfunc.inc.php");

if (!defined("MODULE_TYPE_SPACER")) define('MODULE_TYPE_SPACER', 0);
if (!defined("MODULE_TYPE_CORE")) define('MODULE_TYPE_CORE', 1);
if (!defined("MODULE_TYPE_BASE")) define('MODULE_TYPE_BASE', 2);
if (!defined("MODULE_TYPE_NORMAL")) define('MODULE_TYPE_NORMAL', 3);

/* setup errors */
$setupErrors = 0;
$setupWarnings = 0;

/* just as a memory aid:
 * [0] -> name
 * [1] -> selected for installation
 * [2] -> module type
 * [3] -> dependancies
 * [4] -> enable (enter into mgw_modules) after setup
 * [5] -> description
 * [6] -> version
 * [7] -> version_mtime
 * [8] -> date
 * [9] -> author
 *[10] -> email
 *[11] -> compatibility
 */
if (!isset($_SESSION["SETUP"]["done"])) {
    /* save posted data */
    if (isset($_POST["modules"]) and is_array($_POST["modules"])) {
        foreach ($_SESSION["SETUP"]["modules"] as $key => $val) {
	    if ($_SESSION["SETUP"]["modules"][$key][2]!=MODULE_TYPE_NORMAL) continue;
            if (in_array($key, $_POST["modules"])) {
		$_SESSION["SETUP"]["modules"][$key][1] = 1;
		$_SESSION["SETUP"]["modules"][$key][4] = 1;
            } else {
            	$_SESSION["SETUP"]["modules"][$key][1] = 0;
            }
        }
    }
    
    /* create log arrays */
    $logArray = array();
    $errArray = array();
    $logArray[] = "--------------------------------------------------------------------------------\n";
    $logArray[] = "MOREGROUPWARE SETUP\n";
    $logArray[] = "Started ".date("H:i, d M, Y")."\n";
    $logArray[] = "--------------------------------------------------------------------------------\n";
    
    /* connect to db */
    $conn = ADONewConnection($_SESSION["SETUP"]["dbtype"]);
    if ($conn->Connect($_SESSION["SETUP"]["dbhost"], $_SESSION["SETUP"]["dbuser"], $_SESSION["SETUP"]["dbpass"], $_SESSION["SETUP"]["dbname"])) {
    	$logArray[] = "\nConnected to '".$_SESSION["SETUP"]["dbtype"]."' database '".$_SESSION["SETUP"]["dbname"]."' as user '".$_SESSION["SETUP"]["dbuser"]."'.\n";
    } else {
      	setup_die("Connection failed in Step 6: Is your database server still running? (Host ".$_SESSION["SETUP"]["dbhost"].", User ".$_SESSION["SETUP"]["dbuser"].", Database ".$_SESSION["SETUP"]["dbname"].")");
    }

    /* just as a memory aid:
     * [0] -> name
     * [1] -> selected for installation
     * [2] -> module type
     * [3] -> dependancies
     * [4] -> enable (enter into mgw_modules) after setup
     * [5] -> description
     * [6] -> version
     * [7] -> version_mtime
     * [8] -> date
     * [9] -> author
     *[10] -> email
     *[11] -> compatibility
     *[12] -> secure
     */
    $logArray[] = "\nDEPENDANCIES:\n";
    $logArray[] = "--------------------------------------------------------------------------------\n";
    foreach ($_SESSION["SETUP"]["modules"] as $module) {
	// check dependancies
	if($module[1] == 1 and (is_array($module[3]) and count($module[3] > 0))){
	    // loop through dependancies
	    while(list($k, $depmod) = each($module[3])){
		//see if the module is not already selected
		if(! (isset($_SESSION["SETUP"]["modules"][$depmod]) && $_SESSION["SETUP"]["modules"][$depmod][1] == 1)){
		    $logArray[] = $depmod." is needed by ".$module[0]."! Selecting it...\n";
		    $_SESSION["SETUP"]['modules'][$depmod][1] = 1;
		    $_SESSION["SETUP"]['modules'][$depmod][4] = 0;
		    reset($_SESSION["SETUP"]["modules"]);
		}
	    }
	}
    }
    $logArray[] = "\nDone.\n";

    /* install modules ... order: core, base, user
     * create table from sql data first, install modules after:
     *
     * pass 1: create tables
     * pass 2: install modules
     */
    $order = array(MODULE_TYPE_CORE, MODULE_TYPE_BASE);
    for ($t=0; $t<2; $t++) {
    	reset($order);
        if ($t==0) {
	    $logArray[] = "\nCREATING TABLES:\n";
	    $logArray[] = "--------------------------------------------------------------------------------\n";
        } else {
	    $logArray[] = "Done.\n";
        }
        foreach ($order as $type) {
	    /* log text ... */
	    if ($type==MODULE_TYPE_CORE and $t>0) {
            	$logArray[] = "\nCORE MODULES:\n";
		$logArray[] = "--------------------------------------------------------------------------------\n";
            }
            if ($type==MODULE_TYPE_BASE and $t>0) {
            	$logArray[] = "\nBASE MODULES:\n";
		$logArray[] = "--------------------------------------------------------------------------------\n";
            }

            foreach ($_SESSION["SETUP"]["modules"] as $module) {
            	/* skip not chosen modules */
            	if ($module[1]!=1) continue;
                
                /* skip modules that are not of the current type */
                if ($module[2]!=$type) continue;
                
                /* PASS 1 */
                if ($t==0) {
		    if (file_exists(ROOTPATH."/modules/".$module[0]."/definition2.xml")) {
			$logArray[] = "Creating tables for ".$module[0]."...";
                        $sqlErrors = false;

			include_once(ROOTPATH."/include/adodb/adodb-xmlschema.inc.php");

			$schema = new adoSchema($conn);
			$schema->setPrefix( "mgw" );
			$sqls = $schema->ParseSchema( ROOTPATH."/modules/".$module[0]."/definition2.xml" );
			foreach ($sqls as $key=>$sql) {
			    if ($_SESSION["SETUP"]["dbtype"]=="mysql") {
				$sqls[$key] = str_replace("LONGTEXT","TEXT",$sqls[$key]);
				$sqls[$key] = str_replace("DATETIME","TIMESTAMP",$sqls[$key]);
			    }
			}
			$schema->Destroy();

			// check if core version is at least equal
			if ($module[11]!="" and (float)$gwversion_number >= (float)$module[11]) {
			    if (count($sqls)>0) {
				foreach ($sqls as $sql) {
				    if($sql!="" and !$conn->Execute(trim($sql))) {
					if(strstr($sql, 'CREATE') && strstr($sql, 'INDEX')){
					    $errArray[] = "Error during CREATE INDEX. Continuing...\nSQL:".$sql."\n";
					    $setupWarnings++;
					}
					else{
					    $sqlErrors = true;
					    $setupErrors++;
					    $errArray[] = "[".$module[0]."]\nSQL: ".$sql."\n";
					    $errArray[] = $conn->ErrorMsg();
					    $errArray[] = "\n";
					}
				    }
				}
			    }
			    
			    if ($sqlErrors) {
				$logArray[] = "FAILED, see ".basename($errorLog)." for details.\n\n";
			    } else {
				$logArray[] = " done.\n";
			    }
			    if (file_exists(ROOTPATH."/modules/".$module[0]."/setup/install.php")) {
				$logArray[] = "Launching custom install.php for ".$module[0]."...\n";
				include ROOTPATH."/modules/".$module[0]."/setup/install.php";
			    }
			}
			else{
			    $setupErrors++;
			    $logArray[] = "FAILED, see ".basename($errorLog)." for details.\n\n";
			    $errArray[] = "[".$module[0]."]\n: ".$sql."\n";
			    $errArray[] = "Version of core install lower than required by module!\n";
			}
		    }
		    
                    if (file_exists(ROOTPATH."/modules/".$module[0]."/setup/install.sql")) {
			$logArray[] = "Executing install.sql for ".$module[0]."...";
                        $sqlErrors = false;
                        $sqlfile = @file(ROOTPATH."/modules/".$module[0]."/setup/install.sql");
                    	
                        $sqlbuffer = "";
                        for($o=0;$o<count($sqlfile);$o++) {
			    if(substr(trim($sqlfile[$o]),0,1) != '#' and strlen(trim($sqlfile[$o]))>0) $sqlbuffer .= $sqlfile[$o];
                        }
                        $sql_array = explode(";",$sqlbuffer);
                    	unset($sqlbuffer);
                    	for($i=0;$i<count($sql_array);$i++) {
                            if(strlen(trim($sql_array[$i])) > 0) {
				if(!$conn->Execute($sql_array[$i])) {
				    $sqlErrors = true;
                                    $setupErrors++;
                                    $errArray[] = "[".$module[0]."]\nSQL: ".$sql_array[$i]."\n";
				    $errArray[] = $conn->ErrorMsg();
                                    $errArray[] = "\n";
				}
			    }
                    	}
                        if ($sqlErrors) {
			    $logArray[] = "FAILED, see ".basename($errorLog)." for details.\n\n";
                        }else{
			    $logArray[] = " done.\n\n";
                        }
                    }
                } else {
                    /* install module */
                    $logArray[] = "\nInstalling module ".strtoupper($module[0]).":\n";

		    $sql = "INSERT INTO mgw_modules (secure, modulename, version, version_mtime, date, author, email, description, compatibility, dependancies, module_type, active, lu_user, lu_date) VALUES (".$module[12].",'".$module[0]."','".(isset($module[6])?$module[6]:"")."','".(isset($module[7])?$module[7]:"")."','".(isset($module[8])?$module[8]:"")."','".(isset($module[9])?$module[9]:"")."','".(isset($module[10])?$module[10]:"")."',".$conn->QMagic($module[5]).",'".(isset($module[11])?$module[11]:"")."','".(is_array($module[2])?implode($module[2],","):"")."',".$type.",'1', '1', ".$conn->DBTimeStamp(time()).")";
		    if(!$res = $conn->Execute($sql))  {
			$logArray[] = "FAILED, see ".basename($errorLog)." for details.\n";
			$errArray[] = "[".$module[0]."] SQL: ".$sql."\n";
			$errArray[] = $conn->ErrorMsg();
			$errArray[] = "\n";
			$setupErrors++;
			continue;
		    } else {
			$logArray[] = "Entry created in mgw_modules.\n";
		    }

		    if(($type!=MODULE_TYPE_CORE) && ($module[2] == 1)){

			$sql = "INSERT INTO mgw_rights (modulename, user_group_id, _read, _write, _delete,_delete_others, _modify, _modify_others, _module_level,lu_user, lu_date) VALUES ('".$module[0]."', '50000', '1', '1', '1', '1','1', '1', '9', '1', ".$conn->DBTimeStamp(time()).")";
                	if(!$res = $conn->Execute($sql))  {
			    $logArray[] = "FAILED, see ".basename($errorLog)." for details.\n";
			    $errArray[] = "[".$module[0]."] SQL: ".$sql."\n";
			    $errArray[] = $conn->ErrorMsg();
			    $errArray[] = "\n";
			    $setupErrors++;
			    continue;
			} else {
			    $logArray[] = "Default rights created.\n";
			}
                
			if ($module[0] != "admin" && $module[0] != "admin2" ) {
			    $sql = "INSERT INTO mgw_rights (modulename, user_group_id, _read, _write, _delete,_delete_others, _modify, _modify_others, _module_level,lu_user, lu_date) VALUES ('".$module[0]."', '50001', '1', '1', '1', '1','1', '1', '3', '1', ".$conn->DBTimeStamp(time()).")";
			    if(!$res = $conn->Execute($sql))  {
				$logArray[] = "FAILED, see ".basename($errorLog)." for details.\n";
				$errArray[] = "[".$module[0]."] SQL: ".$sql."\n";
				$errArray[] = $conn->ErrorMsg();
				$errArray[] = "\n";
				$setupErrors++;
				continue;
			    } else {
				$logArray[] = "Default rights created.\n";
			    }
			}
                    }
                    $logArray[] = "Module ".$module[0]." installed.\n";
                }
            }
        }
    }

    $logArray[] = "\nFINISHING SETUP\n";
    $logArray[] = "--------------------------------------------------------------------------------\n";

    // populate mgw_languages
    // langcode, description, charset, active, lu_user, lu_date
    reset($_SESSION["SETUP"]['languages']);
    foreach($_SESSION["SETUP"]['languages'] as $k => $v){
	$k = explode(';', $k);
	$sql = "INSERT INTO mgw_languages (langcode, description, charset, active, lu_date) VALUES ('{$k[0]}','$v','{$k[1]}',1,".$conn->DBTimeStamp(time()).")";
	if(!$conn->Execute($sql)){
	    $sqlErrors = true;
	    $setupErrors++;
	    $errArray[] = "While populating mgw_languages\nSQL: ".$sql."\n";
	    $errArray[] = $conn->ErrorMsg();
	    $errArray[] = "\n";
	}
    }

    // set admin password
    $sql = "UPDATE mgw_users SET pw='".md5($_SESSION["SETUP"]['adminpw'])."' WHERE id=1";
    if(!$conn->Execute($sql))  {
	$sqlErrors = true;
	$setupErrors++;
	$errArray[] = "\nWhile setting admin passsword in mgw_users\nSQL: ".$sql."\n";
	$errArray[] = $conn->ErrorMsg();
	$errArray[] = "\n";
    } else {
	$logArray[] = "\nAdmin password set in mgw_users.\n";
    }

    /* create smarty cache dirs */
    $logArray[] = "\nCreating smarty cache dir ".$htmlTemplates."...";
    if (!file_exists($htmlTemplates)) {
	if (@mkdir($htmlTemplates, octdec(700))) {
	    $logArray[] = " done.\n";
	} else {
	    $logArray[] = " FAILED!\n";
	    $errArray[] = "Failed to create smarty cache dir ".$htmlTemplates.".\n";
	    $setupErrors++;
	}
    } else {
	if (is_writeable($htmlTemplates)) {
	    $logArray[] = " Already exists (writeable).\n";
	} else {
	    $logArray[] = " FAILED!\n";
	    $errArray[] = "The directory ".$htmlTemplates." already exists, but is not writeable.\n";
	    $setupWarnings++;
	}
    }
    /*
    $logArray[] = "\nCreating smarty cache dir ".$wmlTemplates."...";
    if (!file_exists($wmlTemplates)) {
	if (@mkdir($wmlTemplates, octdec(700))) {
	    $logArray[] = " done.\n";
	} else {
	    $logArray[] = " FAILED!\n";
	    $errArray[] = "Failed to create smarty cache dir ".$wmlTemplates.".\n";
	    $setupWarnings++;
	}
    } else {
	if (is_writeable($wmlTemplates)) {
	    $logArray[] = " Already exists (writeable).\n";
	} else {
	    $logArray[] = " FAILED!\n";
	    $errArray[] = "The directory ".$wmlTemplates." already exists, but is not writeable.\n";
	    $setupErrors++;
	}
    }
    */

    /* only write config if there were no errors because we mayb e able to 
     * correct these automaticly ... for now we do it like this
     */
    if ($setupErrors==0) {
        if ($_SESSION["SETUP"]["auth_method"]=="ntlm")
	    $_SESSION["SETUP"]["auth_method"] = "sql";
    	// create config file
        $configString[] = "<?php";
        $configString[] = "";
	$configString[] = "/******************************************************************************";
        $configString[] = " * MORE.GROUPWARE CONFIG FILE                                                 *";
        $configString[] = " *                                                                            *";
        $configString[] = " * This file is auto-generated by setup, only modify if you are sure of what  *";
        $configString[] = " * you are doing.                                                             *";
        $configString[] = " *                                                                            *";
        $configString[] = " * http://www.moregroupware.org/                                              *";
        $configString[] = " *                                                                            *";
        $configString[] = " * Programmed by Marc Logemann & Marcel Meulemans (30-10-2002)                *";
        $configString[] = " * Programmed by Thomas Bley                      (04-10-2003)                *";
        $configString[] = " * Programmed by karsten Dambekalns               (08-10-2003)                *";
        $configString[] = " ******************************************************************************/";
        $configString[] = "";
        $configString[] = "/* GENERAL */";
        $configString[] = "\$appconf['dbvendor'] = '". $_SESSION["SETUP"]["dbtype"]. "';";
        $configString[] = "\$appconf['dbhost'] = '". $_SESSION["SETUP"]["dbhost"]. "';";
        $configString[] = "\$appconf['dbuser'] = '". $_SESSION["SETUP"]["dbuser"]. "';";
        $configString[] = "\$appconf['dbpassword'] = '". $_SESSION["SETUP"]["dbpass"]. "';";
        $configString[] = "\$appconf['dbname'] = '". $_SESSION["SETUP"]["dbname"]. "';";

	$url = parse_url($_SESSION["SETUP"]["rooturl"]);
        if ($_SESSION["SETUP"]["dynamicurl"]==1)
	    $configString[] = "\$appconf['rooturl'] = ".
		"((isset(\$_SERVER['HTTPS']) && \$_SERVER['HTTPS']=='on') ? 'https://' : 'http://').\$_SERVER['HTTP_HOST'].'".$url['path']."';";
	else
	    $configString[] = "\$appconf['rooturl'] = ".
		"((isset(\$_SERVER['HTTPS']) && \$_SERVER['HTTPS']=='on') ? 'https://' : 'http://').'".$url['host'].$url['path']."';";

        $configString[] = "\$appconf['session_name'] = '". $_SESSION["SETUP"]["sessionname"]."';";
        $configString[] = "\$appconf['theme'] = 'default';";
        $configString[] = "\$appconf['auth_method']= '". $_SESSION["SETUP"]["auth_method"]. "';";
        $configString[] = "\$appconf['use_ntlm_auth']= '". $_SESSION["SETUP"]["use_ntlm_auth"]. "';";
        $configString[] = "\$appconf['encrypt_pwd']= '". $_SESSION["SETUP"]["encrypt_pwd"]. "';";
        $configString[] = "\$appconf['forcessl']= '". $_SESSION["SETUP"]["forcessl"]. "';";
        if ($_SESSION["SETUP"]["auth_method"]=="ldap") {
	    $configString[] = "";
            $configString[] = "/* LDAP */";
            $configString[] = "\$appconf['auth_ldaptype'] = '". $_SESSION["SETUP"]["auth_ldaptype"]. "';";
            $configString[] = "\$appconf['auth_ldaphost'] = '". $_SESSION["SETUP"]["auth_ldaphost"]. "';";
            $configString[] = "\$appconf['auth_ldapbase'] = '". $_SESSION["SETUP"]["auth_ldapbase"]. "';";
            $configString[] = "\$appconf['auth_ldapuid'] = '". $_SESSION["SETUP"]["auth_ldapuid"]. "';";
            $configString[] = "\$appconf['auth_ldappasswd'] = '". $_SESSION["SETUP"]["auth_ldappasswd"]. "';";
            $configString[] = "\$appconf['auth_ldapsuffixe'] = '". $_SESSION["SETUP"]["auth_ldapsuffixe"]. "';";
            $configString[] = "\$appconf['create_accounts_on_login'] = ". $_SESSION["SETUP"]["create_accounts_on_login"].";";
        }
        $configString[] = "";
        $configString[] = "/* FORMATING */";
        $configString[] = "\$appconf['mgw_version'] = '". $gwversion. "';";
        $configString[] = "\$appconf['mgw_version_number'] = '". $gwversion_number. "';";
        $configString[] = "\$appconf['mgw_version_name'] = '". $gwversion_name. "';";
        $configString[] = "\$appconf['mgw_releasedate'] = '". $gwreleasedate. "';";
        $configString[] = "\$appconf['def_language'] = '". $_SESSION["SETUP"]["lang"]. "';";
        $configString[] = "\$appconf['def_charset'] = '". $_SESSION["SETUP"]["charset"]. "';";
        
        $configString[] = "";
        $configString[] = "/* PATHS */";
        $configString[] = "define('ROOTPATH', '".ROOTPATH. "');";
        $configString[] = "define('SMARTY_DIR', ROOTPATH.'/include/smarty/');";
        $configString[] = "define('INCLUDEPATH', ROOTPATH.'/include/');";

        $configString[] = "";
        $configString[] = "if (\$appconf['rooturl'][strlen(\$appconf['rooturl'])-1]!='/') \$appconf['rooturl'] .= '/';";
        $configString[] = "define('ROOTURL', \$appconf['rooturl']);";

        $configString[] = "";
        $configString[] = "define('SETUP_RUNNING', false);";
        $configString[] = "define('LANG_DEBUG', false);";
	if($_SESSION["SETUP"]['usedbsessions'])
	  $configString[] = "define('USE_DB_SESSIONS', true);";
	else
	  $configString[] = "define('USE_DB_SESSIONS', false);";
        $configString[] = "";
        $configString[] = "?>";
        
        $logArray[] = "\nCreating config file...";
        if ($fp = fopen(ROOTPATH."/config.inc.php", "w")) {
	    foreach($configString as $line) {
            	fwrite($fp, $line."\n");
            }
	    fclose($fp);
	    chmod(ROOTPATH."/config.inc.php", octdec(600));
            $logArray[] = " done.\n";
        } else {
	    $logArray[] = " ERROR.\n";
            $setupErrors++;
        }
    
    }
    
    $logArray[] = "\n\n--------------------------------------------------------------------------------\n";
    $logArray[] = "\nSetup finished with ".$setupErrors." errors and ".$setupWarnings." warnings.\n";
    
    /* write log files */
    $str = "";
    if ($fp = @fopen($setupLog, "a+")) {
    	if (count($logArray)>0) {
	    for ($i=0; $i<count($logArray); $i++) {
            	$str .= $logArray[$i];
    	    	fwrite($fp, $logArray[$i]);
    	    }
       	}
        fclose($fp);
    }
    if ($fp = @fopen($errorLog, "a+")) {
    	if (count($errArray)>0) {
	    for ($i=0; $i<count($errArray); $i++) {
    	    	fwrite($fp, $errArray[$i]);
    	    }
       	}
        fclose($fp);
    }
    
    /* save error/warn count */
    $_SESSION["SETUP"]["errors"] = $setupErrors;
    $_SESSION["SETUP"]["warnings"] = $setupWarnings;

    // set auth
    $_SESSION["SETUP"]['authenticated'] = true;
} 

if (isset($_POST["showlog"])) {
    $smarty->assign("showlog", 1);
    $smarty->assign("logfile", implode("", @file($setupLog)));
    
    $nav = true;
    $smarty->append("nav", array(0=>"_prev",1=>Lang::getLanguageString("prev"),2=>1));
} else {
    $nav = true;
    if ($_SESSION["SETUP"]["errors"]>0) {
    	$smarty->append("nav", array(0=>"restart",1=>Lang::getLanguageString("restart"),2=>1));
    	$smarty->append("nav", array(0=>"login",1=>Lang::getLanguageString("login"),2=>0));
    } else {
    	$smarty->append("nav", array(0=>"login",1=>Lang::getLanguageString("login"),2=>1));
    }
    $smarty->append("subnav", array(0=>"showlog",1=>Lang::getLanguageString("showlog"),2=>1));

    $smarty->assign("rooturl", $_SESSION["SETUP"]["rooturl"]);        
    $smarty->assign("errorcount", $_SESSION["SETUP"]["errors"]);
    $smarty->assign("warncount", $_SESSION["SETUP"]["warnings"]);
    $smarty->assign("install_warn", Lang::getParmLang(Lang::getLanguageString("install_warn"),array($_SESSION["SETUP"]["warnings"])));
}

/* make sure we can't run setup again */
$_SESSION["SETUP"]["done"] = true;

?>
