<?php
//error_reporting(E_ALL);
error_reporting(0);

ob_start(); 
include_once('../config/config.php'); 
include_once('../config/settings.php');
include_once('../install/cls_serverconfig.php');

/*
 * get the path dynamically
 * NOTE:- need to add www via htaccess if required
 */
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) .$s . "://";
define('ROOT_URL', $protocol );


        
$current_path = getcwd();  
if (strstr($current_path, 'public_html')) {
    $path_part = explode('/public_html', $current_path);
} elseif (strstr($current_path, 'httpdocs')) {
    $path_part = explode('/httpdocs', $current_path);
} else {
    $path_part[1] = '';
}

$upload_dir = str_replace('upgrade4.1', '', $current_path);

$path_part[1] .= '/';
$path_part[1] = str_replace('project/upgrade4.1/', '', $path_part[1]);

define('BASE_URL', ROOT_URL . $_SERVER['SERVER_NAME'] . $path_part[1]);



$perm_flag = true;
$perm_msg = '';
$error_message = '';
$error = false;
$installed = false;
$user_data = array();
$post_flag = false;

$configfile = "../config/config.php";
$settingsfile = "../config/settings.php";
//$oldSettingsFile = "../settings.php";

$schemafile = "sql/upgrade_schema.sql";
$datafile = "sql/upgrade_data.sql";

$serverOS = ServerConfig::getServerOS();
$serverSettings = ServerConfig::checkServerConfiguration();
$serverCurrentSettings = ServerConfig::getServerSettings();
$host_name = parse_url($_SERVER['HTTP_HOST']);

if (isset($_POST['upgraderCheck'])) {

    $post_flag = true;

    //automatically set the folder permissions
  


    // Get connection
    $connection = @mysqli_connect(MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD);
    if ($connection === false) {
        $error = true;
        $message .= " * Connection Not Successful! Please verify your database details!<br>";
    } else {
        $dbselected = @mysqli_select_db($connection, MYSQL_DB);
        mysqli_query("SET SESSION sql_mode ='' ");
        if (!$dbselected) {
            $error = true;
            $message .= " * Database could not be selected! Please verify your database details!<br>";
        }
    }
    $sqlPrefix = MYSQL_TABLE_PREFIX;
    // Get adminEmail
    $lookUpdate = mysqli_query("SELECT value FROM ".$sqlPrefix."lookup");
    $admin_email = '';
        $sqlsettingsData = mysqli_query("SELECT value, settingfield FROM " . $sqlPrefix . "lookup WHERE settingfield IN ('vadmin_email', 'sitename')");
        if($sqlsettingsData){
            while($sqlres = mysqli_fetch_array($sqlsettingsData)){
                if($sqlres['settingfield'] == 'vadmin_email'){
                    $admin_email = $sqlres['value'];
                }
                else{
                    $site_name = $sqlres['value'];
                }
            }
        }
    //proceed with corresponding action
    $version = '2.0';
    if ($error) {
        $message = "<u><b>Please correct the following errors to continue:</b></u>" . "<br><br>" . $message;
    } else {

        //update ReserveLogic config file
        $fp = fopen($configfile, "w+");
        $configcontent = "<?php\n";
        $configcontent .= "define('INSTALLED', true); \n\n";
        $configcontent .= "define('VERSION', $version); \n\n";
        $configcontent .= "\n?>";
        fwrite($fp, $configcontent);

      
        
        //--------------------------------IMPORT RESERVELOGIC DB HERE-------------------------//
        $sqlquery = @fread(@fopen($schemafile, 'r'), @filesize($schemafile));
        $sqlquery = preg_replace('/tbl_/', $sqlPrefix , $sqlquery);
        $sqlquery = ServerConfig::splitsqlfile($sqlquery, ";");

        for ($i = 0; $i < sizeof($sqlquery); $i++) {
            mysqli_query($connection,$sqlquery[$i]);
        }

        $dataquery = @fread(@fopen($datafile, 'r'), @filesize($datafile));
        $dataquery = preg_replace('/tbl_/', $sqlPrefix, $dataquery);
        $dataquery = ServerConfig::splitsqlfile($dataquery, ";");
        for ($i = 0; $i < sizeof($dataquery); $i++) {
            mysqli_query($connection, $dataquery[$i].";");
        }       
      
       
        $installed = true;

        //send confirmation email to admin
        $subject = "Script Upgraded at " . $site_name;
        
        $headers = "From: " . $site_name . "<" . $admin_email . ">\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
        
        $mailcontent = "Hello , <br>";
        $mailcontent .= "Your Site is successfully upgraded.<br> <a href='" . BASE_URL . "' target='_blank'>Click Here to Access your Site</a>";
        $mailcontent .= "<br><a href='" . BASE_URL . "cms' target='_blank'>Click Here to Access your Site Administration Control Panel</a> <br><br>";
        $mailcontent .= "Your Admin Username   :  admin";
        $mailcontent .= "<br>Your Admin Password   :  admin";        
        $mailcontent .= "<br> Thanks and regards,<br> " . $site_name . " Team";

        /* Email Template */
        $email_temp_qry = "SELECT mail_template_body FROM ".$sqlPrefix."mail_template WHERE mail_template_name='installer_mail'";
        $email_temp = mysqli_query($email_temp_qry);
        $mailMsgArr = mysqli_fetch_array($email_temp);
        $mailMsg = NULL;
        $dateVal = date("m/d/Y");
        $copyright = 'copyright '.date('Y').' '.$site_name.' All rights reserved';
        
        if(count($mailMsgArr) > 0) {
            $mailMsg = $mailMsgArr['mail_template_body'];
        } // End If
        if(!empty($mailMsg)){
                $mailMsg = str_replace("{SITE_LOGO}", "<img src='".BASE_URL . "project/install/css/logo.png'/>", $mailMsg);
                $mailMsg = str_replace("{Date}", $dateVal, $mailMsg);
                $mailMsg = str_replace("{SITE_NAME}", $site_name, $mailMsg);
                $mailMsg = str_replace("{MAIL_CONTENT}", $mailcontent, $mailMsg);
                $mailMsg = str_replace("{COPYRIGHT}", $copyright, $mailMsg);
            } else {
                $mailMsg =$mailcontent;
            }

        $mailcontent = $mailMsg;
        @mail(addslashes($admin_email), $subject, $mailcontent, $headers);
    }
}

