<?php

error_reporting(E_ALL | E_STRICT);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, "assert_callcack");

function log_event($result)
{
	return;
	print('--- <br />');
	$lines = explode("\n", $result['calendardata']);
	print("$lines[0]<br />");
	foreach ($lines as $line){
		print("$line<br />");
	}
}

$db = new SQLite3(getenv("SURGEMAIL_ROOT").getenv("CALDAV_DB"));

$count1 = 0;
$count1a = 0;
$count1b = 0;
$count2 = 0;

$results = $db->query('SELECT * FROM calendarobjects WHERE calendardata LIKE "%NaN0%";');
while ($result = $results->fetchArray()) {
		log_event($result);
		$count1a++;
}
$results = $db->query('SELECT * FROM calendarobjects WHERE calendardata LIKE "%DTSTART:' . chr(0x0a) . '%";');
while ($result = $results->fetchArray()) {
		log_event($result);
		$count1b++;
}
$count1 = $count1a + $count1b;

if($count1==0){
	print("no invalid event records");
	return;
}

if(!$_GET['action_it']){
	print("$count1 invalid event records found (type_nan=$count1a type_blank=$count1b) ");
	return;
}

$db->query('DELETE FROM calendarobjects WHERE calendardata LIKE "%NaN0%";');
$db->query('DELETE FROM calendarobjects WHERE calendardata LIKE "%DTSTART:' . chr(0x0a) . '%";');

$results = $db->query('SELECT * FROM calendarobjects WHERE calendardata LIKE "%NaN0%";');
while ($result = $results->fetchArray()) {
		log_event($result);
		$count2++;
}
$results = $db->query('SELECT * FROM calendarobjects WHERE calendardata LIKE "%DTSTART:' . chr(0x0a) . '%";');
while ($result = $results->fetchArray()) {
		log_event($result);
		$count2++;
}

if($count2>0){
	$removed = $count1-$count2;
	print("$removed invalid records removed, $count2 remaining?? (type_nan=$count1a type_blank=$count1b)");
	return;
}

print("$count1 invalid records removed (type_nan=$count1a type_blank=$count1b) ");

