Web2SL Chat

This is a chat bridge between an HTML/AJAX webpage, and Second Life. The webpage is served from the prim itself. This script uses my Object DNS and FloatText Progress Bar scripts.

LSL

Main Script

string DNSName="ChatBox";
string url;
integer CHANGED_URL = 1792;
integer DNSRegistered;
string chatpage;
key line_query;
integer chatpage_length;
integer chatpage_readline;
integer lhandle;
key request;

string progress;
string empty = "□";
string filled = "■";
integer value;

string StringReplace(string source, string old, string new)
{
    integer pos;
    string str = source;
    string pre = "";
    if (pos > 0)
    {
        pre = llGetSubString(source, 0, pos - 1);
        str = llGetSubString(source, pos, -1);
    }
    integer len = llStringLength(old);
    integer index = llSubStringIndex(str, old);
    while (index > -1)
    {
        str = llInsertString(llDeleteSubString(str, index, index + len - 1), index, new);
        index = llSubStringIndex(str, old);
    }
    return pre + str;
}

settext(integer send)
{
    if (send==TRUE)
    {
        llSetText("Server Online\nhttp://primchat.co.cc/"+DNSName+"/"+"\nSending...",<1,0,0>,1);
    }
    else
    {
        llSetText("Server Online\nhttp://primchat.co.cc/"+DNSName+"/",<0,1,0>,1);
    }
}

default
{
    state_entry()
    {
        llSay(0,"Starting up, please wait");
        line_query = llGetNumberOfNotecardLines("chatpage");        
    }

    changed(integer c)
    {
        if (c & (CHANGED_URL) )
        {
            llRequestURL();
        }
        else if (c & CHANGED_INVENTORY)
        {
            llResetScript();
        }
        else if (c & CHANGED_REGION)
        {
            llResetScript();
        }
        else if (c & CHANGED_TELEPORT)
        {
            llResetScript();
        }
        else if (c & CHANGED_REGION_START)
        {
            llResetScript();
        }
    }

    on_rez(integer i)
    {
        llResetOtherScript("ODNS");
        llResetOtherScript("Owner Control");
        llResetScript();
    }

    link_message(integer s, integer n, string str, key id)
    {
        if (n==201)
        {
            llSay(0,"Error registering DNS!\n"+str);
        }
        else if (n==200)
        {
            llSetText("DNS Registered Succesfully!",<0,1,0>,1);
            llSay(0,"http://primchat.co.cc/"+DNSName+"/");
            DNSRegistered=TRUE;
            settext(FALSE);
        }
    }

    dataserver(key query, string data)
    {
        if (query==line_query)
        {
            chatpage_length = (integer)data;
            chatpage_readline = 0;
            llSetText("",<1,1,1>,1);
            llGetNotecardLine("chatpage",chatpage_readline);
        }
        else
        {
            if (chatpage_readline<chatpage_length+1)
            {
                float temp = chatpage_readline/10;
                integer x = llFloor(temp);
                string progress;
                progress+="Loading Chatpage\n";
                integer i;
                while (i<x+1)
                {
                    progress+=filled;
                    i++;
                }
                while (i<13)
                {
                    progress+=empty;
                    i++;
                }
                llSetText(progress,<1,1,1>,1);
                if (data!=""){chatpage+="\n";}
                chatpage+=data;
                chatpage_readline++;
                llGetNotecardLine("chatpage",chatpage_readline);
            }
            else
            {
                llSetText("Registering URL...",<1,0,0>,1);
                llRequestURL();
            }
        }
    }

    http_request(key id, string method, string body)
    {
        if (method == URL_REQUEST_GRANTED)
        {
            url = body;
            chatpage = StringReplace(chatpage, "%DNSNAME%", DNSName);
            llSetText("Registering with DNS...",<1,1,1>,1);
            llMessageLinked(LINK_THIS,100,DNSName+"^"+url,"");
            lhandle = llListen(0,"","","");
        }
        else if (method == URL_REQUEST_DENIED)
        {
            llSay(0, "Something went wrong, no url. " + body);
        }
        else if (method == "GET")
        {
            llHTTPResponse(id,200,chatpage);
        }
        else if (method == "POST")
        {
            string headers = llGetHTTPHeader(id,"x-path-info");
            if (headers=="/login/")
            {
                string time = (string)llGetUnixTime();
                integer index = llStringLength(time)-4;
                time = llGetSubString(time,index,llStringLength(time));
                llHTTPResponse(id,200,body+time);
                llSay(0,body+time+" has entered");                    
            }
            else if (headers=="/sendchat/")
            {
                llSay(0,body);
            }
        }
        else
        {
            llHTTPResponse(id,405,"Unsupported Method");
        }
    }

    http_response(key id, integer status, list meta, string body)
    {
        settext(FALSE);
        if (body!="sent" && llSubStringIndex(body,"DNS")==-1 && body!="cleared")
        {
            llSay(0,"Error Sending Message!\n"+body);
        }
    }

    listen(integer chan, string name, key id, string mess)
    {
        if (mess!="")
        {
            string chat_text = "(SL) "+name+": "+mess;        
            request = llHTTPRequest("http://yoursite.com/lslchat/msg_gateway.php",[HTTP_METHOD, "POST", HTTP_MIMETYPE, "application/x-www-form-urlencoded"], "name="+llEscapeURL(DNSName)+"&method=sendchat&data="+llEscapeURL(chat_text)+"&slcheck=yes");
            settext(TRUE);
        }

    }

    touch_start(integer n)
    {
        if (llDetectedKey(0)==llGetOwner())
        {
            llMessageLinked(LINK_THIS,1111,DNSName,"");
        }
        else
        {
            llSay(0,"http://primchat.co.cc/"+DNSName+"/");
        }
    }
}

