- <?php
- /*
- ini_set('display_errors', 1);
- ini_set('display_startup_errors', 1);
- error_reporting(E_ALL);
- */
- session_start();
- include('config.php');
- include('habit.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;
- case 'habit_cal_daily': // get unfiltered main cal averages - output JSON
- header('Content-Type: application/json');
- if(isset($_GET['habit'])){
- $result = habit_cal_daily($_GET['habit']);
- echo $result;
- }else{
- echo "0";
- }
- break;
- case 'habit_cal_weekly': // get unfiltered main cal averages - output JSON
- header('Content-Type: application/json');
- if(isset($_GET['habit'])){
- $result = habit_cal_weekly($_GET['habit']);
- echo $result;
- }else{
- echo "0";
- }
- break;
- case 'habit_update': // get unfiltered main cal averages - output JSON
- header('Content-Type: application/json');
- if(isset($_GET['habit'])){
- habit_update($_GET['habit'], $moodlog);
- $result = habit_get_json($_GET['habit'], $moodlog, $habitlog);
- echo $result;
- }else{
- echo "0";
- }
- break;
- case 'habit_all_stats': // get unfiltered main cal averages - output JSON
- header('Content-Type: application/json');
-
- $result = habit_get_json_all( $moodlog, $habitlog );
- echo $result;
-
- 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";
- $returnstring = "<div class=\"sub-header\">$ymd2</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();
- $newtag = 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;
- case '#':
- $newtag[] = $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";
- foreach($newtag as $tag)
- $returnstring .= "<span class=\"pretaghist\" onclick=\"addFilterTag($(this).text());\">$tag</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];
- if($mood != 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]);
- $dateTime->setTime(12, 0, 0); // Set the time to 1am
- $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";
- }
-
- function getMyUrl(){
- $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
- $host = $_SERVER['HTTP_HOST'];
- $port = $_SERVER['SERVER_PORT'];
-
- // Exclude standard ports to prevent redundancy in the URL
- if (($protocol === 'http' && $port != 80) || ($protocol === 'https' && $port != 443)) {
- $url = "$protocol://$host";
- } else {
- $url = "$protocol://$host";
- }
-
- return $url;
- }
-
- ?>
-
- <html>
- <head>
-
- <link rel="stylesheet" href="/deps/all.css" >
-
- <script type="text/javascript" src="/deps/d3.v3.min.js"></script>
- <script type="text/javascript" src="/deps/cal-heatmap.min.js"></script>
- <link rel="stylesheet" href="/deps/cal-heatmap.css" />
-
- <link href="/deps/google-fonts.css" rel="stylesheet">
- <link rel="stylesheet" href="/deps/jquery-ui.css">
- <link rel="stylesheet" href="/deps/fa.css">
- <script src="/deps/jquery-1.12.4.js"></script>
- <script src="/deps/jquery-ui.js"></script>
- <link rel="stylesheet" href="/style.css" >
-
- <script src="/script.js"></script>
- <script src="/habit.js"></script>
- </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>
-
- <div class="habit-main-title">Habits</div>
-
- <div class="habit-container-wrapper">
-
-
- <?php
-
- $fileContent = file_get_contents($habitlog);
- if ($fileContent === false) {
- die("Error reading the file.");
- }
- $resultArray = habit_parse_file($fileContent);
-
- foreach ($resultArray as $section) {
- $align = "";
- $buttonClass = "";
- $buttText = "";
- if($section['Category'][0] == "d"){
-
- $type = "day";
- $cat = "(daily)";
- if($section['Category'][1] == "+"){
- $align = "good";
- $calCol = "#58e81b";
- $title1 = "Streak";
- $title2 = "Missed";
- $title3 = "Top";
- $result1 = habit_get_stat_streak($section['Activity'], $moodlog);
- $result2 = habit_get_stat_missed($section['Activity'], $moodlog);
- $result3 = habit_get_stat_top($section['Activity'], $moodlog);
-
- }
- if($section['Category'][1] == "-"){
- $align = "bad";
- $calCol = "#e81b1b";
- $title1 = "Streak";
- $title2 = "Total (Year)";
- $title3 = "Top";
- $result1 = habit_get_stat_missed($section['Activity'], $moodlog);
- $result2 = habit_get_stat_year($section['Activity'], $moodlog);
- $result3 = habit_get_stat_top_missing($section['Activity'], $moodlog);
- }
- $todayCheck = habit_check_daily($section['Activity'], $moodlog);
- if ($todayCheck) {
- $buttonClass = 'button-'.$align;
- }
- }
- if($section['Category'][0] == "w"){
- $multiplier = $section['Category'][1];
- $type = "week";
- $cat = "(weekly x $multiplier)";
- $align = "good";
- $title1 = "Streak";
- $title2 = "Missed";
- $title3 = "Top";
- $result1 = habit_get_stat_streak_week($section['Activity'], $multiplier, $moodlog);
- $result2 = habit_get_stat_missed_week($section['Activity'], $multiplier, $moodlog);
- $result3 = habit_get_stat_top_week($section['Activity'], $multiplier, $moodlog);
-
- $todayCheck = habit_check_daily($section['Activity'], $moodlog);
- $weekCount = habit_count_weekly($section['Activity'], $moodlog);
-
- if( $weekCount < $section['Category'][1] )
- if($todayCheck)
- $buttText = $weekCount;
- if($weekCount >= $multiplier)
- $buttonClass = 'button-done';
- if( $todayCheck ) {
- $buttonClass = 'button-neut';
- if($weekCount >= $multiplier)
- $buttonClass = 'button-good';
- }
-
- }
-
- // for creating the calendar
- $calendar = "";
- if($type == "day"){
- $calendar = '<div id="habit-cal-'.$section['Activity'].'" class="habit-cal-day"></div>';
- }
- if($type == "week"){
- $weekCal = create_new_weekly_cal();
- $calendar = '<div id="habit-cal-'.$section['Activity'].'" class="habit-cal-week">'.$weekCal.'</div>';
- }
-
- // echo "Category: {$section['Category']}<br />
- // <!--Value: {$section['Value']}<br />-->
- // Activity: {$section['Activity']}<br />
- // Description: {$section['Description']}<br />
- // $stats<br />
- // <br />";
- echo '
- <div class="habit-container" id="'.$section['Activity'].'">
- <div class="habit-log">
- <button class="habit-log-button '.$buttonClass.'" onClick="updateHabit(\''.$section['Activity'].'\')">'.$buttText.'</button>
- </div>
- <div class="'.$align.' habit-title">#'.$section['Activity'].' <div class="habit-timescale">'.$cat.'</div></div>
- <div class="habit-desc">'.$section['Description'].'</div>
- <div class="habit-score"><div class="score-title">'.$title1.'</div><div class="result1">'.$result1.'</div></div>
- <div class="habit-score"><div class="score-title">'.$title2.'</div><div class="result2">'.$result2.'</div></div>
- <div class="habit-score"><div class="score-title">'.$title3.'</div><div class="result3">'.$result3.'</div></div>
- '.$calendar.'
- </div>
- ';
-
- if($type == "day"){
- $urlToGet = getMyUrl();
- $urlToGet .= "/index.php?action=habit_cal_daily&habit=".$section['Activity'];
- echo ('
- <script>
- calHeatMapInstances[\''.$section['Activity'].'\'] = initializeDailyCalendar(\'#habit-cal-'.$section['Activity'].'\', {
- data: "'.$urlToGet.'",
- id: "'.$section['Activity'].'",
- legendColors: {
- min: "'.$calCol.'",
- max: "'.$calCol.'",
- },
- });
- </script>');
- }
- if($type == "week"){
- echo '<script>update_weekly_cal("'.$section['Activity'].'", '.$multiplier.');</script>';
- }
- }
-
- ?>
-
-
-
- </div>
- </div>
-
- </center>
- </body>
- </html>