<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class WV42_RBAC implements sly_Authorisation_Provider, pac_PDOProvider, pac_DestinationProvider {
	private $pdo          = null;
	private $prefix       = '';
	private $destinations = array();

	public function __construct() {
		$dbdata = sly_Core::config()->get('DATABASE');

		$this->pdo    = sly_DB_PDO_Connection::getInstance($dbdata['DRIVER'], $dbdata['HOST'], $dbdata['LOGIN'], $dbdata['PASSWORD'], $dbdata['NAME'])->getPDO();
		$this->prefix = $dbdata['TABLE_PREFIX'];

		pac_Core::init($this, $this);
	}

	/**
	 *
	 * @param  $userId
	 * @param  $operation
	 * @param  $objectId
	 * @return boolean
	 */
	public function hasPermission($userId, $destination, $token, $value = true) {
		if ($value !== true) $value = (string) $value;
		$user = WV42_UserCache::getPacUser($userId);
		return $user->hasPermission($destination, $token, $value);
	}

	public function getPDO() {
		return $this->pdo;
	}

	public function getPrefix() {
		return $this->prefix;
	}

	public function getDestination($id) {
		$destConfig = sly_Authorisation::getConfig();

		if (!array_key_exists($id, $destConfig)) {
			throw new sly_Authorisation_Exception('Destination '.$id.' does not exist.');
		}

		if (!array_key_exists($id, $this->destinations)) {
			$config = $destConfig[$id];
			$tokens = sly_makeArray(array_keys($config['token']));
			$supers = isset($config['supers']) ? $config['supers'] : array();

			if (isset($config['list'])) {
				$d = new pac_Destination_List($id, $tokens, 'string', $supers);
			}
			else {
				$d = new pac_Destination_Plain($id, $tokens, $supers);
			}

			$this->destinations[$id] = $d;
		}

		return $this->destinations[$id];
	}
}
