<?php
/* $Id: save_settings.inc.php,v 1.26 2005/12/24 10:41:58 leyeti Exp $ */
if(!defined("SETUP_RUNNING")) die('Use index.php for running setup!');

include("../include/crypt.inc.php");
include("../include/adodb/adodb.inc.php");
include("../include/adodb/adodb-error.inc.php");

/* array to store the errors that occured */
$errors = array();

// we POST from the form, not going backwards
if(isset($_POST["dbtype"])){

    /* db type */
    $_SESSION["SETUP"]["dbtype"] = $_POST["dbtype"];

    /* db host */
    // if empty set to localhost unless postgres7 is used (empty hostname possible)
    if (!isset($_POST["dbhost"]) or ($_POST["dbtype"] != "postgres7" && $_POST["dbhost"]==""))
	$_SESSION["SETUP"]["dbhost"] = "localhost";
    elseif(isset($_POST["dbhost"]))
	$_SESSION["SETUP"]["dbhost"] = $_POST["dbhost"];

    /* db user */
    if(isset($_POST["dbuser"]))
	$_SESSION["SETUP"]["dbuser"] = $_POST["dbuser"];
    
    /* db pass */
    if(isset($_POST["dbpass"]))
	$_SESSION["SETUP"]["dbpass"] = $_POST["dbpass"];
    
    /* db name */
    if (!isset($_POST["dbname"]) or $_POST["dbname"]=="") {
	$dberrorarray[] = Lang::getLanguageString("err_dbname");
	$_SESSION["SETUP"]["dbname"] = "";	
    }    
    elseif(isset($_POST["dbname"]))
	$_SESSION["SETUP"]["dbname"] = $_POST["dbname"];
    
    /* rooturl */
    if (!isset($_POST["rooturl"]) or $_POST["rooturl"]=="") {
	$miscerrorarray[] = Lang::getLanguageString("err_rooturl");
	$_SESSION["SETUP"]["rooturl"] = ((isset($_SERVER['HTTPS'])) ? "https://" : "http://").$_SERVER["HTTP_HOST"].str_replace(SETUP_DIR,"",dirname($_SERVER["PHP_SELF"]));	
    }
    elseif(isset($_POST["rooturl"]))
	$_SESSION["SETUP"]["rooturl"] = $_POST["rooturl"];
    if ($_SESSION["SETUP"]["rooturl"][strlen($_SESSION["SETUP"]["rooturl"])-1]!="/") $_SESSION["SETUP"]["rooturl"] .= "/";

    /* url check */
    if (isset($_POST["skipurlcheck"]))
	$_SESSION["SETUP"]["skipurlcheck"] = 1;
    else
	$_SESSION["SETUP"]["skipurlcheck"] = 0;
    
    /* dynamic url */
    if (isset($_POST["dynamicurl"])) {
	$_SESSION["SETUP"]["dynamicurl"] = 1;
	$_SESSION["SETUP"]["skipurlcheck"] = 1;
    }
    else
	$_SESSION["SETUP"]["dynamicurl"] = 0;

    /* dynamic url */
    if (isset($_POST["forcessl"])) {
	$_SESSION["SETUP"]["forcessl"] = 1;
    }
    else
	$_SESSION["SETUP"]["forcessl"] = 0;
    
    /* rootpath */
    if(ini_get('magic_quotes_gpc') && isset($_POST["rootpath"])) $_POST["rootpath"] = stripslashes($_POST["rootpath"]);
    if (!isset($_POST["rootpath"]) or $_POST["rootpath"]=="" or !is_dir($_POST["rootpath"])) {
	$miscerrorarray[] = Lang::getLanguageString("err_rootpath");
	$_SESSION["SETUP"]["rootpath"] = ROOTPATH;	
    }    
    elseif(isset($_POST["rootpath"]))
	$_SESSION["SETUP"]["rootpath"] = $_POST["rootpath"];
    
    /* session name */
    if (!isset($_POST["sessionname"]) or $_POST["sessionname"]=="") {
	$miscerrorarray[] = Lang::getLanguageString("err_sessname");
	$_SESSION["SETUP"]["sessionname"] = "MGWSESSION";	
    }
    elseif(isset($_POST["sessionname"]))
	$_SESSION["SETUP"]["sessionname"] = $_POST["sessionname"];
    
    /* use db sessions */
    if (isset($_POST["usedbsessions"])) {
	$_SESSION["SETUP"]["usedbsessions"] = true;
    }
    else
	$_SESSION["SETUP"]["usedbsessions"] = false;
    
    /* auth method */
    $_SESSION["SETUP"]["use_ntlm_auth"] = false;
    if (!isset($_POST["auth_method"]) or $_POST["auth_method"]=="")
	$_SESSION["SETUP"]["auth_method"] = "sql";
    elseif (isset($_POST["auth_method"]) and $_POST["auth_method"]=="ntlm") {
	$_SESSION["SETUP"]["auth_method"] = "ntlm";
	$_SESSION["SETUP"]["use_ntlm_auth"] = true;
    }
    elseif (isset($_POST["auth_method"]) and $_POST["auth_method"]=="ldap") {
	$_SESSION["SETUP"]["auth_method"] = "ldap";
	unset($_POST["encrypt_pwd"]);
    }
    elseif(isset($_POST["auth_method"]))
	$_SESSION["SETUP"]["auth_method"] = $_POST["auth_method"];

    /* encrypt_pwd */
    if (isset($_POST["encrypt_pwd"]))
	$_SESSION["SETUP"]["encrypt_pwd"] = 1;
    else
	$_SESSION["SETUP"]["encrypt_pwd"] = 0;

    // admin password
    if (!isset($_POST["adminpw1"]) || $_POST["adminpw1"]=="" ||
	!isset($_POST["adminpw2"]) || $_POST["adminpw2"]==""){
	$miscerrorarray[] = Lang::getLanguageString("err_adminpass");
    }
    elseif($_POST["adminpw1"] != $_POST["adminpw2"])
	$miscerrorarray[] = Lang::getLanguageString("err_adminpass");
    else
	$_SESSION["SETUP"]["adminpw"] = $_POST["adminpw1"];
}

