<?php
/*
 * TribesNext Delegated Community Enhancement Server
 * 
 * Session JSON API
 * 
 * This script provides a JSON interface for session negotiation with the
 * TribesNext system. JSON is provided both for the GWT based web client
 * front end, and for users wishing to build their own clients or notification
 * systems.
 * 
 * Currently available methods:
 *  - Login by password.
 *  - Logout.
 */

require_once '../lib/challenge.php';
require_once 
'../lib/synchronize.php';
require_once 
'../lib/database.php';

function 
tn_json_session_die($type)
{
    
header("HTTP/1.1 " $type);
    print(
"<h1>Fatal Error</h1><h2>" $type "</h2>");
    die();
}

$link database_connectDatabase();

if (!isset(
$_REQUEST['method']))
{
    
tn_json_session_die("501 Not Implemented");
}
else
{
    
$guid = (isset($_REQUEST['guid']) ? $_REQUEST['guid'] : "");
    
$uuid = (isset($_REQUEST['uuid']) ? $_REQUEST['uuid'] : "");
    
$password = (isset($_REQUEST['pw']) ? $_REQUEST['pw'] : "");
    
$username = (isset($_REQUEST['un']) ? $_REQUEST['un'] : "");
    
$method $_REQUEST['method'];
    
    if (
$method === "login")
    {
        if (
$guid === "")
        {
            
$guid = (strlen($username) > tn_sync_lookup($username) : "");
            if (
$guid !== "")
            {
                
$hash sha1("3.14159265" strtolower($username) . $password);
                
$uuid tn_challenge_hash($guid$hash);
                if (
$uuid === "")
                {
                    
$out = array();
                    
$out['status'] = "error";
                    
$out['message'] = "user or password invalid";
                    
$output json_encode($out);
                }
                else
                {
                    
$out = array();
                    
$out['status'] = "success";
                    
$out['uuid'] = $uuid;
                    
$out['guid'] = $guid;
                    
$out['message'] = "logged in";
                    
$output json_encode($out);
                }
            }
            else
            {
                
$out = array();
                
$out['status'] = "error";
                
$out['message'] = "user or password invalid";
                
$output json_encode($out);
            }
        }
    }
    else if (
$method === "logout")
    {
        if (
tn_challenge_isAuthorized($guid$uuid))
        {
            
tn_challenge_logout($guid$uuid);
            
$out = array();
            
$out['status'] = "success";
            
$output json_encode($out);
        }
    }
    else
    {
        
tn_json_session_die("501 Not Implemented");
    }
    if (isset(
$_REQUEST['jsonp']))
    {
        
// avoid content injection exploits on jsonp parameter
        
$jsonp $_REQUEST['jsonp'];
        if (
strlen($jsonp) < 50 && preg_match("/[a-zA-Z0-9_]+/"$jsonp))
        {
            
$output $jsonp "(" $output ");";
        }
    }
    print(
$output);
}

database_disconnectDatabase($link);
?>