<?php
function fillString($string, $targetlength)
{
    while(strlen($string) < $targetlength)
    {
        $string = "0".$string;
    }

    return $string;
}

function left($str, $length) 
{
    return substr($str, 0, $length);
}

function right($str, $length) 
{
    return substr($str, -$length);
}

function guidv4($data = null) {
    // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
    $data = $data ?? random_bytes(16);
    assert(strlen($data) == 16);

    // Set version to 0100
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    // Set bits 6-7 to 10
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

    // Output the 36 character UUID.
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

function ping($host, $port) 
{ 
    $waitTimeoutInSeconds = 2; 
    if($fp = @fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds))
    {
        fclose($fp);
        return true;
    }

    return false;
}

function getDataFromHTTP($URL, $contend = "", $requestTyp = "application/text")
{
    try
    {
        if($contend != "")
        {
            return @file_get_contents($URL, true, stream_context_create(array('http' => array('header'  => 'Content-type: '.$requestTyp, 'method' => 'POST', 'timeout' => 0.5, 'content' => $contend))));
        }else{
            return @file_get_contents($URL);
        }
    } catch (Exception $e) {
        echo "(HTTP REQUEST) error while conntect to remote server. : ".$URL;
    }
}

function sendInworldIM($fromUUID, $toUUID, $fromName, $targetURL, $text) 
{
    $rawXML	=	"<?xml version=\"1.0\" encoding=\"utf-8\"?><methodCall><methodName>grid_instant_message</methodName><params><param><value><struct><member><name>position_x</name><value><string>0</string></value></member><member><name>position_y</name><value><string>0</string></value></member><member><name>position_z</name><value><string>0</string></value></member><member><name>to_agent_id</name><value><string>".$toUUID."</string></value></member><member><name>from_agent_session</name><value><string>00000000-0000-0000-0000-000000000000</string></value></member><member><name>im_session_id</name><value><string>".$fromUUID."</string></value></member><member><name>from_agent_name</name><value><string>".$fromName."</string></value></member><member><name>from_agent_id</name><value><string>".$fromUUID."</string></value></member><member><name>binary_bucket</name><value><string>AA==</string></value></member><member><name>region_handle</name><value><i4>0</i4></value></member><member><name>region_id</name><value><string>00000000-0000-0000-0000-000000000000</string></value></member><member><name>parent_estate_id</name><value><string>1</string></value></member><member><name>timestamp</name><value><string>".time()."</string></value></member><member><name>dialog</name><value><string>AA==</string></value></member><member><name>offline</name><value><string>AA==</string></value></member><member><name>from_group</name><value><string>FALSE</string></value></member><member><name>message</name><value><string>".$text."</string></value></member></struct></value></param></params></methodCall>";
    getDataFromHTTP($targetURL, $rawXML, "text/xml");
}

function getAssetServerURI($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 getAssetImage($assetServer, $assetUUID)
{
    global $DATA;
    chdir("/var/www/html");

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

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

    return false;
}

function getTopRegionHTML($row)
{
    if(!isset($row['Image']))
        return;

    if(!file_exists("./data/RegionImages/".$row['Image'].".jpg"))
        $row['Image'] = "notFound";

    if(!isset($row['Description']))
        $row['Description'] = "(Es wurde noch keine Beschreibung hinterlegt.)";

    return '<section id="banner"><div class="content"><header><h1>'.substr($row['Name'], 0, 50).'</h1><p>Online: '.$row['OnlineCount'].'</p></header><p>'.substr($row['Description'], 0, 800).'</p><ul class="actions"><a href="info/'.$row['UUID'].'.html" class="button big html5lightbox">Menr Infos</a></ul></div>
        <span class="image object"><img style="min-height: 450px; max-height: 45px;" src="./data/RegionImages/'.$row['Image'].'.jpg" alt="Region Image '.substr($row['Name'], 0, 50).'" /></span></section>';
}

function getRegionHTML($row)
{
    if(!file_exists("./data/RegionImages/".$row['Image']."jpg"))
        $row['Image'] = "notFound";

    if(!isset($row['Description']))
        $row['Description'] = "(Es wurde noch keine Beschreibung hinterlegt.)";

    return '<article><a href="index.php?page=regionInfo&id='.$row['UUID'].'" class="image"><img src="./data/RegionImages/'.$row['Image'].'.jpg" alt="Region Image '.substr($row['Name'], 0, 50).'" /></a>
    <h3>'.substr($row['Name'], 0, 50).'</h3><p>Online: '.$row['OnlineCount'].'</p><p>'.substr($row['Description'], 0, 300).'</p><ul class="actions"><li><a href="info/'.$row['UUID'].'.html" class="button html5lightbox">Menr Infos</a></li></ul></article>';
}
?>