<?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");

define('DEC_KEY_FILE', '/etc/httpd/conf.d/auth_tkt.conf');
define('DEC_SECRETKEY_DIRECTIVE', 'TKTAuthSecret');

$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";
}

/**
 *  暗号化用のキーをファイルから取得する
 *
 *  @access public
 *  @param  string   ファイル
 *  @return string   キー
*/
function getSecretKey($file)
{
    $matches = array();
    $secretKey = "";

    $content = file_get_contents($file);
    if( $content === false ){
        // Cannot read key file
        return null;
    }

    if(preg_match( "/^\s*".DEC_SECRETKEY_DIRECTIVE."\s+[\"']*([^\"']*)[\"']*/mi", $content, $matches)) {
        $secretKey = $matches[1];
    }

    return $secretKey;
}

/**
 *  文字列の復号化を行う
 *
 *  @access public
 *  @return string   復号化された文字列
*/
function desDecrypt($string, $file = DEC_KEY_FILE)
{
    if ($string === null || $string === '') {
        return $string;
    }

    $string = base64_decode($string);

    $key = getSecretKey($file);
    if (!$key) {
        return null;
    }

    $tmpstr = $string;
    $key = md5($key);
    $checksum = $key;

    $td = mcrypt_module_open('tripledes', '', 'cfb', '');
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = substr($tmpstr, 0, $iv_size);
    $tmpstr = substr($tmpstr, $iv_size);

    if (mcrypt_generic_init($td, $key, $iv) != -1) {
        $c_t = mdecrypt_generic($td, $tmpstr);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        if (!strncmp($c_t, $checksum, 32)) {
            return substr($c_t, 32);
        }
    }

    return null;
}
?>
