Newer
Older
moodlog_web / index.php
root on 7 May 2019 16 KB Initial commit
<?php
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/
session_start();
include('config.php');
$error = "";

if(isset($_REQUEST['password']) && md5($_REQUEST['password']) == $password){
	$_SESSION['loggedin'] = true;
}

if(!isset($_SESSION['loggedin']) || isset($_GET['logout'])){
	if(isset($_SESSION['loggedin']))
		unset($_SESSION['loggedin']);
	include('login.html');
	die();
}

/***
 * actions here for API / AJAX 
 */
if(isset($_GET['action'])){
	switch ($_GET['action']) {
		case 'main_cal': // get unfiltered main cal averages - output JSON
			header('Content-Type: application/json');
			$result = main_cal();
			echo "{".$result."}";
			break;
		case 'filtered_cal': // get filtered main cal averages (filter=+test-test@test-test...) - output JSON
			header('Content-Type: application/json');
			if(isset($_GET['filter'])){
				$result = filtered_cal($_GET['filter']);
				echo "{".$result."}";
			}else{
				echo "0";
			}
			break;
		case 'date': // get specific date's log - output HTML
			if(isset($_GET['date'])){
				$result = today($_GET['date']);
				echo $result;
			}else{
				echo "0";
			}
			break;
		case 'date_average': // get specific date's average - output no.
			if(isset($_GET['date'])){
				$result = day_avg($_GET['date']);
				echo $result;
			}else{
				echo "0";
			}
			break;
		case 'latest': // get latest 5 tags - output JSON
			if(isset($_GET['tag'])){
				$result = latest($_GET['tag']);
				echo $result;
			}else{
				echo "0";
			}
			break;
		case 'top': // get top 5 tags - output JSON
			if(isset($_GET['tag'])){
				$result = toptag($_GET['tag']);
				echo $result;
			}else{
				echo "0";
			}
			break;
		case 'alltag': // get all tags in popularity order - output JSON
			$result = alltag();
			echo $result;
			break;
		case 'save':
			if(isset($_GET['log'])){ // save a new moodlog
				$result = new_log($_GET['log']);
				echo $result;
			}else{
				echo "0";
			}
			break;
		default:
			# code...
			break;
	}
	die();
}

//$result = today("2018-09-13");
//echo $result;

function today($ymd){
	global $moodlog;
	$ymd = strtotime($ymd);
	$dateTime = new \DateTime(null, new DateTimeZone('Europe/London'));
	$dateTime->setTimestamp($ymd);
	$date = $dateTime->format('Y-m-d');
	$ymd2 = date("Y-m-d", strtotime("$date"));
//echo $ymd2;

	$returnstring = "<div class=\"sub-header\">$justdate</div>\n";
	$count = 0;

	$moodfile = @fopen($moodlog, "r");
	if ($moodfile) {
	    while (($line = fgets($moodfile)) !== false) {
	    	/***
	    	 * if date < cutoff stop adding
	    	 */
	    	$cutoff = $date = strtotime(date("Y-m-d", strtotime("$ymd2 -0 day")));

	     	$newpos = array();
	     	$newneg = array();
	     	$newcon = array();
	     	$newstr = "";

	        $split1 = explode("[", $line);
	        $split2 = explode("]", $split1[1]);
	        $words = explode(" ", $split2[1]);
	        foreach($words as $word){
	        	if($word <> ""){
		        	switch (mb_substr($word[0], 0, 1)) {
		        		case '+':
		        			$newpos[] = $word;
		        			break;
		        		case '-':
		        			$newneg[] = $word;
		        			break;
		        		case '@':
		        			$newcon[] = $word;
		        			break;
		        		default:
		        			$newstr .= " $word";
		        			break;
		        	}
		        }
	        }

	        $datetime = $split1[0];
	        if(strtotime($datetime) < $cutoff)
	        	break;
	        $justdate = date("Y-m-d", strtotime($datetime));
	        if(strtotime($ymd2) == strtotime($justdate)){
	        	$count++;
		        $mood = $split2[0];
		        $fulldate = date("Y-m-d H:i", strtotime($datetime));
				$returnstring .= "<span class=\"datehist\">$fulldate</span>\n<span class=\"hpyhist\">[$mood]</span><span class=\"pretexthist\">$newstr</span>\n";

				foreach($newpos as $pos)
		       		$returnstring .= "<span class=\"preposhist\" onclick=\"addFilterPos($(this).text());\">$pos</span>\n";
		       	foreach($newneg as $neg)
		       		$returnstring .= "<span class=\"preneghist\" onclick=\"addFilterNeg($(this).text());\">$neg</span>\n";
		       	foreach($newcon as $con)
		       		$returnstring .= "<span class=\"preconhist\" onclick=\"addFilterCon($(this).text());\">$con</span>\n";
		       	$returnstring .= "<br />";
	     	}
	       	
	    }
	    fclose($moodfile);
	    return ($count > 0)? $returnstring : "0";
	} else {
	    return "!ERROR! File: ".$moodfile." doesn't exist. !ERROR!<br />";
	} 
}

