<?php
$session_name_new = "sidsuite_idp";
$session_name_org = session_name($session_name_new);

session_start();
$_SESSION['lang'] = 'en';
require_once("../lib/util.php");


$logid = 'IdsyncIdp';
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
	$log = &Log::singleton('syslog', LOG_LOCAL5, $logid);
} else {
	$opts = array('locking' => true, 'timeFormat' => '%Y/%m/%d %H:%M:%S');
	$log = &Log::singleton('file', '/opt/secioss/var/log/auth.log', $logid, $opts);
}

$conf = parse_ini_file("../conf/idsync.ini", true);
if (empty($conf)) {
	 $log->crit(logformat("Can't read idsync.ini"));
	 exit(1);
}
if (!isset($conf['password'])) {
	 $log->crit(logformat("Set password configuration"));
	 exit(1);
}
$pwconf = $conf['password'];

$code = 1;
$message = '';
$response_xml = 
'<?xml version="1.0" encoding="UTF-8"?>
<response>
  <code>%d</code>
  <message>%s</message>
</response>
';

if (isset($_POST['username']) && isset($_POST['password'])) {
	if (isset($pwconf['multitenant']) && $pwconf['multitenant']) {
		$_SESSION['tenant'] = $_POST['username'];
		$code = 0;
		$message = 'Success';
	} else {
		$ldapConn = ldap_connect($pwconf['uri']);
		if (ldap_bind($ldapConn, $_POST['username'], $_POST['password'])) {
			$_SESSION['authuser'] = $_POST['username'];
			$_SESSION['authpwd'] = $_POST['password'];
			$code = 0;
			$message = 'Bind success';
			$log->notice(logformat("LDAP bind success"));
		}
		else {
			$code = ldap_errno($ldapConn);
			$message = "LDAP bind failed($code): ".ldap_error($ldapConn);
			$log->err(logformat($message));
		}
	}
}
else {
	$message = 'Parameter error';
	$log->err(logformat("Parameter error"));
}

printf($response_xml, $code, $message);

?>
