<?php
/**
 *
 * @author Allan Wrethman In2Naos L <allan AT staff D0T atmail DoT com>
 * @version
 */
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

require_once 'Zend/Controller/Plugin/Abstract.php';

   
class Atmail_Controller_Action_Helper_Acl extends Zend_Controller_Action_Helper_Abstract
{
    private $_auth;
	private $_acl;
	
	private $_serviceAuth = array('module' => 'default', 
							'controller' => 'index', 
							'action' => 'auth');
	
	private $_noauth = array('module' => 'default',
							 'controller' => 'index',
							 'action' => 'index');
						 
	private $_noacl = array('module' => 'default',
							'controller' => 'index',
							'action' => 'index');
	
	public function __construct($auth, $acl)
	{
		$this->_auth = $auth;
		$this->_acl = $acl;    
	}  
						
	public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        //$this->getResponse()->appendBody("<p>routeStartup() called</p>\n");
    }

    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        //$this->getResponse()->appendBody("<p>routeShutdown() called</p>\n");
    }

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        //$this->getResponse()->appendBody("<p>dispatchLoopStartup() called</p>\n"); 
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
		if ($this->_auth->hasIdentity()) {
			$role = $this->_auth->getIdentity()->Role;
		} else {
			$role = 'guest';
		}

		$controller = $request->controller;
		$action = $request->action;
		$module = $request->module;
		$resource = $controller;

		if (!$this->_acl->has($resource)) {
			$resource = null;
		}

		if (!$this->_acl->isAllowed($role, $resource, $action)) {
			if (!$this->_auth->hasIdentity()) {
				$module = $this->_noauth['module'];
				$controller = $this->_noauth['controller'];
				$action = $this->_noauth['action'];
			} else {
				$module = $this->_noacl['module'];
				$controller = $this->_noacl['controller'];
				$action = $this->_noacl['action']; 
			}                 
		}

		$request->setModuleName($module);
		$request->setControllerName($controller);
		$request->setActionName($action);
		
    }

    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        //$this->getResponse()->appendBody("<p>postDispatch() called</p>\n");
    }

    public function dispatchLoopShutdown()
    {
        //$this->getResponse()->appendBody("<p>dispatchLoopShutdown() called</p>\n");
    }
}
