<?php

	include_once("../includes/config.php");
	
	$schemafile = "schema_upgrade_2.3.sql";
	$datafile = "data_upgrade_2.3.sql";
	$configfile = "../includes/config.php";
	
	$configcontents = @fread(@fopen($configfile, 'r'), @filesize($configfile));
	$pos = strpos($configcontents, "UPGRADED2.3");
	
	$zipdir="../products/zip/";
	
	$csvdir="../csv/";
        $category_dir = "../categories";
        $categories_avatar_dir = "../categories/avatar";
        $home_page_banner_dir = "../homepagebanners";
	
	/*if ($pos === false)
	{;
	}
	else
	{
		header("Location:../index.php");
	}*/
	
	$upgraded = false;
	
	
/*-----------Database Settings--------------*/
	
	$txtDBServerName = $HOST;
	$txtDBName 		 = $DATABASENAME;
	$txtDBUserName 	 = $USER;
	$txtDBPassword 	 = $PASSWORD;
	$txtDBPrefix 	 = $tableprefix;
	$txtRootServer   = $rootserver;
	$txtServer       = SITE_URL;
	$txtSecureServer = SECURE_SITE_URL;
	$sellerFriendly=enable_seller_friendly;

        
	


	function splitsqlfile($sql, $delimiter)
	{
		// Split up our string into "possible" SQL statements.
		$tokens = explode($delimiter, $sql);
		// try to save mem.
		$sql = "";
		$output = array();
		// we don't actually care about the matches preg gives us.
		$matches = array();
		// this is faster than calling count($oktens) every time thru the loop.
		$token_count = count($tokens);
		for ($i = 0; $i < $token_count; $i++) {
			// Don't wanna add an empty string as the last thing in the array.
			if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0))) {
				// This is the total number of single quotes in the token.
				$total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
				// Counts single quotes that are preceded by an odd number of backslashes,
				// which means they're escaped quotes.
				$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);
	
				$unescaped_quotes = $total_quotes - $escaped_quotes;
				// If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
				if (($unescaped_quotes % 2) == 0) {
					// It's a complete sql statement.
					$output[] = $tokens[$i];
					// save memory.
					$tokens[$i] = "";
				} else {
					// incomplete sql statement. keep adding tokens until we have a complete one.
					// $temp will hold what we have so far.
					$temp = $tokens[$i] . $delimiter;
					// save memory..
					$tokens[$i] = "";
					// Do we have a complete statement yet?
					$complete_stmt = false;
	
					for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++) {
						// This is the total number of single quotes in the token.
						$total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
						// Counts single quotes that are preceded by an odd number of backslashes,
						// which means they're escaped quotes.
						$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);
	
						$unescaped_quotes = $total_quotes - $escaped_quotes;
	
						if (($unescaped_quotes % 2) == 1) {
							// odd number of unescaped quotes. In combination with the previous incomplete
							// statement(s), we now have a complete statement. (2 odds always make an even)
							$output[] = $temp . $tokens[$j];
							// save memory.
							$tokens[$j] = "";
							$temp = "";
							// exit the loop.
							$complete_stmt = true;
							// make sure the outer loop continues at the right point.
							$i = $j;
						} else {
							// even number of unescaped quotes. We still don't have a complete statement.
							// (1 odd and 1 even always make an odd)
							$temp .= $tokens[$j] . $delimiter;
							// save memory.
							$tokens[$j] = "";
						}
					} // for..
				} // else
			}
		}
		return $output;
	}

	$display_button = "";	
	
	if(isset($_POST['submit']))
	{
	
        if (!is_writable($configfile) || !is_readable($configfile)  )
        {
        $error = true;
        $message .= " * Config file not writable! Please change the permission of 'includes/config.php' to 777 <br>";
        }
	if (!is_writable($zipdir) || !is_readable($zipdir) || !@file_exists("$zipdir".".")  ) {
        $error = true;
        $message .= " * Change the permission  (chmod 777 for linux server) of 'products/zip' folder in the root to 777 <br>";
        }
	if (!is_writable($csvdir) || !is_readable($csvdir) || !@file_exists("$csvdir".".")  ) {
        $error = true;
        $message .= " * Change the permission  (chmod 777 for linux server) of 'csv' folder in the root to 777 <br>";
        }
        if (!is_writable($category_dir) || !is_readable($category_dir)  )
        {
        $error = true;
        $message .= "* Change the permission  (chmod 777 for linux server) of 'categories' folder in the root to 777 <br>";
        }
        if (!is_writable($categories_avatar_dir) || !is_readable($categories_avatar_dir)  )
        {
        $error = true;
        $message .= "* Change the permission  (chmod 777 for linux server) of 'categories/avatar' folder in the root to 777 <br>";
        }
        if (!is_writable($home_page_banner_dir) || !is_readable($home_page_banner_dir)  )
        {
        $error = true;
        $message .= "* Change the permission  (chmod 777 for linux server) of 'homepagebanners' folder in the root to 777 <br>";
        }
				
		/*---------Datbase Connection Details--------------*/	
	
			$connection = @mysql_connect($txtDBServerName, $txtDBUserName, $txtDBPassword);
		
			
		
			if($connection === false)
			{
				$error = true;
				$message .= " * Connection Not Successful! Please verify your database details!<br><br>";
			}
			else
			{
				$dbselected = @mysql_select_db($txtDBName, $connection);
				
				if (!$dbselected)
				{
					$error = true;
					$message .= " * Database could not be selected! Please verify your database details!<br><br>";
				}
				
			}
					
			 if($error)
			 {
				$message = "<u><b>Please correct the following errors to continue:</b></u>" . "<br><br>" . $message;
				
				//echo $message;
			
			 }
			 else
			 {
			 		//store config file details
					$configfile_content=file_get_contents($configfile);

					$configcontent = "<?php\n";
        			$configcontent .= "define('INSTALLED', true); \n\n";
					$configcontent .= "define('UPGRADED2.3', true);" . "\n";
		
					$configcontent .= '$HOST = "' . $txtDBServerName . "\";" . "\n";
        			$configcontent .= '$DATABASENAME = "' . $txtDBName . "\";" . "\n";
        			$configcontent .= '$USER = "' . $txtDBUserName . "\";" . "\n";
       				$configcontent .= '$PASSWORD = "' . $txtDBPassword . "\";" . "\n\n";
			        $configcontent .= '$tableprefix = "' . $txtDBPrefix . "\";" . "\n";
		

        			$configcontent .= '$conn = mysql_connect($HOST, $USER, $PASSWORD);';
        			$configcontent .= "\n";
       				$configcontent .= 'mysql_select_db($DATABASENAME, $conn);'."\n";
		
					$configcontent .='$sql=" SELECT * FROM ".$tableprefix."settings";'."\n";
					$configcontent .='$result=mysql_query($sql) or die(mysql_error());'."\n";
					$configcontent .='$row = mysql_fetch_array($result);'."\n";
					$configcontent .='$logoimage=$row["site_logo"];'."\n";
					$configcontent .='$featureddisplay=$row["publish_featured"];'."\n";
					$configcontent .='$newitemdisplay=$row["publish_newitem"];'."\n";
					$configcontent .='$sitestyle=$row["site_style"];'."\n";
					$configcontent .='$shopingcartdisplay=$row["publish_shoppingcart"];'."\n";
					$configcontent .='define("SITE_EMAIL", $row["site_email"]);'."\n";
					$configcontent .='define("SITE_NAME", $row["site_name"]);'."\n";
					$configcontent .='define("SITE_URL", $row["site_url"]);'."\n";
					$configcontent .='define("SECURE_SITE_URL", $row["site_secure_url"]);'."\n";
					$configcontent .= '$imagefolder = SITE_URL . "/images";'."\n";
					$configcontent .= '$rootserver = SITE_URL;'."\n". "\n";

					$configcontent .= '$logofolder = SITE_URL . "/banners";'."\n";
					$configcontent .= '$enable_seller_friendly = "' . $sellerFriendly . "\";" . "\n";
						
					$configcontent .= '$stylesfolder = SITE_URL . "/style";'."\n";
        			$configcontent .= "\n?>";
		
					//replace installed with upgrad with new values
					$final_configcontent=str_replace($configfile_content,$configcontent,$configfile_content);

					//final result write into config.inc.php
					if(@file_exists($configfile))
					{
						//rename old file
						@rename('old_'.$configfile);
					}//end if
		
					//changes write into config.inc.php
					@fwrite(@fopen($configfile,'w+'),$final_configcontent);

					
					$sqlquery = @fread(@fopen($schemafile, 'r'), @filesize($schemafile));
					$sqlquery = preg_replace('/multicart_/', $txtDBPrefix, $sqlquery);
					$sqlquery = splitsqlfile($sqlquery, ";");

                                        
				
/*------------------Creating The Tables---------------------*/

					for($i = 0; $i < sizeof($sqlquery); $i++)
					{
						mysql_query($sqlquery[$i], $connection) or die(mysql_error());
					}
					
					
					$dataquery = @fread(@fopen($datafile, 'r'), @filesize($datafile));
					$dataquery = preg_replace('/multicart_/', $txtDBPrefix, $dataquery);
					$dataquery = splitsqlfile($dataquery, ";");
				
/*-----------------Populating The Tables With Initial Data----------------------*/
				
					for($i = 0; $i < sizeof($dataquery); $i++)
					{
						mysql_query($dataquery[$i], $connection);
					}
				
			$products_backup = "SELECT * FROM ".$txtDBPrefix. "products_backup";
                         $query_product = mysql_query($products_backup) or die(mysql_error());
                         while($productObj = mysql_fetch_object($query_product)) {

                            $insert_products = "INSERT INTO ".$txtDBPrefix. "products SET product_name = '".$productObj->product_name."'";
                            if($productObj->product_code !="") {
                             $insert_products .= ",product_code = '".$productObj->product_code."'";
                            }
                            if($productObj->product_description !="") {
                             $insert_products .= ",product_description = '".$productObj->product_description."'";
                            }
                            if($productObj->product_price !="") {
                             $insert_products .= ",product_price = '".$productObj->product_price."'";
                            }
                            if($productObj->product_category !="") {
                             $insert_products .= ",product_category = '".$productObj->product_category."'";
                            }
                            if($productObj->product_artist_id !="") {
                             $insert_products .= ",product_artist_id = '".$productObj->product_artist_id."'";
                            }
                            if($productObj->date_added !="") {
                             $insert_products .= ",date_added = '".$productObj->date_added."'";
                            }
                            if($productObj->deleted !="") {
                             $insert_products .= ",deleted = '".$productObj->deleted."'";
                            }
                            if($productObj->featured !="") {
                             $insert_products .= ",featured = '".$productObj->featured."'";
                            }
                            if($productObj->vdigital_product !="") {
                             $insert_products .= ",vdigital_product = '".$productObj->vdigital_product."'";
                            }
                            if($productObj->vapproved !="") {
                             $insert_products .= ",vapproved = '".$productObj->vapproved."'";
                            }

                            mysql_query($insert_products);
                            $product_id = mysql_insert_id();


                            $insert_product_options = "INSERT INTO ".$txtDBPrefix. "product_options SET product_id = '".$product_id."'";
                            if($productObj->product_height !="") {
                             $insert_product_options .= ",product_height = '".$productObj->product_height."'";
                            }
                            if($productObj->product_width !="") {
                             $insert_product_options .= ",product_width = '".$productObj->product_width."'";
                            }
                            if($productObj->product_length !="") {
                             $insert_product_options .= ",product_length = '".$productObj->product_length."'";
                            }
                            if($productObj->product_image_small !="") {
                             $insert_product_options .= ",image_small = '".$productObj->product_image_small."'";
                            }
                            if($productObj->product_image_big !="") {
                             $insert_product_options .= ",image_big = '".$productObj->product_image_big."'";
                            }
                            if($productObj->product_stock !="") {
                             $insert_product_options .= ",product_stock = '".$productObj->product_stock."'";
                            }
                            if($productObj->reorder_level !="") {
                             $insert_product_options .= ",reorder_level = '".$productObj->reorder_level."'";
                            }
                            if($productObj->discount !="") {
                             $insert_product_options .= ",discount = '".$productObj->discount."'";
                            }
                            if($productObj->discountdescription !="") {
                             $insert_product_options .= ",discount_description = '".$productObj->discountdescription."'";
                            }
                            if($productObj->nproduct_shipping_weight !="") {
                             $insert_product_options .= ",product_shipping_weight = '".$productObj->nproduct_shipping_weight."'";
                            }
                            mysql_query($insert_product_options);

                         }
			 $upgraded = true;
			 
			 
			 $display_button = "none";
			 }
		
	
	}






