Go Back   vb.org Archive > vBulletin 3 Discussion > vB3 Programming Discussions

Reply
 
Thread Tools Display Modes
  #1  
Old 05-21-2011, 06:44 AM
asdfadrian asdfadrian is offline
 
Join Date: May 2011
Posts: 31
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default Custom chat not showing Usernames?

Hello there I have a custom chat that functions properly; however, it doesnt properly display the usernames. Can someone help me with this?

Online Demo
Notice how when you type, it doesnt show the username. such as below
Code:
[02:38:05] This is the message
When it should display as:
Code:
[02:38:05] Username: This is the message
PHP Code:
<?php
// Start a session and get/generate a random user_id
// We'll use this user_id to create pseudo-uniquely colored chat lines later
// Close the session (a session can only be accessed by one process at a time)
error_reporting(0);
session_start();
header('Cache-control: private'); // IE6 fix
header("Content-Type: text/html; charset=utf-8");
//if (!isset($_SESSION['USER_ID'])) $_SESSION['USER_ID'] = rand(1, 24);
//$USER_ID = $_SESSION['USER_ID'];

$con mysql_connect ("xxxxxxx","xxxxxxx""xxxxxxx");
 
mysql_select_db ("xxxxxxx");

$userid intval($_COOKIE[bbuserid]); 
$sql = @mysql_query("SELECT username FROM user WHERE userid=$USER_ID");

                while (
$row = @mysql_fetch_array($sql)){
                
$username $row['username'];
            }

session_write_close();
ob_flush();
flush();

// Path to the text files holding the chat window content
$fn 'chat.txt';

