<?php

session_start();

require_once 'core_factory.php';
Logaholic_sessionStart();

$lang = Logaholic_setLang();
include_once "languages/$lang.php";

# All database errors will be raised as errors.  No need for special handling.
require_once("vendor/adodb/adodb-php/adodb-errorhandler.inc.php");   
# Use adodb for database work.
require_once("vendor/adodb/adodb-php/adodb.inc.php");

include_once "includes/install.php";
$install = new Install();

# Set the variables from the session if available
if(!empty($_SESSION['TmpGlobal']) && !file_exists($install->global_file)){
	# check some individual fields
	$install->PostPreChecks($_SESSION['TmpGlobal'], false);
	if($install->errors == 0){
		$install->SetNewConnection($_SESSION['TmpGlobal']);
		$install->ConnectDb();
	} else {
		unset($_SESSION['TmpGlobal']);
	}
}	

# All is good now rename the file and respond good
if(isset($_POST['validation'])){
	if(empty($_SESSION['TmpGlobal']) && file_exists($install->global_file)){
		die("ok");
	}

	if($_POST['validation'] == 'ok' && !empty($_SESSION['TmpGlobal'])){
		
		# Add Admin user if there really is no one logged in
		if(!empty($_SESSION['TmpGlobal']['adminUser'])){
			$install->AddAdmin();
		}		
		# Now write the global file
		$install->WriteGlobal();

		# Empty session		
		$_SESSION['TmpGlobal'] = [];
												
		if(file_exists($install->global_file)){
			die("ok");
		} else {
			$install->Invalid(_ERROR_WRITING_GLOBAL);
		}		
	} else {
		$install->Invalid(_INVALID_VALIDATION);
	}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta charset="UTF-8">
        <title>Logaholic | Install</title>
        <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
        <link rel="icon" href="favicon.ico" type="image/x-icon">
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
        <link href="components/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <link rel="stylesheet" href="templates/logaholic_6/font-awesome-4.3.0/css/font-awesome.min.css">
        <!-- Theme style -->
        <link href="templates/logaholic_6/css/AdminLTE.css" rel="stylesheet" type="text/css" />
		<link href="templates/logaholic_6/css/install.css" rel="stylesheet" type="text/css" >        

        <!-- Logaholic 6 CSS -->        
        <link href="templates/logaholic_6/css/ui.css" rel="stylesheet" type="text/css" />
        <link href="templates/logaholic_6/css/ui.responsive.css" rel="stylesheet" type="text/css" />

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
          <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
        <![endif]-->
        <style>
        	

        </style>
    </head>
    <body class="skin-logaholic">
        <!-- header logo: style can be found in header.less -->
        <header class="header">
            <a href="index.php" class="logaholiclogo hidden-xs" title="Logaholic Control Panel"><i></i><span>Logaholic</span></a>
           
            <!-- Header Navbar: style can be found in header.less -->
            <nav class="navbar navbar-static-top" role="navigation">
              <div class="welcome"><?php echo _WELCOME_LOGAHOLIC_SOFTWARE; ?></div>
            </nav>
        </header>
        <div class="wrapper row-offcanvas row-offcanvas-left">
            <!-- Right side column. Contains the navbar and content of the page -->
            <aside class="right-side strech">
                <!-- Content Header (Page header) -->
                <section class="content-header">
                    <h1>
                        <span class="confname">&nbsp;</span>
                        <small class="pagename">Logaholic Installation</small>
                    </h1>
                </section>         
                <!-- Main content -->
                <section class="content">
                	<?php
                	if(file_exists($install->global_file)){
						include_once "common.inc.php";
						if($session->logged_in == 1 && $session->isAdmin()){
						} else {
							echoWarning(_NO_PERMISSION_FOR_ADMIN_AREA. ".<br><a href='index.php'>". _CLICK_HERE_TO_CONTINUE .".</a>");
							echo "</div></aside></section></body></html>"; exit;
						}
					}
                	?>                    		
					<div id="installWrapper">
						<div id="content">
							<div id="settings">
									<div class="col-sm-7">
										<div class="box box-solid box-primary">
											<div class="box-header">
												<h3 class="box-title"><?php echo _DATABASE_SETTINGS; ?></h3>
											</div>
											<div class="box-body">
												<?php									

												# Check if the form posted data, if so do handling for it 
												$install->FormDataChecks();
												$install->AdminsCheck();
												?>												
												<form id="dbform" name="dbform" method="post">
													<div class="form-group">
				                                        <label for="DatabaseName"><?php echo _DB_NAME;?></label>
				                                        <input type="text" size="35"  name="DatabaseName" value="<?php echo $install->DatabaseName; ?>" class="form-control"
				                                        	data-help="<?php echo _DB_NAME_EXPLAIN; ?>">
				                                    </div>
													<div class="form-group">
				                                        <label for="mysqlserver"><?php echo _DB_SERVER;?></label>
				                                        <input type="text" size="35"  name="mysqlserver" value="<?php echo $install->mysqlserver; ?>" class="form-control"
				                                        	data-help="<?php echo _DB_SERVER_EXPLAIN; ?>">
				                                    </div>
													<div class="form-group">
				                                        <label for="mysqluname"><?php echo _DB_USERNAME;?></label>
				                                        <input type="text" size="35"  name="mysqluname" value="<?php echo $install->mysqluname; ?>" class="form-control"
				                                        	data-help="<?php echo _DB_USERNAME_EXPLAIN; ?>">
				                                    </div>
													<div class="form-group">
				                                        <label for="mysqlpw"><?php echo _DB_PASSWORD;?></label>
				                                        <input type="password" size="35"  name="mysqlpw" value="<?php echo $install->mysqlpw; ?>" class="form-control"
				                                        	data-help="<?php echo _DB_PASSWORD_EXPLAIN; ?>">
				                                    </div>
													<div class="form-group">
				                                        <label for="mysqlprefix"><?php echo _DB_PREFIX;?></label> (optional)
				                                        <input type="text" size="35"  name="mysqlprefix" value="<?php echo $install->mysqlprefix; ?>" class="form-control"
				                                        	data-help="<?php echo _PLEASE_ENTER_PREFIX; ?>">
				                                    </div>
													<div class="form-group">
				                                        <label for="mysqltmp"><?php echo _MYSQLTMP;?></label>
				                                        <input type="text" size="35" name="mysqltmp" value="<?php echo $install->mysqltmp; ?>" class="form-control"
				                                        	data-help="<?php echo _MYSQLTMP_DESC; ?>">
				                                    </div>
													<div class="form-group">
				                                        <label for="datadir"><?php echo _DATADIR;?></label>
				                                        <input type="text" size="35" name="datadir" value="<?php echo $install->datadir; ?>" class="form-control"
				                                        	data-help="<?php echo _DATADIR_DESC; ?>">
				                                    </div>

													<?php if($install->adminNeeded === true){ ?>
														<div class="form-group">
					                                        <label for="adminUser"><?php echo _ADMIN_USERNAME;?></label>
					                                        <input type="text" size="35" name="adminUser" value="<?php echo $install->adminUser; ?>" class="form-control"
					                                        	data-help="<?php echo _ADMIN_USERNAME_DESC; ?>">
					                                    </div>
					                                    <div class="form-group">
					                                        <label for="adminName"><?php echo _ADMIN . " ". _NAME;?></label>
					                                        <input type="text" size="35" name="adminName" value="<?php echo $install->adminName; ?>" class="form-control"
					                                        	data-help="<?php echo _NAME_EXPLAIN; ?>">
					                                    </div>
					                                    <div class="form-group">
					                                        <label for="adminEmail"><?php echo _ADMIN . " ". _EMAIL_ADDRESS;?></label>
					                                        <input type="text" size="35" name="adminEmail" value="<?php echo $install->adminEmail; ?>" class="form-control"
					                                        	data-help="<?php echo _EMAIL_ADDRESS_EXPLAIN; ?>">
					                                    </div>
														<div class="form-group">
					                                        <label for="adminUserPass"><?php echo _ADMIN_PASSWORD;?></label>
					                                        <input type="password" size="35" name="adminUserPass" value="<?php echo $install->adminUserPass; ?>" class="form-control"
					                                        	data-help="<?php echo _ADMIN_PASSWORD_DESC; ?>">
					                                    </div>
													<?php } ?>
													<div class="form-group">
														<button class="btn btn-primary" name="save" type="submit" style="<?php if(!$install->adminNeeded){ echo 'display:none;'; } ?> font-size: 16px;" ><?php echo _SAVE; ?></button>
														<input type="hidden" name="PrevDatabaseName" value="<?php echo $install->DatabaseName; ?>" />
														<input type="hidden" name="PrevPrefix" value="<?php echo $install->mysqlprefix; ?>" />
													</div>	
												</form>
												<div style="clear:both;">&nbsp;</div>
											</div>	
										</div>	
										<div class="box box-solid box-primary">
											<div class="box-header">
												<h3 class="box-title"><?php echo _MYSQL_SETTINGS; ?></h3>
											</div>
											<div class="box-body">
												<?php 
												# Check if Mysqli extension is loaded
												$install->CheckMysqli();

												if($install->connected === true){
													# See if the mysql time tables are up to date
													if($install->CheckMysqlTimeZoneTables() === true){
														$install->echoValid(_MYSQL_TIMETABLES_FOUND);
													} else {
														$install->echoNotice(
															_MYSQL_TIMETABLES_NOT_FOUND	
															, str_replace("%X%",
                                                                          "<a href='https:///dev.mysql.com/doc/refman/5.6/en/time-zone-support.html' target='_blank'>", _PLEASE_INSTALL_TIME_TABLES) . "</a>"
														);
													}

													if($install->CheckMysqlTmp()){
														# check if mysql load data infile is possible
														$install->CheckLoadDataInfile();
													} else {
														$install->echoInvalid(
                                                            _MYSQLTMP_NOT_WRITEABLE
															,
                                                            "<a href='https:///www.logaholic.com/manual/installation/file-permissions/' target='_blank'>" . _HELP ."</a>"
														);
													}
													
												} else { 		
													$install->echoInvalid(_ERROR_NO_CONN);
												} 
												?>
												<div style="clear:both;">&nbsp;</div>
											</div>	
										</div>	
										<div class="box box-solid box-primary">
											<div class="box-header">
												<h3 class="box-title"><?php echo _FILE_CHECK; ?></h3>
											</div>
											<div class="box-body">
												<?php
												# Check if dirs and files permissions are set corect
												$install->FilePermissionsChecks();
												?>
												<div style="clear:both;">&nbsp;</div>
											</div>
										</div>
										<div class="box box-solid box-primary">
											<div class="box-header">
												<h3 class="box-title"><?php echo _PHP_SETTINGS; ?></h3>
											</div>
											<div class="box-body">
												<?php
												$install->PhpSettings();
												?>
												<div style="clear:both;">&nbsp;</div>
											</div>	
										</div>									
									</div>
									<div class="col-sm-5">	
				                    	<div class="box box-solid box-warning helptxt" style="min-height:250px">
				                            <div class="box-header">                                                          
				                                <h3 class="box-title"><i class="fa fa-info-circle">&nbsp;</i> <span>Help</span></h3>
				                                
				                            </div>
				                            <div class="box-body"><?php echo _INSTALL_INTRO; ?></div>
				                        </div> 									
									</div>

									<div style="clear:both;">&nbsp;</div>
									<?php
									if (!$install->db || !$install->db->IsConnected()) {
										# Only show buttons when we have a database object

									} else if($install->errors == 0){
										?>
										<div id="staticOptions">
											<button class="btn btn-success" onclick="GoNext();"><?php echo _CONTINUE; ?></button>
											<button class="btn btn-default" onclick="location.href = location.href;"><?php echo _CHECK_AGAIN; ?></button> 
										</div>
										<?php
									} else {
										?>
										<div id="staticOptions">
											<button class="btn btn-default disabled" onclick="alert('Please resolve all red issues before continuing.');"><?php echo _CONTINUE; ?></button>
											<button class="btn btn-success" onclick="location.href = location.href;"><?php echo _CHECK_AGAIN; ?></button> 
										</div>
										<?php
									}
								?>
								<div style="float:left; height:90px; width: 100%;"></div>
							</div>
						</div>
					</div>
                </section><!-- /.content -->
            </aside><!-- /.right-side -->
        </div><!-- ./wrapper -->

       
        <script src="components/jquery/js/jquery-1.11.3.min.js"></script>  
        <script type="text/javascript">
		function UpdateHelp(title,txt) {
			if (txt==undefined) {
				txt =  "<?php echo _MOVE_YOUR_MOUSE_FOR_HELP; ?>";
				title = "<?php echo _HELP; ?>";
			}
			if (txt == $(".helptxt .box-body").html()) {
				return;
			}

			$(".helptxt .box-body").fadeOut(100, function(){
				$(".helptxt .box-title span").html(title);
				$(".helptxt .box-body").html(txt);
				$(".helptxt .box-body").fadeIn();
			});
		}

		function getFileName() {
				//this gets the full url
				var url = document.location.href;
				//this removes the anchor at the end, if there is one
				url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
				//this removes the query after the file name, if there is one
				url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
				//this removes everything before the last slash in the path
				url = url.substring(url.lastIndexOf("/") + 1, url.length);
				//return
				return url;
			}

			function GoNext(){
				$.ajax({
					url: getFileName(),
					type: "POST",
					data: { "validation" : "ok" },
					success: function (result) {
						if(result == 'ok'){
							if (document.location.protocol=="https:") { var ptcl = "https:" } else { var ptcl = "http:" }
							window.location = ptcl + "//<?php echo $_SERVER['HTTP_HOST'] . str_replace("install.php","", $_SERVER["REQUEST_URI"]); ?>";
						}
					}
				});				
			}

			$(document).on("keydown", "#dbform input", function(){
				$("#dbform button[name='save']").show();
			});

        	$("input, select").on("focus mouseover", function(e) {				
				var txt = $(this).attr("data-help");
				var title = $("label[for='"+$(this).attr("name")+"']").html();		
				
				UpdateHelp(title,txt);
			});
        </script>
        
    </body>
</html>