?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<link href="style.css" rel="stylesheet" type="text/css">
<script>
function DisplayHtAccessDiv()
{

	if(document.frmUpgradation.sellerFriendly.checked)
	{
		document.getElementById("htaccessDiv").style.display = "";
		document.getElementById("htaccessDivMsg").style.display = "";
	}
	else
	{
		document.getElementById("htaccessDiv").style.display = "none";
		document.getElementById("htaccessDivMsg").style.display = "none";
	}	

}
</script>

	<body>

	<center>

	<div align="left" id="layout">
	
		<div align="left" id="header">
		<!--header area start -->
				
				<div align="left" id="logo"><img src="images/defaultlogo.gif" alt="" width="125" height="39" border="0" /></div>
				
				<div align="right" id="header_right">
				<!--
				 <a href="javascript:;">Contact Us</a>&nbsp;|&nbsp;
				 -->
				 <a href="javascript:;">&nbsp;</a>
				


		</div>		
				
		<!--header area end -->
		</div>
		
		
		<div align="left" class="main_body">
			<!--mainbody area start -->
			
			
			<div align="left" id="item_details">
	
	
			<!--items display area start -->
		
			<div align="left" id="items_top_area">
					<img src="images/top_title_left.gif" alt="" class="items_top_area_img" />
					<div align="left" id="items_top_area_ttl">Multicart 2.4 Upgradation</div>
					<img src="images/top_title_right.gif" alt="" class="items_top_area_img" />&nbsp;&nbsp;
					<a title="If you have any difficulty, submit a ticket to the support department" href="#" onClick="window.open('http://www.iscripts.com/support/postticketbeforeregister.php','','top=100,left=100,width=820,height=550,scrollbars=yes,toolbar=no,status=yrd,resizable=yes');">														
						<strong>Get Support</strong>
					</a>
			</div>
			
			<div>&nbsp;</div>
			
					
		
			<div>

			<form name="frmUpgradation" method="post" action="#">
					<table cellpadding="0" cellspacing="0" width="100%">
					<tr>
						<td align="center" class="text_information"><?php echo $message?></td>
					</tr>
