<?php

//XXX General Functinons
function install_validate_hosting_requirements(){
	global $dic;
	$phpVer =  phpversion();
	list($major, $minor) = explode('.', $phpVer);
	if(!($major==7 && $minor>=4)){
		return array(
			'ok' => 0,
			'msg' => str_replace('##phpversion##',$phpVer ,$dic['sysreq_phpver_problem'])
		);
	}

	if(!extension_loaded('mbstring')){
		return array(
			'ok' => 0,
			'msg' => str_replace(array('##libname##', '##libcode##'),array('Multibyte String', 'mbstring') ,$dic['sysreq_phplib_problem'])
		);
	}
	if(!extension_loaded('pdo')){
		return array(
			'ok' => 0,
			'msg' => str_replace(array('##libname##', '##libcode##'),array('PDO MySQL', 'pdo_mysql') ,$dic['sysreq_phplib_problem'])
		);
	}
	if(!extension_loaded('curl')){
		return array(
			'ok' => 0,
			'msg' => str_replace(array('##libname##', '##libcode##'),array('Client URL Library ', 'curl') ,$dic['sysreq_phplib_problem'])
		);
	}
	if(!extension_loaded('zip')){
		return array(
			'ok' => 0,
			'msg' => str_replace(array('##libname##', '##libcode##'),array('Zlib Compression', 'zip') ,$dic['sysreq_phplib_problem'])
		);
	}
	if(!extension_loaded('openssl')){
		return array(
			'ok' => 0,
			'msg' => str_replace(array('##libname##', '##libcode##'),array('OpenSSL', 'openssl') ,$dic['sysreq_phplib_problem'])
		);
	}
	//

	if(!extension_loaded("IonCube Loader")){
		return array(
			'ok' => 0,
			'msg' => str_replace(array('##libname##', '##libcode##'),array('IonCube Loader', '') ,$dic['sysreq_phplib_problem'])
		);
	}

	return array(
		'ok' => 1,
		'msg' => ''
	);
}
function peg_get_app_folder(){
    if(defined('WEBAPP_MAIN_PATH') ){
        return WEBAPP_MAIN_PATH;
    }
}

//XXX CURL
function install_curl_request($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    
    return $output;
}