function main_cal(){
	global $moodlog;
	$toreturn = "";
	
	$moodfile = @fopen($moodlog, "r");
	if ($moodfile) {
		$newtimes = array();
	    while (($line = fgets($moodfile)) !== false) {
	    	/***
	    	 * if date < cutoff stop adding
	    	 */
	    	$cutoff = $date = strtotime(date("Y-m-d", strtotime("-10 month")));

	        $split1 = explode("[", $line);
	        $split2 = explode("]", $split1[1]);

	        $datetime = $split1[0];
	        if(strtotime($datetime) < $cutoff)
	        	break;

	        $mood = $split2[0];
	        //$justdate = date("Y-m-d", strtotime($datetime));
	         //$dt2 = explode("-", $datetime);
		 //$dtd = explode(" ", $dt2[2]);
		 //$dateTime = new \DateTime(null, new DateTimeZone('Europe/London'));
		 //$dateTime->setDate($dt2[0], $dt2[1], $dtd[0]);
		 //$justdate = $dateTime->format('Y-m-d');
		$dtd = explode(" ", $datetime);
		$justdate = $dtd[0];

		$newtimes[$justdate][] = $mood;
	    }
	    fclose($moodfile);
	    foreach($newtimes as $date=>$md){
	    	$average = round(array_sum($md) / count($md));
	    	
//$datetime = strtotime($date);
		$dt22 = explode("-", $date);
                $dtd2 = explode(" ", $dt22[2]);
                $dateTime = new \DateTime(null, new DateTimeZone('Europe/London'));
                $dateTime->setDate($dt22[0], $dt22[1], $dtd2[0]);
                $justdate2 = $dateTime->getTimestamp();

	    	$toreturn .= "\"$justdate2\":$average,";
	    }

	    return substr($toreturn, 0, -1);
	} else {
	    return "!ERROR! File: ".$moodfile." doesn't exist. !ERROR!<br />";
	} 
}

function filtered_cal($filter){
	global $moodlog;
	$toreturn = "";

	$pattern = '/(?=[+-@][a-zA-Z0-9])/';
	$limit = -1;
	$flags = PREG_SPLIT_NO_EMPTY;
	$tags = preg_split ($pattern, $filter, $limit, $flags);

	$moodfile = @fopen($moodlog, "r");
	if ($moodfile) {
		$newtimes = array();
	    while (($line = fgets($moodfile)) !== false) {
	    	/***
	    	 * if date < cutoff stop adding
	    	 */
	    	$cutoff = $date = strtotime(date("Y-m-d", strtotime("-10 month")));

	        $split1 = explode("[", $line);
	        $split2 = explode("]", $split1[1]);

	        $datetime = $split1[0];
	        if(strtotime($datetime) < $cutoff)
	        	break;

	        $mood = $split2[0];
	        $justdate = date("Y-m-d", strtotime($datetime));

	        $words = explode(" ", $split2[1]);
	        
	        foreach($words as $word){
	        	$word = trim($word);
	        	if (in_array($word, $tags, true))
	        		$newtimes[$justdate][] = $mood;
	        }
	        
	    }
	    fclose($moodfile);
	    foreach($newtimes as $date=>$md){
	    	$average = round(array_sum($md) / count($md));
	    	$datetime = strtotime("$date");
	    	$toreturn .= "\"$datetime\":$average,";
	    }

	    return substr($toreturn, 0, -1);
	} else {
	    return "!ERROR! File: ".$moodfile." doesn't exist. !ERROR!<br />";
	} 
}

