Index: trunk/admin/install.php
===================================================================
diff -u -r13 -r315
--- trunk/admin/install.php	(.../install.php)	(revision 13)
+++ trunk/admin/install.php	(.../install.php)	(revision 315)
@@ -3,22 +3,15 @@
 
 //$new_version = '1.0.2';
 
-define("GET_LICENSE_URL", "http://www.in-portal.net/licensing/license.php");
+define("GET_LICENSE_URL", "http://www.intechnic.com/myaccount/license.php");
 define('BACKUP_NAME', 'dump(.*).txt'); // how backup dump files are named
 $general_error = '';
 
-if ($_POST['install_type'] != '') {
-	$install_type = $_POST['install_type'];
-}
-else if ($_GET['install_type'] != '') {
-	$install_type = $_GET['install_type'];
-}
-
 $pathtoroot = "";
 if(!strlen($pathtoroot))
 {
-  //$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));PATH_TRANSLATED
-  $path=dirname(realpath($_SERVER['PATH_TRANSLATED']));
+  $path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
+  //$path=dirname(realpath($_SERVER['PATH_TRANSLATED']));
   if(strlen($path))
   {
     /* determine the OS type for path parsing */
@@ -67,6 +60,7 @@
     $pathtoroot = ".".$pathchar;
   }
 }
+
 $path_char = GetPathChar();
 //phpinfo(INFO_VARIABLES);
 
@@ -76,26 +70,32 @@
   $pathtoroot = $pathtoroot.$pathchar;
 }
 
+if( file_exists($pathtoroot.'debug.php') && !defined('DEBUG_MODE') ) include_once($pathtoroot.'debug.php');
+
 $is_install = TRUE;
 $admin = substr($path,strlen($pathtoroot));
-$state = $_GET["state"];
+$state = isset($_GET["state"]) ? $_GET["state"] : '';
 if(!strlen($state))
 {
-	$state = $_POST["state"];
+	$state = isset($_POST['state']) ? $_POST['state'] : '';
 }
 
