Text File Based Shoutbox

Hi,

One of my friends asked me how to make a Flash based shoutbox, so this is what I have come up with after a little playing around.

It uses Flash using ActionScript 2 with some php (needs 5.1) processing to add in html tags to an external text field that is then used to display the “shouts”. The shout box is styled via CSS, which is parsed using actionScript from an external CSS file and passed to php as a variable.

There is a fair degree of error checking. It limits a user to 200 characters in the message field, along with 3 presses of the “enter” or “return” keys. Plus, the php sets a browser cookie, limiting posts to one every 30 mins. Email addresses are required and validated and a name is required. Each post is date stamped via php.

I’m really only beginning with Flash and more so with PHP. So I’m sure there are better ways much of this could be done.

I haven’t really come across many text based shoutbox implementations, so I thought this may be of use to some people here.

Preview the file here: shoutbox

Get the zip archive here: archive

If you want to run this off your local machine, you will need php installed and your webserver turned on…

Here is the ActionScript Code:


//by http://www.noponies.com
//Dale Sattler 

stop();
//import general component controls
import mx.controls.*;

//style the alert box components text
import mx.styles.CSSStyleDeclaration;
var alertStyle = new CSSStyleDeclaration();
alertStyle.setStyle("fontWeight","bold");
Alert.buttonStyleDeclaration = alertStyle;
Alert.titleStyleDeclaration = alertStyle;


//Set up some of our preliminary variables
comments_txt.maxChars = 200;//max chars in comments field
comments_txt.restrict = "^<>/";//restrict users ability to enter in rouge html and break the text field display
var maxReturns:Number = 3;//max presses of the enter key in comments
var returnCount:Number = 0;//init var for max enter key presses
var stylesArray:Array = [];//empty array used to store css class styles

loadText = new LoadVars();//load in the external text vars


loadText.onLoad = function(success) {
	if (success)
	{
		shouts_txt.htmlText = this.mycontent;
	} else
	{
		//catch an errors in our text loading
		shouts_txt.text = "There has been a FATAL ERROR - Data has not loaded";
	}
};


// create a new TextField.StyleSheet instance which will be used to load in the CSS file.
var css_styles:TextField.StyleSheet = new TextField.StyleSheet();

// define the event handler for the onLoad event.
css_styles.onLoad = function(success:Boolean) {
	// if the styles were able to be loaded and parsed successfully
	if (success)
	{
		//here we cycle through our style sheet and remove any styles that are not classes, for instance the 'a' tags
		//we can assume that any class will be prefixed with a '.' which is standard css practice
		var tempStyles:Array = this.getStyleNames();
		tempStyles.sort();

		for (var i = 0; i<tempStyles.length; i++)
		{
			var styleName_str:String = tempStyles*;
			if (styleName_str.charAt(0) == ".")
			{
				//stylesArray.push(styleName_str);//end up with an array of just our css classes
				stylesArray.push(styleName_str.slice(1, styleName_str.length));//strip the "." from the class
				
			}
		}
		//Style the shouts text box
		shouts_txt.styleSheet = css_styles;
	} else
	{
		// else the styles failed to load/parse, so display an error in the authoring environment.
		trace("Error loading CSS file.");
	}
};
// load the style sheet.
css_styles.load("styles.css");


/*load in the vars from php - conditional switch depending on what gets returned
from the php script */

var myVars:LoadVars = new LoadVars();
myVars.onLoad = function():Void  {
	switch (myVars.verify)
	{
		case "success" ://when we get a OK status returned from the server, we load in the external text file.
			//status_txt.text = "data Saved";//debug
			//path to your text file here
			loadText.load("shouts.txt");
			break;
		case "toomanyposts" ://check for too many posts from user
			//status_txt.text = "too many posts";//debug
			Alert.show("Only one post per hour is  allowed in this application","Too Many Posts",Alert.OK);
			break;
	}
};

//load in existing posts
loadText.load("shouts.txt");

