<?php
/**
 * Jin Authenticator plugin. Put this file into 2 places:
 * mce/plugins/imagemanager/classes/Plugins
 * mce/plugins/filemanager/classes/Plugins
 */

/**
 * JinAuthenticatorImpl.php
 *
 * @package MCFileManager.filesystems
 * @author Moxiecode
 * @copyright Copyright © 2005, Moxiecode Systems AB, All rights reserved.
 *
 * This is a example file of how to implement a custom authenticator.
 */

/**
 * This class is a session authenticator implementation, this implementation will check for session keys defined by the
 * config options "authenticator.session.logged_in_key, authenticator.session.groups_key".
 *
 * @package MCFileManager.Authenticators
 */
class JinAuthenticatorImpl extends BaseAuthenticator {
    /**#@+
	 * @access private
	 */

	var $_userKey;

    /**#@+
	 * @access public
	 */

	/**
	 * Main constructor.
	 */
	function JinAuthenticatorImpl() {
	}

	/**
	 * Initializes the authenicator.
	 *
	 * @param Array $config Name/Value collection of config items.
	 */
	function init(&$config) {

		// Setup session keys
		$this->_userKey = $config['authenticator.session.user_key'];

		// check user authorization from Jin
		$error = $this->authUsingZenSession($_REQUEST['zen_sbr'], 'browser');
		if (strlen($error) > 0)
		{
			$error = $this->authUsingZenSession($_REQUEST['zen_sll'], 'longlife');
			if (strlen($error) > 0)
			{
				die($error);
			}
		}
	
		// change root for this user only
		$config['filesystem.rootpath'] .= '/' . $_SESSION[$this->_userKey];
	}

	/**
	 * Returns true/false if the user is logged in or not.
	 *
	 * @return bool true/false if the user is logged in or not.
	 */
	function isLoggedin() {

		return isset($_SESSION[$this->_userKey]);
	}

	/**#@-*/
	
	function authUsingZenSession($sescode, $sesdir)
	{
		if (! strlen($sescode) > 0)
			 return "AE1: session cookie not found";
	
		$baseDir = __FILE__;
		$baseDir = ereg_replace("\\\\", "/", $baseDir);
		$baseDir = substr($baseDir, 0, strpos($baseDir, "mce/plugins/"));
		
		$sessionLoc = "zen-sitebox/session/$sesdir/";
		$sessionDir = $baseDir . $sessionLoc;
		if (! is_dir($sessionDir))
			$sessionDir = $baseDir . "../" . $sessionLoc;
		if (! is_dir($sessionDir))
			return "AE2: session directory not found [$sessionDir]";

		$authFile = $sessionDir . substr($sescode, 0, 6) . '/' . substr($sescode, 6, 2) . '/' . substr($sescode, 8, 2) . '/' . $sescode . '/AUTH.Jin';

		if (! is_file($authFile))
			return "AE3: you are not logged in";
		
		$lines = file($authFile);
		
		$_SESSION[$this->_userKey] = $lines[0];
		
		return '';
	}
	
}

?>