<?php

/**
 * Authentication Backend for Dokuwiki
 */
 
// Note: rename to ofb.class.php when using in dokuwiki
// Configuration: Set oFb path (relative or absolute), the current path will be the dokuwiki root (!)
// (note that the working directory may vary)
ini_set('error_log', '/var/www/soscisurvey/html/system/logfiles/errorlog.dokuwiki.txt');
ini_set('log_errors', 1);
error_reporting(E_ALL & ~E_DEPRECATED);
require_once('/var/www/soscisurvey/html/inc/SoSciWorkingDir.php');

// Include basic auth class
// require_once('basic.class.php');

class auth_plugin_authsosci extends DokuWiki_Auth_Plugin {
	
	function __construct() {
		// Include required classes from SoSci
		SoSciWorkingDir::changeThere();
		require_once('../inc/GeneralFramework.php');
		GeneralFramework::disableAutoload();
		// Note: The dokuwiki will disable GeneralFramework's autoloading
		require_once('../inc/DbConnection.php');
		require_once('../inc/DbQuery.php');
		require_once('../inc/definitions.php');
		require_once('../inc/SystemLib.php');
		require_once('../inc/SoSci.php');
		require_once('../inc/functions.php');		// Various functions
		require_once('../inc/Lang.php');
		SoSci::loadConfiguration();
		Lang::initLanguage();
		DbConnection::connect(DB_OFB);
		require_once('../inc/CacheRead.php');
		require_once('../inc/ErrorRegister.php');
		require_once('../inc/BasicObject.php');
		require_once('../inc/DateLib.php');
		require_once('../inc/Account.php');
		require_once('../inc/CurrentUser.php');
		require_once('../inc/Authorisation.php');
		require_once('../inc/Project.php');
		require_once('../inc/StringLib.php');
		
		// Load language module Account (because we may be in another directory, later)
		Lang::text('Account', Lang::typeTitle, 'edit');
		
		// Close DokuWiki's Session
		session_destroy();
		
		// Init user
		CurrentUser::init();
		
		// Return to dokuwiki working directory
		SoSciWorkingDir::changeBack();
		
		// Disable reporting of E_NOTICE and error logging
		error_reporting(E_ALL ^ E_NOTICE);
		ini_set('log_errors', 0);
		
		// Successful if all found
		$this->success = true;
		
		// Set available functionality
		$this->cando = array (
			'addUser'     => false, // can Users be created?
			'delUser'     => false, // can Users be deleted?
			'modLogin'    => false, // can login names be changed?
			'modPass'     => false, // can passwords be changed?
			'modName'     => false, // can real names be changed?
			'modMail'     => false, // can emails be changed?
			'modGroups'   => false, // can groups be changed?
			'getUsers'    => false, // can a (filtered) list of users be retrieved?
			'getUserCount'=> false, // can the number of users be retrieved?
			'getGroups'   => true, // can a list of available groups be retrieved?
			'external'    => true, // does the module do external auth checking?
			'logout'      => true  // can the user logout again?
		);
	}
	
	/*
	 * Login user as CurrentUser
	 */
	public function checkPass($user, $pass) {
		// Login user
		$ret = CurrentUser::login($user, $pass);
		if ($ret !== true) {
			return false;
		}
		
		// Generally, the login was accepted
		return CurrentUser::isLoggedIn();
	}
	
	/*
	 * Set user group by user's authorisations
	 */
	public function getUserData($user, $requireGroups = true) {
		$account = Account::initByLogin($user);
		
		if ($account === null) {
			return false;
		}
		
		$groups = self::resolveUsersGroups($account);
		
		// Return data
		return array(
			'name' => $account->getName(),
			'mail' => $account->get('email'),
			'grps' => $groups
		);
	}
	
	/*
	 * Log out CurrentUser
	 */ 
	public function logOff() {
		CurrentUser::logout();
	}
	
	/**
	 * Resolve the groups of a User.
	 * @param User $user oFb User
	 * @return array Groups
	 */
	private static function resolveUsersGroups(Account $user) {
		// Resolve group
		if ($user->checkServerAuth('isBanned') or $user->checkServerAuth('isFixed')) {
			$groups = array('banned');
		} else {
			$groups = array();
			if ($user->checkServerAuth('adminServer')) {
				$groups[] = 'admin';
			}
			if ($user->checkServerAuth('adminSurvey')) {
				$groups[] = 'user';
			}
		}
		
		return $groups;
	}
	
	/*
	 * The available groups are fixed
	 */
	public function retrieveGroups($start=0, $limit=0) {
		return array(
			'admin', // Server administrator
			'user',  // Good SoSci Survey user
			'banned' // Bad user
		);
	}
	
	/*
	 * oFb will ignore any sticky setting
	 */
	public function trustExternal($user, $pass, $sticky=false) {
		if (empty($user)) {
			$ret = true;
		} else {
			// Login user (check login)
			$ret = CurrentUser::login($user, $pass);
			if ($ret !== true) {
				$errors = $ret->errGet();
				foreach ($errors as $msg) {
					msg($msg);
				}
			}
		}
		
		// Generally, the login was accepted
		if (($ret !== true) or !CurrentUser::isLoggedIn()) {
			// to be sure
		    auth_logoff();
			return false;
		}
		
		$user = CurrentUser::getActiveAccount();
		$GLOBALS['USERINFO'] = array(
			'name' => $user->getName(),
			'mail' => $user->get('email'),
			'grps' => self::resolveUsersGroups($user)
		);
		$_SERVER['REMOTE_USER'] = $user->get('login');
		
		$_SESSION[DOKU_COOKIE]['auth']['user'] = $user->get('login');
		$_SESSION[DOKU_COOKIE]['auth']['info'] = $GLOBALS['USERINFO']; 
		
		return true;
	}
	
}

?>