// Did the browser request the chat content?
// If so, it provided this script with its last known line number
$read = &$_GET['r'];
if (isset(
$read)) {
  
// Create the chat file if neccessary
  
if (!file_exists($fn)) {
    
touch($fn);
    
chmod($fn0644);
  }
  if (
$read == 0chat_write('<E>');
  
// The script will not exit on its own on user disconnect
  // this way we can later add a "user left chat" message
  
ignore_user_abort(true);
  
$i 0;
  while (
true) {
    
// Open the chat file and get the current line number
    
$f fopen($fn'r');
    
flock($f2);
    
$offset 0;
    
$offset trim(fgets($f));
    
// Break the loop if the browser is not up to date
    
if ($offset $read) break;
    
// If the browser is up to date, wait
    
flock($f3);
    
fclose($f);
    @
set_time_limit(0);
    
// By default we wait 3 seconds between each check
    // However, after one minute of complete silence in the chat we step
    // back to 10 second periods to save server resources
    
if ($i 20sleep(10);
    else 
sleep(3);
    
// To check for user disconnection we have to output at least one byte
    // We'll echo a line break since this does no harm to our JavaScript
    
echo "\n";
    
ob_flush();
    
flush();
    if (
connection_status() != 0) {
      
// This is where a user disconnection is detected
      // You could add stuff to display "user left chat" messages here
      
chat_write('<L>');
      exit();
    }
    
$i++;
  }
  
// If the loop was exited, we end up here
  // Now, echo all missing lines
  
while ($s fgets($f)) {
    echo 
utf8_encode($s);
    if (
$offset <= ++$read) break;
  }
  
// Close the file, exit
  
flock($f3);
  
fclose($f);
  exit();
}

// This function writes one line into the chat file
// For easiest accessibility newer lines are on top!
function chat_write($write) {
  global 
$USER_ID$fn;
  
// Maximum line count
  
$maxlines 35;
  if (
trim($write) == '') return;
  
// Create the chat file if neccessary
  
if (!file_exists($fn)) {
    
touch($fn);
    
chmod($fn0644);
  }
  
// Open the chat file and get the current line number
  
$f fopen($fn'r+');
  
flock($f2);
  
$offset 0;
  
fscanf($f"%s\n"$offset);
  
// Increase by one as we're adding a new line now
  
$offset++;
  
$i 0;
  
$chat '';
  
// First we have to read the whole file
  // Lines are being read one by one until we're at the end or until we reach $maxlines
  
while (($i $maxlines) && ($s fgets($f))) {
    
$chat .= $s;
    
$i++;
  }
  
// This is the actual line we're adding
  // You see: The chat file contains JavaScript calls
  // This way no parsing of the lines is neccessary
  // We'll just need to eval() them in our JavaScript
  
$time date('H:i:s');
  
$js "cs($offset,$USER_ID,'$time','$username','$write','');\n";
  
// Go to the top
  
fseek($f0);
  
// Empty the file
  
ftruncate($f0);
  
// Write the new offset
  
fwrite($f"$offset\n");
  
// Write the new line
  
fwrite($f$js);
  
// And then the rest
  
fwrite($f$chat);
  
// Close the file
  
flock($f3);
  
fclose($f);
  
// We'll return the last added line to the calling
  
return $js;
}

function 
chat_delete($delete) {
  global 
$fn;
  if (
$delete == '') exit();
  if (!
file_exists($fn)) {
    
touch($fn);
    
chmod($fn0644);
  }
  
$f fopen($fn'r+');
  
flock($f2);
  
$offset 0;
  
fscanf($f"%s\n"$offset);
  
$chat '';
  
$i 0;
  while (
$s fgets($f)) {
    
$s str_replace("'$delete'""''"$s);
    
$chat .= $s;
    
$i++;
  }
  
fseek($f0);
  
ftruncate($f0);
  
fwrite($f"$offset\n");
  
fwrite($f$chat);
  
flock($f3);
  
fclose($f);
}

// Did the browser send a new chat line?
$write = &$_POST['w'];
if (isset(
$write)) {
  if (
$write == '') exit();
  
// Remove the slashes that were added to the form contents by PHP automatically
  
$write stripslashes($write);
  
// Transform characters like < and > into their HTML representations
  
$write htmlspecialchars($writeENT_QUOTES);
  
$write addslashes($write);
  if (
strpos($write'/del ') === 0) {
    
$delete str_replace('/del '''$write);
    
chat_delete($delete);
    exit();
  }
  
// Wordwrap after 100 characters and add the new lines to the chat file
  
$lines wordwrap($write100"\n"true);
  
$lines explode("\n"$lines);
  foreach (
$lines as &$line) {
    
// The function returns the added line
    // We'll output this so the users can read their own texts without delay right after sending
    
echo utf8_encode(chat_write($line));
  }
  exit();
}
?>
var lines    = 35;
var title    = '';
var offset   = 0;
var messages = new Array();
var message  = document.getElementById('message');
var chat     = document.getElementById('chat');
var tmrRead = setTimeout('chat_read();', 300);

function request_write(url, post) {
  r = false;
  if (window.XMLHttpRequest) {
    r = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      r = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        r = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
      }
    }
  }
  if (!r) return false;
  r.onreadystatechange = alert_write;
  if (post == null) {
    r.open('GET', url, true);
    r.send(null);
  } else {
    r.open('POST', url, true);
    r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    r.send(post);
  }
}

function alert_write() {
  try {
    if ((r.readyState == 4) && (r.status == 200)) parse(r.responseText);
  } catch(e) {
  }
}

function request_read(url, post) {
  r2 = false;
  if (window.XMLHttpRequest) {
    r2 = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      r2 = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        r2 = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
      }
    }
  }
  if (!r2) return false;
  r2.abort();
  r2.onreadystatechange = alert_read;
  if (post == null) {
    r2.open('GET', url, true);
    r2.send(null);
  } else {
    r2.open('POST', url, true);
    r2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    r2.send(post);
  }
}

function alert_read() {
  clearTimeout(tmrRead);
  try {
    if ((r2.readyState == 4) && (r2.status == 200)) {
      parse(r2.responseText);
      tmrRead = setTimeout('chat_read();', 30);
    }
  } catch(e) {
    tmrRead = setTimeout('chat_read();', 3000);
  }
}

function chat_read() {
  clearTimeout(tmrRead);
  request_read('chat.php?r='+offset, null);
}

function keyup(e) {
  if (window.event) k = window.event.keyCode;
  else if (e) k = e.which;
  else return true;
  if (k == 13) chat_write();
}

