Karczma / Chat

Marek Szydełko
05.09.2015

Odnajdując dalej swoje skrypty, po długiej przerwie, znalazłem jeszcze skrypt chatu / karczmy. Zapewne nie mój, pewnie znaleziono-przerobiony, co widzać po komentarzu do drugiego pliku ^^. Pamiętam, że miałem problem, bo nie wiedziałem czy jest optymalny i czy wstawienie go do gry, nie jest samobójstwem. Może zaprezentuje:


chat.php:

<html>
    <head>
<script language="JavaScript" type="text/javascript">
            var sendReq = getXmlHttpRequestObject();
            var receiveReq = getXmlHttpRequestObject();
            var lastMessage = 0;
            var mTimer;
            //Function for initializating the page.
            function startChat() {
                //Set the focus to the Message Box.
                document.getElementById('txt_message').focus();
                //Start Recieving Messages.
                getChatText();
            }       
            //Gets the browser specific XmlHttpRequest Object
            function getXmlHttpRequestObject() {
                if (window.XMLHttpRequest) {
                    return new XMLHttpRequest();
                } else if(window.ActiveXObject) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } else {
                    document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
                }
            }
           
            //Gets the current messages from the server
            function getChatText() {
                if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
                    receiveReq.open("GET", 'getChat.php?chat=1&place=<? echo $title; ?>&last=' + lastMessage, true);
                    receiveReq.onreadystatechange = handleReceiveChat;
                    receiveReq.send(null);
                }           
            }
            //Add a message to the chat server.
            function sendChatText() {
                if(document.getElementById('txt_message').value == '') {
                    alert("You have not entered a message");
                    return;
                }
                if (sendReq.readyState == 4 || sendReq.readyState == 0) {
                    sendReq.open("POST", 'getChat.php?chat=1&place=<? echo $title; ?>&last=' + lastMessage, true);
                    sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    sendReq.onreadystatechange = handleSendChat;
                    var param = 'message=' + document.getElementById('txt_message').value;
                    param += '&name=<? echo $player['name'];?>';
                    param += '&chat=1';
                    sendReq.send(param);
                    document.getElementById('txt_message').value = '';
                }                           
            }
            //When our message has been sent, update our page.
            function handleSendChat() {
                //Clear out the existing timer so we don't have
                //multiple timer instances running.
                clearInterval(mTimer);
                getChatText();
            }
            //Function for handling the return of chat text
            function handleReceiveChat() {
                if (receiveReq.readyState == 4) {
                    var chat_div = document.getElementById('div_chat');
                    var xmldoc = receiveReq.responseXML;
                    var message_nodes = xmldoc.getElementsByTagName("message");
                    var n_messages = message_nodes.length
                    for (i = 0; i < n_messages; i++) {
                        var user_node = message_nodes[i].getElementsByTagName("user");
                        var text_node = message_nodes[i].getElementsByTagName("text");
                        var time_node = message_nodes[i].getElementsByTagName("time");
                        chat_div.innerHTML += '<b>'+ user_node[0].firstChild.nodeValue + ':</b>&nbsp;';
                        chat_div.innerHTML += text_node[0].firstChild.nodeValue + '<br />';
                        chat_div.scrollTop = chat_div.scrollHeight;
                        lastMessage = (message_nodes[i].getAttribute('id'));
                    }
                    mTimer = setTimeout('getChatText();',2000); //Refresh our chat in 2 seconds
                }
            }
            //This functions handles when the user presses enter.  Instead of submitting the form, we
            //send a new message to the server and return false.
            function blockSubmit() {
                sendChatText();
                return false;
            }
            //This cleans out the database so we can start a new chat session.
            function resetChat() {
                if (sendReq.readyState == 4 || sendReq.readyState == 0) {
                    sendReq.open("POST", 'getChat.php?chat=1&last=' + lastMessage, true);
                    sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    sendReq.onreadystatechange = handleResetChat;
                    var param = 'action=reset';
                    sendReq.send(param);
                    document.getElementById('txt_message').value = '';
                }                           
            }
            //This function handles the response after the page has been refreshed.
            function handleResetChat() {
                document.getElementById('div_chat').innerHTML = '';
                getChatText();
            }   
        </script>
    </head>
    <body onload="javascript:startChat();">
           
        <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="Powiedz" onclick="javascript:sendChatText();" />
        </form>
        <div id="div_chat" align='left' style="height: 300px; width: 500px; overflow: auto; border: 1px solid #555555;"></div>
    </body>
   