-include("install/install_lib.php");
+include($pathtoroot.$admin."/install/install_lib.php");
+
+$install_type = GetVar('install_type', true);
+$force_finish = isset($_REQUEST['ff']) ? true : false;
+
 $ini_file = $pathtoroot."config.php";
 if(file_exists($ini_file))
 {
     $write_access = is_writable($ini_file);
-    $ini_vars = parse_ini_file($ini_file,TRUE);
+    $ini_vars = inst_parse_portal_ini($ini_file,TRUE);
 
     foreach($ini_vars as $secname => $section)
     {
       foreach($section as $key => $value)
       {
-          $key = "g_".$key;      
+          $key = "g_".str_replace('-', '', $key);      
           global $$key;
           $$key = $value;
       }
@@ -129,7 +129,17 @@
 $configs[3] = "in-portal:configure_categories";
 $mods[3] = "In-Portal";
 
-if(strlen($g_DBType)>0 && strlen($state)>0 && $state !="dbinfo" && $state !="db_config_save")
+// simulate rootURL variable: begin
+	$rootURL = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME']);
+	$tmp = explode('/', $rootURL);
+	if( $tmp[ count($tmp) - 1 ] == $admin) unset( $tmp[ count($tmp) - 1 ] );
+	$rootURL = implode('/', $tmp).'/';
+	unset($tmp);
+	//echo "RU: $rootURL<br>";
+// simulate rootURL variable: end
+
+$db_savings = Array('dbinfo', 'db_config_save', 'db_reconfig_save'); //, 'reinstall_process'
+if( isset($g_DBType) && $g_DBType && strlen($state)>0 && !in_array($state, $db_savings) )
 {
     require_once($pathtoroot."kernel/startup.php");
     $localURL=$rootURL."kernel/";
@@ -159,7 +169,7 @@
 }
 
 require_once($pathtoroot.$admin."/install/inst_ado.php");
-
+$helpURL = $rootURL.$admin.'/help/install_help.php?destform=popup&help_usage=install';
 ?>
 <html>
 <head>
@@ -183,10 +193,34 @@
 			function Continue() {
 				document.iform1.submit();
 			}
+			
+			function CreatePopup(window_name, url, width, height)
+			{
+				// creates a popup window & returns it
+				if(url == null && typeof(url) == 'undefined' ) url = '';
+				if(width == null && typeof(width) == 'undefined' ) width = 750;
+				if(height == null && typeof(height) == 'undefined' ) height = 400;
+				
+				
+				return window.open(url,window_name,'width='+width+',height='+height+',status=yes,resizable=yes,menubar=no,scrollbars=yes,toolbar=no');  	
+			}
+			
+			function ShowHelp(section)
+			{
+				var frm = document.getElementById('help_form');	
+				
+				frm.section.value = section;
+				frm.method = 'POST';
+				CreatePopup('HelpPopup','<?php echo $rootURL.$admin; ?>/help/blank.html'); // , null, 600);
+				frm.target = 'HelpPopup';
+				frm.submit();
+			}
+
 		</SCRIPT>        
 </head>
 
 <body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" style="height: 100%">
+<form name="help_form" id="help_form" action="<?php echo $helpURL; ?>" method="post"><input type="hidden" id="section" name="section" value=""></form>
 <form enctype="multipart/form-data" name="iform1" id="iform1" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
 <table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
 	<tr>
@@ -198,7 +232,7 @@
 					<td rowspan="3" width="100000" align="right">&nbsp;</td>
 					<td width="400"><img alt="" src="images/blocks.gif" width="400" height="73"></td>
 				</tr>
-				<tr><td align="right" background="images/version_bg.gif" class="head_version" valign="top"><img alt="" src="images/spacer.gif" width="1" height="14">In-Portal Version 1.0.0: English US</td></tr>
+				<tr><td align="right" background="images/version_bg.gif" class="head_version" valign="top"><img alt="" src="images/spacer.gif" width="1" height="14">In-Portal Version <?php echo GetMaxPortalVersion($pathtoroot.$admin)?>: English US</td></tr>
 				<tr><td><img alt="" src="images/blocks2.gif" width="400" height="2"><br></td></tr>
 				<tr><td bgcolor="black" colspan="4"><img alt="" src="images/spacer.gif" width="1" height="1"><br></td></tr>
 			</table>
@@ -211,13 +245,11 @@
 if(!strlen($state))
     $state = @$_POST["state"];
 //echo $state;
+
 if(strlen($state)==0)
 {
     $ado = inst_GetADODBConnection();
-    if($ado)
-    {
-        $installed = TableExists($ado,"ConfigurationAdmin,Category,Permissions");
-    }
+    $installed = $ado ? TableExists($ado,"ConfigurationAdmin,Category,Permissions") : false;
     
     if(!minimum_php_version("4.1.2"))
     {    
@@ -271,16 +303,19 @@
     }    
     
     if($installed)
-    { 
-        $state="reinstall";
+    {     	
+    	$state="reinstall";
     }
     else {
       $state="dbinfo";
     }
 
 }
+
 if($state=="reinstall_process")
 {
+	$login_err_mesg = ''; // always init vars before use
+	if( !isset($g_License) ) $g_License = '';
 	$lic = base64_decode($g_License);
     if(strlen($lic))
     {
@@ -305,8 +340,13 @@
       }
       else
       {
-		$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['UserName'])."&password=".md5($_POST['UserPass'])."&domain=".$_SERVER['SERVER_NAME'], "r");
+      	$act = '';
+      	if (ConvertVersion($g_InPortal) >= ConvertVersion("1.0.5")) {
+      		$act = 'check';
+      	}
+		$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['UserName'])."&password=".md5($_POST['UserPass'])."&action=$act&license_code=".base64_encode($g_LicenseCode)."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_SERVER['SERVER_NAME']), "r");
 		if (!$rfile) {
+			$login_err_mesg = "Unable to connect to the Intechnic server!";
 			$LoggedIn = false;		
 		}
 		else {
@@ -318,6 +358,7 @@
 			@fclose($rfile);
 			
 			if (substr($rcontents, 0, 5) == 'Error') {
+				$login_err_mesg = substr($rcontents, 6);
 				$LoggedIn = false;				
 			}
 			else {
@@ -380,70 +421,83 @@
       else
       {      
          $state="reinstall";
-         $login_error = "Invalid Username or Password - Try Again";
+         $login_error = $login_err_mesg;//"Invalid Username or Password - Try Again";
       }
 }
 
 if ($state == "upgrade") {
     $ado = inst_GetADODBConnection();
     
     $Modules = array();
-    $Texts = array();
-
-	$sql = "SELECT Name, Version FROM ".$g_TablePrefix."Modules";
-	$rs = $ado->Execute($sql);
-	
-	while ($rs && !$rs->EOF) {
-		$p = strtolower($rs->fields['Name']);
-//		$modules .= strtolower($rs->fields['Name']).',';
-//		$rs->MoveNext();
-//	}
-	
-//	$mod_arr = explode(",", substr($modules, 0, strlen($modules) - 1));
-	
-//    foreach($mod_arr as $p)
-//    {        
-    	if ($p == 'in-portal') {
-    		$p = '';
-    	}    
-    	
-    	$dir_name = $pathtoroot.$p."/admin/install/upgrades/";
-    	$dir = @dir($dir_name);    	
-    	//echo "<pre>"; print_r($dir); echo "</pre>";
-    	
-    	while ($file = $dir->read()) {
-	        if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
-	        { 
-	        	$file = str_replace("inportal_upgrade_v", "", $file);
-	        	$file = str_replace(".sql", "", $file);
-	        	
-	        	if ($file != '') {
-	        		$sql = "SELECT count(*) AS count FROM ".$g_TablePrefix."Modules WHERE Name = '".$rs->fields['Name']."' AND Version = '$file'";
-	        		$rs1 = $ado->Execute($sql);
-	        		
-	        		if ($rs1->fields['count'] == 0) {
-//	        			$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '".$p."'";
-//	        			$rs2 = $ado->Execute($sql);
-						$Texts[] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
-	        			$Modules[] = $rs->fields['Name'];
-	        		}
-	        	}
-	        }
-    	}
-    	$rs->MoveNext();    	
+    $Texts = array();    
+    
+    if (str_replace('.', '', GetMaxPortalVersion($pathtoroot.$admin)) >= 105 && ($g_LicenseCode == '' && $g_License != '')) {	
+    	$state = 'reinstall';
+    	$inst_error = "Your license must be updated before you can upgrade. Please don't use 'Existing License' option, instead either Download from Intechnic or Upload a new license file!";
     }
-    	
-	$include_file = "install/upgrade.php";
+    else {
+		$sql = "SELECT Name, Version FROM ".$g_TablePrefix."Modules";
+		
+		$rs = $ado->Execute($sql);
+		
+		$i = 0;		
+		while ($rs && !$rs->EOF) {
+			$p = strtolower($rs->fields['Name']);        
+	    
+	    	if ($p == 'in-portal') {
+	    		$p = '';
+	    	}    
+	    	
+	    	$dir_name = $pathtoroot.$p."/admin/install/upgrades/";
+	    	
+	    	$dir = @dir($dir_name);    	
+	    	
+	    	while ($file = $dir->read()) {
+		        if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
+		        { 		        	
+		        	if (strstr($file, 'inportal_upgrade_v')) {
+			        	$file = str_replace("inportal_upgrade_v", "", $file);
+			        	$file = str_replace(".sql", "", $file);		        		
+			        	
+		        		$sql = "SELECT count(*) AS count FROM ".$g_TablePrefix."Modules WHERE Name = '".$rs->fields['Name']."' AND Version = '$file'";
+		        		$rs1 = $ado->Execute($sql);
+		        		
+		        		if ($rs1->fields['count'] == 0 && ConvertVersion($file) > ConvertVersion($rs->fields['Version'])) {
+		        			if ($Modules[$i-1] == $rs->fields['Name']) {
+								$Texts[$i-1] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
+		        				$i--;
+		        			}
+		        			else {
+		        				$Texts[$i] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
+		        				$Modules[$i] = $rs->fields['Name'];
+		        			}
+		        			
+		        			$i++;
+		        		}	        		
+		        	}
+		        }	        
+	    	}
+	    	
+	    	$rs->MoveNext();    	
+	    }
+	    	
+		$include_file = $pathtoroot.$admin."/install/upgrade.php";
+	}
 }
 
 if ($state == "upgrade_process") {
-	
+    $ado = inst_GetADODBConnection();	
 	$mod_arr = $_POST['modules'];
-		
+
     foreach($mod_arr as $p)
     {
         $mod_name = strtolower($p);
         
+		$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '$p'";
+		$rs = $ado->Execute($sql);	
+
+		$current_version = $rs->fields['Version'];
+        
     	if ($mod_name == 'in-portal') {
     		$mod_name = '';
     	}
@@ -455,49 +509,46 @@
     	$tmp1 = 0;
     	$tmp2 = 0;
     	while ($file = $dir->read()) {
-	        if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
-	        { 
-	        	$file = str_replace("inportal_upgrade_v", "", $file);
-	        	$file = str_replace(".sql", "", $file);
-	        	
-	        	if ($file != '') {
-	        		$tmp1 = str_replace(".", "", $file);	        		
+				if ($file != "." && $file != ".." && !is_dir($dir_name.$file)) { 	        	
+	        	if (strstr($file, 'inportal_upgrade_v')) {
+		        	$file_tmp = str_replace("inportal_upgrade_v", "", $file);
+		        	$file_tmp = str_replace(".sql", "", $file);	        		
+		        	
+	        		if (ConvertVersion($file_tmp) > ConvertVersion($current_version)) {
+    					$filename = $pathtoroot.$mod_name."/admin/install/upgrades/$file";
+			        	//echo "Trying Version: $try_version<br>";
+			        	if(file_exists($filename))
+			       		{
+			    			RunSQLFile($ado, $filename);
+				      		set_ini_value("Module Versions", $p, $try_version);
+				      		save_values();
+			    		}	        		
+	        		
+/*	        		$tmp1 = str_replace(".", "", $file);	        		
 	        		if ($tmp1 > $tmp2) {
 	        			$new_version = $file;
-	        		}
+	        		}*/
 	        	}
 	        }
-	        $tmp2 = $tmp1;
+	        //$tmp2 = $tmp1;
+				}
     	}
-	        		    		
-    	
-    	$version_nrs = explode(".", $new_version);
-    	
-    	for ($i = 0; $i < $version_nrs[0] + 1; $i++) {
-    		for ($j = 0; $j < $version_nrs[1] + 1; $j++) {
-    			for ($k = 0; $k < $version_nrs[2] + 1; $k++) {
-    				$try_version = "$i.$j.$k";
-    				
-			    	$filename = $pathtoroot.$mod_name."/admin/install/upgrades/inportal_upgrade_v$try_version.sql";
-			        
-			        if(file_exists($filename))
-			       	{
-			    		RunSQLFile($ado, $filename);
-				      	set_ini_value("Module Versions", $p, $try_version);
-				      	save_values();
-			    	}
-    			}
-    		}
-    	}
     }
-	
-	$state = "finish";
-	$include_file = "install/install_finish.php";
+    
+	$state = 'languagepack_upgrade';    
+}	
+
+// upgrade language pack
+if($state=='languagepack_upgrade')
+{
+	$state = 'lang_install_init';
+	$_POST['lang'][] = 'english.lang';
+	$force_finish = true;
 }
 
 if($state=="db_reconfig_save")
 {
-    $ini_vars = parse_ini_file($ini_file,TRUE);
+    $ini_vars = inst_parse_portal_ini($ini_file,TRUE);
 
     foreach($ini_vars as $secname => $section)
     {
@@ -509,40 +560,13 @@
       }
     }
     unset($ado);
-    $ado = inst_GetADODBConnection();
-    if($ado->ErrorNo()!=0)
-    {
-        $db_error = "Connection Error: (".$ado->ErrorNo().") ".$ado->ErrorMsg();
-        $state = "db_reconfig";
-
-    }
-    else
-    {
-        if(!TableExists($ado,"ConfigurationAdmin,Category,Permissions"))
-        {
-            $state="db_reconfig";
-            $db_error = "An In-Portal Database was not found at this location";
-        }
-        else {
-		    set_ini_value("Database", "DBType",$_POST["ServerType"]);
-		    set_ini_value("Database", "DBHost",$_POST["ServerHost"]);
-		    set_ini_value("Database", "DBName",$_POST["ServerDB"]);
-		    set_ini_value("Database", "DBUser",$_POST["ServerUser"]);
-		    set_ini_value("Database", "DBUserPassword",$_POST["ServerPass"]);
-		    set_ini_value("Database","TablePrefix",$_POST["TablePrefix"]);           
-		
-		    save_values();        	
-		    
-            $state = "finish";
-            $include_file = "install/install_finish.php";
-        }
-    }
+	$ado = VerifyDB('db_reconfig', 'finish', 'SaveDBConfig', true);
 }
 
 
 if($state=="db_reconfig")
 {
-  $include_file = "install/db_reconfig.php";	
+  $include_file = $pathtoroot.$admin."/install/db_reconfig.php";	
 }
 
 if($state=="restore_file")
@@ -571,7 +595,7 @@
 	           $tmp_vers = $file_tmp_cont[0];
 	
 	           $vers_arr = explode(";", $tmp_vers);           
-	           $ini_values = parse_ini_file($ini_file);
+	           $ini_values = inst_parse_portal_ini($ini_file);
 	        
 	           foreach ($ini_values as $key => $value) {
 	           		foreach ($vers_arr as $k) {
@@ -592,16 +616,16 @@
            }
            else {
            		$state = "warning";
-           		$include_file = "install/warning.php";
+           		$include_file = $pathtoroot.$admin."/install/warning.php";
            }
 		}
 		else {
 			if ($_POST['backupdate'] != '') {
-				$include_file = "install/restore_select.php";
+				$include_file = $pathtoroot.$admin."/install/restore_select.php";
 		  		$restore_error = "$backupfile not found or could not be read";		
 			}
 			else {
-				$include_file = "install/restore_select.php";
+				$include_file = $pathtoroot.$admin."/install/restore_select.php";
 		  		$restore_error = "No backup selected!!!";	
 			}					
 		}
@@ -612,7 +636,7 @@
 if($state=="restore_select")
 {
 	if( isset($_POST['backupdir']) ) $filepath = stripslashes($_POST['backupdir']);
-	$include_file = "install/restore_select.php";	
+	$include_file = $pathtoroot.$admin."/install/restore_select.php";	
 }
 
 if($state=="restore_run")
@@ -622,7 +646,7 @@
   if(!strlen($backupfile))
     $backupfile = SuperStrip($_GET['File'], true);
       	
-  $include_file = "install/restore_run.php";	
+  $include_file = $pathtoroot.$admin."/install/restore_run.php";	
 }
 
 if($state=="db_config_save")
@@ -635,7 +659,7 @@
     set_ini_value("Database","TablePrefix",$_POST["TablePrefix"]);           
 
     save_values();
-    $ini_vars = parse_ini_file($ini_file,TRUE);
+    $ini_vars = inst_parse_portal_ini($ini_file,TRUE);
 
     foreach($ini_vars as $secname => $section)
     {
@@ -647,43 +671,31 @@
       }
     }
     unset($ado);
-    $ado = inst_GetADODBConnection();
-    if($ado->ErrorNo()!=0)
-    {
-        $db_error = "Connection Error: (".$ado->ErrorNo().") ".$ado->ErrorMsg();
-        $state = "dbinfo";
-
-    }
-    else
-    {
-        if(TableExists($ado,"ConfigurationAdmin,Category,Permissions"))
-        {
-            $state="dbinfo";
-            $db_error = "An In-Portal Database already exists at this location";
-        }
-        else
-            $state = "license";
-    }
+    $ado = VerifyDB('dbinfo', 'license');
 }
 
 if($state=="dbinfo")
 {
   	if ($install_type == '') {
   		$install_type = 1;
   	}
-	$include_file = "install/dbinfo.php";
+	$include_file = $pathtoroot.$admin."/install/dbinfo.php";
 }
 
 if ($state == "download_license") {
 	$ValidLicense = FALSE;
-	if ($_POST['login'] != '' && $_POST['password'] != '') {
+	
+	$lic_login = isset($_POST['login']) ? $_POST['login'] : '';
+	$lic_password = isset($_POST['password']) ? $_POST['password'] : '';
+	
+	if ($lic_login != '' && $lic_password != '') {
 		// Here we determine weather login is ok & check available licenses
 		
-		$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['login'])."&password=".md5($_POST['password'])."&domain=".$_SERVER['SERVER_NAME'], "r");
+		$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['login'])."&password=".md5($_POST['password'])."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_SERVER['SERVER_NAME']), "r");
 		if (!$rfile) {
 			$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
 			$state = "get_license";
-			$include_file = "install/get_license.php";			
+			$include_file = $pathtoroot.$admin."/install/get_license.php";			
 		}
 		else {
 			$rcontents = '';
@@ -696,22 +708,25 @@
 			if (substr($rcontents, 0, 5) == 'Error') {
 				$get_license_error = substr($rcontents, 6);
 				$state = "get_license";
-				$include_file = "install/get_license.php";					
+				$include_file = $pathtoroot.$admin."/install/get_license.php";					
 			}
 			else {
 				if (substr($rcontents, 0, 3) == "SEL") {
 					$state = "download_license";
 					$license_select = substr($rcontents, 4);
-					$include_file = "install/download_license.php";
+					$include_file = $pathtoroot.$admin."/install/download_license.php";
 				}
 				else {
 					// Here we get one license
-		            $data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $rcontents));
+					$tmp_data = explode('Code==:', $rcontents);
+				
+	            	$data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $tmp_data[0]));				
 					inst_ParseLicense($data);
 		            $ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
 		            if($ValidLicense)
 		            {
 		                set_ini_value("Intechnic","License",base64_encode($data));
+	                	set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);		                
 		                save_values();
 		                $state="domain_select";
 		                $got_license = 1;
@@ -731,15 +746,21 @@
 	else if ($_POST['licenses'] == '') {
 		$state = "get_license";
 		$get_license_error = "Username and / or password not specified!!!";
-		$include_file = "install/get_license.php";
+		$include_file = $pathtoroot.$admin."/install/get_license.php";
 	}
 	else {
 		// Here we download license
-		$rfile = @fopen(GET_LICENSE_URL."?license_id=".md5($_POST['licenses'])."&dlog=".md5($_POST['dlog'])."&dpass=".md5($_POST['dpass'])."&domain=".$_POST['domain'], "r");
+		echo "LICENSE_ID: ".md5($_POST['licenses'])."<br>";
+		echo "DLOG: ".md5($_POST['dlog'])."<br>";
+		echo "DPASS: ".md5($_POST['dpass'])."<br>";
+		echo "VERSION: ".GetMaxPortalVersion($pathtoroot.$admin)."<br>";
+		echo "DOMAIN: ".base64_encode($_POST['domain'])."<br>";
+		
+		$rfile = @fopen(GET_LICENSE_URL."?license_id=".md5($_POST['licenses'])."&dlog=".md5($_POST['dlog'])."&dpass=".md5($_POST['dpass'])."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_POST['domain']), "r");
 		if (!$rfile) {
 			$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
 			$state = "get_license";
-			$include_file = "install/get_license.php";			
+			$include_file = $pathtoroot.$admin."/install/get_license.php";			
 		}
 		else {
 			$rcontents = '';
@@ -752,15 +773,19 @@
 			if (substr($rcontents, 0, 5) == 'Error') {
 				$download_license_error = substr($rcontents, 6);
 				$state = "download_license";
-				$include_file = "install/download_license.php";					
+				$include_file = $pathtoroot.$admin."/install/download_license.php";					
 			}
 			else {
-	            $data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $rcontents));				
+				$tmp_data = explode('Code==:', $rcontents);
+							
+	            $data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $tmp_data[0]));				
 	            inst_ParseLicense($data);
 	            $ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
 	            if($ValidLicense)
 	            {
 	                set_ini_value("Intechnic","License",base64_encode($data));
+	                // old licensing script doen't return 2nd parameter (licanse code)
+	                if( isset($tmp_data[1]) ) set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
 	                save_values();
 	                $state="domain_select";
 	            }
@@ -778,11 +803,12 @@
 
 if($state=="license_process")
 {
-    $ValidLicense = FALSE;
-    switch($_POST["lic_opt"])
+    $ValidLicense = FALSE;    
+    $tmp_lic_opt = GetVar('lic_opt', true);
+    switch($tmp_lic_opt)
     {
     case 1: /* download from intechnic */
-        $include_file = "install/get_license.php";
+        $include_file = $pathtoroot.$admin."/install/get_license.php";
         $state = "get_license";
     	//if(!$ValidLicense)
         //{
@@ -800,13 +826,17 @@
                 $lic = fread($fp,filesize($pathtoroot."themes/tmp.lic"));
                 fclose($fp);
             }      
-            $data = inst_LoadLicense(FALSE,$pathtoroot."themes/tmp.lic");
+            
+            $tmp_data = inst_LoadLicense(FALSE,$pathtoroot."themes/tmp.lic");            
+            $data = $tmp_data[0];
+            
             @unlink($pathtoroot."themes/tmp.lic");
             inst_ParseLicense($data);
             $ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
             if($ValidLicense)
             {
                 set_ini_value("Intechnic","License",base64_encode($data));
+                set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
                 save_values();
                 $state="domain_select";
             }
@@ -845,6 +875,9 @@
         }
     break;
     case 4:
+       //set_ini_value("Intechnic","License",base64_encode("local"));
+       //set_ini_value("Intechnic","LicenseCode",base64_encode("local"));
+       //save_values();    
        $state="domain_select";
     break;
     }
