<?php
    function getServerURI($homeURL, $userID)
    {
        $xml        = '<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>get_server_urls</methodName><params><param><value><struct><member><name>userID</name><value><string>'.$userID.'</string></value></member></struct></value></param></params></methodCall>';
        $optionen   = stream_context_create(array('http' => array('timeout' => 1, 'method'  => 'POST', 'header'  => 'Content-Type: application/xml', 'content' => $xml)));
        $result     = file_get_contents($homeURL, false, $optionen);   
        
        $servers = new SimpleXMLElement($result);

        foreach ($servers->params->param->value->struct[0] as $serverEntry)
        {
            if($serverEntry->name == 'SRV_AssetServerURI')
                return $serverEntry->value->string->__toString();
        }
    }

    function getAssetData($assetServer, $assetUUID)
    {
        global $DATA;
        chdir("/var/www/html");

        if(!is_file('./data/RegionImages/'.$assetUUID.'.png'))
        {
            $DATA['WGETCMD']    =   '/usr/bin/wget '.$assetServer.'assets/'.$assetUUID.'/data -O /tmp/'.$assetUUID;
            $DATA['MPEGCMD']    =   '/usr/bin/ffmpeg -i /tmp/'.$assetUUID.' ./data/RegionImages/'.$assetUUID.'.png';
    
            $DATA['WGET']   = shell_exec($DATA['WGETCMD']);
            $DATA['FFMPEG'] = shell_exec($DATA['MPEGCMD']);
        }

        return $assetUUID.'.png';
    }

    function getRegionStats($regionHostName)
    {
        $optionen   = stream_context_create(array('http' => array('timeout' => 1)));
        $result     = file_get_contents("http://".$regionHostName."/jsonSimStats", false, $optionen); 

        if($result != "")
        {
            return json_decode($result);
        }
    }

    if(isset($_SERVER['HTTP_X_SECONDLIFE_SHARD']) && isset($_SERVER['HTTP_X_SECONDLIFE_REGION']))
    {
        $DATA                   =   array();
        $DATA['RegionData']     =   explode("(", $_SERVER['HTTP_X_SECONDLIFE_REGION']);
        $DATA['RegionName']     =   trim($DATA['RegionData'][0]);
        $DATA['RegionID']       =   md5($_SERVER['HTTP_X_SECONDLIFE_REGION'].$_REQUEST['grid']);
        $DATA['Position']       =   trim(str_replace(" ", "", str_replace(")", "", str_replace("(", "", $_SERVER['HTTP_X_SECONDLIFE_LOCAL_POSITION']))));
        $DATA['PositionData']   =   explode(",", $DATA['Position']);
        
        $DATA['PositionData'][0]    =   explode(".", $DATA['PositionData'][0])[0];
        $DATA['PositionData'][1]    =   explode(".", $DATA['PositionData'][1])[0];
        $DATA['PositionData'][2]    =   explode(".", $DATA['PositionData'][2])[0];

        
        $DATA['GridHomeURI']    =   $_REQUEST['GridHomeURI'];
        $DATA['Link']           =   "hop://".str_replace("http://", "", $DATA['GridHomeURI']).":".$DATA['RegionName']."/".$DATA['PositionData'][0]."/".$DATA['PositionData'][1]."/".$DATA['PositionData'][2];
        $DATA['AgentCount']     =   $_REQUEST['AgentCount'];
        $DATA['Beschreibung']   =   file_get_contents("php://input");
        
        $DATA['AssetServer']    =   getServerURI($DATA['GridHomeURI'], $_SERVER['HTTP_X_SECONDLIFE_OWNER_KEY']);
        $DATA['AssetPath']      =   getAssetData($DATA['AssetServer'], $_REQUEST['RegionImageTexture']);

        $DATA['GridName']       =   $_REQUEST['GridName'];

        if(!isset($DATA['RegionName']) || @$DATA['RegionName'] == "")die("ERROR: RegionName");
        if(!isset($DATA['Beschreibung']) || @$DATA['Beschreibung'] == "")die("ERROR: Beschreibung");
        if(!isset($DATA['GridHomeURI']) || @$DATA['GridHomeURI'] == "")die("ERROR: GridHomeURI");
        if(!isset($DATA['AgentCount']) || @$DATA['AgentCount'] == "")die("ERROR: AgentCount");
        if(!isset($DATA['GridName']) || @$DATA['GridName'] == "")die("ERROR: GridName"); 

        $MYSQLDATA              =   array('RegionID' => $DATA['RegionID'], 'RegionName' => $DATA['RegionName'], 'RegionBeschreibung' => $DATA['Beschreibung'], 'RegionLink' => $DATA['Link'],'PositionX' => $DATA['PositionData'][0], 'PositionY' => $DATA['PositionData'][1], 'PositionZ' => $DATA['PositionData'][2], 'GridName' => $DATA['GridName'], 'ImageName' => $DATA['AssetPath'], 'LastSeen' => time(), 'OnlineUser' => $DATA['AgentCount']);
        $statementSend = $RUNTIME['PDO']->prepare('REPLACE INTO Regions (RegionID, RegionName, RegionBeschreibung, RegionLink, PositionX, PositionY, PositionZ, GridName, ImageName, LastSeen, OnlineUser) VALUES (:RegionID, :RegionName, :RegionBeschreibung, :RegionLink, :PositionX, :PositionY, :PositionZ, :GridName, :ImageName, :LastSeen, :OnlineUser)');
        $statementSend->execute($MYSQLDATA);

        echo "OK";
    }else{
        die("ERROR: LSL");
    }

    //file_put_contents("debug-".time().".txt", print_r($GLOBALS, true));
?>