</html>

getChat.php

<?php
/*
    This is the PHP backend file for the AJAX Driven Chat application.
   
    You may use this code in your own projects as long as this copyright is left
    in place.  All code is provided AS-IS.
    This code is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
   
    For the rest of the code visit http://www.DynamicAJAX.com
   
    Copyright 2005 Ryan Smith / 345 Technical / 345 Group.
*/

//Send some headers to keep the user's browser from caching the response.
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-Type: text/xml; charset=utf-8");

require('database.php');

//Check to see if a message was sent.
if(isset($_POST['message']) && $_POST['message'] != '') {
    $sql = "INSERT INTO inn(chat_id, user_id, user_name, message, post_time, location) VALUES (".db_input($_GET['chat']).", 1, '".db_input($_POST['name'])."', '" . db_input($_POST['message']) . "', NOW(), '".$_GET['place']."')";
    db_query($sql);
}
//Check to see if a reset request was sent.
if(isset($_POST['action']) && $_POST['action'] == 'reset') {
    $sql = "DELETE FROM inn WHERE chat_id = " . db_input($_GET['chat']);
    db_query($sql);
}

//Create the XML response.
$xml = '<?xml version="1.0" ?><root>';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
    $xml .='Your are not currently in a chat session.  <a href="">Enter a chat session here</a>';
    $xml .= '<message id="0">';
    $xml .= '<user>Admin</user>';
    $xml .= '<text>Your are not currently in a chat session.  &lt;a href=""&gt;Enter a chat session here&lt;/a&gt;</text>';
    $xml .= '<time>' . date('h:i') . '</time>';
    $xml .= '</message>';
} else {
    $last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
    $sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') as post_time" .
        " FROM inn WHERE location='".$_GET['place']."' AND chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
    $message_query = db_query($sql);
    //Loop through each message and create an XML message node for each.
    while($message_array = db_fetch_array($message_query)) {
        $xml .= '<message id="' . $message_array['message_id'] . '">';
        $xml .= '<user>' . htmlspecialchars($message_array['user_name']) . '</user>';
        $xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
        $xml .= '<time>' . $message_array['post_time'] . '</time>';
        $xml .= '</message>';
    }
}
$xml .= '</root>';
echo $xml;
?>

 

database.php

 


<?php
  db_connect() or die('Unable to connect to database server!');

  function db_connect($server = 'localhost', $username = 'root', $password = '', $database = '....', $link = 'db_link') {
    global $$link;

    $$link = mysql_connect($server, $username, $password);

    if ($$link) mysql_select_db($database);

    return $$link;
  }
//Function to handle database errors.
  function db_error($query, $errno, $error) {
    die('<font color="#000000"><b>' . $errno . ' - ' . $error . '<br><br>' . $query . '<br><br><small><font color="#ff0000">[STOP]</font></small><br><br></b></font>');
  }
//Function to query the database.
  function db_query($query, $link = 'db_link') {
    global $$link;

    $result = mysql_query($query, $$link) or db_error($query, mysql_errno(), mysql_error());

    return $result;
  }
//Get a row from the database query
  function db_fetch_array($db_query) {
    return mysql_fetch_array($db_query, MYSQL_ASSOC);
  }
//The the number of rows returned from the query.
  function db_num_rows($db_query) {
    return mysql_num_rows($db_query);
  }
//Get the last auto_increment ID.
  function db_insert_id() {
    return mysql_insert_id();
  }
//Add HTML character incoding to strings
  function db_output($string) {
    return htmlspecialchars($string);
  }
//Add slashes to incoming data
  function db_input($string, $link = 'db_link') {
    global $$link;

    if (function_exists('mysql_real_escape_string')) {
      return mysql_real_escape_string($string, $$link);
    } elseif (function_exists('mysql_escape_string')) {
      return mysql_escape_string($string);
    }

    return addslashes($string);
  }

?>

Zgłoś swój pomysł na artykuł

Więcej w tym dziale Zobacz wszystkie