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

/*
* A5 DB to A6 CALDAV
* Migration
*
* Usage : inserts a calendar event into a6 caldav.
*/

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

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

// Lets give the script some ram!
ini_set('memory_limit', -1);

// remove php time limit
set_time_limit(0);

// uncomment to enable IMAP debugging
define('ATMAIL_IMAP_ERR', '/tmp/atmail-imap-err');

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");

//Site application root and paths
//all references to directories have / appended to eliminate posibility of direcory reference composition resulting in '/....' as in root 
//i.e. when composing a directory string, all components dont/cant/wont start with a / eliminating the possibility if a resulting string referring to OS root

//Setup Zend Loader
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
//$loader->registerNamespace('App_'); //for model namespacing
$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';

$no_pass = false;
if($argc != 3)
{
	die("Usage: caldav_migrate.php user pass < file.ics\n");
}
# * read a5 user
# * create caldav user if !exist
# * read a5 calendar database
# * convert to a6 vevent entry

# connect to the sql server
$username = $argv[1];
$password = $argv[2];

$calname = "Private";

// caldav glue	
$url = $cal_url;
$line = '';

while( ( $current_line = fgetcsv(STDIN, 10000, ",") ) !== FALSE )
{
	if ( is_null($current_line[0]))
	{
		continue;
	}
	$line .= $current_line[0] . "\n";
}

//TODO: ignore header/column heading lines
// Skip blank lines
if ( is_null($line))
{
	die("unable to read file");
}

echo "$cal_url : $username : ";

// ASSUME : that the user exists, the user import will have run already.
$_calendar = new calendar(array('URL' => $url, 'Account' => $username, 'Password' => $password, 'Calendar' => "calendar", 'home', 'largeInstall' => 0));
list($junk, $line) = explode('BEGIN:VCALENDAR', $line);
list($line, $junk) = explode('END:VCALENDAR', $line);

// ensure there is no garbage
$line = 'BEGIN:VCALENDAR' . $line . 'END:VCALENDAR';
if(strpos($line, 'METHOD:') != FALSE)
{
	// we need no method specified
	list($top, $bottom) = explode('METHOD:', $line);
	list($junk, $bottom) = explode("\n", $bottom, 2);
	$line = $top . "\n" . $bottom;
}

$uid = array('', 'no-uid-conflict');
$total_retries = 10;
while($uid[1] == 'no-uid-conflict' && $total_retries != 0)
{
	$uid = $_calendar->add_raw_record($line, 'rw', '/calendars/' . $username . '/calendar/');
	if($uid[1] == 'no-uid-conflict')
	{
		print ("ERROR: Unable to import, UID conflicts. Trying again.\n");
	}
	$total_retries --;
}

if($total_retries == 0)
{
	fwrite(STDOUT, "FAILED\n");
}
else
{
	fwrite(STDOUT, $uid[0] . " added\n");
}

unset($_calendar);

