Index: trunk/admin/install.php
===================================================================
diff -u -r4237 -r7391
--- trunk/admin/install.php	(.../install.php)	(revision 4237)
+++ trunk/admin/install.php	(.../install.php)	(revision 7391)
@@ -1,81 +1,26 @@
 <?php
 
 error_reporting(E_ALL);
-ini_set('max_execution_time', 0);
+set_time_limit(0);
+ini_set('memory_limit', -1);
 
 define('BACKUP_NAME', 'dump(.*).txt'); // how backup dump files are named
 $general_error = '';
 
-$pathtoroot = "";
-if( !(isset($pathtoroot) && $pathtoroot) )
-{
-  $path=dirname(realpath(__FILE__));
-  //$path=dirname(realpath(__FILE__));
-  if(strlen($path))
-  {
-    /* determine the OS type for path parsing */
-    $pos = strpos($path,":");
-    if ($pos === false)
-    {
-      $gOS_TYPE="unix";
-      $pathchar = "/";
-    }
-    else
-    {
-      $gOS_TYPE="win";
-      $pathchar="\\";
-    }
-    $p = $path.$pathchar;
-    /*Start looking for the root flag file */
-    if( !isset($pathtoroot) ) $pathtoroot = '';
-    while(!strlen($pathtoroot) && strlen($p))
-    {
-      $sub = substr($p,strlen($pathchar)*-1);
-      if($sub==$pathchar)
-      {
-        $filename = $p."root.flg";
-      }
-      else
-        $filename = $p.$pathchar."root.flg";
-      if(file_exists($filename))
-      {
-        $pathtoroot = $p;
-      }
-      else
-      {
-        $parent = realpath($p.$pathchar."..".$pathchar);
-	if($parent!=$p)
-	{
-	  $p = $parent;
-	}
-	else
-	  $p = "";
-      }
-    }
-    if( !(isset($pathtoroot) && $pathtoroot) )
-      $pathtoroot = ".".$pathchar;
-  }
-  else
-  {
-    $pathtoroot = ".".$pathchar;
-  }
-}
+// new path detection without K4 init: begin
+define('FULL_PATH', realpath(dirname(__FILE__).'/..') );
+define('BASE_PATH', rtrim(preg_replace('#/admin$#', '', str_replace('\\', '/', dirname($_SERVER['PHP_SELF']))), '/'));
+$rootURL = 'http://'.$_SERVER['HTTP_HOST'].rtrim(BASE_PATH, '/').'/admin/';
+// new path detection without K4 init: end
 
-$path_char = GetPathChar();
-//phpinfo(INFO_VARIABLES);
+$pathtoroot = FULL_PATH.'/';
+$admin = 'admin';
 
-$sub = substr($pathtoroot,strlen($pathchar)*-1);
-if($sub!=$pathchar)
-{
-  $pathtoroot = $pathtoroot.$pathchar;
-}
-
 ini_set('include_path', '.');
 
 if (!defined('IS_INSTALL')) define('IS_INSTALL',1);
 if( file_exists($pathtoroot.'debug.php') && !(defined('DEBUG_MODE') && DEBUG_MODE) ) include_once($pathtoroot.'debug.php');
 
-$admin = substr($path,strlen($pathtoroot));
 $state = isset($_GET["state"]) ? $_GET["state"] : '';
 if(!strlen($state))
 {
@@ -119,6 +64,7 @@
     set_ini_value("Database", "DBUserPassword", "");
     set_ini_value("Database", "DBName", "");
     set_ini_value("Module Versions", "In-Portal", "");
+
     save_values();
   }
 }
@@ -160,7 +106,7 @@
     //require_once ($pathtoroot."kernel/admin/include/navmenu.php");
     require_once ($pathtolocal."admin/include/navmenu.php");
     require_once($pathtoroot.$admin."/toolbar.php");
-    
+
     set_cookie(SESSION_COOKIE_NAME, '', adodb_mktime() - 3600, rtrim(BASE_PATH, '/') );
 }
 
@@ -364,33 +310,42 @@
 	$login_err_mesg = ''; // always init vars before use
 	if( !isset($g_License) ) $g_License = '';
 	$lic = base64_decode($g_License);
-    if(strlen($lic))
-    {
-            a83570933e44bc66b31dd7127cf3f23a($lic);
-            $ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
-    }
+	if(strlen($lic))
+	{
+		a83570933e44bc66b31dd7127cf3f23a($lic);
+		$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
+	}
 