function chat_display() {
  html = '';
  i = 0;
  while ((i < lines) && (i < offset)) {
    h = offset-i;
    if (messages[h]) html = messages[h] + html;
    i++;
  }
  chat.innerHTML = html;
  if (title != '') {
    title = title.replace(/&amp;/g, '&');
    title = title.replace(/&quot;/g, '"');
    title = title.replace(/'/g, '\'');
    title = title.replace(/&lt;/g, '<');
    title = title.replace(/&gt;/g, '>');
    document.title = title;
  }
}

function chat_write() {
  request_write('chat.php', 'w='+escape(message.value));
  message.value = '';
}

function cs(o, i, t, u, m, c) {
  if (m == '<E>') {
    if (u != '') messages[o] = '<span id="C'+i+'">['+t+'] * '+u+' has entered the chat *</span><br />';
  } else if (m == '<L>') {
    if (u != '') messages[o] = '<span id="C'+i+'">['+t+'] * '+u+' has left the chat *</span><br />';
  } else {
    if (u != '') {
      u += ':';
      spaces = 5 - u.length;
      for (j = 0; j < spaces; j++) u += "&nbsp;";
      u += ' ';
    }
    if (title == '') title = m;
    m = m.replace(/ /g, '&nbsp;');
    messages[o] = '<span id="C'+i+'">['+t+'] '+u+'<b>'+m+'</b></span><br />';
  }
  if (o > offset) {
    offset = o;
    window.focus();
    message.focus();
  }
}

function parse(s) {
  if (s != '') {
    s = unescape(s);
    eval(s);
    chat_display();
  }
}
Reply With Quote
  #2  
Old 05-21-2011, 04:35 PM
asdfadrian asdfadrian is offline
 
Join Date: May 2011
Posts: 31
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Here is a screenshot of the issue.

The conding header for the non-boxed area of the screenshot is shown below:
Code:
error_reporting(0);
session_start();
header('Cache-control: private'); // IE6 fix
header("Content-Type: text/html; charset=utf-8");
if (!isset($_SESSION['USER_ID'])) $_SESSION['USER_ID'] = rand(1, 24);
$USER_ID = $_SESSION['USER_ID'];

session_write_close();
ob_flush();
flush();
Whereas the red boxed portion has the header:
Code:
error_reporting(0);
session_start();
header('Cache-control: private'); // IE6 fix
header("Content-Type: text/html; charset=utf-8");

$con = mysql_connect ("xxxxxx","xxxxxx", "xxxxxx");
 mysql_select_db ("aaronxxxxxx_vbulletin");

$userid = intval($_COOKIE[bbuserid]); 
$sql = @mysql_query("SELECT username FROM user WHERE userid=$USER_ID");

				while ($row = @mysql_fetch_array($sql)){
				$username = $row['username'];
			}

session_write_close();
ob_flush();
flush();
Attached Images
File Type: png nousers.PNG (23.0 KB, 0 views)
Reply With Quote
  #3  
Old 05-21-2011, 04:44 PM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

You have this:
Code:
$userid = intval($_COOKIE[bbuserid]);  
$sql = @mysql_query("SELECT username FROM user WHERE userid=$USER_ID");
Don't you mean $userid instead of $USER_ID?

And why are you doing a while loop when you are only expecting one row returned?
Reply With Quote
  #4  
Old 05-21-2011, 05:28 PM
asdfadrian asdfadrian is offline
 
Join Date: May 2011
Posts: 31
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

I am not entirely sure whether its $userid or $USER_ID but when I changed it to $userid, the chat doesnt work no more. It doesnt connect the user. So it must be $USER_ID.

As for the while loop, I did that because I will code the rest where I will add
$icon = $row['icon'];
$color = $row['color'];

So each user will have a custom icon, if none then they will have a generic icon set for their particularity usergroup. The color is for the text color of each usergroup's username. So "User 1" as an Admin will be Blue, where as "User2" a regular member, will just be white.
Reply With Quote
  #5  
Old 05-21-2011, 07:37 PM
kh99 kh99 is offline
 