//check current directory permissions
//foreach ($directories as $dir) {
//    $permission = ServerConfig::fileWritable($dir, 'project/'.$dir);
//    if (!$permission['status']) {
//        $error = true;
//        $error_message .= $permission['message'];
//    }
//}

if ($installed) {
    header("location: upgrade_success.php");
    exit;
}

/*
$lines = file($oldSettingsFile);
function get_value_of($name){
    global $lines;
    for($i=1; $i < count($lines);$i++){
    @list($key, $val) = @explode('=', @trim($lines[$i]) );
    if(trim($key) == trim($name))
        return str_replace(";",'',str_replace("'",'',$val));
    }
}
*/

$upgraderTitle = 'iScripts Socialware Upgrader';
$productName = 'Socialware';

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title><?php echo $upgraderTitle; ?></title>
    </head>
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script type="text/javascript" src="../js/install.js"></script>
    <link href="css/install.css" rel="stylesheet" type="text/css" />
    <body>
        <div class="header_row">
            <div class="header_container  sitewidth">
                <table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
                    <tr>
                        <td width="23%" align="left" ></td>
                        <td width="77%" align="right">
                            <h4><?php echo $upgraderTitle; ?></h4>
                            <div align="center" id="items_top_area">
                                &nbsp;&nbsp;