-      $LoggedIn = FALSE;
-      if($_POST["UserName"]=="root")
-      {
-          $ado =& inst_GetADODBConnection();
-          $sql = "SELECT * FROM ".$g_TablePrefix."ConfigurationValues WHERE VariableName='RootPass'";
+	$LoggedIn = FALSE;
+	if($_POST["UserName"]=="root")
+	{
+		$ado =& inst_GetADODBConnection();
+		$sql = "SELECT * FROM ".$g_TablePrefix."ConfigurationValues WHERE VariableName='RootPass'";
 
-          $rs = $ado->Execute($sql);
-          if($rs && !$rs->EOF)
-          {
-              $RootPass = $rs->fields["VariableValue"];
+		$rs = $ado->Execute($sql);
+		if($rs && !$rs->EOF)
+		{
+			$RootPass = $rs->fields["VariableValue"];
 
-              if(strlen($RootPass)>0)
-                  $LoggedIn = ($RootPass==md5($_POST["UserPass"]));
-          }
-      }
-      else
-      {
-      	$act = '';
-      	if (ConvertVersion($g_InPortal) >= ConvertVersion("1.0.5")) {
-      		$act = 'check';
-      	}
+			if(strlen($RootPass)>0) {
+				if (ConvertVersion($g_InPortal) >= ConvertVersion("1.3.0")) {
+					$LoggedIn = ($RootPass==md5(md5($_POST["UserPass"]).'b38'));
+				}
+				else {
+					$LoggedIn = ($RootPass==md5($_POST["UserPass"]));
+				}
+			}
+		}
+		else {
+			$login_err_mesg = 'Invalid username or password';
+		}
+	}
+	else
+	{
+		$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['HTTP_HOST']), "r");
 		if (!$rfile) {
 			$login_err_mesg = "Unable to connect to the Intechnic server!";
@@ -412,79 +367,79 @@
 				$LoggedIn = true;
 			}
 		}
-      	//$LoggedIn = ($i_User == $_POST["UserName"] && ($i_Pswd == $_POST["UserPass"]) && strlen($i_User)>0) || strlen($i_User)==0;
-      }
+		//$LoggedIn = ($i_User == $_POST["UserName"] && ($i_Pswd == $_POST["UserPass"]) && strlen($i_User)>0) || strlen($i_User)==0;
+	}
 