Join Date: Aug 2009
Location: Maine
Posts: 13,185
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by asdfadrian View Post
I am not entirely sure whether its $userid or $USER_ID but when I changed it to $userid, the chat doesnt work no more. It doesnt connect the user. So it must be $USER_ID.
I understand what you're saying, but it doesn't make sense for it use $USER_ID since it's never set (the code is commented out). My guess would be that when you use $userid it's finding the user name, but then you're getting a js error in code that wasn't executed when the user name was blank.

Or not.
Reply With Quote
  #6  
Old 05-22-2011, 04:51 PM
asdfadrian asdfadrian is offline
 
Join Date: May 2011
Posts: 31
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Well I have modified the top of the code a bit so that the code would work if the $user_id was blank. I tried both the $userid and $USER_ID and still nothing.

So I can ensure that its not an error with there being no userid or username.. Unless my code is wrong?
Here is the modified original code:
PHP Code:
global $vbulletin;
require_once(
'./global.php');   

$con mysql_connect ("xxxxxxx","xxxxxxx""xxxxxxx"); 
 
mysql_select_db ("xxxxxxx"); 

$userid intval($_COOKIE[bbuserid]); 
$sql = @mysql_query("SELECT username FROM user WHERE userid=$userid");

                while (
$row = @mysql_fetch_array($sql)){
                
$name $row['username'];
                
$icon $row['icon'];
                
$color $row['color'];
            }

if(
$color == 0)
            {
                
$color "#989579";
            }

if (
$icon == '')
            {
                
$icon 'http://www.hiveworkshop.com/forums/images_all/chat_ranks/new/user.png';
            }
            

if (
$userid == ''){
            
                
$username 'Guest';    
            } 
I have also attempted to see if maybe another approach would work. Yet nothing. Again, unless I did something wrong?
PHP Code:
global $vbulletin;
require_once(
'./global.php');   
   
   
//if (!isset($_SESSION['userid'])) $_SESSION['userid'] = rand(1, 24);
//$userid = $_SESSION['userid'];
$userid $vbulletin->userinfo['userid'];
$username $vbulletin->userinfo['username'];

if (
$userid == ''){
            
                
$username 'Guest';    
            } 
Reply With Quote
  #7  
Old 05-22-2011, 05:02 PM
kh99 kh99 is offline
 
Join Date: Aug 2009
Location: Maine
Posts: 13,185
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Is your php file included (or "required") in another file, or is it supposed to be "stand-alone". I'm not sure if you're showing all the code in what you posted above, but if that file isn't being included in another vbulletin file, then you need to define some things before including global.php. If it is being included, then you probably don't need to include global.php.

Your original code had "error_reporting(0);" and some '@'s at the beginning of some function calls. You might want to remove those, at least temporarily, so you can see any PHP errors that you might be getting.
Reply With Quote
  #8  
Old 05-22-2011, 05:36 PM
asdfadrian asdfadrian is offline
 
Join Date: May 2011
Posts: 31
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Well theres 3 files involved. chat.php, chat.txt and chat.htm Everything I have showed you is the complete code. Chat.txt as you can imagine, is just the file it writes to and displays.