<!--                                <a title="OnlineInstallationManual" href="#" onClick="window.open('<?php echo BASE_URL; ?>project/Docs/Installation_Manual.pdf','OnlineInstallationManual','top=100,left=100,width=820,height=550,scrollbars=yes,toolbar=no,status=yrd');"><strong>Installation manual</strong></a> |
                                <a title="Readme" href="#" onClick="window.open('<?php echo BASE_URL; ?>project/Docs/Readme.txt','Readme','top=100,left=100,width=820,height=550,scrollbars=yes,toolbar=no,status=yrd');"><strong>Readme</strong></a> |-->
                                <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>
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <table width="100%"  border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td><img src="css/spacer.gif" width="1" height="5"></td>
            </tr>
        </table>
        <table width="100%"  border="0" cellspacing="0" cellpadding="0">
            <tr>

                <td width="76%" valign="top" height ="400">
                    <!-- Here's where I want my views to be displayed -->
                    <table width="80%" border="0" cellpadding="0" cellspacing="0" align="center">
                        <tr>
                            <td>
                                <!--------Installer starts------------------------->

                                <!--items display area start -->
                                <?php
                                if ($serverSettings == "FAILURE") {
                                    ?>
                                    <table width="100%" border=0 align="center">
                                        <?php
                                        foreach ($serverCurrentSettings as $settings) {
                                            $span_class = $settings['flag'] ? "install_value_ok" : "install_value_fail";
                                            ?>
                                            <tr>
                                                <td>
                                                    <?php echo $settings['feature']; ?> <span class="<?php echo $span_class; ?>"><?php echo $settings['setting']; ?></span>
                                                </td>
                                            </tr>
                                            <?php
                                        }
                                        ?>
                                        <tr>
                                            <td>
                                                <span class="install_value_fail">Fatal errors detected.  Please correct the above red items and reload.</span>
                                            </td>
                                        </tr>
                                    </table>

                                    <?php
                                } else if (!$installed) {
                                    ?>
                                    <table width="80%" border="0" align="center">
                                        <tr>
                                            <td align="center" ><b><font size="1">
                                                    <div align="justify" >
                                                        <br>
                                                        <font color="#F4700E" size="+1">Thank you for choosing <?php echo $productName;?>&nbsp;</font> <br><br>
                                                        <font color="#000000" size="2">To complete this upgradation process, please enter the details below.</font>
                                                    </div>

                                                    </font></b>
                                            </td>
                                        </tr>
                                        <?php if ($post_flag) { ?>
                                            <tr>
                                                <td align=center class="message" >
                                                    <div align="left" class="text_information">
                                                        <br>
                                                        <font color="#FF0000"><?php echo $perm_msg; ?></font><br>
                                                        <font color="#FF0000"><?php echo $error_message . '<br/>' . $message; ?></font><br>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php } ?>
                                        <tr>
                                            <td class=maintext align="left" >
                                               
                                                <br>
                                                <form name="frmInstall" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                                                    <br>

<!--                                                    <FIELDSET>
                                                        <LEGEND class='block_class'>File Permissions</LEGEND>
                                                        <table width=85% border="0" cellpadding="2" cellspacing="2" class=maintext>
                                                            <tr>
                                                                <td colspan="2" align="left">
                                                                    <b>
                                                                        <?php if ($serverOS['chmodstatus'] == '777') { ?>
                                                                            <?php echo $productName;?> requires that some of the folders have write permission. You can provide an FTP login so that this process is done automatically.<br/><br/>
                                                                            For security reasons, it is best to create a separate FTP user account with access to the <?php echo $productName;?> upgradation only and not the entire web server. Your host can assist you with this.
                                                                            If you have difficulties completing upgradation without these credentials, please click "I would provide permissions manually" to do it yourself.<br/><br/>
                                                                        <?php } elseif ($serverOS['chmodstatus'] == '000') { ?>
                                                                            <?php echo $productName;?> requires that some of the folders have write permission. Please provide write permission for the following files :-<br/><br/>
                                                                        <?php } elseif ($serverOS['chmodstatus'] == '755') { ?>
                                                                            <?php echo $productName;?> requires that some of the folders have write permission.<br/><br/>
                                                                        <?php } ?>
                                                                    </b>
                                                                </td>
                                                            </tr>
                                                            <?php if ($serverOS['write'] == 'UNWRITABLE') { ?>
                                                                <tr>
                                                                    <td class=maintext align="left">FTP username</td>
                                                                    <td width="61%" align=left>
                                                                        <input name="FTPusername"  id="FTPusername" type="text" size="50" value="<?php echo htmlentities($user_data['FTPusername']); ?>">								
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td class=maintext align="left">FTP password</td>
                                                                    <td width="61%" align=left>
                                                                        <input name="FTPpassword"  id="FTPpassword" type="password" size="50" value="<?php echo htmlentities($user_data['FTPpassword']); ?>">
                                                                    </td>
                                                                </tr>
                                                                <?php if ($serverOS['chmodstatus'] == '777') { ?>
                                                                    <tr>
                                                                        <td colspan="2" align="left">
                                                                            <input type="checkbox" name="auto_set" id="auto_set" onclick="divToggle(this)" /> &nbsp; I would provide permissions manually
                                                                        </td>
                                                                    </tr>                                                
                                                                    <?php
                                                                }
                                                            } else {
                                                                ?>
                                                                <tr>
                                                                    <td colspan="2" align="left">
                                                                        <b>File permissions are OK.</b>
                                                                    </td>
                                                                </tr>
                                                            <?php } ?>
                                                        </table>
                                                        <?php if ($serverOS['write'] == 'UNWRITABLE') { ?>
                                                            <div id="err_div" style="<?php if ($serverOS['chmodstatus'] == '777') { ?>display:none<?php } ?>">
                                                                <fieldset>
                                                                    <legend>Directories/Files List</legend>
                                                                    <?php echo $error_message; ?>
                                                                </fieldset>
                                                            </div>
                                                        <?php } ?>
                                                    </FIELDSET>-->
                                                                            
                                                    <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='../styles/images/arrow.png' />&nbsp;Take the backup of the existing Socialware files and folders!! </td>
														</tr>
														<tr>
															<td colspan="3">&nbsp;</td>
														</tr>
														<tr>
															<td colspan="2">&nbsp;</td>
															<td class="maintext"><img src='../styles/images/arrow.png' />&nbsp;Take the backup of the existing Socialware Database !! </td>
														</tr>
														<tr>
															<td colspan="3">&nbsp;</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='../styles/images/arrow.png' />&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='../styles/images/arrow.png' />&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>
														</table>
														<br />
											  </FIELDSET>
                                                    <br>
                                                    <br>
                                                    <table width=85% border=0 cellpadding="2" cellspacing="2" class=maintext>
                                                        <tr><td>&nbsp;</td></tr>
                                                        <tr>
                                                            <td align="center">
                                                                <input type="submit" name="btnContinue" value="Upgrade" class="buttn_admin">
                                                            </td>
                                                        </tr>
                                                    </table>

                                                    <!-- DO NOT REMOVE -->
                                                    <input type="hidden" name="upgraderCheck" id="upgraderCheck" value="1" />
                                                    <!-- ------------- -->
                                                </form>	
                                            </td>
                                        </tr>
                                    </table>
                                    <?php
                                }
                                ?>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <div class="installr_footer"></div>
    </body>
</html>