Owner Control

integer handle;
string DNSName;
key request;
default
{
    link_message(integer s, integer n, string str, key id)
    {
        if (n==1111)
        {
            DNSName = str;
            handle = llListen(-987,"","","");
            llDialog(llGetOwner(),"Please choose an option",["Reset","Clear Log","Open URL"],-987);
        }
    }

    listen(integer chan, string name, key id, string mess)
    {
        llListenRemove(handle);
        if (mess=="Reset")
        {
            llSay(0,"Resetting Scripts...");
            llResetOtherScript("ODNS");
            llResetOtherScript("SL Web Chat");
            llResetScript();
        }
        else if (mess=="Clear Log")
        {
            request = llHTTPRequest("http://zetaphor.net/lslchat/msg_gateway.php",[HTTP_METHOD, "POST", HTTP_MIMETYPE, "application/x-www-form-urlencoded"], "name="+DNSName+"&method=clearlog");
        }
        else if (mess=="Open URL")
        {
            llLoadURL(llGetOwner(),"Opening chat page","");
        }
    }

    http_response(key id, integer status, list meta, string body)
    {
        if (id==request)
        {
            if (body=="cleared")
            {
                llOwnerSay("Log cleared succesfully!");
            }
            else
            {
                llOwnerSay("Error clearing log!\n"+body);
            }
        }
    }
}

Chatpage Notecard

<html>
<head>
<title>SL Web Chat</title>
<script type="text/javascript">
var sendReq = getXmlHttpRequestObject();
var chatReq = getXmlHttpRequestObject();
var nickReq = getXmlHttpRequestObject();
var nick = "";
var dnsname = "%DNSNAME%";
var paused = false;
var newnick;
function getNick(){
nick = prompt('Enter a nickname','Web Chatter');
login();
}            
function getXmlHttpRequestObject() 
{
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
}
}            
function login() 
{
if (nick == null || nick == '') {
alert("You did not enter a nickname!");
getNick();
}
else{
if (sendReq.readyState == 4 || sendReq.readyState == 0){
document.getElementById('p_status').innerHTML = 'Logging In...';
sendReq.open("POST", 'http://zetaphor.net/lslchat/msg_gateway.php', true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleLoginRequest; 
var param = 'method=login';
param += '&name=' + dnsname;
param += '&data=' + nick;
sendReq.send(param);                    
document.getElementById('txt_message').value = '';
}
}        
}
function handleLoginRequest(){
if (sendReq.responseText!=''){
document.getElementById('p_status').innerHTML = 'Current Status: Logged In';
nick = sendReq.responseText;
document.getElementById('p_nick').innerHTML = 'Nickname: '+nick;
loaddiv = document.getElementById('div_chatload');        
loaddiv.onreadystatechange = switchContents;
aTimer = setTimeout('getChatText();',1000);
}
}
function getChatText(){
if (sendReq.readyState == 4 || sendReq.readyState == 0){            
sendReq.open("POST", 'http://zetaphor.net/lslchat/msg_gateway.php', true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleGetChat; 
var param = 'method=getchat';
param += '&name=' + dnsname;
sendReq.send(param);    
}    
if (paused==false){aTimer = setTimeout('getChatText();',1000);bTimer = setTimeout('switchContents();',800);}
}
function handleGetChat(){
document.getElementById('div_chatload').innerHTML = sendReq.responseText;
}
function blockSubmit(){
sendChatText();
return false;
}            
function switchContents(){
var contentcheck = document.getElementById('div_chatload').innerHTML;
if (document.getElementById('div_chat').innerHTML != contentcheck){
document.getElementById('div_chat').innerHTML = document.getElementById('div_chatload').innerHTML;
var objDiv = document.getElementById("div_chat");
objDiv.scrollTop = objDiv.scrollHeight;
}
}
function sendChatText(){
chatReq.open("POST", 'http://zetaphor.net/lslchat/msg_gateway.php', true);
chatReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
var param = 'method=sendchat';
param += '&name=' + dnsname;
param += '&data='+escape('(Web) ' +nick+': '+ document.getElementById('txt_message').value);
chatReq.send(param);    
document.getElementById('txt_message').value = '';
}
function pauseLog(){
if (paused==false){
clearTimeout(aTimer);
clearTimeout(bTimer);
document.getElementById('p_status').innerHTML = 'Current Status: Chat Log Paused!';
document.getElementById('btn_pause_chat').value = 'Unpause Chatlog';
paused = true;
}
else{
aTimer = setTimeout('getChatText();',1000);
bTimer = setTimeout('switchContents();',800);
document.getElementById('p_status').innerHTML = 'Current Status: Logged In';
document.getElementById("btn_pause_chat").value = 'Pause Chatlog';                    
paused = false;
}
}
</script>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">        
</head>
<body onload="javascript:getNick();">
Direct Link: <a href="http://primchat.co.cc/%DNSNAME%/">http://primchat.co.cc/%DNSNAME%/</a>
<p id="p_status">Current Status: Getting Nick</p>
<p id="p_nick">Nickname: </p>
<div id="div_chat" style="height: 300px; width: auto; overflow: auto; background-color: #CCCCCC; border: 1px solid #555555;">            
</div>
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="txt_message" name="txt_message" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="javascript:sendChatText();" />
<input type="button" name="btn_pause_chat" id="btn_pause_chat" value="Pause Chatlog" onclick="javascript:pauseLog();" />
</form><br />This page is best viewed with <a href="http://www.firefox.com">FireFox</a>
<div id="div_chatload" style="height: 5px; width: 5px; visibility: hidden; overflow: auto; background-color: #CCCCCC; border: 1px solid #555555;">            
</div>    
</body>
</html>

PHP

Download PHP

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License