Below is the chat.htm:
PHP Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml2/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<
meta http-equiv="content-style-type" content="text/css" />
<
title>Hordechat 2.0</title>
<
style type="text/css">
<!--
body {color:blackbackground:whitefont-family:verdana,arial,helvetica,sans-seriffont-size:13px;}
#C1  {color:#000;}
#C2  {color:#008;}
#C3  {color:#004;}
#C4  {color:#080;}
#C5  {color:#088;}
#C6  {color:#084;}
#C7  {color:#040;}
#C8  {color:#048;}
#C9  {color:#044;}
#C10 {color:#800;}
#C11 {color:#808;}
#C12 {color:#804;}
#C13 {color:#880;}
#C14 {color:#888;}
#C15 {color:#884;}
#C16 {color:#840;}
#C17 {color:#848;}
#C18 {color:#844;}
#C19 {color:#400;}
#C20 {color:#408;}
#C21 {color:#404;}
#C22 {color:#480;}
#C23 {color:#4CC;}
#C24 {color:#440;}
#chat {height:561px; width:830px; font-family:courier new,monospace; font-size:11px; line-height:16px; border:1px solid #CCC; background:#EEE;}
#message {font-family:courier new,monospace; font-size:12px; color:#00F;}
a.copyright {font-size10pxcolor:#888;}
-->
</
style>
</
head>
<
body>
<
div id="chat">Connected!<br />
  <
br />
  If 
chat does not refreshbeing by typing below and submitting a message
</
div>
&
nbsp;<input id="message" type="text" size="100" onkeyup="keyup(event);" />
<
input type="button" value="Submit" onclick="chat_write();" /><br />
<
class="copyright" href="http://hordestudio.com" target="_blank">Hordestudio.com Chatscript by Atmosferic</a>
<
script language="JavaScript" type="text/javascript" src="chat.php"></script>
</
body>
</
html
Alright I will enable the error_reporting back to (1). As for the @ you mean completely remove the call? Alright, done. I hope the above file helps. Its not a vb_template, so no need to define or eval anything. It makes things more easier.
Reply With Quote
  #9  
Old 05-22-2011, 06:16 PM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

This will not do anything:
Code:
$sql = @mysql_query("SELECT username FROM user WHERE userid=$userid");

                while ($row = @mysql_fetch_array($sql)){
                $name = $row['username'];
                $icon = $row['icon'];
                $color = $row['color'];
            }
You have a select statement that selects the username. That is all. There is no such thing as $row['color'] or $row['icon']. And, before you go think you can just add icon and color to the select statement, take a look at your user table - do you see those fields there? Nope. So, what are you trying to grab?
Reply With Quote
  #10  
Old 05-22-2011, 06:53 PM
kh99 kh99 is offline
 
Join Date: Aug 2009
Location: Maine
Posts: 13,185
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by asdfadrian View Post
Alright I will enable the error_reporting back to (1).
I think you want error_reporting(-1) to turn on all errors.


Quote:
As for the @ you mean completely remove the call? Alright, done. I hope the above file helps. Its not a vb_template, so no need to define or eval anything. It makes things more easier.
No, just the '@', which says to ignore errors from that call.
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 11:11 PM.


Powered by vBulletin® Version 3.8.12 by vBS
Copyright ©2000 - 2025, vBulletin Solutions Inc.
X vBulletin 3.8.12 by vBS Debug Information
  • Page Generation 0.04599 seconds
  • Memory Usage 2,386KB
  • Queries Executed 12 (?)
More Information
Template Usage:
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_header_end
  • (1)ad_header_logo
  • (1)ad_navbar_below
  • (1)ad_showthread_beforeqr
  • (1)ad_showthread_firstpost
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (6)bbcode_code
  • (4)bbcode_php
  • (3)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)navbar
  • (3)navbar_link
  • (120)option
  • (1)pagenav
  • (1)pagenav_curpage
  • (2)pagenav_pagelink
  • (10)post_thanks_box
  • (10)post_thanks_button
  • (1)post_thanks_javascript
  • (1)post_thanks_navbar_search
  • (10)post_thanks_postbit_info
  • (10)postbit
  • (1)postbit_attachment
  • (10)postbit_onlinestatus
  • (10)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available:
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files:
  • ./showthread.php
  • ./global.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/class_hook.php
  • ./includes/modsystem_functions.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_post_thanks.php 

Hooks Called:
  • init_startup
  • init_startup_session_setup_start
  • init_startup_session_setup_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • style_fetch
  • cache_templates
  • global_start
  • parse_templates
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • forumjump
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • post_thanks_function_post_thanks_off_start
  • post_thanks_function_post_thanks_off_end
  • post_thanks_function_fetch_thanks_start
  • post_thanks_function_fetch_thanks_end
  • post_thanks_function_thanked_already_start
  • post_thanks_function_thanked_already_end
  • fetch_musername
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • post_thanks_function_can_thank_this_post_start
  • postbit_attachment
  • pagenav_page
  • pagenav_complete
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • showthread_complete