<?php
$path = ini_get('include_path');
$path =  dirname(__FILE__) . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

require_once("Log.php");
require_once("Secioss/AutoLogin.php");
require_once("Smarty/Smarty.class.php");

$lang = null;
if (isset($_SESSION['lang']) && $_SESSION['lang']) {
    $lang = $_SESSION['lang'];
} else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    $accept_lang = ','.$_SERVER['HTTP_ACCEPT_LANGUAGE'].',';
    if (preg_match('/,ja[,;\-]/', $accept_lang)) {
        $lang = 'ja';
    } else if (preg_match('/,en[,;\-]/', $accept_lang)) {
        $lang = 'en';
    }
}
$msgfile = 'message'.($lang ? "_$lang" : '').'.php';
if (!file_exists('../lib/'.$msgfile)) {
    $msgfile = 'message.php';
}
require_once($msgfile);

function getTemplateFile($name, $tenant, $lang) {
    if ($tenant && is_dir("./templates/$tenant")) {
        $file = "$tenant/".$name;
    } else {
        $file = $name;
    }

    if ($lang && file_exists("./templates/$file".'_'.$lang.'.tpl')) {
        $file .= '_'.$lang.'.tpl';
    } else {
        $file .= '.tpl';
    }

    return $file;
}

function sam_auth($url, $username, $password)
{
    $req =& new HTTP_Request("$url?userid=$username&ip=".$_SERVER['REMOTE_ADDR']);
    $req->setMethod(HTTP_REQUEST_METHOD_POST);
    $req->addPostData('password', $password);
    $res = $req->sendRequest();
    if (PEAR::isError($res) || $req->getResponseCode() != 200) {
        return PEAR::raiseError("Authentication server returns error response", -1);
    }

    $xml = simplexml_load_string($req->getResponseBody());
    $rc = intval($xml->code);
    $tokens = null;
    if ($rc < 0) {
        return PEAR::raiseError(strval($xml->message), -1);
    } else if ($rc == 0) {
        $tokens = strval($xml->tokens);
        $ticket = strval($xml->ticket);
    }

    return array($rc, $tokens, $ticket);
}

function logformat($message)
{
    $ipaddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-';
    if (isset($_SERVER['REMOTE_USER'])) {
        $user = $_SERVER['REMOTE_USER'];
    } else if (isset($_SESSION['username'])) {
        $user = $_SESSION['username'];
    } else {
        $user = '-';
    }
    $tenant = preg_match('/@(.+)$/', $user, $matches) ? $matches[1] : '-';

    return "$ipaddr; $tenant; $user; $message";
}

?>
