<?php
/**
 * CodeIgniter Controller
 *
 * @category CodeIgniter
 * @license /_licenses/untermStrich/agb_normal.pdf
 * @author Christian Koller
 * @copyright 2009 untermStrich
 * @package controllers
 * @version $Id: dav.php christian $
*/

require_once APPPATH.'us_libraries/vendor/autoload.php';

/**
 * The WebDAV functions controller of untermStrich
 */
class Webdav extends My_Controller
{
    public function __construct()
    {
        parent::__construct();
        
    }
    
    /**
     * Remap all requests
     *
     * @param   string  $object_called  Name of the called object
     * @return  void
     */
    public function _remap($object_called)
    {
        $dav_log_msg = 'Hello '.$object_called;
        log_message('info', $dav_log_msg, false, 'dav');

        $this->load->us_library('dav/DavUstrichVirtualDirTrait');
        $this->load->us_library('dav/DavUstrichAuthBackend');
        $this->load->us_library('dav/DavUstrichFile');
        $this->load->us_library('dav/DavUstrichDirectory');
        $this->load->us_library('dav/DavUstrichLock');

        $rootDirectory = new DavUstrichDirectory('');
        
        $server = new Sabre\DAV\Server($rootDirectory);
        
        $full_base_url = base_url().'webdav/';
        $server->setBaseUri(parse_url($full_base_url, PHP_URL_PATH));
        
        $pdo = $this->_get_pdo();
        $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        $lockBackend = new DavUstrichLock($pdo);
        
        $lockPlugin = new Sabre\DAV\Locks\Plugin($lockBackend);
        $server->addPlugin($lockPlugin);
        
        $authBackend = new DavUstrichAuthBackend();
        $authPlugin = new Sabre\DAV\Auth\Plugin($authBackend);
        $server->addPlugin($authPlugin);
        
        $server->addPlugin(new Sabre\DAV\Browser\Plugin());
        
        $server->exec();
    }
    
    /**
     * Get PDO for locking
     * 
     * @return \PDO
     */
    private function _get_pdo()
    {
        require_once(APPPATHLIVE.'helpers/db_helper.php');
        
        include(APPPATH.'config/database.php');
        $params = $db['default'];
        
        db_prepare_params($params);
        
        return new PDO('mysql:host='.$params['hostname'].';port='.$params['port'].';dbname='.$params['database'], $params['username'], $params['password']);
    }
}