@@ -854,7 +887,7 @@
 
 if($state=="license")
 {
-    $include_file = "install/sel_license.php";    
+    $include_file = $pathtoroot.$admin."/install/sel_license.php";    
 
 }
 
@@ -882,35 +915,36 @@
     	}    
     	
     	$dir_name = $pathtoroot.$p."/admin/install/upgrades/";
+    	
     	$dir = @dir($dir_name);    	
     	//echo "<pre>"; print_r($dir); echo "</pre>";
     	
     	while ($file = $dir->read()) {
 	        if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
 	        { 
-	        	$file = str_replace("inportal_upgrade_v", "", $file);
-	        	$file = str_replace(".sql", "", $file);
 	        	
-	        	if ($file != '') {
+	        	if (strstr($file, 'inportal_upgrade_v')) {
+		        	$file = str_replace("inportal_upgrade_v", "", $file);
+		        	$file = str_replace(".sql", "", $file);	        		
 	        		if ($p == '') {
 	        			$p = 'in-portal';
 	        		}
 	        		$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '".$p."'";
 	        		$rs = $ado->Execute($sql);
 	        		
-	        		if (str_replace(".", "", $rs->fields['Version']) < str_replace(".", "", $file)) {
+	        		if (ConvertVersion($rs->fields['Version']) < ConvertVersion($file)) {
 	        			$show_upgrade = true;
 	        		}
 	        	}
 	        }
     	}    	
     }
-    	
-    if ($install_type == '') {
+  
+    if ( !isset($install_type) || $install_type == '') {
     	$install_type = 2;
     }    
     
-	$include_file = "install/reinstall.php";
+	$include_file = $pathtoroot.$admin."/install/reinstall.php";
 }
 
 if($state=="login")
@@ -942,12 +976,12 @@
 
 if($state=="getuser")
 {
-        $include_file = "install/login.php";
+        $include_file = $pathtoroot.$admin."/install/login.php";
 }
 
 if($state=="set_domain")
 {
-    if(!is_array($i_Keys))
+    if( !is_array($i_Keys) || !count($i_Keys) )
     {
         $lic = base64_decode($g_License);
         if(strlen($lic))
@@ -956,20 +990,34 @@
            $ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));            
         }
     }