-      if($LoggedIn)
-      {
-        if (!(int)$_POST["inp_opt"]) {
-          	$state="reinstall";
-          	$inst_error = "Please select one of the options above!";
-        }
-        else {
-	      	switch((int)$_POST["inp_opt"])
-	          {
-	          case 0:
-	              $inst_error = "Please select an option above";
-	          break;
-	          case 1:
-	              /* clean out all tables */
-	              $install_type = 4;
-	              $ado =& inst_GetADODBConnection();
-	              $filename = $pathtoroot.$admin."/install/inportal_remove.sql";
-	              RunSchemaFile($ado,$filename);
+	if($LoggedIn)
+	{
+		if (!(int)$_POST["inp_opt"]) {
+			$state="reinstall";
+			$inst_error = "Please select one of the options above!";
+		}
+		else {
+			switch((int)$_POST["inp_opt"])
+			{
+				case 0:
+				$inst_error = "Please select an option above";
+				break;
+				case 1:
+				/* clean out all tables */
+				$install_type = 4;
+				$ado =& inst_GetADODBConnection();
+				$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
+				RunSchemaFile($ado,$filename);
 
-	              // removing other tables
-	              $tables = $ado->MetaTables();
+				// removing other tables
+				$tables = $ado->MetaTables();
 
-	              foreach($tables as $tab_name) {
-	              	if (stristr($tab_name, $g_TablePrefix."ses_")) {
-	              		$sql = "DROP TABLE IF EXISTS $tab_name";
-	              		$ado->Execute($sql);
-	              	}
-	              }
+				foreach($tables as $tab_name) {
+					if (stristr($tab_name, $g_TablePrefix."ses_")) {
+						$sql = "DROP TABLE IF EXISTS $tab_name";
+						$ado->Execute($sql);
+					}
+				}
 
-	              /* run install again */
-	              $state="license";
-	          break;
-	          case 2:
-	          	  $install_type = 3;
-	              $state="dbinfo";
-	          break;
-	          case 3:
-	          	  $install_type = 5;
-	              $state="license";
-	          break;
-	          case 4:
-	          		$install_type = 6;
-	              /* clean out all tables */
-	              $ado =& inst_GetADODBConnection();
-	              //$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
-	              //RunSchemaFile($ado,$filename);
-	              /* run install again */
-	              $state="restore_select";
-	          break;
-	          case 5:
-	          	$install_type = 7;
-	          	/* change DB config */
-	          	$state="db_reconfig";
-	          break;
-	          case 6:
-	          	$install_type = 8;
-	          	$state = "upgrade";
-	          break;
-	          case 7:
-	          	$install_type = 9;
-	          	$state = "fix_paths";
-	          break;
-	       }
-	    }
-      }
-      else
-      {
-         $state="reinstall";
-         $login_error = $login_err_mesg;//"Invalid Username or Password - Try Again";
-      }
+				/* run install again */
+				$state="license";
+				break;
+				case 2:
+				$install_type = 3;
+				$state="dbinfo";
+				break;
+				case 3:
+				$install_type = 5;
+				$state="license";
+				break;
+				case 4:
+				$install_type = 6;
+				/* clean out all tables */
+				$ado =& inst_GetADODBConnection();
+				//$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
+				//RunSchemaFile($ado,$filename);
+				/* run install again */
+				$state="restore_select";
+				break;
+				case 5:
+				$install_type = 7;
+				/* change DB config */
+				$state="db_reconfig";
+				break;
+				case 6:
+				$install_type = 8;
+				$state = "upgrade";
+				break;
+				case 7:
+				$install_type = 9;
+				$state = "fix_paths";
+				break;
+			}
+		}
+	}
+	else
+	{
+		$state="reinstall";
+		$login_error = $login_err_mesg;//"Invalid Username or Password - Try Again";
+	}
 }
 
 if ($state == "upgrade") {
@@ -524,6 +479,11 @@
 		    	$dir_name = $pathtoroot.$mod_path."/admin/install/upgrades/";
 		    	$dir = @dir($dir_name);
 
+		    	if (!$dir) {
+		    		$rs->MoveNext();
+		    		continue;
+		    	}
+
 		    	$upgrades_arr = Array();
 
 		    	$new_version = '';
@@ -551,8 +511,8 @@
 		    			$filename = $pathtoroot.$mod_path."/admin/install/upgrades/$file";
 				       	if(file_exists($filename))
 					   		{
-								include($filename);
-								if($result&2)break;
+									include($filename);
+									if( $result & 2 ) break;
 					   		}
 			      	}
 		    	}
@@ -593,10 +553,10 @@
 
 	    	$rs->MoveNext();
 	    }
-		
-	    $sql = 'DELETE FROM '.$g_TablePrefix.'Cache WHERE VarName = "config_files"';
-		$ado->Execute($sql);
-		
+
+	    $sql = 'DELETE FROM '.$g_TablePrefix.'Cache WHERE VarName IN ("config_files","configs_parsed","sections_parsed")';
+			$ado->Execute($sql);
+
 		$include_file = $pathtoroot.$admin."/install/upgrade.php";
 	}
 }
@@ -605,17 +565,16 @@
 	// K4 applition is now always available during upgrade process
 	if (!defined('FULL_PATH')) {
 		define('FULL_PATH', realpath(dirname(__FILE__).'/..'));
-		define('APPLICATION_CLASS', 'MyApplication');
 	}
-	
-	include_once(FULL_PATH.'/kernel/kernel4/startup.php');
+
+	include_once(FULL_PATH.'/core/kernel/startup.php');
 	$application =& kApplication::Instance();
 	$application->Init();
-	
+
 	// force rereading of configs
 	$unit_config_reader =& $application->recallObject('kUnitConfigReader');
-	$unit_config_reader->scanModules(MODULES_PATH);	
-	
+	$unit_config_reader->scanModules(MODULES_PATH);
+
 	$ado =& inst_GetADODBConnection();
 	$mod_arr = $_POST['modules'];
 