function install_curl_request_post($Url, $data = array() ){
    $ch = curl_init ($Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET') );
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    
    $output = curl_exec ($ch);
    if(!$output){
        return 'Curl error: ' . curl_error($ch);
    }
    return $output;
}

//XXX FTP
function install_check_ftp_connect(){
    $ftp_server = $_SERVER['SERVER_NAME'];
    $ftp_user 	= $_REQUEST['ftp_user'];
    $ftp_pass	= $_REQUEST['ftp_pass'];
    $ftp_port 	= $_REQUEST['ftp_port'];
    
    
    if(!isset($_REQUEST['sftp']) or ($_REQUEST['sftp']!='1')){
        $ftp_sftp='0';
    }
    else{
        $ftp_sftp='1';
    }
    
    
    
    if(substr($ftp_pass , 0 , 10)=='peg_crypt02:'){
        $ftp_pass = pegasus_decrypt(substr($ftp_pass,10));
    }
    
    // set up a connection or die
    $conn_id = peg_ftp_connect($ftp_server , $ftp_port, $ftp_sftp);
    //$conn_id = ftp_connect('127.0.0.1' , $ftp_port  ) or die("Couldn't connect to " .  $ftp_server  . " " . $ftp_port . " ");
    
    // try to login
    if (!ftp_login($conn_id, $ftp_user, $ftp_pass)) {
        return false;
    }
    return true;
}

function peg_ftp_connect($ftp_server , $ftp_port , $ftp_sftp){
	$con = false;

	if($ftp_sftp=='1'){
		if(function_exists('ftp_ssl_connect')){
			$con=ftp_ssl_connect ($ftp_server,  $ftp_port);
		}
	}


	if (false === $con) {
		$con = ftp_connect($ftp_server, $ftp_port );
		if($con===false ){
			if($ftp_server != '127.0.0.1'){
				return peg_ftp_connect('127.0.0.1' , $ftp_port , $ftp_sftp);
			}else{				
				die("Couldn't connect to " .  $ftp_server  . " " . $ftp_port . " ");
				return false;
			}
		}
	}
	return $con;
}

/**
 * FTP Connect
 */
function install_ftp_connect(){
	$ftp_server = $_SERVER['SERVER_NAME'];
	$ftp_user 	= $_REQUEST['ftp_user'];
	$ftp_pass	= $_REQUEST['ftp_pass'];		
	$ftp_port 	= $_REQUEST['ftp_port'];

	if(!isset($_REQUEST['sftp']) or ($_REQUEST['sftp']!='1')){
		$ftp_sftp='0';
	}
	else{
		$ftp_sftp='1';
	}
	
	if(substr($ftp_pass , 0 , 10)=='peg_crypt:'){
		$ftp_pass = pegasus_decrypt(substr($ftp_pass,10));
	}		
	
	// set up a connection or die
	$conn_id = peg_ftp_connect($ftp_server , $ftp_port , $ftp_sftp);
		
	// try to login
	if (!ftp_login($conn_id, $ftp_user, $ftp_pass)) {
		return false;			
	}	
	if(isset($_REQUEST['passv']) && ($_REQUEST['passv']=='1')){
		ftp_pasv($conn_id, true)  or die("Cannot switch to passive mode");
	}
	
	return $conn_id;			
}
	
/**
 * install_fto. 
 */
function install_ftp_putAll($conn_id, $src_dir, $dst_dir, $options = array( 'recursively' => true)) {
	if(!is_dir($src_dir)){
		// return 'install_ftp_putAll' .$src_dir; 
		return  array(0 ,  "install_ftp_putAll " .$src_dir . " to $dst_dir\n"); 
	}
	$log='';
	$d = dir($src_dir);
	$dirs = '';
    //if(is_object($d)){
    while($file = $d->read()) { // do this for each file in the directory
        if ($file != "." && $file != "..") { // to prevent an infinite loop
			if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
				$dirs .=$file . ',';
                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
                    ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
				}
				if($options['recursively']){
					list($ok, $log00, $dirs00) = install_ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file, $options); // recursive part
					if($ok==1){
						$dirs .= $dirs00;
					}
					$log .=  $log00;
				}

            } else {
                $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
				//echo $dst_dir."/".$file . ' <- ' . $src_dir."/".$file ."\n";
                if($upload){
                	$log .= $dst_dir."/".$file . ' <- ' . $src_dir."/".$file ."\n";
                }
				else{
					$log = 'Error while uploading '.$dst_dir."/".$file . ' <- ' . $src_dir."/".$file ."\n";
					return  $log;
				}
            }
        }
    }
    $d->close();
    //}
    return  array(1, $log, $dirs);
}


//XXX MySQL

function install_check_mysql_connect($islocl = false)
{

	$mysql_host = $_REQUEST['mysql_host'];
	$mysql_user = $_REQUEST['mysql_user'];
	$mysql_pass	= $_REQUEST['mysql_pass'];
	$mysql_port = $_REQUEST['mysql_port'];
	$mysql_db   = $_REQUEST['mysql_db'];


	global $pdo;

	$pdo = null;
	if (!extension_loaded('pdo') || !extension_loaded('pdo_mysql')) {
		die('You need to enable the PDO and PDO_MYSQL extensions in your php.');
	}
	try {
	$pdo = new PDO("mysql:host=$mysql_host;port=$mysql_port;",$mysql_user,$mysql_pass);
	}catch(PDOException $err) {
		die($err->getMessage());
	}
	if (!$pdo) {
		//trigger_error('Could not connect to MySQL: ' . mysql_error() , E_USER_ERROR);
		return false;
	}

	$ret = $pdo->query("USE $mysql_db");
	if (!$ret) {
		if ($islocl) {
			$sql = 'CREATE DATABASE ' . $mysql_db;
			if ($pdo->query($sql)) {
				return true;
			} else {
				return false;
			}
		}

		//trigger_error('Could not select the database: ' . mysql_error() , E_USER_ERROR);
		return false;
	}

	return true;
}
/**
 * Aνέβασμα αρχείου. 
 */