+    
     if($_POST["domain"]==1)
     {
         $domain = $_SERVER['HTTP_HOST'];
-        set_ini_value("Intechnic","Domain",$domain);
-        save_values();
-        $state="runsql";
+        
+        if (strstr($domain, $i_Keys[0]['domain']) || inst_IsLocalSite($domain)) {
+        	set_ini_value("Intechnic","Domain",$domain);
+        	save_values();
+        	$state="runsql";
+        }
+        else {
+        	$DomainError = 'Domain name selected does not match domain name in the license!';
+        	$state = "domain_select";
+        }        	
     }
     else
     {
         $domain = str_replace(" ", "", $_POST["other"]);
         if ($domain != '') {
-        	set_ini_value("Intechnic","Domain",$domain);
-        	save_values();
-        	$state="runsql";
+        	if (strstr($domain, $i_Keys[0]['domain']) || inst_IsLocalSite($domain)) {
+        		set_ini_value("Intechnic","Domain",$domain);
+        		save_values();
+        		$state="runsql";
+        	}
+	        else {
+	        	$DomainError = 'Domain name entered does not match domain name in the license!';
+	        	$state = "domain_select";
+	        }         	
         }
         else {
         	$DomainError = 'Please enter valid domain!';
@@ -990,7 +1038,7 @@
         }
     }
   
