<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

/*
* Usage : inserts a calendar event into a6 caldav.
*/

define('APP_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
set_include_path(APP_ROOT . "../../application/models/" . PATH_SEPARATOR . APP_ROOT . "../../library/" . PATH_SEPARATOR . APP_ROOT . "../../" . PATH_SEPARATOR . APP_ROOT . "../../library/Atmail/CalDav" . PATH_SEPARATOR . "library/" . PATH_SEPARATOR . get_include_path());

//Error reporting on
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);

// Lets give the script some ram!
// remove php time limit
ini_set('memory_limit', -1);
set_time_limit(0);

mb_internal_encoding('UTF-8');
iconv_set_encoding("internal_encoding", "UTF-8");//setting gave grief at some point, i suspect it was surrounding Lucene, but needed for ZF mime header decoding. this doesnt work, possible because conflicts with php.ini setting
iconv_set_encoding("input_encoding", "BASE-64");
iconv_set_encoding("output_encoding", "UTF-8");

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->setFallbackAutoloader(true);
$loader->suppressNotFoundWarnings(false);


$siteBaseUrl = substr($_SERVER["SCRIPT_NAME"],0,strpos($_SERVER["SCRIPT_NAME"],'index.php'));
Zend_Registry::set( 'siteBaseUrl', $siteBaseUrl );

//Load general functions
Zend_Loader::loadFile('Atmail/General.php', null, true);
Zend_Loader::loadFile('Atmail/RenderHelpers.php', null, true);
Zend_Loader::loadFile('Atmail/Exception.php', null, true);

// Get database configuration    
$dbConfig = new Zend_Config_Ini('config/dbconfig.ini', 'production');
Zend_Registry::set('dbConfig', $dbConfig);
$dbAdapter = dbAdapterFactory($dbConfig);
Zend_Db_Table::setDefaultAdapter($dbAdapter);
Zend_Registry::set('dbAdapter', $dbAdapter);

//Get main configuration from database
$config = new Atmail_Config_Mysql($dbConfig, true);
Zend_Registry::set('config', $config);
$locale = new Zend_Locale();
Zend_Registry::set('Zend_Locale', $locale);
session_name('ATMAIL6');

// Load the CalDavUrl from the DB
$cal_url = $config->defaultUserSettings['CalDavUrl'];

unset($config);
unset($settings);

include 'application/models/calendar.php';

if($argc < 9)
{
	die("Usage: insert_calendar_entry.php calendar username pass title note start end location allday recurrencetype[optional]\n");
}

$calname 		= $argv[1];
$user 			= $argv[2];
$password 		= $argv[3];
$Title			= $argv[4];
$CalMessage		= $argv[5];
$DateStart		= process_date($argv[6]);
$DateEnd		= process_date($argv[7]);
$Location 		= $argv[8];
$AllDayEvent		= $argv[9];
$recurrenceType		= $argv[10];
if($recurrenceType == '' )

{
	$recurrenceType = 0;
}
$UserFrom=$UserTo=$user;
$Alert='';
$Type='';
$Task='' ;

// caldav glue	
$entry_username = $UserFrom;
$entry_password = $password;
$url = $cal_url;

// ASSUME : that the user exists, the user import will have run already.
$_calendar = new calendar(array('URL' => $url, 'Account' => $entry_username, 'Password' => $entry_password, 'Calendar' => "calendar", 'home', 'largeInstall' => 0));

if($Title == "(null)")
	$Title = "";			
if($CalMessage == "(null)")
	$CalMessage = "";
if($Location == "(null)")
	$Location = "";

$args = array(
	'task' => 0,
	'title' => $Title,
	'description' => $CalMessage,
	'dateStart' => $DateStart,
	'dateEnd' => $DateEnd,
	'location' => $Location,
	'allDayEvent' => $AllDayEvent,
	'calendarUrl' => $calname
);
$uid = $_calendar->add_record($args);

$args['uid'] = $uid[0];
$args['task'] = 0;
$args['recurrenceType'] = $recurrenceType;
$args['recurrenceEndType']  = 1;
$args['recurrenceEndAfterX'] = 4;

$uid = $_calendar->update_record($args);


function process_date($dateStr)
{
	list($date, $time) = explode(' ', $dateStr);
	if(strstr($date, 'NOW') != NULL)
	{
		list($junk, $addition) = explode('+', $date);
		$date = date('Y-n-d', mktime(0, 0, 0, date("m")  , date("d")+$addition, date("Y")));
	}
	if(strstr($time, 'NOW') != NULL)
	{
		list($junk, $addition) = explode('+', $time);
		$time = date('H:i:s', mktime(date('H') + $addition, date('i'), date('s'),0,0,0));
	}
	return $date . ' ' . $time;
}



