1<?php
2/* $Id: save_settings.inc.php,v 1.26 2005/12/24 10:41:58 leyeti Exp $ */
3if(!defined("SETUP_RUNNING")) die('Use index.php for running setup!');
4
5include("../include/crypt.inc.php");
6include("../include/adodb/adodb.inc.php");
7include("../include/adodb/adodb-error.inc.php");
8
9/* array to store the errors that occured */
10$errors = array();
11
12// we POST from the form, not going backwards
13if(isset($_POST["dbtype"])){
14
15    /* db type */
16    $_SESSION["SETUP"]["dbtype"] = $_POST["dbtype"];
17
18    /* db host */
19    // if empty set to localhost unless postgres7 is used (empty hostname possible)
20    if (!isset($_POST["dbhost"]) or ($_POST["dbtype"] != "postgres7" && $_POST["dbhost"]==""))
21	$_SESSION["SETUP"]["dbhost"] = "localhost";
22    elseif(isset($_POST["dbhost"]))
23	$_SESSION["SETUP"]["dbhost"] = $_POST["dbhost"];
24
25    /* db user */
26    if(isset($_POST["dbuser"]))
27	$_SESSION["SETUP"]["dbuser"] = $_POST["dbuser"];
28
29    /* db pass */
30    if(isset($_POST["dbpass"]))
31	$_SESSION["SETUP"]["dbpass"] = $_POST["dbpass"];
32
33    /* db name */
34    if (!isset($_POST["dbname"]) or $_POST["dbname"]=="") {
35	$dberrorarray[] = Lang::getLanguageString("err_dbname");
36	$_SESSION["SETUP"]["dbname"] = "";
37    }
38    elseif(isset($_POST["dbname"]))
39	$_SESSION["SETUP"]["dbname"] = $_POST["dbname"];
40
41    /* rooturl */
42    if (!isset($_POST["rooturl"]) or $_POST["rooturl"]=="") {
43	$miscerrorarray[] = Lang::getLanguageString("err_rooturl");
44	$_SESSION["SETUP"]["rooturl"] = ((isset($_SERVER['HTTPS'])) ? "https://" : "http://").$_SERVER["HTTP_HOST"].str_replace(SETUP_DIR,"",dirname($_SERVER["PHP_SELF"]));
45    }
46    elseif(isset($_POST["rooturl"]))
47	$_SESSION["SETUP"]["rooturl"] = $_POST["rooturl"];
48    if ($_SESSION["SETUP"]["rooturl"][strlen($_SESSION["SETUP"]["rooturl"])-1]!="/") $_SESSION["SETUP"]["rooturl"] .= "/";
49
50    /* url check */
51    if (isset($_POST["skipurlcheck"]))
52	$_SESSION["SETUP"]["skipurlcheck"] = 1;
53    else
54	$_SESSION["SETUP"]["skipurlcheck"] = 0;
55
56    /* dynamic url */
57    if (isset($_POST["dynamicurl"])) {
58	$_SESSION["SETUP"]["dynamicurl"] = 1;
59	$_SESSION["SETUP"]["skipurlcheck"] = 1;
60    }
61    else
62	$_SESSION["SETUP"]["dynamicurl"] = 0;
63
64    /* dynamic url */
65    if (isset($_POST["forcessl"])) {
66	$_SESSION["SETUP"]["forcessl"] = 1;
67    }
68    else
69	$_SESSION["SETUP"]["forcessl"] = 0;
70
71    /* rootpath */
72    if(ini_get('magic_quotes_gpc') && isset($_POST["rootpath"])) $_POST["rootpath"] = stripslashes($_POST["rootpath"]);
73    if (!isset($_POST["rootpath"]) or $_POST["rootpath"]=="" or !is_dir($_POST["rootpath"])) {
74	$miscerrorarray[] = Lang::getLanguageString("err_rootpath");
75	$_SESSION["SETUP"]["rootpath"] = ROOTPATH;
76    }
77    elseif(isset($_POST["rootpath"]))
78	$_SESSION["SETUP"]["rootpath"] = $_POST["rootpath"];
79
80    /* session name */
81    if (!isset($_POST["sessionname"]) or $_POST["sessionname"]=="") {
82	$miscerrorarray[] = Lang::getLanguageString("err_sessname");
83	$_SESSION["SETUP"]["sessionname"] = "MGWSESSION";
84    }
85    elseif(isset($_POST["sessionname"]))
86	$_SESSION["SETUP"]["sessionname"] = $_POST["sessionname"];
87
88    /* use db sessions */
89    if (isset($_POST["usedbsessions"])) {
90	$_SESSION["SETUP"]["usedbsessions"] = true;
91    }
92    else
93	$_SESSION["SETUP"]["usedbsessions"] = false;
94
95    /* auth method */
96    $_SESSION["SETUP"]["use_ntlm_auth"] = false;
97    if (!isset($_POST["auth_method"]) or $_POST["auth_method"]=="")
98	$_SESSION["SETUP"]["auth_method"] = "sql";
99    elseif (isset($_POST["auth_method"]) and $_POST["auth_method"]=="ntlm") {
100	$_SESSION["SETUP"]["auth_method"] = "ntlm";
101	$_SESSION["SETUP"]["use_ntlm_auth"] = true;
102    }
103    elseif (isset($_POST["auth_method"]) and $_POST["auth_method"]=="ldap") {
104	$_SESSION["SETUP"]["auth_method"] = "ldap";
105	unset($_POST["encrypt_pwd"]);
106    }
107    elseif(isset($_POST["auth_method"]))
108	$_SESSION["SETUP"]["auth_method"] = $_POST["auth_method"];
109
110    /* encrypt_pwd */
111    if (isset($_POST["encrypt_pwd"]))
112	$_SESSION["SETUP"]["encrypt_pwd"] = 1;
113    else
114	$_SESSION["SETUP"]["encrypt_pwd"] = 0;
115
116    // admin password
117    if (!isset($_POST["adminpw1"]) || $_POST["adminpw1"]=="" ||
118	!isset($_POST["adminpw2"]) || $_POST["adminpw2"]==""){
119	$miscerrorarray[] = Lang::getLanguageString("err_adminpass");
120    }
121    elseif($_POST["adminpw1"] != $_POST["adminpw2"])
122	$miscerrorarray[] = Lang::getLanguageString("err_adminpass");
123    else
124	$_SESSION["SETUP"]["adminpw"] = $_POST["adminpw1"];
125}
126
127// create ADOdb instance
128$conn = ADONewConnection($_SESSION["SETUP"]["dbtype"]);
129
130/* attempt to create db if prompted */
131if (isset($_POST["trytocreatedb"])) {
132    // try to connect with create user
133    @$conn->Connect($_SESSION["SETUP"]["dbhost"], $_POST["cdbuser"], $_POST["cdbpass"]);
134    if($conn->MetaError() == DB_ERROR_ACCESS_VIOLATION){
135	  $dberrorarray[] = Lang::getLanguageString("err_condb_cuser");
136    } elseif($conn->MetaError() == DB_ERROR){
137	  $dberrorarray[] = Lang::getLanguageString("err_db");
138    } else{
139	  $dict = NewDataDictionary($conn);
140	  @$dict->ExecuteSQLArray($dict->CreateDatabase($_SESSION["SETUP"]['dbname']));
141	  if ($conn->MetaError() == DB_ERROR_CANNOT_CREATE){
142	    $dberrorarray[] = Lang::getLanguageString("err_create_db");
143	  } elseif($conn->MetaError() == DB_ERROR_ALREADY_EXISTS){
144	    $dberrorarray[] = Lang::getLanguageString("err_create_exists");
145	  } elseif($conn->MetaError() == DB_ERROR){
146	    $dberrorarray[] = Lang::getLanguageString("err_db");
147	  } elseif ($conn->MetaError()!=0) {
148	    $dberrorarray[] = $conn->MetaError()." ".$conn->MetaErrorMsg($conn->MetaError());
149	  }
150    }
151}
152
153/* test db connection with normal user */
154@$conn->Connect($_SESSION["SETUP"]["dbhost"], $_SESSION["SETUP"]["dbuser"], $_SESSION["SETUP"]["dbpass"], $_SESSION["SETUP"]["dbname"]);
155if($conn->MetaError() == DB_ERROR_CONNECT_FAILED){
156    $dberrorarray[] = Lang::getLanguageString("err_dbconn");
157}
158elseif($conn->MetaError() == DB_ERROR_ACCESS_VIOLATION){
159    $dberrorarray[] = Lang::getLanguageString("err_condb_user");
160}
161elseif ($conn->MetaError() == DB_ERROR_NOSUCHDB) {
162    $dberrorarray[] = Lang::getLanguageString("err_condb_name");
163}
164elseif($conn->MetaError() == DB_ERROR){
165    $dberrorarray[] = Lang::getLanguageString("err_db");
166}
167else {
168    /* check if the actual database user has create rights (drop rights) */
169    $dict = NewDataDictionary($conn);
170    //  delete_me_please (testfield int
171    $dict->ExecuteSQLArray($dict->CreateTableSQL('delete_me_please','testfield I'));
172    if ($conn->MetaError() == DB_ERROR_CANNOT_CREATE){
173	$dberrorarray[] = Lang::getLanguageString("err_createtable");
174    }
175    elseif($conn->MetaError() == DB_ERROR){
176	$dberrorarray[] = Lang::getLanguageString("err_db");
177    }
178    else {
179 	$dict->ExecuteSQLArray($dict->DropTableSQL('delete_me_please'));
180 	if ($conn->MetaError() == DB_ERROR_CANNOT_DROP){
181 	    $dberrorarray[] = Lang::getLanguageString("err_droptable");
182 	}
183	elseif($conn->MetaError() == DB_ERROR){
184	    $dberrorarray[] = Lang::getLanguageString("err_db");
185	}
186    }
187}
188
189/* url check */
190if($_SESSION["SETUP"]["skipurlcheck"]!=1){
191
192	if(!function_exists('get_headers')) {
193		// function get_headers for php < 5
194	   /**
195	   * @return array
196	   * @param string $url
197	   * @param int $format (default 0)
198	   * @desc Fetches all the headers
199	   * @author cpurruc fh-landshut de, stuart at sixletterwords dot com, denilson at vialink dot com dot br, matthieu dot paineau at wanadoo dot fr
200	   */
201	   function get_headers($url,$format=0){
202	       $url_info=parse_url($url);
203		   if (!isset($url_info['path'])) {
204		       $url_info['path']="/";
205		   }
206
207		   if ($url_info['scheme']=="https"){
208		   		$prot =  "ssl://";
209				$port = 443;
210		   }
211		   else {
212		   		$prot = "";
213				$port = 80;
214		   }
215	       $fp=fsockopen($prot.$url_info['host'], $port, $errno, $errstr, 30);
216	       if($fp) {
217	                        if (isset($url_info['query'])) {
218	                            $query = "?".$url_info['query'];
219	                        }
220	                        else $query="";
221	           $head = "GET ".$url_info['path'].$query." HTTP/1.0\r\n".
222	                   "Host: ".$url_info['host']."\r\n".
223	                                   "\r\n";
224
225	           fputs( $fp, $head );
226			   $end = "\r\n\r\n";
227			   $var = "";
228			   while (!feof($fp))
229	           {
230	               $var.=fgets($fp, 1280);
231	               if(strpos($var,$end))
232	                   break;
233	           }
234	           fclose($fp);
235
236			   $var=preg_replace("/".$end.".*\$/",'',$var);
237	           $var=explode("\r\n",$var);
238
239	           $headers = array();
240	           if ($format==1) {
241			   		foreach($var as $i => $content){
242	                   	if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$content,$parts)){
243	                       $headers[$parts[1]]=$parts[2];
244						}
245						else{
246							$headers[$i]=$content;
247						}
248	               	}
249	           }
250			   else{
251			   		$headers=$var;
252			   }
253
254	           return $headers;
255	       }
256		   else {
257			 return false;
258		   }
259	   }
260   }//if function not exists
261
262	//new code for avoid need of curl extension:
263	$headers = get_headers($_SESSION["SETUP"]["rooturl"] . "index.php");
264	if ( !ereg(" 200 ",$headers[0])){ //$headers[0] contain HTTP response code
265		$miscerrorarray[] = Lang::getLanguageString("err_rooturl_wrong");
266	}
267
268    //======= old code here :
269    /* check if URL to moregroupware root is correct
270     * use the curl extension to do so if available
271
272    if(function_exists("curl_init")){
273		$ch = curl_init($_SESSION["SETUP"]["rooturl"] . "index.php");
274		curl_setopt ($ch, CURLOPT_NOBODY, 0);
275		ob_start();
276		curl_exec ($ch);
277		ob_end_clean();
278		$cret = curl_getinfo($ch);
279		curl_close ($ch);
280		if($cret["http_code"]!=200) $miscerrorarray[] = Lang::getLanguageString("err_rooturl_wrong");
281    } elseif((!stristr($_SESSION["SETUP"]["rooturl"],"https")) && (ini_get("allow_url_fopen")==1)){
282    	// do not use this check when using SSL (k-fish)
283     	// and do it only if fopen on URLs is allowed.
284		if(!@fopen($_SESSION["SETUP"]["rooturl"]."index.php", "r")) {
285		    $miscerrorarray[] = Lang::getLanguageString("err_rooturl_wrong");
286		}
287    }
288	*/
289	//======= end of old code.
290}
291
292/* check if rootpath to moregroupware is correct */
293if(isset($_POST["rootpath"]) and !file_exists($_POST["rootpath"] . "/index.php")) {
294    $miscerrorarray[] = Lang::getLanguageString("err_rootpath");
295}
296
297/* if no error occured unset the array */
298if (isset($miscerrorarray) and count($miscerrorarray)==0) unset($miscerrorarray);
299if (isset($dberrorarray) and count($dberrorarray)==0) unset($dberrorarray);
300
301/* all settings ok? */
302if (!isset($miscerrorarray) and !isset($dberrorarray)) $_SESSION["SETUP"]["settings_ok"] = true;
303?>
304