-    $include_file = "install/domain.php";
+    $include_file = $pathtoroot.$admin."/install/domain.php";
 }
 
 
@@ -1064,13 +1112,13 @@
        	$state="RootPass";
   }
   else {
-  	  $include_file = "install/install_finish.php";
+  	  $include_file = $pathtoroot.$admin."/install/install_finish.php";
       $state="finish";
   }
 }
 
 if ($state == "finish") {
-	$include_file = "install/install_finish.php";
+	$include_file = $pathtoroot.$admin."/install/install_finish.php";
 }
 
 if($state=="RootSetPass")
@@ -1098,7 +1146,7 @@
 
 if($state=="RootPass")
 {
-    $include_file = "install/rootpass.php";
+    $include_file = $pathtoroot.$admin."/install/rootpass.php";
 }
 
 if($state=="lang_install_init")
@@ -1153,13 +1201,14 @@
 			 		if(is_object($l))
 			 		{
 			 			$LangId = $l->Get("LanguageId");
+			 			$NewLang = false;
 			 		}
 			 		else
 			 		{
 			 			$l = new clsLanguage();
 			 			$l->Set("Enabled",1);
 			 			$l->Create();
-			 			$NewLang = TRUE;
+			 			$NewLang = true;
 			 			$LangId = $l->Get("LanguageId");
 			 		}
 					foreach($LangRoot->children as $tag)