<?php

	if(!$upgraded)
	{
	
?>					
					
					<tr>
						<td align="center" valign="top" >
						<b><font size="1">
						<div align="justify" >
						<br>
							<font color="#F4700E" size="+1">Thank you for purchasing the upgrade kit of Multicart 2.4</font> <br><br>
							<div id="htaccessDiv" style="display:none">
							
							&nbsp;&nbsp;&nbsp;&nbsp;<img src="../images/install_steps.jpg"> Change the permission (chmod) of '.htaccess' file to 777. <br><br>
							
							</div>
					
						</div>
		
						</font></b>
						</td>
					</tr>
										<tr>
											<td>
												<FIELDSET>
														<LEGEND class="block_class">Upgradation Instructions</LEGEND>
														<br />
														<table width="100%" border="0" cellpadding="0" cellspacing="0">
														<tr>
															<td colspan="3" class="maintext"><font class="required">*</font>&nbsp;Make sure that you have done the following things before pressing the 'Upgrade' button</td>
														</tr>
														<tr>
															<td colspan="3">&nbsp;</td>
														</tr>
														<tr>
															<td colspan="2">&nbsp;</td>
															<td class="maintext"><img src="images/arrow1.gif" />&nbsp;Take the backup of the existing Multicart files and folders!! </td>
														</tr>
														<tr>
															<td colspan="3">&nbsp;</td>
														</tr>
														<tr>
															<td colspan="2">&nbsp;</td>
															<td class="maintext"><img src="images/arrow1.gif" />&nbsp;Take the backup of the existing Multicart Database !! </td>
														</tr>
														<tr>
															<td colspan="3">&nbsp;</td>
														</tr>
														<tr>
														  <td colspan="2">&nbsp;</td>
														  <td ><img src="images/arrow1.gif" />Change the permission (<b><font size="1"><font color="#000000">chmod 777 for linux server</font></font></b>) of 'includes/config.php' to 777. <br />
													      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(After installation dont forget to change it back to 644)</td>
														  </tr>
														<tr>
														  <td colspan="2">&nbsp;</td>
														  <td class="maintext">&nbsp;</td>
														  </tr>
														  <tr>
														  <td colspan="2">&nbsp;</td>
														  <td ><img src="images/arrow1.gif" />Change the permission (<b><font size="1"><font color="#000000">chmod 777 for linux server</font></font></b>) of 'products/zip' folder to 777. <br />
													      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
														  </tr>
														<tr>
														  <td colspan="2">&nbsp;</td>
														  <td class="maintext"><img src="images/arrow1.gif" />Change the permission (<b><font size="1"><font color="#000000">chmod 777 for linux server</font></font></b>) of 'digital_product' folder to 777. </td>
														  </tr>
														    <tr>
														  <td colspan="2">&nbsp;</td>
														  <td ><img src="images/arrow1.gif" />Change the permission (<b><font size="1"><font color="#000000">chmod 777 for linux server</font></font></b>) of 'csv' folder to 777. <br />
													      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
														  </tr>
                                                                                                                  <tr>
														  <td colspan="2">&nbsp;</td>
														  <td class="maintext"><img src="images/arrow1.gif" alt=""/>Change the permission (<b><font size="1"><font color="#000000">chmod 777 for linux server</font></font></b>) of 'categories/avatar' folder to 777. </td>
														  </tr>
                                                                                                                    <tr>
														  <td colspan="2">&nbsp;</td>
														  <td class="maintext"><img src="images/arrow1.gif" alt=""/>Change the permission (<b><font size="1"><font color="#000000">chmod 777 for linux server</font></font></b>) of 'categories' folder to 777. </td>
														  </tr>
                                                                                                                    <tr>
														  <td colspan="2">&nbsp;</td>
														  <td class="maintext"><img src="images/arrow1.gif" alt=""/>Change the permission (<b><font size="1"><font color="#000000">chmod 777 for linux server</font></font></b>) of 'homepagebanners' folder to 777. </td>
														  </tr>
														  <tr>
														  <td colspan="2">&nbsp;</td>
														  <td class="maintext">&nbsp;</td>
														  </tr>
														<tr>
															<td colspan="2">&nbsp;</td>
															<td class="maintext"><img src="images/arrow1.gif" />&nbsp;Once it is done press the 'Upgrade' button to start the upgradation procedure...</td>
														</tr>
														
														<tr>
															<td colspan="3">&nbsp;</td>
														</tr>
														<tr>
															<td colspan="2">&nbsp;</td>
															<td class="maintext"><img src="images/arrow1.gif" />&nbsp;When the upgradation procedure is completed successfully <br />&nbsp;&nbsp;&nbsp;cross check your existing files and database with the upgraded one</td>
														</tr>
														<tr>
														  <td colspan="2">&nbsp;</td>
														  <td height="30" class="maintext"><img src="images/arrow1.gif" />&nbsp; Copy following folders from the backup (portfolios, products,digital_product,banners) to the new upgrade.</td>
														  </tr>
														</table>
														<br />
											  </FIELDSET>
												</td>
											</tr>
											<tr>
												<td>&nbsp;</td>
											</tr>
											<tr>
												<td>
													<div id="upgradeButton" style="display:<?php echo $display_button?>">
														<table cellspacing="0" cellpadding="0" width="100%">
															<tr>
																<td align="center"><input type="submit" class="button" name="submit" value="Upgrade"></td>
															</tr>
														</table>	
													</div>
												</td>
											</tr>
											<tr>
												<td>&nbsp;</td>
											</tr>
<?php

	}
	else
	{
	
?>
			<tr>
				<td align="center"><font color="#F4700E" size="+1">Multicart 2.4 Upgradation Is Completed Successfully !!</font></td>
			</tr>
			<tr>
				<td>&nbsp;</td>
			</tr>
			<tr>
				<td>
					<fieldset>
						<legend class="block_class">Site Login Details</legend>
							<table cellpadding="0" cellspacing="0" width="100%">
							<tr>
								<td colspan="2">&nbsp;</td>
							</tr>
							<tr>
								<td width="15%"><b><font size="-1">Admin URL&nbsp;:</font></b></td>
								<td width="85%"><a style="cursor:pointer" href="<?php echo $txtRootServer?>/admin/login.php"><?php echo $txtRootServer?>/admin/login.php&nbsp;<img src="../images/admin_login_install.jpg" border="0" height="25"></a></td>
							</tr>
						
							<tr>
								<td colspan="2">&nbsp;</td>
							</tr>
							<tr>
								<td width="15%"><b><font size="-1">Home URL&nbsp;:</font></b></td>
								<td width="85%"><a style="cursor:pointer" href="<?php echo $txtRootServer?>/index.php"><?php echo $txtRootServer?>/index.php&nbsp;<img src="../images/home_page.jpg" border="0" height="25"></a></td>
							</tr>
							
							</table>
						</fieldset>	
				</td>
			</tr>
			
<?php

	}