function day_avg($ymd){
	global $moodlog;
	$mood = array();
	$average = 0;

	$moodfile = @fopen($moodlog, "r");
	//$date = date("Y-m-d", $ymd);
	//$date = date("Y-m-d", strtotime("$date +1 day"));

	$dateTime = new \DateTime(null, new DateTimeZone('Europe/London'));
	$dateTime->setTimestamp($ymd);
	$date = $dateTime->format('Y-m-d');
	$date = date("Y-m-d", strtotime("$date"));

	//$currentTime = new DateTime();
	//$currentTime = DateTime::createFromFormat( 'U', $ymd );
	//$date = $currentTime->format( 'c' );

	$cutoff = strtotime("$date -0 day");
	
	//echo $date." cutoff: ".$cutoff;
	//$date = new DateTime();
	//$date->setTimestamp($ymd);
	//echo $date->format('U = Y-m-d H:i:s') . "\n";

	if ($moodfile) {
	    while (($line = fgets($moodfile)) !== false) {

	        $split1 = explode("[", $line);
	        $split2 = explode("]", $split1[1]);

	        $datetime = $split1[0];
	        if(strtotime($datetime) < $cutoff)
	        	break;

	        if(strncmp($date, $datetime, 10) == 0 )
		        $mood[] = $split2[0];	
	    }
	 //   echo "$ymd ";
	 //   echo $date;
	 //   print_r($mood);
	    if($mood)
	    	$average = round(array_sum($mood) / count($mood));
	    return $average;
	} else {
	    return "0";
	} 
}

function latest($tag){
	global $moodlog;
	$count = 0;
	

	$newpos = array();
 	$newneg = array();
 	$newcon = array();

	$moodfile = @fopen($moodlog, "r");
	if ($moodfile) {
	    while (($line = fgets($moodfile)) !== false) {

	     	$newstr = "";

	        $split1 = explode("[", $line);
	        $split2 = explode("]", $split1[1]);
	        $words = explode(" ", $split2[1]);
	        foreach($words as $word){
	        	if($word <> ""){
		        	switch (mb_substr($word[0], 0, 1)) {
		        		case '+':
		        			$newpos[] = trim($word);
		        			break;
		        		case '-':
		        			$newneg[] = trim($word);
		        			break;
		        		case '@':
		        			$newcon[] = trim($word);
		        			break;
		        	}
		        }
	        }

	       
	       	
	    }
	    fclose($moodfile);
	    switch ($tag) {
			case 'pos':
				$newpos = array_unique($newpos);
				$newArray = array_slice($newpos, 0, 5, false);
				break;
			case 'neg':
				$newneg = array_unique($newneg);
				$newArray = array_slice($newneg, 0, 5, false);
				break;
			case 'con':
				$newcon = array_unique($newcon);
				$newArray = array_slice($newcon, 0, 5, false);
				break;
			default:
				return 0;
				break;
		}
		return json_encode($newArray);
	    
	} else {
	    return "!ERROR! File: ".$moodfile." doesn't exist. !ERROR!<br />";
	} 
}

function toptag($tag){
	global $moodlog;
	$count = 0;
	

	$newpos = array();
 	$newneg = array();
 	$newcon = array();

	$moodfile = @fopen($moodlog, "r");
	if ($moodfile) {
	    while (($line = fgets($moodfile)) !== false) {

	     	$newstr = "";

	        $split1 = explode("[", $line);
	        $split2 = explode("]", $split1[1]);
	        $words = explode(" ", $split2[1]);
	        foreach($words as $word){
	        	if($word <> ""){
		        	switch (mb_substr($word[0], 0, 1)) {
		        		case '+':
		        			$newpos[] = trim($word);
		        			break;
		        		case '-':
		        			$newneg[] = trim($word);
		        			break;
		        		case '@':
		        			$newcon[] = trim($word);
		        			break;
		        	}
		        }
	        }

	       
	       	
	    }
	    fclose($moodfile);
	    switch ($tag) {
			case 'pos':
				$acv=array_count_values($newpos); 
				arsort($acv); 
				$result=array_keys($acv); 
				$newArray = array_slice($result, 0, 5, false);
				break;
			case 'neg':
				$acv=array_count_values($newneg); 
				arsort($acv); 
				$result=array_keys($acv); 
				$newArray = array_slice($result, 0, 5, false);
				break;
			case 'con':
				$acv=array_count_values($newcon); 
				arsort($acv); 
				$result=array_keys($acv); 
				$newArray = array_slice($result, 0, 5, false);
				break;
			default:
				return 0;
				break;
		}
		return json_encode($newArray);
	    
	} else {
	    return "!ERROR! File: ".$moodfile." doesn't exist. !ERROR!<br />";
	} 
}

