<?php

/**
 * This plugin provides logging functions
 * 
 * @package Atmail
 * @subpackage Dav 
 * @copyright Copyright (C) 2011 Atmail. (Based on Sabre_DAV_Auth_Plugin, see file for copyright)
 * @author Atmail
 * @license http://atmail.com/license
 */
class Atmail_Dav_Logging_Plugin extends Sabre_DAV_ServerPlugin
{

    /**
     * Reference to main server object 
     * 
     * @var Sabre_DAV_Server 
     */
    private $server;

    /**
     * Logging backend
     * 
     * @var Atmail_DAV_Logging_Backend_Abstract 
     */
    private $loggingBackend;
    
    /**
     * __construct 
     * 
     * @param Atmail_Dav_Logging_IBackend $loggingBackend 
     * @return void
     */
    public function __construct(Atmail_Dav_Logging_IBackend $loggingBackend)
    {
        $this->loggingBackend = $loggingBackend;
    }

    /**
     * Initializes the plugin. This function is automatically called by the server  
     * 
     * @param Sabre_DAV_Server $server 
     * @return void
     */
    public function initialize(Sabre_DAV_Server $server)
    {
        $this->server = $server;
        $this->server->subscribeEvent('beforeMethod' ,array($this,'beforeMethod'),30);
    }

    /**
     * Returns a plugin name.
     * 
     * Using this name other plugins will be able to access other plugins
     * using Sabre_DAV_Server::getPlugin 
     * 
     * @return string 
     */
    public function getPluginName()
    {
        return 'log';
    }

    /**
     * This method is called before any HTTP method, but after authentication.
     * 
     * @param string $method
     * @throws Sabre_DAV_Exception_NotAuthenticated
     * @return bool 
     */
    public function beforeMethod($method, $url)
    {
        $authPlugin = $this->server->getPlugin('auth');
        if (!$authPlugin) {
            $userName = '';
        } else {
            $userName = $authPlugin->getCurrentUser();
        }

		// Only log attempts from an IP address, not direct API call
		if(!empty($_SERVER["REMOTE_ADDR"]))
    		$this->loggingBackend->log($userName, $method, $url);   	

    	return;
    }

}
