<?php
// ics_attachment.php
// RJM Programming
// November, 2016
// Based on PHPtoICS.php at https://gist.github.com/vtedesco/5671155 ... in the last if ... thanks
if (isset($_GET['msg'])) {
$pcont=@file_get_contents("ics_attachment.php");
$pbits=explode("/" . "/ " . $_GET['msg'] . " ", explode('?' . '>', $pcont)[0]);
if (sizeof($pbits) > 1) {
  $postpbits=explode("/" . "/ ", explode("/" . "/ " . (1 + $_GET['msg']) . " ", $pbits[-1 + sizeof($pbits)])[0]);
  $msg="";
  $okay=true;
  for ($i=0; $i<sizeof($postpbits); $i++) {
    if (substr($postpbits[$i],0,9) == "999999999") {
      $okay=false;
    } else if ($okay) {
      $msg.=$postpbits[$i];
    }
  }
  echo "<!doctype html>
<html>
<head>
<title>Calendar *.ics file creation - RJM Programming - November, 2016</title>
</head>
<body style='background-color:yellow;'><p>" . $msg . "</p></body></html>";
} else {
  echo "";
}
} else if (!isset($_POST['id'])) {
date_default_timezone_set('Australia/Perth');	
$qbits=@file_get_contents("ics_attachment.php");
$msgno=1;
while (strpos($qbits, "/" . "/ " . $msgno . " ") !== false) {
  $msgno++;
}
echo "<!doctype html>
<html>
<head>
<title>Calendar *.ics file creation - RJM Programming - November, 2016</title>
<link href='//www.rjmprogramming.com.au/PHP/emboss_h1.css' rel='stylesheet' type='text/css'>
<style>
input { width:40%; }
</style>
<script type='text/javascript'>
function dodates() {
  var dd=new Date();
  var qw=eval((eval(dd.toTimeString().replace('-',' ').replace('+',' ').split(' ')[2]) - eval(dd.toTimeString().replace('-',' ').replace('+',' ').split(' ')[2] % 100)) / 100) + eval((0.0 + eval(dd.toTimeString().replace('-',' ').replace('+',' ').split(' ')[2] % 100)) / 60.0);
  if (dd.toTimeString().indexOf('+') != -1) qw=-qw;
  document.getElementById('tz').value=qw;
  document.getElementById('datestart').value=dd.getFullYear() + ('0' + eval(1 + dd.getMonth())).slice(-2) + ('0' + dd.getDate()).slice(-2) + ':' + dd.toTimeString().split(' ')[0].replace(/:/g,'');
  document.getElementById('dateend').value=dd.getFullYear() + ('0' + eval(1 + dd.getMonth())).slice(-2) + ('0' + dd.getDate()).slice(-2) + ':' + dd.toTimeString().split(' ')[0].replace(/:/g,'');
  document.getElementById('title').focus();
}
</script>
</head>
<body style='background-color:yellow;' onload=' dodates(); '>
<h1>Create Calendar iCal File</h1>
<h3>RJM Programming</h3>
<h3>November, 2016</h3>
<h4>Thanks to <a target=_blank title='https://gist.github.com/vtedesco/5671155' href='https://gist.github.com/vtedesco/5671155'>https://gist.github.com/vtedesco/5671155</a></h4>
<form action='./ics_attachment.php' method='POST'>
<input type='hidden' id='tz' name='tz' value='-10'></input>
<input type='hidden' id='id' name='id' value='" . $msgno . "'></input><br><br>
Title: <input type='text' id='title' name='title' value=''></input><br><br>
Address: <input type='text' id='address' name='address' value=''></input><br><br>
Description: <input type='text' id='description' name='description' value=''></input><br><br>
Start Date (YYYYmmdd:HH24MISS) Local Time: <input type='text' id='datestart' name='datestart' value='" . date("Ymd:His") . "'></input><br><br>
End Date (YYYYmmdd:HH24MISS) Local Time: <input type='text' id='dateend' name='dateend' value='" . date("Ymd:His") . "'></input><br><br>
Subtitle: <input type='text' id='stage' name='stage' value=''></input><br><br>
Event<br>Recall<br>Text: <textarea rows=12 cols=80 name='eventwords' id='eventwords' value=''></textarea><br><br>
<input type='submit' value='Create iCal Calendar Entry' style='background-color:pink;'></input>
<input type='text' id='junk' value='' style='margin-left:-98765px;width:1px;height:1px;'></input>
</form>
</body>
</html>
";
} else {
if (isset($_POST['eventwords']) && isset($_POST['id'])) {
$ptmsg=explode(" ", "/" . "/ " . $_POST['id'] . " " . urldecode($_POST['eventwords']));
//echo sizeof($ptmsg);
if (sizeof($ptmsg) > 3) {
if ($ptmsg[2] != "") {
//echo "here";
//exit;
file_put_contents("ics_attachment.php", explode('?' . '>', file_get_contents("ics_attachment.php"))[0] . "\n/" . "/ " . $_POST['id'] . " " . str_replace("\n", "\n/" . "/ ", str_replace('?' . '>', '', urldecode($_POST['eventwords']))) . "\n" . "?" . ">");
} else {
$x="";
}
} else {
$x="";
}
}
// Fetch vars
$event = array(
	'id' => $_POST['id'],
	'title' => urldecode($_POST['title']),
    'address' => urldecode($_POST['address']),
	'description' => urldecode($_POST['description']),
	'datestart' => $_POST['datestart'],
	'dateend' => $_POST['dateend'],
	'address' => urldecode($_POST['stage'])
);
// iCal date format: yyyymmddThhiissZ
// PHP equiv format: Ymd\This
// The Function
function dateToCal($time) {
  date_default_timezone_set('UTC');	
  //echo "\n" . date('Ymd\This', $time) . 'Z';
  return date('Ymd\This', $time) . 'Z';
}
function tzbit($ts) {
  $outts=$ts;
  if (isset($_POST['tz'])) {
    if ($_POST['tz'] != "") {
      $di="PT" . str_replace("-","",urldecode($_POST['tz'])) . "H";
      $parsed_date = DateTime::createFromFormat('Ymd:His', $ts);
      if (strpos(urldecode($_POST['tz']), "-") !== false) {
      $parsed_date->sub(new DateInterval($di));
      } else {
      $parsed_date->add(new DateInterval($di));
      }
      $outts = $parsed_date->format('Ymd:His');
      //echo $outts . " " . $di . " ";
    }
  }
  return $outts;
}  
// Build the ics file
$ical = 'BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTEND:' . str_replace(':','T',tzbit($event['dateend'])) . 'Z
UID:' . md5($event['title']) . '
DTSTAMP:' . time() . '
LOCATION:' . addslashes($event['address']) . '
DESCRIPTION:' . addslashes($event['description']) . '
URL;VALUE=URI:http://www.rjmprogramming.com.au/PHP/ics_attachment.php?msg=' . $event['id'] . '
SUMMARY:' . addslashes($event['title']) . '
DTSTART:' . str_replace(':','T',tzbit($event['datestart'])) . 'Z
END:VEVENT
END:VCALENDAR';
//echo $ical;
//exit;
//set correct content-type-header
if ($event['id']) {
	header('Content-type: text/calendar; charset=utf-8');
	header('Content-Disposition: attachment; filename=rjmprogramming-event.ics');
	echo $ical;
} else {
	// If $id isn't set, then kick the user back to home. Do not pass go, and do not collect $200.
	header('Location: /');
}
}
// -1 No message
// 999999999 No message
?>