//submit button
submit_btn.onRelease = function() {
	if (!email_txt.length || email_txt.indexOf("@") == -1 || email_txt.indexOf(".") == -1)
	{
		//validate email
		email_txt.text = "Invalid Email!";
		Selection.setFocus("email_txt");
	} else if (!name_txt.length)
	{
		//require a name
		name_txt.text = "Missing Name";
		Selection.setFocus("name_txt");
	} else
	{

		//run a function to decide what style class to apply to the shout box output
		var rawString:String = loadText.mycontent;
		var index1 = rawString.indexOf("p class=\""+stylesArray[0]+"\"");
		var index2 = rawString.indexOf("p class=\""+stylesArray[1]+"\"");
		
		if (index1 == index2)
		{
			setStyles = (stylesArray[0]);
		} 
		
		//toggle styles
		if (index1 == 1)
		{
			setStyles = (stylesArray[1]);
		} 
		
		if (index2 == 1)
		{
			setStyles = (stylesArray[0]);
		}

		//send and load the variables
		myVars.userName = name_txt.text;
		myVars.userEmail = email_txt.text;
		myVars.userComments = comments_txt.text;
		myVars.setShoutStyles = setStyles;
		myVars.sendAndLoad("shout.php",myVars,"POST");
	}
};


/*Listener object to track the use of the enter key in our comments
text box. We don't really want too many returns, so we limit the amount of
new lines that can be made*/

var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
	// stop people adding in too many returns - they are allowed 3 here.
	if (Key.getCode() == Key.ENTER)
	{
		returnCount++;
		if (returnCount>=maxReturns)
		{
			//Do something about user entering too many returns
			//set the focus of the application to null. This essentially captures the enter key
			Selection.setFocus(Null);
			//throw and alert
			Alert.show("Only "+maxReturns+" line breaks are allowed in this application","Too Many Returns",Alert.OK);

		}
	}
};
Key.addListener(keyListener);


/*set up a lister object on the comments text field
so we can populate a count down object indicating how many more
characters a user has left*/

var txtListener:Object = new Object();
txtListener.onChanged = function() {
	chars = String(comments_txt.text).length;
	charsLeft_txt.text = comments_txt.maxChars-chars;
};
comments_txt.addListener(txtListener);

Here is the relevant php code:

<?php

//scripted by http://www.noponies.com
//Note, this php script requires php 5.1!

$userName = $_POST['userName'];
$userEmail = $_POST['userEmail'];
$userComments = $_POST['userComments'];
$setShoutStyles = $_POST['setShoutStyles'];

//date stamp - use if you want
//$theDate = date('l dS \of F Y h:i:s A');
$theDate = date('m.d.y, g:i a'); 

//name of your text file
$filename = 'shouts.txt';

//set the variable flash needs to import dynamic external text
//the length of this, provides the point for php to read content from the text file
$flashVar = "mycontent=";

//Find out the length of the flashvar variable - use length as the offset value below
$offSet = strlen($flashVar);

//get the existing content from the file
$file_string = file_get_contents($filename,FALSE,NULL,$offSet,filesize($filename));

//join all our various variables into one variable that we can pass to the
//put_contents function later on

//un comment line below to not combine email and name
//$add = $flashVar . "<p class=\"" . $setShoutStyles . "\">"  . $userName . "  " .  $userEmail  . "  at:" . "<i>" . $theDate . "</i>" . "<br>" . $userComments . "<br>" . "</p>" . $file_string; 

//create mailto link from name
$add = $flashVar . "<p class=\"" . $setShoutStyles . "\">" .  "<a href=\"mailTo:" . $userEmail . "\">" . $userName . "</a>" . "  at: " . "<i>" . $theDate . "</i>" . "<br>" . $userComments . "<br>" . "</p>" . $file_string; 

//set the write function to a var so we can notify flash if we successfully wrote the file

//conditional test to see if a cookie has been set. If it has been set, we dont allow a post. If not
//we allow the write function and post. Flash is alerted in each instance so we can
//respond accordingly

if (isset($_COOKIE["shouter"])){
    echo "&verify=toomanyposts&";
}else{
  $write = file_put_contents($filename, $add, LOCK_EX);//put contents back into file - obtain a lock on the file to prevent corruption
  echo "&verify=success&";
  }

//set cookie here
setcookie("shouter", "Shout", time()+1800);//30 mins expiry


?>

Let me know if it craps out. I had a weird issue where if I changed one of the CSS style names, it wouldn’t update in Flash, even though it was parsing correctly. I still have no idea what was causing that.

Remember, it needs php 5.1 for some of the php functions to work, namely the file_get_contents() and file_putt_contents() functions. If you for some reason decide to change the variable used in the text file, make sure you update the php and AS files to reflect this change. The text file that stores the posts must be writable by PHP. Check this if you have issues

Enjoy :crazy:

I just test it… and doesnt work!
I do not know why… but when i try to shout something and hit submit button… nothing happens!

What could be happen?
Peace

Its probably getting cached by your browser…