@@ -1169,10 +1218,12 @@
 	  					case "PHRASES":
 	  	  					foreach($tag->children as $PhraseTag)
 	  	  					{	  		
-	  							$Phrase = $PhraseTag->attributes["LABEL"];
-	  							$Translation = base64_decode($PhraseTag->contents);
+	  							$Phrase = $ado->qstr($PhraseTag->attributes["LABEL"]);
+  								$Translation = $ado->qstr(base64_decode($PhraseTag->contents));
+  								
 	  							$PhraseType = $PhraseTag->attributes["TYPE"];  	
-	  							$psql = "INSERT INTO $PhraseTable (Phrase,Translation,PhraseType,LanguageId) VALUES ('$Phrase','$Translation',$PhraseType,$LangId)";
+	  							$psql = "INSERT INTO $PhraseTable (Phrase,Translation,PhraseType,LanguageId) VALUES ($Phrase,$Translation,$PhraseType,$LangId)";
+	  							
 	  							$ado->Execute($psql);
 	  								//echo "$psql <br>\n";  	  						
 	  	  					}
@@ -1248,55 +1299,64 @@
   
   if($Status==0)
   { 
-    	$Offset = $objLanguages->ReadImportTable($PhraseTable, 1,"0,1,2",TRUE,200,$Offset);
+    	$Offset = $objLanguages->ReadImportTable($PhraseTable, 1,"0,1,2", $force_finish ? false : true, 200,$Offset);
   		if($Offset>=$Total)
   		{    	
     		$Offset=0;
     		$Status=1;        			
     	}
     	
-    	if ($_POST['next_step']) {
-    		$next_step = $_POST['next_step'];
-    	}
-    	else if ($_GET['next_step']) {
-    		$next_step = $_GET['next_step'];
-    	}
+    	$next_step = GetVar('next_step', true);
     	
+		if($force_finish == true) $next_step = 3;
 		$NextUrl = $_SERVER['PHP_SELF']."?Offset=$Offset&Status=$Status&state=lang_install&next_step=$next_step&install_type=$install_type";
-		$include_file = "install/lang_run.php";
+		if($force_finish == true) $NextUrl .= '&ff=1';
+		$include_file = $pathtoroot.$admin."/install/lang_run.php";
   }
   else 
   {
   	  if(!is_object($objMessageList))
   	    $objMessageList = new clsEmailMessageList();
   	    
   	    
-  	  $Offset = $objMessageList->ReadImportTable($EventTable,TRUE,100,$Offset);
+  	  $Offset = $objMessageList->ReadImportTable($EventTable, $force_finish ? false : true,100,$Offset);
   	  
   	  if($Offset>$Total)
   	  {
-    	if ($_POST['next_step']) {
-    		$next_step = $_POST['next_step'];
-    	}
-    	else if ($_GET['next_step']) {
-    		$next_step = $_GET['next_step'];
-    	}  	  	
+    	$next_step = GetVar('next_step', true);
+    	  	
+    	if($force_finish == true) $next_step = 3;
   	  	$NextUrl = $_SERVER['PHP_SELF']."?Offset=$Offset&Status=$Status&State=lang_install&next_step=$next_step&install_type=$install_type";
-  	  	$include_file = "install/lang_run.php";
+  	  	if($force_finish == true) $NextUrl .= '&ff=1';
+  	  	$include_file = $pathtoroot.$admin."/install/lang_run.php";
   	  }
   	  else
-  	    $state="lang_default";
+  	  {
+  	    if( !$force_finish )
+  	    {
+  	    	$state = 'lang_default';
+  	    }
+  	    else
+  		{
+  	    	$_POST['next_step'] = 4;
+  	    	$state = 'finish';
+			$include_file = $pathtoroot.$admin."/install/install_finish.php";
+  		}
+  	  }
   }
 }
 