function install_mysql_upload_sql($filename, $islocl=false) {
  
	// Name of the file
 
		
	$mysql_host 	  = $_REQUEST['mysql_host'];
	$mysql_username   = $_REQUEST['mysql_user'];
	$mysql_password	  = $_REQUEST['mysql_pass'];		
	$mysql_database   = $_REQUEST['mysql_db'];
	$mysql_port 	  = $_REQUEST['mysql_port'];
	

	global $pdo;

	$pdo = null;
	if (!extension_loaded('pdo') || !extension_loaded('pdo_mysql')) {
		die('You need to enable the PDO and PDO_MYSQL extensions in your php.');
	}
	try {
	$pdo = new PDO("mysql:host=$mysql_host;dbname=$mysql_database;port=$mysql_port;",$mysql_username,$mysql_password);
	}catch(PDOException $err) {
		die($err->getMessage());
	}
	if (!$pdo) {
		//trigger_error('Could not connect to MySQL: ' . mysql_error() , E_USER_ERROR);
		return false;
	}

	$ret = $pdo->query("USE $mysql_database");
	if (!$ret) {
		return false;
	}
	$pdo->query('set names utf8;');	
 
	$pdo->query("DROP FUNCTION IF EXISTS peg_new_nr01;");
	$pdo->query("CREATE FUNCTION peg_new_nr01 (_table CHAR(50), _counter BIGINT(15) )
	/********************************************************************
	updates table p75 with a counter and returns the new nr01 value for a table. 
	
	_table = table name to find new nr01 for
	_counter = value to be added. If missed =1 
	*********************************************************************/
	
	RETURNS bigint(15) DETERMINISTIC
	BEGIN
		DECLARE loc_minnr01 bigint(15);
		DECLARE loc_maxp75 bigint(15);
		/* loc_nr01 used for return value*/
		SET @loc_nr01=0;
	
		/* loc_minnr01 = cor000.min_nr01 */
		SET loc_minnr01=ifnull((select min_nr01 from cor000 where nr01=1), 0);
	
		/* loc_maxp75 = max(nr01) from p50 */
		SET loc_maxp75=ifnull((select max(nr01) from p75), loc_minnr01);
		
		SET loc_maxp75 = loc_maxp75+1;
		SET _counter= if(_counter<=0, 1, _counter);
	   
		SET loc_minnr01 =if(_table='p70' , 0 ,  loc_minnr01);
		 
		IF ( select nr01 FROM p75 where p01=_table ) IS NULL 
		THEN 
		
			INSERT INTO p75 (nr01, p01, p010)    
		VALUES (loc_maxp75, _table, 0);
	 
		END IF;               
	
		UPDATE p75
		SET p010 = @loc_nr01:=greatest(p010 + _counter, loc_minnr01)
		WHERE p01=_table;
		
		RETURN @loc_nr01; 
	END;");


	if($islocl and file_exists("../../../servers/MySQLServer/bin/mysql.exe") and file_exists('install_files/install/sql/install.sql')){
		$mysql_path = realpath("../../../servers/MySQLServer/bin/mysql.exe");
		
		$sql_path = realpath("install_files/install/sql/install.sql");
		if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
			$mysql_path = str_replace('\\','\\\\', $mysql_path);
			$sql_path = str_replace('\\','\\\\', $sql_path);
		}	
		return exec("$mysql_path -u$mysql_username -p$mysql_password -P$mysql_port $mysql_database  < $sql_path", $output, $ret); 
	}


	// Temporary variable, used to store current query
	$templine = '';

	// Read in entire file
	//$lines = file($filename);

	
	$templine = '';
	$DELIMITER = ';';
	$D_LEN = 1;

	// Read in entire file
	$lines = file($filename);
	if(!$lines) return 1;

	
	foreach ($lines as $line_num => $line) {
	
		$line = trim($line);
		
			if(substr($line, 0, 9) == 'DELIMITER') { // change delimiter
				$DELIMITER = str_replace('DELIMITER ', '', $line);
				$D_LEN = strlen($DELIMITER);
				continue;
		}
		
			// Only continue if it's not a comment
		if(substr($line, 0, 2) != '--' && $line != '') { // Add this line to the current segment
			$templine .= $line;
			
			// If it has a DELIMITER at the end, it's the end of the query
			if(substr($line, -$D_LEN, $D_LEN) == $DELIMITER) {
				$pdo->query(rtrim($templine, $DELIMITER)) or print('Error performing query \'' .
				$templine . '\': ' . mysql_error() . '');
				$templine = ''; // Reset temp variable to empty
			} else {
				$templine .= "\n";
			}
		}
	}	
		

} 

//XXX FILES
function install_unzip_file($fl) {
	  
	$zip = new ZipArchive;
			
	if ($zip->open("install_files/" . $fl) === TRUE) {
		if(!is_dir("install_files/" . str_replace(".zip"  , "" , $fl ) . "/")){
			mkdir("install_files/" . str_replace(".zip"  , "" , $fl ) . "/" , 0777 );
		}
				
		$zip->extractTo("install_files/" . str_replace(".zip"  , "" , $fl ) . "/");
		$zip->close();
									
		$file_path00 = "install_files/" . str_replace(".zip"  , "" , $fl ) . "/" ;
				
		//pegasus_delete_directory("../../tmp/" . str_replace(".zip"  , "" , $fl ) . "/");
		//unlink("../../tmp/" . $fl);
	}
}

