<?php

/**
*   This file can be used to upgrade your loagholic installation from the command line
*	Usage: php upgrade.php
*	If you get an error, you may have to invoke the script like this:
*	php -d open_basedir=/ upgrade.php
**/

# these are some functions added by michael, because he keeps forgetting to update the version number in the source of this file, so lets ask the user
function read() {
	if ($fp=fopen("/dev/stdin", "r")) {
		$input=fgets($fp, 255);
		fclose($fp);
		return str_replace("\n","",$input);
	} else {
		echo "\n\nYou may have to invoke the script like this:\n\n   php -d open_basedir=/  upgrade.php \n\n";
		exit();
	}
}
    
function getuserinput() {
	print("what version do you want to upgrade to ( e.g. enter: logaholic_[EDITION]_[VERSION][.tar.gz or .zip] ):\n");
	$filename = read();
	return $filename;
}

function download($filename) {
	global $dir;
	$url = "https://www.logaholic.com/logadl/$filename";
	
	$fp = fopen ("$dir/$filename", 'w+');//This is the file where we save the information
	$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
	curl_setopt($ch, CURLOPT_TIMEOUT, 50);
	curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
	//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_exec($ch); // get curl response
	curl_close($ch);
	fclose($fp);
}

function checkfilename($filename){
	# explode on '_' 
	$name_parts = explode("_",$filename);
	
	# Check and kill all uncertainties
	if(count($name_parts) != 3){
		die("Invalid package (parts)!");
	}else if(empty($name_parts[0]) || empty($name_parts[1]) || empty($name_parts[2])){
		die("Invalid package (empty)!");
	} else if($name_parts[0] != "logaholic"){
		die("Invalid package (software)!");
	} else if($name_parts[1] != "free" && $name_parts[1] != "she" && $name_parts[1] != "enterprise"){
		die("Invalid package (distribution)!");
	}

	# Congrats! Moving on to level 2 security! :D
	# continue checks with explodes on '.'
	$versionExt = explode(".",$name_parts[2]);
	if(count($versionExt) != 2 && count($versionExt) != 3){
		die("Invalid version (parts)!");
	} else if(!is_numeric($versionExt[0])){
		die("Invalid version (version)!");
	} else if(empty($versionExt[2]) && $versionExt[1] != "zip"){
		die("Invalid version (extension)!");
	} else if($versionExt[1] != "tar" || $versionExt[2] != "gz"){
		die("Invalid version (extension)!");
	}

	# Ok! ;)
	return true;
}

function copyfiles($filename) {
	global $dir, $loga_dir,$apipath;
	if(strpos($filename,".tar.gz") !== false){
		$file = str_replace(".tar.gz","",$filename);
	} else {
		$file = str_replace(".zip","",$filename);
	}

	
	system("cp -rfp $dir/$file/logaholic/* $loga_dir/.");

	# Check for API
	if(!empty($apipath)){
		system("cp -rfp $dir/$file/logaholic_api/* $apipath/.");
	}
}

function unpackfile($filename){
	global $dir;
	if(strpos($filename,".tar.gz") !== false){		
		system("cd $dir; tar -xvzf $filename");
	} else {
		system("unzip $filename");
	}
}

function removeoldinstall($filename){
	global $dir, $loga_dir,$apipath;
	# Get the filename without extension.
	$file = explode(".", $filename);
	$file = $file[0];

	# first copy the updateall.php script to the new folder so we can put it back later
	if(file_exists("$loga_dir/components/MaintenanceScripts/updateall.php")){
		system("cp -p $loga_dir/components/MaintenanceScripts/updateall.php $dir/$file/logaholic/components/MaintenanceScripts/.");
	}

	# copy mylogo.php
	if(file_exists("$loga_dir/mylogo.php")){
		system("cp -p $loga_dir/mylogo.php $dir/$file/logaholic/.");
	}

	# Copy the GeoLite2-City.mmdb
	if(file_exists("$loga_dir/components/geoip/GeoLite2-City.mmdb")){
		system("cp -p $loga_dir/components/geoip/GeoLite2-City.mmdb $dir/$file/logaholic/components/geoip/.");
	}

	# Clear the directories
	$rm_dirs = array("user_login","templates","reports","log_formats","languages","includes","images","Core");
	foreach ($rm_dirs as $remove) {
		system("rm -rf $loga_dir/$remove");
	}

	# Clear the components directory except the Maintenscript folder with only upgrade.php in it
	system("find $loga_dir/components -not -name 'components' -not -name 'MaintenanceScripts' -not -name 'upgrade.php' | xargs rm -rf");
	
	# Clear the Logaholic root with directories intact
	system("rm -f $loga_dir/* 2> /dev/null");


	# Check for API
	if(!empty($apipath)){
		system("cp -p $apipath/config.php $dir/$file/logaholic_api/.");
	}
}

function deletedownloadfiles($filename){
	global $dir;
	if(strpos($filename,".tar.gz") !== false){
		$file = str_replace(".tar.gz","",$filename);
		system("rm -rf $dir/$file.tar.gz");
		system("rm -rf $dir/$file");
	} else {
		$file = str_replace(".zip","",$filename);
		system("rm -rf $dir/$file.zip");
		system("rm -rf $dir/$file");
	}
}

if (php_sapi_name() !== 'cli') {
	die('This script can only be run from the command line');
}

if (empty($argv[1])) {
	$filename = getuserinput();
} else {
	$filename = $argv[1];
}

$apipath = "";
if (!empty($argv[2])) {
	$apipath = (substr($argv[2], -1) == "/") ? substr($argv[2],0, -1) : $argv[2];
}

# Setting to remove old files or not
$cleanup = false;

# set the directory where the file must be stored to. the files dir..
$dir = str_replace("components/MaintenanceScripts","files",dirname(__FILE__));
$loga_dir = str_replace("/files","",$dir);

checkfilename($filename);
download($filename);
if(file_exists("$dir/$filename")){
	unpackfile($filename); # unpack the downloaded file
	if($cleanup === true){
		removeoldinstall($filename);
	}
	copyfiles($filename); # copy the file to the correct location
	deletedownloadfiles($filename); # deletes unpacked folders and the download zip file
} else {
	echo ("Failed to download the file (enter: logaholic_[EDITION]_[VERSION][.tar.gz or .zip]): $filename\n");
}
?>

