<?php

$dont_close_session = true;
$accessControl = array(
	"ProfileRequired" => true
);
# When we want to do an export of the data set the file as a stream
if(!empty($_REQUEST['export']) || isset($_REQUEST["update_country"])) { $accessControl["StreamFile"] = true; }

require_once '../../AccessControl.php';


// this is an url select helper
if (isset($_REQUEST['qurl'])) {
    $val = $_REQUEST['qurl'];
    if (substr($val, 0, 1) != "/") {
        $val = "%" . $val;
    }
    //if (strpos($val, "?")!==false) {
    //    exit('{ "Status" : "Error", "Callout" : true, "Message": "A KPI should not contain a question mark." }');
    //} else {
    $query = "select url as item from {$profile->tablename_urls} where url like " . $db->Quote(
            $val . '%'
        ) . " order by id asc limit 10";

    if (CheckIfTableExists($profile->tablename_urls)) {
        $res = $db->Execute($query) or die(
        json_encode(
            array("Status" => "Error", "Callout" => true, "Message" => $db->ErrorMsg())
        )
        );
    }
    $returndata = array($val);
    while ($row = $res->FetchRow()) {
        $returndata[] = $row['item'];
    }
    echo '{ "Status" : "Success", "Data": ' . json_encode($returndata) . ' }';
    exit();
    //}
}


// this saves the profile
if (isset($_REQUEST['saveprofile'])) {

	if ($_REQUEST['conf']=="newcnf") {
		$editprofile = new SiteProfile();
	} else {
		$editprofile = $profile;
	}

	if (!isset($_REQUEST['new'])) {
		$new = 0;
	} else {
		$new= $_REQUEST['new'];
	}

	$saved = "";
	$saveerror = false;
	include_once "../../includes/saveprofile.php";
	if ($saveerror==false) {
		echo '{ "Status" : "Success", "Message": "'.$saved.'", "NewName" : "'.$editprofile->profilename.'" }';
	} else {
		echo '{ "Status" : "Error", "Message": "'.$saved.'" }';
	}

}

//delete data from profile
if(!empty($_REQUEST['deletedatarange'])) {
    $what = $_REQUEST["what"];

    set_time_limit(86400);

    if (!$validUserRequired || ($session->canEditProfiles() !== null && $session->canUpdateLogs() !== null)) {
        if ($what == 4) {
            $f = mktime(0, 0, 0, $_REQUEST["fmonth"], $_REQUEST["fday"], $_REQUEST["fyear"]);
            $t = mktime(23, 59, 59, $_REQUEST["tmonth"], $_REQUEST["tday"], $_REQUEST["tyear"]);

            $m = DeleteDataFiles($profile, $f, $t);
        } else {
            $m = DeleteRange($profile, $what);
        }
        echo '{ "Status": "Success", "Message" : "' . $m . '"}';
    } else {
        $m = _SORRY_NO_PERMISSIONS;
        echo '{ "Status": "Error", "Message" : "' . $m . '"}';
    }
}

//delete all database data from profile
if(!empty($_REQUEST['deletedatabase'])) {
	if ($profile->profileloaded) {
        if (!$validUserRequired || ($session->canEditProfiles() !== null && $session->canUpdateLogs() !== null)) {
            deleteDataTable($profile);

            createDataTable($profile);

            # Reset data fields in the profiles table
            ResetProfileSettings($profile);


            $m = DeleteDataFiles($profile);
            $m .= "" . _DELETED_DB_TABLES . " " . _AND_SUMMARIES_PROFILE_SAVED . " ";
            echo '{ "Status": "Success", "Message" : "' . $m . '"}';
        } else {
            $m = _SORRY_NO_PERMISSIONS;
            echo '{ "Status": "Error", "Message" : "' . $m . '"}';
        }
    }
}

//delete profile
if(!empty($_REQUEST['deleteprofile'])) {
	if ($profile->profileloaded) {
        if (!$validUserRequired || ($session->canEditProfiles() !== null && $session->canUpdateLogs() !== null)) {
            $m = "";
            $status = "Success";

            $query = "Delete from " . TBL_PROFILES . " where profileid = " . $profile->profileid;
            if (!$db->Execute($query)) {
                die('{ "Status": "Error", "Message" : "' . _COULDNT_DELETE_PROFILE . " " . $db->ErrorMsg() . '"}');
            } else {
                $m .= _DELETED_PROFILE . ": <b>" . $profile->profilename . "</b>";
            }
            $m .= deleteProfileData($profile->profilename);

            if (!$db->Execute("drop table " . $profile->tablename)) {
                $m .= _COULDNT_DROP_TABLE . " " . $profile->tablename . ", " . $db->ErrorMsg();
                $status = "Error";
            } else {
                $m .= _DROPPED_DB_TABLES . ": " . $profile->profilename;
            }

            $m .= deleteDataTable($profile);

            # now delete the remaining files from the data directory
            $m .= DeleteProfileFiles($profile);

            $m .= _SUMMARY_TABLES_DROPPED . ".<br>" . _DONE;

            # finally, remove the profile from the users profile lists
            $m .= DeleteProfileFromUsers($profile->profilename);


            unset($_SESSION['profileobject']);
            unset($_SESSION['profilename']);
            unset($_SESSION['userinfo']);

            echo '{ "Status": "' . $status . '", "Message" : "' . $m . '"}';
        } else {
            $m = _SORRY_NO_PERMISSIONS;
            echo '{ "Status": "Error", "Message" : "' . $m . '"}';
        }
	}
}