function alltag(){
	global $moodlog;
	$count = 0;
	

	$newtag= array();

	$moodfile = @fopen($moodlog, "r");
	if ($moodfile) {
	    while (($line = fgets($moodfile)) !== false) {

	     	$newstr = "";

	        $split1 = explode("[", $line);
	        $split2 = explode("]", $split1[1]);
	        $words = explode(" ", $split2[1]);
	        foreach($words as $word){
	        	if($word <> ""){
		        	switch (mb_substr($word[0], 0, 1)) {
		        		case '+':
		        			$newtag[] = trim($word);
		        			break;
		        		case '-':
		        			$newtag[] = trim($word);
		        			break;
		        		case '@':
		        			$newtag[] = trim($word);
		        			break;
		        	}
		        }
	        }  	
	    }
	    fclose($moodfile);
	    
		$acv=array_count_values($newtag); 
		arsort($acv); 
		$result=array_keys($acv); 
		
		return json_encode($result);
	    
	} else {
	    return "!ERROR! File: ".$moodfile." doesn't exist. !ERROR!<br />";
	} 
}

function new_log($log){
	global $moodlog;
	$pattern = '/(?=[+-@|][a-zA-Z0-9])/';
	$limit = -1;
	$flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
	$result = preg_split ($pattern, $log, $limit, $flags);
	//print_r($result);

	$timestamp = date("Y-m-d H:i");
	$no = rtrim($result[0], "|");
	$msg = "";
	$pos = "";
	$neg = "";
	$con = "";

	foreach($result as $item){
		switch ($item[0]) {
			case '|':
				$msg .= substr($item, 1)." ";
				break;
			case '+':
				$pos .= "$item ";
				break;
			case '-':
				$neg .= "$item ";
				break;
			case '@':
				$con .= "$item ";
				break;
		}
	}
	$toadd = "$timestamp [$no] ".$msg.$pos.$neg.$con."\n";
	$toadd .= file_get_contents($moodlog);
	file_put_contents($moodlog, $toadd);
	echo "1";
}

?>

<html>
	<head>

		<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
		<script type="text/javascript" src="https://d3js.org/d3.v3.min.js"></script>
		<script type="text/javascript" src="https://cdn.jsdelivr.net/cal-heatmap/3.3.10/cal-heatmap.min.js"></script>
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/cal-heatmap/3.3.10/cal-heatmap.css" />
		<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700" rel="stylesheet">
		<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
		<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
  		<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  		<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
		<link rel="stylesheet" href="style.css" >
	</head>
	<body>
		
		<center>
			<?php if($error <> ""){echo $error; } ?>

			<div class="banner">
				<div class="header"><a href="/?logout"><i class="fas fa-heartbeat" ></i></a> moodlog.txt</div>

				<div class="new-log">
					
					  <input type="range" id="happyval" value="5" min="1" max="10"/>
					  <input  class="input" id="tags" placeholder="(+,-,@) description"/>
					  <input type="button" value="+" onClick="updatePretext();"/>
					  <input type="button" value="add" class="add" onClick="submitMood();"/>
					
				</div>
				<div class="preview">
					<span class="date">2018-09-11 20:27</span><span class="hpyno">[5]</span><span class="pretext" onClick="updatePretext();"></span></div>

				<div class="filter" style="display:none">
					<span class="filtitle">Filters:</span>
					<span class="fas fa-search" style="float:right;font-size:15px;" onclick="applyFilters();"></span>
				</div>
			</div>

			<div id="cal-heatmap"></div>

			<div class="top10s">
				<div class="toppos">
					<div class="sub-header">Top 5 positive</div>
				</div>
				<div class="topneg">
					<div class="sub-header">Top 5 negative</div>
				</div>
				<div class="topcon">
					<div class="sub-header">Top 5 context</div>
				</div>
				<div class="latpos">
					<div class="sub-header">Latest 5 positive</div>
				</div>
				<div class="latneg">
					<div class="sub-header">Latest 5 negative</div>
				</div>
				<div class="latcon">
					<div class="sub-header">Latest 5 context</div>
				</div>
			</div>

			<div class="fullday">
				<div class="previewhist">
					
					<?php
						$result = today(date("Y-m-d"));
						if($result != "0")
							echo $result;
					?>
					
				</div>
			</div>
		</center>

		<script src="script.js"></script>
 
	</body>
</html>