?>
			</table>
			
			</form>					
		
	
	
			</div>	
			
			
			
			
			
			
	
	
		<div align="left" class="float_clear1"></div>
					
					
		 <!--items display area end -->
		  </div>
		
			
		<!--center content area end-->	


		<div align="left" class="float_clear"><img src="images/clear.gif" alt="" width="1" height="1" /></div>		
		<!--mainbody area end -->
        </div>
		<div align="left" class="float_clear"><img src="images/clear.gif" alt="" width="1" height="1" /></div>


<!----Footer Area Starts----------------->

<div align="left" class="float_clear"><img src="images/clear.gif" alt="" width="1" height="1" /></div>
		
		<div align="left" class="copyright_area">
		<!--copyright area start -->
		
				<div align="left" id="copyright_lft">
<!--				
				<a href="javascript:;">Privacy Statement</a> &nbsp;|&nbsp;
				  <a href="javascript:;">Contact Us</a>&nbsp;|&nbsp;
-->				  
				  
  
				  
				  
				  
				</div>
				<div align="right" id="copyright_rgt">Powered by <a href="http://www.iscripts.com/multicart" target="_blank"><font color="#F4700E"><b>iScripts Multicart</b></font></a>. A premium product from <a href="http://www.iscripts.com" class="" target="_blank"><font color="#F4700E"><b>iScripts.com</b></font></a></div>
		
		<!--copyright area start -->
		</div>
	</div>
</center>
</body>
</html>