//show database info
if(!empty($_REQUEST['databaseinfo'])) {
	if ($q = $db->Execute("SELECT table_schema \"Data Base Name\", table_name, sum( data_length + index_length ) / 1024 / 1024 \"Data Base Size in MB\" FROM information_schema.TABLES where table_schema='$DatabaseName' and (table_name='$profile->tablename' or table_name like '$profile->tablename\_%') GROUP BY table_schema, table_name")) {
		//echo "SELECT table_schema \"Data Base Name\", table_name, sum( data_length + index_length ) / 1024 / 1024 \"Data Base Size in MB\" FROM information_schema.TABLES where table_schema='$DatabaseName' and (table_name='$profile->tablename' or table_name like '$profile->tablename\_%') GROUP BY table_schema, table_name";            
		$chk=$q->FetchRow();
		$info = _TOTAL_SIZE_OF_THIS_PROFILE." ".number_format($chk[2],0)." MB. ";


		$q = $db->Execute("select count(*) as hits, MIN(timestamp) as minstamp, MAX(timestamp) as maxstamp from $profile->tablename");
		$chk=$q->FetchRow();

		$from = $chk['minstamp'];
		$to = $chk['maxstamp'];

		$info .= _THERE_ARE." {$chk['hits']} "._RECORDS_IN_MAIN_SPANNING." ";
		$info .= date("Y-m-d",$chk['minstamp']) . " to ";
		$info .= date("Y-m-d,  H:i:s",$chk['maxstamp']) . ". ("._SEE_MORE_STATISTICS_BELOW.")<br><br>";
		$info .= _PROFILE_STRUCTURE_VERSION_IS.": ". $profile->structure_version;


		$query= "SELECT table_name, table_rows, sum( data_length + index_length ) / 1024 / 1024 \"Data Base Size in MB\" ";
		$query .= "FROM information_schema.TABLES where table_schema='$DatabaseName' and (table_name='$profile->tablename' or table_name like '$profile->tablename\_%') GROUP BY table_name, table_rows";
		
		$qe = $db->execute($query);
		
		$d = array();
		$i = 0;
		while($rows = $qe->fetchRow()){
			$d[$i][0] = $rows[0];
			$d[$i][1] = number_format($rows[1]);
			$d[$i][2] = number_format($rows[2]);
			$i ++;
		}

		$newdata = array();
		$newdata["Status"] = "Success";
		$newdata["info"] = $info;
		$newdata["data"] = $d;
		echo json_encode($newdata);
	}
}

// this handles the dashboard reset/delete
if(!empty($_REQUEST['restoredefaultdashboard'])) {
	$profile->setDefaultDashboard();
	echo '{ "Status": "Success", "Message": "'._YOUR_DEFAULT_DASHBOARD_HAS_BEEN_RESTORED.'" }';
}
if(!empty($_REQUEST['deletedashboards'])) {
	$profile->dashboards = array();
	$profile->Save();
	echo '{ "Status": "Success", "Message": "'. _DASHBOARDS_REMOVED .'" }';
}

