<?php

/*

CalDAV & CardDAV server endpoint

This endpoint assumes the server is running from:
APP_ROOT/dav/server.php/

*/

// Atmail bootloader
include '../bootloader.php';
set_time_limit(1800);

// Files we need
require_once '../library/DateTime.php';
require_once '../library/DateTimeZone.php';
require_once '../library/Atmail/autoload.php';
require_once '../library/Sabre/autoload.php';

// settings
date_default_timezone_set('GMT');

/* If no PATH_INFO is set, SabreDAV will be unable to guess the root of the 
 * server. We'll redirect the user in this case, hoping this will *just work*
 */
if (!isset($_SERVER['PATH_INFO']) || !$_SERVER['PATH_INFO']) {
    header('Location: ' . $_SERVER['REQUEST_URI'] . '/');
    die();
}

$pdo = Zend_Registry::get('dbAdapter')->getConnection();

//Mapping PHP errors to exceptions
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

$server = new Atmail_Dav_Server($pdo);

// This is a rather naive check to find the base url. We're just going to look
// at the request_uri and assume that the first segment containing this 
// filename is the base url.
$r_uri = $_SERVER['REQUEST_URI'];
$baseUri = substr($r_uri, 0, strpos($r_uri, '/' . basename(__FILE__))) . '/' . basename(__FILE__) . '/';
// Not setting a base uri, but let SabreDAV use the guessing algoritm.
$server->setBaseUri($baseUri);

// fire off the 'preDavExec' event to the plugins
pluginCall('preDavExec');

// And off we go!
$server->exec();
