<?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' => 1.0, 'content' => $contend))));
        }else{
            return @file_get_contents($URL, true, stream_context_create(array('http' => array('timeout' => 1.0))));
        }
    } 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 getTopRegionHTML($row)
{
    if(!isset($row['Image']))
        return;

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

    if(!isset($row['Description']) || trim($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="region_-'.$row['UUID'].'.html" class="button big html5lightbox">Menr Infos</a></ul></div>
        <span class="image object"><img style="min-height: 450px; max-height: 450px;" 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']) || trim($row['Description']) == "")
        $row['Description'] = "(Es wurde noch keine Beschreibung hinterlegt.)";

    return '<article><a href="index.php?page=regionInfo&id='.$row['UUID'].'" class="image"><img style="min-height: 250px; max-height: 250px;" 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="region_'.$row['UUID'].'.html" class="button html5lightbox">Menr Infos</a></li></ul></article>';
}

function getGridInfo($homeURL)
{
     $optionen   = stream_context_create(array('http' => array('timeout' => 2, 'method'  => 'GET')));
     $result     = file_get_contents($homeURL."/get_grid_info", false, $optionen);   
     $returnData = array();

     $servers = new SimpleXMLElement($result);

     $returnData['platform'] = $servers['platform'];
     $returnData['gridname'] = $servers['gridname'];

     return $returnData;
}


function getUserServiceURL($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' => 2, 'method'  => 'POST', 'header'  => 'Content-Type: application/xml', 'content' => $xml)));
     $result     = file_get_contents($homeURL, false, $optionen);   
     $returnData = array();

     $servers = new SimpleXMLElement($result);

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

          if($serverEntry->name == 'SRV_AssetServerURI')
               $returnData['SRV_AssetServerURI'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'SRV_InventoryServerURI')
               $returnData['SRV_InventoryServerURI'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'SRV_ProfileServerURI')
               $returnData['SRV_ProfileServerURI'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'SRV_GroupsServerURI')
               $returnData['SRV_GroupsServerURI'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'SRV_IMServerURI')
               $returnData['SRV_IMServerURI'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'SRV_GatekeeperURI')
               $returnData['SRV_GatekeeperURI'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'SRV_HomeURI')
               $returnData['SRV_HomeURI'] = $serverEntry->value->string->__toString();
     }

     return $returnData;
}

function getUserInfo($homeURL, $userID)
{
     $xml        = '<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>get_user_info</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' => 2, 'method'  => 'POST', 'header'  => 'Content-Type: application/xml', 'content' => $xml)));
     $result     = file_get_contents($homeURL, false, $optionen);   
     $returnData = array();

     $servers = new SimpleXMLElement($result);

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

          if($serverEntry->name == 'user_lastname')
               $returnData['user_lastname'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'result')
               $returnData['result'] = $serverEntry->value->string->__toString();
     }

     return $returnData;
}

function getRegionInfo($homeURL, $regionName)
{
     $xml        = '<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>link_region</methodName><params><param><value><struct><member><name>region_name</name><value><string>'.$regionName.'</string></value></member></struct></value></param></params></methodCall>';
     $optionen   = stream_context_create(array('http' => array('timeout' => 2, 'method'  => 'POST', 'header'  => 'Content-Type: application/x-www-form-urlencoded', 'content' => $xml)));
     $result     = file_get_contents($homeURL, false, $optionen);   
     $returnData = array();

     $servers = new SimpleXMLElement($result);

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

          if($serverEntry->name == 'region_image')
               $returnData['region_image'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'uuid')
               $returnData['uuid'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'result')
               $returnData['result'] = $serverEntry->value->string->__toString();
     }

     return $returnData;
}

function getRegionData($homeURL, $uuid)
{
     $xml        = '<?xml version="1.0" encoding="utf-8"?><methodCall><methodName>get_region</methodName><params><param><value><struct><member><name>region_uuid</name><value><string>'.$uuid.'</string></value></member></struct></value></param></params></methodCall>';
     $optionen   = stream_context_create(array('http' => array('timeout' => 2, 'method'  => 'POST', 'header'  => 'Content-Type: application/x-www-form-urlencoded', 'content' => $xml)));
     $result     = file_get_contents($homeURL, false, $optionen);   

     $returnData = array();

     $servers = new SimpleXMLElement($result);

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

          if($serverEntry->name == 'hostname')
               $returnData['hostname'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'server_uri')
               $returnData['server_uri'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'region_name')
               $returnData['region_name'] = $serverEntry->value->string->__toString();

          if($serverEntry->name == 'result')
               $returnData['result'] = $serverEntry->value->string->__toString();
     }

     return $returnData;
}

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