# this does exporting
if(!empty($_REQUEST['export'])) {
    if (!$validUserRequired || $session->canUpdateLogs() !== null) {
        # Export the .gzipped backup file.
        set_time_limit(3600 * 5);

        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');

        $location = "files/" . $profile->profilename . "_export";
        $path = logaholic_dir() . $location;
        if (!file_exists($path)) {
            mkdir($path);
        }

        $from = explode("-", $_REQUEST["fromDate"]);
        $from = mktime(0, 0, 0, $from[1], $from[0], $from[2]);

        $to = explode("-", $_REQUEST["toDate"]);
        $to = mktime(23, 59, 59, $to[1], $to[0], $to[2]);


        $days_in_file = 1;
        $mode = $_REQUEST['mode'];

        $ndays = round(($to - $from) / (86400 * $days_in_file));
        $i = 0;
        $finalto = $to;
        $to = $from;
        $files = array();
        //ob_start();
        while ($i < $ndays) {
            $from = $to;
            $to = $from + (86400 * $days_in_file);

            $q = $db->Execute(
                "SELECT a.timestamp, v.ipnumber AS ipnumber, u.url AS url, up.params AS params, a.status, a.bytes, r.referrer AS referrer, rp.params AS refparams, b.useragent AS useragent FROM {$profile->tablename} as a, {$profile->tablename_visitorids} AS v, {$profile->tablename_urls} AS u, {$profile->tablename_urlparams} AS up, {$profile->tablename_referrers} AS r, {$profile->tablename_refparams} AS rp, {$profile->tablename_useragents} AS b WHERE a.timestamp >= " . $db->Quote(
                    $from
                ) . " and a.timestamp <= " . $db->Quote(
                    $to
                ) . " AND (a.visitorid = v.id AND a.url = u.id AND a.params = up.id AND a.referrer = r.id AND a.refparams = rp.id AND a.useragentid = b.id) ORDER BY a.timestamp"
            );

            $fname = "/{$profile->profilename}." . date("Ymd", $from) . date("-Ymd", $to) . ".$mode.gz";
            $bupfile = $path . $fname;

            $fp = gzopen($bupfile, "w");
            if ($mode == "csv") {
                # Write a header row
                $buffer = "\"IP number\",\"Date\",\"URL\",\"Status\",\"Bytes\",\"Referrer\",\"Useragent\"\n"; //HELP!
                gzwrite($fp, $buffer);
            }
            while ($data = $q->FetchRow()) {
                if ($data["refparams"] == "?") {
                    $data["refparams"] = "";
                }

                $date = date("[d/M/Y:H:i:s +0000]", $data["timestamp"]);
                if ($mode == "csv") {
					$buffer= "\"$data[ipnumber]\",\"$date\",\"".$data["url"].$data["params"]."\",\"$data[status]\",\"$data[bytes]\",\"".$data["referrer"].$data["refparams"]."\",\"".$data["useragent"]."\"\n"; 
				} else {
					$buffer= "$data[ipnumber] - - $date \"GET ".$data["url"].$data["params"]." HTTP/1.1\" ".$data["status"]." ".$data["bytes"]." \"".$data["referrer"].$data["refparams"]."\" \"".$data["useragent"]."\"\n";
				}
				gzwrite ($fp, $buffer);
			}
			gzclose ($fp);
			$files[$i][0] = "<a href='$location$fname'>$fname</a>";
			$files[$i][1] = number_format((filesize($bupfile)/1024),2)." kb";
			Stream(json_encode(array($files[$i][0], $files[$i][1])));

			$i++;

			//lgflush();
		}
		if ($mode=="csv") {
			$msg = ""._OK_CSV_FILE_WRITTEN_IN." <b>$path</b>.". _CSV_OK_HELP_LIST;
		} else {
			$msg = _EXPORTED_DATA_TO_PATH . ": <b>$path/</b>.";    
		}
		$msg .= " ". _RECOMMEND_REMOVE ."<P>";
		
		$res = array("Status" => "Success", "Message" => $msg);	    
		Stream(json_encode($res));
	}
}

# Remove the exported files
if(!empty($_REQUEST['deleteexport'])) {
	$location = "files/".$profile->profilename."_export";
	$path = logaholic_dir(). $location;

	$files = glob($path . "/*");
	foreach ($files as $file) {
		unlink($file);
	}

	echo json_encode(array("Status" => "Success", "Message" => _REMOVED_EXPORTED_FILES));
}


//this updates country info in the table
if (isset($_REQUEST['update_country'])) {	
	if ($profile->profileloaded) {
        if (!$validUserRequired || $session->canUpdateLogs() !== null) {
            $from = explode("-", $_REQUEST["fromDate"]);
            $from = mktime(0, 0, 0, $from[1], $from[0], $from[2]);
            $to = explode("-", $_REQUEST["toDate"]);
            $to = mktime(23, 59, 59, $to[1], $to[0], $to[2]);

            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');

            include "../../includes/update_countries.php";
            $uc = new UpdateCountries();
            $uc->DisplayProgress();
            $uc->UpdateRange($from, $to);
            exit();
        } else {
            echo "<div class=\"indentbody\">";
            echoWarning(_SORRY_NO_PERMISSIONS);
            echo "<P>&nbsp;</P></div>";
        }
	}
}

// this deals with email alerts
if (isset($_REQUEST['emailalerts'])) {
	include_once "../../includes/emailalerts.php";
	$e = new EmailAlerts();
	# If this request is set then we are receiving a request the 'Send Email Alerts Now' button
	if (isset($_POST['testalerts'])) {
		$salerts = $e->SendAlerts(true);
		if(!empty($salerts)){
			foreach ($salerts as $message) {
				echo $message;
			}
		}

		if($e->send == 0){
			echoNotice(_NOTHING_TO_SEND);
		}
	}

	if (isset($_REQUEST['del'])) {
		$e->DeleteAlert($_REQUEST['del']);    
	}

	if (!empty($_POST['email']) && !empty($_POST['emailinterval'])) {
		$e->StoreAlert($_POST);      
	}
	$e->ShowAlerts();
	$e->CreateAlert();
	$e->FootNote(); 

	exit(); 
}

if (!empty($_POST['email']) && !empty($_POST['emailinterval'])) {
	$e->StoreAlert($_POST);      
}