// create ADOdb instance
$conn = ADONewConnection($_SESSION["SETUP"]["dbtype"]);

/* attempt to create db if prompted */
if (isset($_POST["trytocreatedb"])) {
    // try to connect with create user
    @$conn->Connect($_SESSION["SETUP"]["dbhost"], $_POST["cdbuser"], $_POST["cdbpass"]);
    if($conn->MetaError() == DB_ERROR_ACCESS_VIOLATION){
	  $dberrorarray[] = Lang::getLanguageString("err_condb_cuser");
    } elseif($conn->MetaError() == DB_ERROR){
	  $dberrorarray[] = Lang::getLanguageString("err_db");
    } else{
	  $dict = NewDataDictionary($conn);
	  @$dict->ExecuteSQLArray($dict->CreateDatabase($_SESSION["SETUP"]['dbname']));
	  if ($conn->MetaError() == DB_ERROR_CANNOT_CREATE){
	    $dberrorarray[] = Lang::getLanguageString("err_create_db");
	  } elseif($conn->MetaError() == DB_ERROR_ALREADY_EXISTS){
	    $dberrorarray[] = Lang::getLanguageString("err_create_exists");
	  } elseif($conn->MetaError() == DB_ERROR){
	    $dberrorarray[] = Lang::getLanguageString("err_db");
	  } elseif ($conn->MetaError()!=0) {
	    $dberrorarray[] = $conn->MetaError()." ".$conn->MetaErrorMsg($conn->MetaError());
	  }
    }
}

/* test db connection with normal user */
@$conn->Connect($_SESSION["SETUP"]["dbhost"], $_SESSION["SETUP"]["dbuser"], $_SESSION["SETUP"]["dbpass"], $_SESSION["SETUP"]["dbname"]);
if($conn->MetaError() == DB_ERROR_CONNECT_FAILED){
    $dberrorarray[] = Lang::getLanguageString("err_dbconn");
}
elseif($conn->MetaError() == DB_ERROR_ACCESS_VIOLATION){
    $dberrorarray[] = Lang::getLanguageString("err_condb_user");
}
elseif ($conn->MetaError() == DB_ERROR_NOSUCHDB) {
    $dberrorarray[] = Lang::getLanguageString("err_condb_name");        
}
elseif($conn->MetaError() == DB_ERROR){
    $dberrorarray[] = Lang::getLanguageString("err_db");
}
else {
    /* check if the actual database user has create rights (drop rights) */
    $dict = NewDataDictionary($conn);
    //  delete_me_please (testfield int
    $dict->ExecuteSQLArray($dict->CreateTableSQL('delete_me_please','testfield I'));
    if ($conn->MetaError() == DB_ERROR_CANNOT_CREATE){
	$dberrorarray[] = Lang::getLanguageString("err_createtable");
    }
    elseif($conn->MetaError() == DB_ERROR){
	$dberrorarray[] = Lang::getLanguageString("err_db");
    }
    else {
 	$dict->ExecuteSQLArray($dict->DropTableSQL('delete_me_please'));
 	if ($conn->MetaError() == DB_ERROR_CANNOT_DROP){
 	    $dberrorarray[] = Lang::getLanguageString("err_droptable");
 	}
	elseif($conn->MetaError() == DB_ERROR){
	    $dberrorarray[] = Lang::getLanguageString("err_db");
	}
    }
}