+
+
+
 if($state=="lang_default_set")
 {
 //	phpinfo(INFO_VARIABLES);
     $ado = inst_GetADODBConnection();
   	$PhraseTable = GetTablePrefix()."ImportPhrases";
   	$EventTable = GetTablePrefix()."ImportEvents";    
-	$ado->Execute("DROP TABLE $PhraseTable");
-	$ado->Execute("DROP TABLE $EventTable");
+	$ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
+	$ado->Execute("DROP TABLE IF EXISTS $EventTable");
     
 	$Id = $_POST["lang"];
 	
@@ -1314,7 +1374,7 @@
 	{
 		$Packs[$l->Get("LanguageId")] = $l->Get("PackName");
 	}
-	$include_file = "install/lang_default.php";	
+	$include_file = $pathtoroot.$admin."/install/lang_default.php";	
 }
 
 
@@ -1326,7 +1386,7 @@
     {
         $ado = inst_GetADODBConnection();
         require_once $pathtoroot.'kernel/include/tag-class.php';
-        if( !is_object($objTagList) ) $objTagList = new clsTagList();
+        if( !isset($objTagList) || !is_object($objTagList) ) $objTagList = new clsTagList();
         foreach($doms as $p)
         {
             $filename = $pathtoroot.$p."/admin/install.php";
@@ -1338,7 +1398,7 @@
         
     }
     
-    $sql = "SELECT Name FROM ".GetTablePrefix()."Modules";
+/*    $sql = "SELECT Name FROM ".GetTablePrefix()."Modules";
     $rs = $ado->Execute($sql);
     
     while($rs && !$rs->EOF)
@@ -1362,7 +1422,7 @@
 	        	$file = str_replace("inportal_upgrade_v", "", $file);
 	        	$file = str_replace(".sql", "", $file);
 	        	
-	        	if ($file != '') {
+	        	if ($file != '' && !strstr($file, 'changelog') && !strstr($file, 'readme')) {
 	        		$tmp1 = str_replace(".", "", $file);	        		
 	        		if ($tmp1 > $tmp2) {
 	        			$new_version = $file;
@@ -1394,14 +1454,14 @@
     	
     	$rs->MoveNext();
     }    
-    
+*/   
     $state="lang_select";
 }
 
 if($state=="lang_select")
 {
 	$Packs = GetLanguageList();
-	$include_file = "install/lang_select.php";
+	$include_file = $pathtoroot.$admin."/install/lang_select.php";
 }
 
 if($state=="modselect")
@@ -1426,8 +1486,10 @@
     $ado->Execute($sql);
     $sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$g_Domain' WHERE VariableName='Server_Name'";
     $ado->Execute($sql);
+    $sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '".$_SERVER['DOCUMENT_ROOT'].$sitepath."admin/backupdata' WHERE VariableName='Backup_Path'";
+    $ado->Execute($sql);
     $Modules = inst_GetModuleList();
-    $include_file = "install/modselect.php";
+    $include_file = $pathtoroot.$admin."/install/modselect.php";
 }
 
 if(substr($state,0,10)=="postconfig")