@@ -677,6 +636,8 @@
 	   		{
     			$filename = $pathtoroot.$mod_path."/admin/install/upgrades/$file";
 		       	//echo "Running: $filename<br>";
+
+		       	// SQL is processed FIRST (before corresponding PHP according to the sorting order in VersionSort()
 		       	if( file_exists($filename) )
 		       	{
 		       		if($tmp_extension == 'sql')
@@ -697,16 +658,14 @@
 
     // compile stylesheets: begin
 	define('FULL_PATH', realpath(dirname(__FILE__).'/..'));
-	define('APPLICATION_CLASS', 'MyApplication');
-	include_once(FULL_PATH.'/kernel/kernel4/startup.php');
+	include_once(FULL_PATH.'/core/kernel/startup.php');
 	$application =& kApplication::Instance();
 	$application->Init();
 
 	$objThemes->CreateMissingThemes(false);
-	
-	$css_hash = $application->DB->GetCol('SELECT LOWER(Name) AS Name, StylesheetId FROM '.TABLE_PREFIX.'Stylesheets', 'StylesheetId');
 
-	$application->setUnitOption('css', 'AutoLoad', false);
+	$css_hash = $application->Conn->GetCol('SELECT LOWER(Name) AS Name, StylesheetId FROM '.TABLE_PREFIX.'Stylesheets', 'StylesheetId');
+
 	$css_table = $application->getUnitOption('css','TableName');
 	$css_idfield = $application->getUnitOption('css','IDField');
 
@@ -716,12 +675,14 @@
 	$theme_update_sql = 'UPDATE '.$theme_table.' SET '.$css_idfield.' = %s WHERE LOWER(Name) = %s';
 	foreach($css_hash as $stylesheet_id => $theme_name)
 	{
-		$css_item =& $application->recallObject('css');
+		$css_item =& $application->recallObject('css', null, Array('skip_autoload' => true));
 		$css_item->Load($stylesheet_id);
 		$css_item->Compile();
-		$application->DB->Query( sprintf($theme_update_sql, $stylesheet_id, $application->DB->qstr( getArrayValue($css_hash,$stylesheet_id) ) ) );
+		$application->Conn->Query( sprintf($theme_update_sql, $stylesheet_id, $application->Conn->qstr( getArrayValue($css_hash,$stylesheet_id) ) ) );
 	}
-	$application->Done();
+
+	// do redirect, because upgrade scripts can eat a lot or memory used for language pack upgrade operation
+	$application->Redirect('install', Array('state' => 'languagepack_upgrade'), '', 'install.php');
 	// compile stylesheets: end
 
     $state = 'languagepack_upgrade';
@@ -1131,7 +1092,7 @@
 	        	if( preg_match('/inportal_upgrade_v(.*).(php|sql)$/', $file, $rets) )
 	        	{
 	        		if($p == '') $p = 'in-portal';
-	        		
+
 	        		$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '".$p."'";
 	        		$rs = $ado->Execute($sql);
 
@@ -1252,11 +1213,13 @@
   $installed = TableExists($ado,"ConfigurationAdmin,Category,Permissions");
   if(!$installed)
   {
-  		// create tables
+  		// run core install script	
+  		K4_RunSQL('/core/install/install_schema.sql');
+		K4_RunSQL('/core/install/install_data.sql');
+  	
+  		// run in-portal install script
   		$filename = $pathtoroot.$admin."/install/inportal_schema.sql";
       	RunSchemaFile($ado,$filename);
-
-		// insert default info
       	$filename = $pathtoroot.$admin."/install/inportal_data.sql";
       	RunSQLFile($ado,$filename);
 
@@ -1324,16 +1287,6 @@
   }
 }
 
-if ($state == "finish") {
-    $ado =& inst_GetADODBConnection();
-  	$PhraseTable = $g_TablePrefix."ImportPhrases";
-  	$EventTable = $g_TablePrefix."ImportEvents";
-	$ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
-	$ado->Execute("DROP TABLE IF EXISTS $EventTable");
-
-	$include_file = $pathtoroot.$admin."/install/install_finish.php";
-}
-
 if($state=="RootSetPass")
 {
   $pass = $_POST["RootPass"];
@@ -1349,8 +1302,10 @@
   }
   else
   {
-  	  $pass = md5($pass);
-      $sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$pass' WHERE VariableName='RootPass' OR VariableName='RootPassVerify'";
+  	  $pass = md5(md5($pass).'b38');
+      $sql = '	UPDATE '.$g_TablePrefix.'ConfigurationValues
+      			SET VariableValue = '.$ado->qstr($pass).'
+      			WHERE VariableName = "RootPass";';
       $ado =& inst_GetADODBConnection();
       $ado->Execute($sql);
       $state="modselect";
@@ -1365,25 +1320,30 @@
 if($state=="lang_install_init")
 {
 
-  	$ado =& inst_GetADODBConnection();
+	$ado =& inst_GetADODBConnection();
 
-  	if( TableExists($ado, 'Language,Phrase') )
-  	{
+	if( TableExists($ado, 'Language,Phrase') )
+	{
 		// KERNEL 4 INIT: BEGIN
 		define('FULL_PATH', realpath(dirname(__FILE__).'/..'));
-		define('APPLICATION_CLASS', 'MyApplication');
-		include_once(FULL_PATH.'/kernel/kernel4/startup.php');
+		include_once(FULL_PATH.'/core/kernel/startup.php');
 
 		$application =& kApplication::Instance();
 		$application->Init();
 		// KERNEL 4 INIT: END
 
-  		$lang_xml =& $application->recallObject('LangXML');
+		$lang_xml =& $application->recallObject('LangXML');
 
-  		$lang_xml->renameTable('phrases', TABLE_PREFIX.'ImportPhrases');
-  		$lang_xml->renameTable('emailmessages', TABLE_PREFIX.'ImportEvents');
+		if (defined('DBG_FAST_INSTALL') && DBG_FAST_INSTALL) {
+			$lang_xml->tables['phrases'] = TABLE_PREFIX.'Phrase';
+			$lang_xml->tables['emailmessages'] = TABLE_PREFIX.'EmailMessage';
+		}
+		else {
+			$lang_xml->renameTable('phrases', TABLE_PREFIX.'ImportPhrases');
+			$lang_xml->renameTable('emailmessages', TABLE_PREFIX.'ImportEvents');
+		}
 
-	  	$lang_xml->lang_object->TableName = $application->getUnitOption('lang','TableName');
+		$lang_xml->lang_object->TableName = $application->getUnitOption('lang','TableName');
 
 		$languages = $application->GetVar('lang');
 		if($languages)
@@ -1398,29 +1358,35 @@
 			{
 				foreach($modules as $module_name => $module_folder)
 				{
-					$lang_path = MODULES_PATH.'/'.$module_folder.ADMIN_DIR.'/install/langpacks';
+					$lang_path = MODULES_PATH.'/'.$module_folder.'admin/install/langpacks';
 					$lang_xml->Parse($lang_path.'/'.$lang_file, '|0|1|2|', '');
 					if($force_finish) $lang_xml->lang_object->Update();
 				}
 			}
 
-	      	$state = 'lang_install';
-	  	}
-	  	else
-	  	{
-	  		$state = 'lang_select';
-	  	}
+			if (defined('DBG_FAST_INSTALL') && DBG_FAST_INSTALL) {
+				$state = 'lang_default';
+			}
+			else {
+				$state = 'lang_install';
+			}
+		}
+		else
+		{
+			$state = 'lang_select';
+		}
 
-	  	$application->Done();
-  	}
-  	else
-  	{
-  		$general_error = 'Database error! No language tables found!';
-  	}
+		$application->Done();
+	}
+	else
+	{
+		$general_error = 'Database error! No language tables found!';
+	}
 }
 
 if($state=="lang_install")
 {
+	define('FORCE_CONFIG_CACHE', 1);
 	/* do pack install */
 	$Offset = (int)$_GET["Offset"];
 	$Status = (int)$_GET["Status"];
@@ -1495,7 +1461,12 @@
 	$Id = $_POST["lang"];
 
 	$objLanguages->SetPrimary($Id);
-	$state="postconfig_1";
+	if (defined('DBG_FAST_INSTALL')) {
+		$state = 'theme_sel';
+	}
+	else {
+		$state="postconfig_1";
+	}
 }
 
 if($state=="lang_default")
@@ -1726,6 +1697,17 @@
 	echo "<script>window.location='index.php';</script>";
 }
 
+if ($state == "finish") {
+    $ado =& inst_GetADODBConnection();
+  	$PhraseTable = $g_TablePrefix."ImportPhrases";
+  	$EventTable = $g_TablePrefix."ImportEvents";
+	$ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
+	$ado->Execute("DROP TABLE IF EXISTS $EventTable");
+	$ado->Execute('INSERT INTO '.$g_TablePrefix.'Cache (VarName, Data) VALUES (\'ForcePermCacheUpdate\', \'1\')');
+
+	$include_file = $pathtoroot.$admin."/install/install_finish.php";
+}
+
 // init variables
 $vars = Array('db_error','restore_error','PassError','DomainError','login_error','inst_error');
 foreach($vars as $var_name) ReSetVar($var_name);
@@ -1765,6 +1747,7 @@
     $title = "Thank You!";
     $help ="<P>Thanks for using In-Portal!  Be sure to visit <A TARGET=\"_new\" HREF=\"http://www.in-portal.net\">www.in-portal.net</A> ";
     $help.=" for the latest news, module releases and support. </p>";
+    $help.="<p>*Make sure to clean your browser' cache after upgrading In-portal version</p>";
 break;
 case "license":
     $title = "License Configuration";