function install_copyFiles($src_dir, $dst_dir, $options=array('folderPermission'=>0755,'filePermission'=>0644, 'recursively' => true)){
    if(!is_dir($src_dir)){
		return  array(0 ,  "install_copyFiles" .$src_dir . " to $dst_dir\n"); 
    }
    $log='';
    $d = dir($src_dir);
	$dirs = '';
    while($file = $d->read()) { 
        if ($file != "." && $file != "..") { 
            if (is_dir("$src_dir/$file")) {
				$dirs .=$file . ',';
				if(!is_dir("$dst_dir/$file")){
					mkdir("$dst_dir/$file");
				}
				chmod("$dst_dir/$file",$options['folderPermission']);
				if($options['recursively']){
					list($ok, $log00, $dirs00) = install_copyFiles("$src_dir/$file",  "$dst_dir/$file", $options);
					if($ok==1){
						$dirs .= $dirs00;
					}
					$log .=  $log00;
				} 

            } else if (is_file("$src_dir/$file")) {    
                if(copy( "$src_dir/$file" , "$dst_dir/$file" )){
                    chmod("$dst_dir/$file",$options['filePermission']); 
                    $log .= "$dst_dir/$file <-  $src_dir/$file \n";
                } else{
                    $log = "Error while uploading $dst_dir/$file  <-  $src_dir/$file \n";
                    $errors= error_get_last();
                    if(is_array($errors)){
                        $log .=  "COPY ERROR: ".$errors['type'];
                        $log .=  "<br /> ". $errors['message'] ."\n";
                    }

                    return  $log;
                }
            }
        }
    }
    $d->close(); 
    return  array(1, $log, $dirs);
}

function install_generate_log(){
	$handle = fopen("install_files/install.log", "w");
	if(!$handle){
		die('Unable to create file "/install/install_files/install.log"');
	}
	fclose( $handle ) ;

}
function install_update_log($text ){
	$handle = fopen("install_files/install.log", "a");
	if(!$handle){
		die('Unable to create file "/install/install_files/install.log"');
	}

	fprintf($handle,"%s", $text);
	fclose( $handle ) ;
}
	
//XXX TESAE
function install_check_tesae_connect(){
	$tesae_user = $_REQUEST['tesae_user'];
	$tesae_pass	= $_REQUEST['tesae_pass'];		

	$ret_xml =  install_curl_request('http://update.tesae.gr/pegasus/update_hermes/execute.php?action=login&user=' . $tesae_user .'&pass=' .$tesae_pass );
// 	$ret_xml = install_curl_request_post('http://update.tesae.gr/pegasus/update_hermes/execute.php', array(
// 	    action => 'login',
// 	    user => $tesae_user,
// 	    pass => $tesae_pass
// 	));
	
	$xml_login = simplexml_load_string($ret_xml);
	
	if($xml_login->code=='100'){
		 return true;
	}else{
		return false;
	}
}

function check_if_app_exist(){
	$mysql_host = $_REQUEST['mysql_host'];
	$mysql_user = $_REQUEST['mysql_user'];
	$mysql_pass	= $_REQUEST['mysql_pass'];		
	$mysql_port = $_REQUEST['mysql_port'];
	$mysql_db   = $_REQUEST['mysql_db'];
			
	global $pdo;

	$pdo = null;
	if (!extension_loaded('pdo') || !extension_loaded('pdo_mysql')) {
		die('You need to enable the PDO and PDO_MYSQL extensions in your php.');
	}
	try {
	$pdo = new PDO("mysql:host=$mysql_host;dbname=$mysql_db;port=$mysql_port;",$mysql_user,$mysql_pass);
	}catch(PDOException $err) {
		die($err->getMessage());
	}
	if (!$pdo) {
		//trigger_error('Could not connect to MySQL: ' . mysql_error() , E_USER_ERROR);
		return false;
	}
	//echo 'select count(*) as cnt from p50 where nr01>0;';
	$ret = $pdo->query('select count(*) as cnt from p50 where nr01>0;');
	if(!$ret){
		//trigger_error('Could not select the database: ' . mysql_error() , E_USER_ERROR); 
		return false;
	}

	$p50 = $ret->fetchAll();

	if($p50[0]['cnt']>0){
		return true;
	}else{
		return false;
	}
}