/* url check */
if($_SESSION["SETUP"]["skipurlcheck"]!=1){

	if(!function_exists('get_headers')) {
		// function get_headers for php < 5
	   /**
	   * @return array
	   * @param string $url
	   * @param int $format (default 0)
	   * @desc Fetches all the headers
	   * @author cpurruc fh-landshut de, stuart at sixletterwords dot com, denilson at vialink dot com dot br, matthieu dot paineau at wanadoo dot fr
	   */
	   function get_headers($url,$format=0){
	       $url_info=parse_url($url);
		   if (!isset($url_info['path'])) {
		       $url_info['path']="/";
		   }
	
		   if ($url_info['scheme']=="https"){
		   		$prot =  "ssl://";
				$port = 443;
		   }
		   else {
		   		$prot = "";
				$port = 80;
		   }
	       $fp=fsockopen($prot.$url_info['host'], $port, $errno, $errstr, 30);
	       if($fp) {
	                        if (isset($url_info['query'])) {
	                            $query = "?".$url_info['query'];
	                        }
	                        else $query="";
	           $head = "GET ".$url_info['path'].$query." HTTP/1.0\r\n".
	                   "Host: ".$url_info['host']."\r\n".
	                                   "\r\n";
	
	           fputs( $fp, $head );
			   $end = "\r\n\r\n";
			   $var = "";
			   while (!feof($fp))
	           {
	               $var.=fgets($fp, 1280);
	               if(strpos($var,$end))
	                   break;
	           }
	           fclose($fp);
			   
			   $var=preg_replace("/".$end.".*\$/",'',$var);
	           $var=explode("\r\n",$var);
			   
	           $headers = array();
	           if ($format==1) {
			   		foreach($var as $i => $content){
	                   	if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$content,$parts)){
	                       $headers[$parts[1]]=$parts[2];
						}
						else{
							$headers[$i]=$content;
						}
	               	}
	           }
			   else{
			   		$headers=$var;
			   }
	           
	           return $headers;
	       }
		   else {
			 return false;
		   }
	   }
   }//if function not exists
	
	//new code for avoid need of curl extension:
	$headers = get_headers($_SESSION["SETUP"]["rooturl"] . "index.php");
	if ( !ereg(" 200 ",$headers[0])){ //$headers[0] contain HTTP response code
		$miscerrorarray[] = Lang::getLanguageString("err_rooturl_wrong");
	}
	
    //======= old code here :
    /* check if URL to moregroupware root is correct
     * use the curl extension to do so if available
    
    if(function_exists("curl_init")){
		$ch = curl_init($_SESSION["SETUP"]["rooturl"] . "index.php");
		curl_setopt ($ch, CURLOPT_NOBODY, 0);
		ob_start();
		curl_exec ($ch);
		ob_end_clean();
		$cret = curl_getinfo($ch);
		curl_close ($ch);
		if($cret["http_code"]!=200) $miscerrorarray[] = Lang::getLanguageString("err_rooturl_wrong");
    } elseif((!stristr($_SESSION["SETUP"]["rooturl"],"https")) && (ini_get("allow_url_fopen")==1)){
    	// do not use this check when using SSL (k-fish)
     	// and do it only if fopen on URLs is allowed.
		if(!@fopen($_SESSION["SETUP"]["rooturl"]."index.php", "r")) {
		    $miscerrorarray[] = Lang::getLanguageString("err_rooturl_wrong");
		}
    }
	*/
	//======= end of old code.
}

/* check if rootpath to moregroupware is correct */
if(isset($_POST["rootpath"]) and !file_exists($_POST["rootpath"] . "/index.php")) {
    $miscerrorarray[] = Lang::getLanguageString("err_rootpath");
} 

/* if no error occured unset the array */
if (isset($miscerrorarray) and count($miscerrorarray)==0) unset($miscerrorarray);
if (isset($dberrorarray) and count($dberrorarray)==0) unset($dberrorarray);

/* all settings ok? */
if (!isset($miscerrorarray) and !isset($dberrorarray)) $_SESSION["SETUP"]["settings_ok"] = true;
?>