@@ -1436,12 +1498,21 @@
     $step = $p[1];
     
     if ($_POST['Site_Path'] != '') {
-		//echo "ok<br>";
-    	$rfile = @fopen(GET_LICENSE_URL."?url=".base64_encode($_SERVER['SERVER_NAME'].$_POST['Site_Path'])."&domain=".md5($_SERVER['SERVER_NAME']), "r");
+		$sql = "SELECT Name, Version FROM ".$g_TablePrefix."Modules"; 
+		$rs = $ado->Execute($sql);  
+		
+		$modules_str = '';  
+		while ($rs && !$rs->EOF) { 
+			$modules_str .= $rs->fields['Name'].' ('.$rs->fields['Version'].'),'; 
+			$rs->MoveNext(); 
+		} 
+
+		$modules_str = substr($modules_str, 0, strlen($modules_str) - 1);  
+		$rfile = @fopen(GET_LICENSE_URL."?url=".base64_encode($_SERVER['SERVER_NAME'].$_POST['Site_Path'])."&modules=".base64_encode($modules_str)."&license_code=".base64_encode($g_LicenseCode)."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".md5($_SERVER['SERVER_NAME']), "r");
 		if (!$rfile) {
-			$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
-			$state = "postconfig_1";
-			$include_file = "install/postconfig.php";			
+			//$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
+			//$state = "postconfig_1";
+			//$include_file = $pathtoroot.$admin."/install/postconfig.php";			
 		}
 		else {	
 			$rcontents = '';
@@ -1475,7 +1546,7 @@
         	
     if($step <= count($configs)+1)
     {
-         $include_file = "install/postconfig.php";
+         $include_file = $pathtoroot.$admin."/install/postconfig.php";
     }
     else
         $state = "theme_sel";       
@@ -1484,7 +1555,7 @@
 if($state=="theme_sel")
 {
     $objThemes->CreateMissingThemes();
-    $include_file = "install/theme_select.php";
+    $include_file = $pathtoroot.$admin."/install/theme_select.php";
 }
 
 if($state=="theme_set")
@@ -1506,14 +1577,18 @@
     $t->Set("PrimaryTheme",1);
     $t->Update();
     $t->VerifyTemplates();
-	$include_file = "install/install_finish.php";    
+	$include_file = $pathtoroot.$admin."/install/install_finish.php";    
     $state="finish";
 }
 
 if ($state == "adm_login") {
 	echo "<script>window.location='index.php';</script>";
 }
 
+// init variables
+$vars = Array('db_error','restore_error','PassError','DomainError','login_error','inst_error');
+foreach($vars as $var_name) ReSetVar($var_name);
+
 switch($state)
 {
 case "modselect":
@@ -1639,18 +1714,13 @@
 break;
 }
 
-if ($_POST['next_step']) {
-	$tmp_step = $_POST['next_step'];
-}
-else if ($_GET['next_step']) {
-	$tmp_step = $_GET['next_step'];
-}
+$tmp_step = GetVar('next_step', true);
 
 if (!$tmp_step) {
 	$tmp_step = 1;
 }
 
-if ($got_license == 1) {
+if ( isset($got_license) && $got_license == 1) {
 	$tmp_step++;
 }
 
@@ -1713,12 +1783,15 @@
 				    	<li>Integrity Check
 				    </ol>
 					</td>-->
-				    <?php if ($general_error == '') { ?>
+				    <?php 
+				    $lic_opt = isset($_POST['lic_opt']) ? $_POST['lic_opt'] : false;
+				    if ($general_error == '') { 
+				    ?>
 					    <?php if ($install_type == 1) { ?>
 							<ol class="install">
 					    		<li <?php if ($tmp_step == 1) { ?>class="current"<?php } ?>>Database Configuration
-					    		<li <?php if ($tmp_step == 2 || $_POST['lic_opt'] == 1) { ?>class="current"<?php } ?>>Select License
-					    		<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
+					    		<li <?php if ($tmp_step == 2 || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
+					    		<li <?php if ($tmp_step == 3 && $lic_opt != 1) { ?>class="current"<?php } ?>>Select Domain
 					    		<li <?php if ($tmp_step == 4 ) { ?>class="current"<?php } ?>>Set Root Password
 					    		<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
 					    		<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Install Language Packs
@@ -1751,7 +1824,7 @@
 					    <?php } else if ($install_type == 4) { ?>
 							<ol class="install">
 					    		<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
-					    		<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $_POST['lic_opt'] == 1) { ?>class="current"<?php } ?>>Select License
+					    		<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
 					    		<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
 					    		<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Set Root Password
 					    		<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
@@ -1762,8 +1835,8 @@
 					    <?php } else if ($install_type == 5) { ?>
 							<ol class="install">
 					    		<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
-					    		<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $_POST['lic_opt'] == 1) { ?>class="current"<?php } ?>>Select License
-					    		<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
+					    		<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
+					    		<li <?php if ($tmp_step == 3 && $lic_opt != 1) { ?>class="current"<?php } ?>>Select Domain
 					    		<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Finish
 					    	</ol>				    				    
 					    <?php } else if ($install_type == 6) { ?>
@@ -1782,7 +1855,8 @@
 							<ol class="install">
 					    		<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
 					    		<li <?php if ($tmp_step == 2 && $login_error == '' && $inst_error == '') { ?>class="current"<?php } ?>>Select Modules to Upgrade
-					    		<li <?php if ($tmp_step == 3) { ?>class="current"<?php } ?>>Finish
+					    		<li <?php if ($tmp_step == 3) { ?>class="current"<?php } ?>>Language Pack Upgrade
+					    		<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Finish
 					    	</ol>				    				    
 					    <?php } ?>						    			    
 						<?php include($include_file); ?>
@@ -1792,10 +1866,10 @@
 	            	<td width="40%" style="border-left: 1px solid #000; background: #f0f0f0">
 	            		<table width="100%" border="0" cellspacing="0" cellpadding="4">
 							    	<tr>
-							    	  <td class="subsectiontitle" style="border-bottom: 1px solid #000000; background-color:#999"><?php echo $title;?></td>
+							    	  <td class="subsectiontitle" style="border-bottom: 1px solid #000000; background-color:#999"><?php if( isset($title) ) echo $title;?></td>
 							    	</tr>
 							    	<tr>
-							    	  <td class="text"><?php echo $help;?></td>
+							    	  <td class="text"><?php if( isset($help) ) echo $help;?></td>
 							    	</tr>
 							    </table>
 	            	</td>