Category Archives: Chat Scripts

10 PHP FREE Chat Scripts

Chatting online with friends or even with strangers is something we cannot leave without (I guess? lol). So we thought we would share 10 FREE PHP chat modules to help you with that ;) They are useful for web developers. Few of them are so simple that even a kid can install them! Happy chatting!

1. PCPIN Chat

A free resource of powerful and secure professional homepage tools developed in PHP with MySQL backend.

2. Voodoo chat

Voc is a stream-chat engine which is designed to work on high-loaded chat-servers. It is written in PHP, but uses Perl or C++ for Voc-daemon — the special program to handle multiple user-connections.

3. AJAX Chat

Features:
> Easy installation
> Usable as shoutbox
> Multiple channels
> Private messaging
> Private channels
> Invitation system
> Kick offending Users
> Ban offending Users
> Ignoring offending Users
> Online users list with user menu
> and many more…

4. Freeshoutbox

A free shoutbox host Features: – HTML-code, so you can implement your shoutbox onto your site/forum/portal/blog/whatever – Unlimited space/bandwidth – Fast & reliable server – Many templates to choose from, or create your own

5. phpFreeChat

A free, simple to install, fast, customizable and multi languages chat that uses a simple filesystem for message and nickname storage. It uses AJAX to smoothly refresh (no flicker) and display the chat zone and the nickname zone.

6. X7 Chat

A complete recode of X7 Chat designed primarily with efficiency and stability in mind.

7. BlaB! Lite

BlaB! Lite 5 (freeware) BlaB! Lite is an AJAX based and best viewed with any browser chat system that supports MySQL, SQLite & PostgreSQL databases.

8. Java Chat script with PHP backend

A chat software that allows the users of a website or a private network to communicate with each other. The software includes: Java/JavaScript client application. PHP/MySQL chat server.

9. The Hablator

Is an advanced GPL’ed chat script written in PHP and JavaScript. It offers all of the features you could want in a chat script, while maintaining low server requirements, low client requirements, exceptional speed, and simple installation.

10. GrezorTeamSpeak – a simple PHP/Ajax chat script

This application is a simple chat written in PHP/JavaScript. It does not require any database or special software.

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Scripts for Personal or Commercial Use

Welcome to Maian Script World, a collection of free PHP scripts, written by myself, released under the Creative Commons Attribution 2.5 Licence. Some of these scripts were originally released under a commercial licence, but are now completely free of charge. You are free to use these scripts for both commercial or personal use. I only ask that you leave the link to my website in the footer.If you insist on removing the copyright notice, please use the link above for more information.I also have a few commercial products available, the links to these are shown in the right hand menu. These are ideal tools for marketeers. A small number of my products may also be encoded to enforce the copyright removal. If you are interested, click the links for more information.

 

<?php
/*****************************************************************************
*                                                                           *
* Shop-Script FREE                                                          *
* Copyright (c) 2005 WebAsyst LLC. All rights reserved.                     *
*                                                                           *
****************************************************************************/


ini_set("display_errors", "1");

//ADMIN :: categories managment

include("./cfg/connect.inc.php");
include("./includes/database/mysql.php");
include("./cfg/category_functions.php");
include("./cfg/general.inc.php");

//connect to database
db_connect(DB_HOST,DB_USER,DB_PASS) or die (db_error());
db_select_db(DB_NAME) or die (db_error());

//checking for authorized access
session_start();

//current language
include("./cfg/language_list.php");
if (!isset($_SESSION["current_language"]) ||
$_SESSION["current_language"] < 0 || $_SESSION["current_language"] > count($lang_list))
$_SESSION["current_language"] = 0; //set default language

if (isset($lang_list[$_SESSION["current_language"]]) &amp;&amp; file_exists("./languages/".$lang_list[$_SESSION["current_language"]]->filename))
include("./languages/".$lang_list[$_SESSION["current_language"]]->filename); //include current language file
else
{
die("<font color=red><b>ERROR: Couldn't find language file!</b></font>");
}

include("./checklogin.php");
if (!isset($_SESSION["log"]) || strcmp($_SESSION["log"],ADMIN_LOGIN)) //unauthorized
{
die ("You are not authorized to view this page");
}

?><html>

<head>
<link rel=STYLESHEET href="images/backend/style-backend.css" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo DEFAULT_CHARSET;?>">
<title><?php echo ADMIN_CATEGORY_TITLE;?></title>
<script>
function confirmDelete(text,url)
{
temp = window.confirm(text);
if (temp) //delete
{
window.location=url;
}
}
</script>
</head>

<body bgcolor=#D2D2FF>

<?php
function deleteSubCategories($parent) //deletes all subcategories of category with categoryID=$parent
{

//subcategories
$q = db_query("SELECT categoryID FROM ".CATEGORIES_TABLE." WHERE parent=$parent and categoryID<>0") or die (db_error());
while ($row = db_fetch_row($q))
{
deleteSubCategories($row[0]); //recurrent call
}
$q = db_query("DELETE FROM ".CATEGORIES_TABLE." WHERE parent=$parent and categoryID<>0") or die (db_error());

//move all product of this category to the root category
$q = db_query("UPDATE ".PRODUCTS_TABLE." SET categoryID=0 WHERE categoryID=$parent") or die (db_error());
}

function category_Moves_To_Its_SubDirectories($cid, $new_parent)
{
//return true/false



$a = false;
$q = db_query("SELECT categoryID FROM ".CATEGORIES_TABLE." WHERE parent=$cid and categoryID<>0") or die (db_error());
while ($row = db_fetch_row($q))
{
if ($row[0] == $new_parent) $a = true;
else
$a = category_Moves_To_Its_SubDirectories($row[0],$new_parent);
}
return $a;
}

if (!isset($w)) $w=-1; //parent

if (isset($_GET["picture_remove"])) //delete category thumbnail from server
{
$q = db_query("SELECT picture FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());
$r = db_fetch_row($q);
if ($r[0] &amp;&amp; file_exists("./products_pictures/$r[0]")) unlink("./products_pictures/$r[0]");
db_query("UPDATE ".CATEGORIES_TABLE." SET picture='' WHERE categoryID='".$_GET["c_id"]."'") or die (db_error());
}

if (isset($_POST["save"]) &amp;&amp; $_POST["name"]) { //save changes

if (!isset($_POST["must_delete"])) //add new category
{
$q = db_query("INSERT INTO ".CATEGORIES_TABLE." (name, parent, products_count, description, picture, products_count_admin) VALUES ('".$_POST["name"]."',".$_POST["parent"].",0,'".$_POST["desc"]."','',0)") or die (db_error());
$pid = db_insert_id();
}
else //update existing category
{
if ($_POST["must_delete"] != $_POST["parent"]) //if not moving category to itself
{

//if category is being moved to any of it's subcategories - it's
//neccessary to 'lift up' all it's subcategories

if (category_Moves_To_Its_SubDirectories($_POST["must_delete"], $_POST["parent"]))
{
//lift up is required

//get parent
$q = db_query("SELECT parent FROM ".CATEGORIES_TABLE." WHERE categoryID<>0 and categoryID='".$_POST["must_delete"]."'") or die (db_error());
$r = db_fetch_row($q);

//lift up
db_query("UPDATE ".CATEGORIES_TABLE." SET parent='$r[0]' WHERE parent='".$_POST["must_delete"]."'") or die (db_error());

//move edited category
db_query("UPDATE ".CATEGORIES_TABLE." SET name='".str_replace("<","&amp;lt;",$_POST["name"])."', description='".$_POST["desc"]."', parent='".$_POST["parent"]."' WHERE categoryID='".$_POST["must_delete"]."'") or die (db_error());

}
else //just move category
db_query("UPDATE ".CATEGORIES_TABLE." SET name='".str_replace("<","&amp;lt;",$_POST["name"])."', description='".$_POST["desc"]."', parent='".$_POST["parent"]."' WHERE categoryID='".$_POST["must_delete"]."'") or die (db_error());
}
$pid = $_POST["must_delete"];

update_products_Count_Value_For_Categories(0);

}

if (isset($_FILES["picture"]) &amp;&amp; $_FILES["picture"]["name"] &amp;&amp; preg_match('/\.(jpg|jpeg|gif|jpe|pcx|bmp)$/i', $_FILES["picture"]["name"])) //upload category thumbnail
{

//old picture
$q = db_query("SELECT picture FROM ".CATEGORIES_TABLE." WHERE categoryID='$pid' and categoryID<>0") or die (db_error());
$row = db_fetch_row($q);

//upload new photo
$picture_name = str_replace(" ","_", $_FILES["picture"]["name"]);
if (!move_uploaded_file($_FILES["picture"]["tmp_name"], "./products_pictures/$picture_name")) //failed to upload
{
echo "<center><font color=red>".ERROR_FAILED_TO_UPLOAD_FILE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}
else //update db
{
db_query("UPDATE ".CATEGORIES_TABLE." SET picture='$picture_name' WHERE categoryID='$pid'") or die (db_error());
SetRightsToUploadedFile( "./products_pictures/".$picture_name );
}

//remove old picture...
if ($row[0] &amp;&amp; strcmp($row[0], $picture_name) &amp;&amp; file_exists("./products_pictures/$row[0]"))
unlink("./products_pictures/$row[0]");

}

//now close the window (in case of success)
echo "<script>\n";
echo "window.opener.location.reload();\n";
echo "window.close();\n";
echo "</script>\n</body>\n</html>";
}
else { //category edition from

if (isset($_GET["c_id"])) //edit existing category
{
$q = db_query("SELECT name, description, picture FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());
$row = db_fetch_row($q);
if (!$row) //can't find category....
{
echo "<center><font color=red>".ERROR_CANT_FIND_REQUIRED_PAGE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}
$title = "<b>$row[0]</b>";
$n = $row[0];
$d = $row[1];
$picture = $row[2];

if (isset($_GET["del"])) //delete category
{

//photo
$q = db_query("SELECT picture FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());
$r = db_fetch_row($q);
if ($r[0] &amp;&amp; file_exists("./products_pictures/$r[0]")) unlink("./products_pictures/$r[0]");

//delete from db
$q = db_query("DELETE FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());

deleteSubCategories($_GET["c_id"]);

update_products_Count_Value_For_Categories(0);

//close window
echo "<script>\n";
echo "window.opener.location.reload();\n";
echo "window.close();";
echo "</script>\n</body>\n</html>";
}
}
else //create new
{
$title = ADMIN_CATEGORY_NEW;
$n = "";
$d = "";
$picture = "";
}

?>

<center><font color=purple><?php echo $title; ?></font></center>
<form enctype="multipart/form-data" action="category.php" method=post>

<table width=100% border=0>

<tr>
<td align=right>
<?php
if (!isset($_GET["c_id"])) echo ADMIN_CATEGORY_PARENT;
else echo ADMIN_CATEGORY_MOVE_TO;
?>
</td>
<td width=5%>&amp;nbsp;</td>
<td>
<select name="parent">
<option value="0"><?php echo ADMIN_CATEGORY_ROOT;?></option>
<?php
//fill the category combobox
$tmp = isset($_GET["w"]) ? $_GET["w"] : $_POST["parent"];
$cats = fillTheCList(0,0);
for ($i=0; $i<count($cats); $i++)
{
echo "<option value=\"".$cats[$i][0]."\"";
if ($tmp == $cats[$i][0]) //select category
echo " selected";
echo ">";
for ($j=0;$j<$cats[$i][5];$j++) echo "&amp;nbsp;&amp;nbsp;";
echo $cats[$i][1];
echo "</option>";
}
?>
</select>
</td>
</tr>

<tr>
<td align=right><?php echo ADMIN_CATEGORY_NAME;?></td>
<td>&amp;nbsp;</td>
<td><input type="text" name="name" value="<?php echo str_replace("\"","&amp;quot;",$n); ?>" size=13></td>
</tr>

<tr>
<td align=right><?php echo ADMIN_CATEGORY_LOGO;?></td>
<td>&amp;nbsp;</td>
<td><input type="file" name="picture"></td>
<tr>
<td>&amp;nbsp;</td>
<td>&amp;nbsp;</td>
<td>
<?php
if ($picture != "" &amp;&amp; file_exists("./products_pictures/".$picture))
{
echo "<font></font> <a href=\"products_pictures/".$picture."\">$picture</a>\n";
echo "<br><a href=\"javascript:confirmDelete('".QUESTION_DELETE_PICTURE."','category.php?c_id=".$_GET["c_id"]."&amp;w=".$_GET["w"]."&amp;picture_remove=yes');\">".DELETE_BUTTON."</a>\n";
}
else echo "<font>".ADMIN_PICTURE_NOT_UPLOADED."</font>";
?>
</td>
</tr>

<tr>
<td align=right><?php echo ADMIN_CATEGORY_DESC;?><br>(HTML)</td>
<td></td>
<td><textarea name="desc" rows=7 cols=22><?php echo str_replace("\"","&amp;quot;",$d); ?></textarea></td>
</tr>

</table>
<p><center>
<input type="submit" value="<?php echo SAVE_BUTTON;?>" width=5>
<input type="hidden" name="save" value="yes">
<input type="button" value="<?php echo CANCEL_BUTTON;?>" onClick="window.close();">
<?php
//$must_delete indicated which query should be made: insert/update
if (isset($_GET["c_id"]))
{
echo "<input type=\"hidden\" name=\"must_delete\" value=\"".str_replace("\"","",$_GET["c_id"])."\">\n";
echo "<input type=\"button\" value=\"".DELETE_BUTTON."\" onClick=\"confirmDelete('".QUESTION_DELETE_CONFIRMATION."','category.php?c_id=".str_replace("\"","",$_GET["c_id"])."&amp;del=1');\"";
}
?>
</center></p>
</form>

</body>

</html>
<?php }; ?>

Chatbox script PHP

With a Shoutbox, site visitors develope a durable, personal relationship with your homepage.Customer relations is indispensable.Unlimited number of messages.Fully Customizable.Ban hackers IP addresses.Allows users to post comments by the use of comment box without any form of user registration.
Fast AJAX Interface.Multilingual – you can change the language of your Chatbox!.Spam Filter Option provided for this tagboard.Easy to use messaging system written in PHP with AJAX support.Absolutely Free!

 

<?PHP
/* DO NOT CHANGE ANYTHING BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING! */
session_start();
include "header.php";
$salt = "Kz";
$systemMessage = "";
if($_POST['action']=='login') {
$fh = fopen("pw","r");
if(($line=fgets($fh))!=-1) {
list($un,$secret) = explode("%|%",$line);
if($secret==crypt($_POST['uname'].'/'.$_POST['pwd'],$salt)) {
$_SESSION['admin']=time();
$_SESSION['sb_user']=$_POST['uname'];
} else {
$systemMessage="Invalid username or password";
}
fclose($fh);
} else {
$systemMessage="I/O error";
}
} else if($_POST['action']=='logout') {
session_destroy();
echo '<meta http-equiv="refresh" content="1; url=about.php">';
//header("Location: ./about.php");
exit(0);
}
?>
<link rel="stylesheet" href="contact.css" />
<td>
<div align="center" id="pageContent">
<?PHP
if(!$_SESSION['admin']) {
?>
<h2>ShoutboxAdmin :: Login</h2>
<form action="sb_admin.php" method="post">
<input type="hidden" name="action" value="login" />
<span id="errorMessage"><?=$systemMessage?></span>
<table border="0">
<tr><td>Username:</td><td><input type="text" name="uname" /></td></tr>
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td align="right" colspan="2"><input type="submit" value="Login" style="font-weight:bold" /></td></tr>
</table>
</form>
<?PHP
} else {
require_once('./auth/dbconnect.php');
mysql_pconnect($sqlhost,$sqluser,$sqlpwd);
mysql_select_db($dbname);


if($_GET['action']=="del") {
$selection = $_POST['selector'];
$i = 0;
$query = "";
foreach($selection as $message) {
if($i>0) $query .= " OR ";
$query .= "id=$message";
$i++;
}
$res = mysql_query("DELETE FROM sb_chat WHERE $query");
if($res) {
echo '<script type="text/javascript">self.location.href=\'sb_admin.php\'</script>';
} else {
echo mysql_error();
}
} elseif($_GET['action']=="flush") {
$res = mysql_query("DELETE FROM sb_chat");
if($res) {
echo '<script type="text/javascript">self.location.href=\'sb_admin.php\'</script>';
} else {
echo mysql_error();
}
} elseif($_POST['action']=="chpass") {

$t1 = $_POST['username'];
$t2 = $_POST['pwd'];
$secret = crypt($_POST['username'].'/'.$_POST['pwd'],$salt);
$fh = fopen("./pw","w+");
if($fh) {
flock($fh, LOCK_EX);
fwrite($fh,$_POST['username']);
fwrite($fh,'%|%');
fwrite($fh,"$secret");
$_SESSION['sb_user']=$_POST['username'];
echo '<h2>Password changed</h2><a href="sb_admin.php">Go back</a>';
flock($fh, LOCK_UN);
fclose($fh);
} else {
echo mysql_error();
}
} elseif($_GET['action']=="chpassform") {
?>
<script type="text/javascript">
function checkForm() {
if(document.form1.username.value==""||document.form1.pwd.value=="") {
alert('All the fields are required.');
return false;
}
if(document.form1.pwd.value!=document.form1.password1.value) {
alert('Passwords do not match.');
return false;
}
return true;
}
</script>
<h2>ShoutboxAdmin :: Change Password</h2>
<form action="sb_admin.php" method="post" onsubmit="return checkForm()" name="form1" >
<input type="hidden" name="action" value="chpass" />
<table border="0">
<tr><td>Username:</td><td><input type="text" name="username" value="<?=$_SESSION['sb_user']?>" /></td></tr>
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td>Password verification:</td><td><input type="password" name="password1" /></td></tr>
<tr><td align="right" colspan="2"><input type="submit" value="Change password" style="font-weight:bold" /></td></tr>
</table>
</form>
<?PHP
} else {
?>
<script type="text/javascript">
function selectAll() {
var selectors = document.list.selector;
alert(selectors[0]);
for(i=0;i<selectors.length;i++) {
selectors[i].checked=document.getElementById('sel_all').checked;
}
}
function flush() {
if(confirm("Flushing the shoutbox means removing all it's contents. This operation is irreversible. Are you sure that you want to proceed?")) {
self.location.href="sb_admin.php?action=flush";
}
}
</script>
<!--div align="left">
<form action="sb_admin.php" method="post">
<input type="hidden" name="action" value="logout" />
<input type="submit" value="Logout" />
<input type="button" value="Change password" onclick="self.location.href='sb_admin.php?action=chpassform'" />
</form>
</div-->
<span id="errorMessage"><?=$systemMessage?></span>
<?PHP
$limit = 50;
$page = intval($_GET['page']);
if(!$page) $page = 0;
if($row = mysql_fetch_array(mysql_query("SELECT COUNT(id) FROM sb_chat"))) $numrows = $row[0];
$pages = intval($numrows/$limit);
if($numrows%$limit) $pages++;
if($pages < 1) $total = 1;
else $total = $pages;
$first = $page+1;
if(($page+$limit)/$limit < $pages &amp;&amp; $pages > 1) $last = $page+$limit;
else $last = $numrows;
?>
<div align="left">
Messages from <?=(($first>$last)?0:$first)?> to <?=$last?> of <?=$numrows?><br />
</div>
<form action="?action=del" method="POST" name="list" onsubmit="return confirm('Are you sure that you want to delete the selected messages?')">
<div align="left">
<input type="submit" value="Delete selection" />&amp;nbsp;<input type="button" value="Flush the shoutbox" onclick="flush()" />
</div>
<table border="0" width="100%">
<tr><td><!-- input type="checkbox" id="sel_all" onclick="selectAll()" / -->&amp;nbsp;</td><td>Author</td><td>Message</td></tr>
<?PHP
$res = mysql_query("SELECT * FROM sb_chat ORDER BY id DESC LIMIT $page, $limit");
if($res) {
$i=0;
while($row =mysql_fetch_array($res)) {
?>
<tr style="background:<?=(($i%2)?'#ddd':'#eee')?>">
<td width="2%">
<input type="checkbox" name="selector[]" value="<?=$row['id']?>" />
</td>
<td><?=(stripslashes($row['posteur']))?></td>
<td><?=(stripslashes($row['message']))?></td>
</tr>
<?PHP
$i++;
}
}
?>
</table>
<?PHP
if($page > 0) {
$back_page = $page-$limit;
?>
<a href="?page=<?=$back_page?>">&amp;laquo; previous page</a>
<?PHP
}
for($i=1;$i<=$pages;$i++) {
$page_num = $limit*($i-1);
if($page_num!=$page) {
?>
<a href="?page=<?=$page_num?>"><?=$i?></a>
<?PHP
} else {
?>
<b><?=$i?></b>
<?PHP
}
}
if(($page+$limit)/$limit < $pages &amp;&amp; $pages > 1) {
$next_page = $page+$limit;
?>
<a href="?page=<?=$next_page?>">next page &amp;raquo;</a>
<?PHP
}
?>
</form>
<?PHP
}
}
?>
</div>
</td>
<?php
include "footer.php";
?>

PHP Scripts for program called rss2html

FeedForAll has made available a free PHP program called rss2html.php, which can be used by webmasters to automatically display RSS feeds on their website. The resulting webpage will always show the RSS feed’s most current data. The advantage of using the rss2html.php script is that the resulting webpage’s contents will always be up to date, and can be easily spidered by search engines.

 

<?PHP
//
// rss2html.php RSS feed to HTML webpage script
//
// Copyright 2004-2007 NotePage, Inc.
// http://www.feedforall.com
//
// This script may be used and modified freely for business or personal use
// This script may not be resold in any form
// This script may only be redistributed in its original form
//
//
// $Id: rss2html.php,v 3.15 2010/03/16 22:31:38 housley Exp $
//

//
// ==========================================================================
// Configuration options
// ==========================================================================
//
// Set the following variable useFopenURL to one if you want/need to use
// fopen() instead of CURL or FeedForAll_fopen()
$useFopenURL = 0;

//
// If XLMFILE is passed as part of the URL, XMLFILE=, then it will be used
// otherwise the the file below is used.
//$XMLfilename = "http://examlple.com/sample.xml";
$XMLfilename = "sample.xml";

//
// If TEMPLATE is passed as part of the URL. TEMPLATE=, then it will be used
// otherwise the the file below is used.
//$TEMPLATEfilename = "http://examlple.com/sample-template.html";
$TEMPLATEfilename = "sample-template.html";

//
// Since some feeds may have titles or descriptins in the feed or items that
// are longer then want fits in your HTML page it is possible to trim them
// with the following 4 variables.  A values of 0 (ZERO) displays the full
// length.
// CAUTION:  Do not limit a title or description that has HTML in it, the
//           will not produce a valid HTML page.
$limitFeedTitleLength = 0;        // Not limited, in the URL as FeedTitleLength=
$limitFeedDescriptionLength = 0;  // Not limited, in the URL as FeedDescriptionLength=
$limitItemTitleLength = 0;        // Not limited, in the URL as ItemTitleLength=
$limitItemDescriptionLength = 0;  // Not limited, in the URL as ItemDescriptionLength=

//
// date() function documented http://www.php.net/manual/en/function.date.php
$LongDateFormat = "F jS, Y";    // ie, "Jan 21st, 2004"
$ShortDateFormat = "m/d/Y";     // ie, "1/21/2004"
//$ShortDateFormat = "d/m/Y";     // ie, "21/1/2004"
$LongTimeFormat = "H:i:s T O";  // ie, "13:24:30 EDT -0400"
$ShortTimeFormat = "h:i A";     // ie, "1:24 PM"

//
// Timezone - If your server is not in the same timezone as you are the timezone
// of the times and dates produced in the above from can be controlled with the
// below code.  Just uncomment the following line and change to the correct
// zonename.  A full list is available here, http://www.php.net/manual/en/timezones.php
// You town.city probably isn't listed, so look for a neighboring major city
// putenv("TZ=America/New_York");

//
// Registered user of FeedForAll and FeedForAll Mac product(s) have access
// to a caching module.  This enables it's use if it is installed.
$allowCachingXMLFiles = 0;

//
// File access level:  The variable $fileAccessLevel can be used limit what files
// and type of files (local or remote) can be used with rss2html.php
// -1 = Remote files are NOT allowed, only local files allowed for template
//      and feed which have filenames ending in extensions in the
//      $allowedTemplateExtensions and $allowedFeedExtensions lists below
//  0 = Remote files and any local files allowed for template and feed
//  1 = Remote files and only local files allowed for template and feed
//      which have filenames ending in extensions in the
//      $allowedTemplateExtensions and $allowedFeedExtensions lists below
//  2 = No local files allowed, remote files only.
$fileAccessLevel = 1;

//
// Allowed file extensions is a list of the allowable extensions for local for
// the template and the feed.  New entries can be added by following the example
// below.
$allowedTemplateExtensions = Array(".html", ".htm", ".shtml");
$allowedFeedExtensions = Array(".xml", ".rss");

//
// Destination Encoding:  By default rss2html.php converts all feeds to UTF-8
// and then produces webpages in UTF-8 because UTF-8 is capable of displaying
// all possible characters.
$destinationEncoding = "UTF-8";

//
// Missing Encoding Default:  Some feeds do not specify the character set
// they are encoded in.  The XML specification states that if there is no
// encoding specified the XML file, all RSS feeds are XML, must be encoded
// in UTF-8, but experience has show differently.  This specifies the
// encoding that will be used for feeds that don't specify the encoding.
//$missingEncodingDefault = "UTF-8";
$missingEncodingDefault = "ISO-8859-1";

//
// Escape Ampersand In Links:  Proper HTML requires that a link with an
// apersand in while inside of an HTML page have that '&amp;' converted to
// '&amp;amp;'.
$escapeAmpInLinks = 1;

//
// $connectTimeoutLimit allows the limiting the amount of time cURL will
// wait to successfully connect to a remote server.  Use with caution,
// a value too small will cause all connections to fail.
//$connectTimeoutLimit = 30;

//
// $hideErrors: This will prevent all error messages from being displayed.
// CAUTION enabling this will cause rss2html.php to fail silently with
// no indication to why there was no output
// $hideErrors = 1;

// ==========================================================================
// Below this point of the file there are no user editable options.  Your
// are welcome to make any modifications that you wish to any of the code
// below, but that is not necessary for normal use.
// ==========================================================================

// $Log: rss2html.php,v $
// Revision 3.15  2010/03/16 22:31:38  housley
// Fix for PHP 5.3
//
// Revision 3.14  2009/11/23 02:05:12  housley
// Switch to explode() since PHP 5.3.0 made split() decrepit
//
// Revision 3.13  2008/10/18 12:52:36  housley
// Update useragent so feedburner won't detect and change functionality
// for us
//
// Revision 3.12  2008/05/14 00:45:46  housley
// Fix for negative MAXITEMS greater then the number of items
//
// Revision 3.11  2007/09/30 15:23:23  housley
// Check for the existance of fsockopen()
//
// Revision 3.10  2007/07/16 16:48:48  housley
// On some systems the exit statements in here was terminating all PHP
// processing.
//
// Revision 3.9  2007/07/16 13:06:37  housley
// Add ~~~NumberOfFeedItems~~~ to allow access to the number of items that
// will be processed for display.
//
// Revision 3.8  2007/07/08 13:42:39  housley
// Create my own version of fopen() to try and get files when cURL is not
// available.  FeedForAll_fopen() is based on just connecting to the server
// and reading the results.
//
// Revision 3.7  2007/06/25 13:55:10  housley
// Fix mistake where ?buildURL would falsely say a file could be opened,
// when in reality it could not be opened
//
// Revision 3.6  2007/06/05 13:39:38  housley
// Enable access to output caching in rss2html.php
//
// Revision 3.5  2007/05/27 14:32:05  housley
// Add a debug message when switching to fopen() because curl_init() does
// not exist
//
// Revision 3.4  2007/05/04 11:54:19  housley
// When checking for caching, check a function only in the caching module
//
// Revision 3.3  2007/05/03 18:52:16  housley
// Fix typo in debug statement
//
// Revision 3.2  2007/05/03 16:14:07  housley
// * It seems the XML parser doesn't like most of the HTML entities, process them by hand
// * The check to display errors was backwards
//
// Revision 3.1  2007/04/24 11:36:09  housley
// Fix an error that prevented using PHP includes to display more then one
// feed on a page
//
// Revision 3.0  2007/04/16 14:23:03  housley
// Release version 3.0 of the scripts
//
// Revision 2.76  2007/04/13 18:30:10  housley
// * Atom:content might need whole string so always make it available
// * atom:content of type xhtml is in a div that needs to be stripped and
//   then used as is.
//
// Revision 2.75  2007/04/11 19:59:43  housley
// Add an option to hide error messages
//
// Revision 2.74  2007/04/11 18:38:08  housley
// Update the user agent to be 3.0
//
// Revision 2.73  2007/04/11 12:13:12  housley
// * Fix the code to limit the number of items
// * Add some debug messages
//
// Revision 2.72  2007/04/11 10:40:38  housley
// Add some debug messages
//
// Revision 2.71  2007/04/10 17:16:45  housley
// Allow the input caching to be set during buildURL, only for one PHP include
// type
//
// Revision 2.70  2007/04/10 15:19:28  housley
// Allow for the caching for the HTML output of rss2html.php
//
// Revision 2.69  2007/04/04 20:55:46  housley
// Add the ability to set CURLOPT_CONNECTTIMEOUT
//
// Revision 2.68  2007/03/30 13:18:33  housley
// Use getArrayOfFields() and getValueOf() to simplfy tag replacement, except
// where special processing needs to be done
//
// Revision 2.67  2007/03/05 18:23:58  housley
// Don't abort processing on XML parse error, just don't do anything else
//
// Revision 2.66  2007/03/05 01:33:44  housley
// Use a command convert and readFile routines
//
// Revision 2.65  2007/03/05 01:19:45  housley
// Rename FeedForAll_rss2html_readFile() to FeedForAll_scripts_readFile()
//
// Revision 2.64  2007/03/04 13:41:53  housley
// * Pass the parsing mode to the item class
// * Cleanup the feed level processing
// * rss2html uses the separate parser too
//
// Revision 2.63  2007/03/03 21:10:09  housley
// * Make the item a full class object
// * Support parsing the iTunes(R) extension
//
// Revision 2.62  2007/02/26 00:33:53  housley
// Fix assignment in comparison
//
// Revision 2.61  2007/02/14 01:05:52  housley
// Add the option of encoding the '#' in URLs in some conditions
//
// Revision 2.60  2007/01/26 14:08:46  housley
// Show a better method to change timezone
//
// Revision 2.59  2007/01/04 19:01:51  housley
// Parse the new rssMesh.php fields:
//
// <rssMesh:feedImageTitle> => ~~~ItemRssMeshFeedImageTitle~~~
// <rssMesh:feedImageUrl> =>  ~~~ItemRssMeshFeedImageUrl~~~
// <rssMesh:feedImageLink> =>  ~~~ItemRssMeshFeedImageLink~~~
// <rssMesh:feedImageDescription> =>  ~~~ItemRssMeshFeedImageDescription~~~
// <rssMesh:feedImageHeight> =>  ~~~ItemRssMeshFeedImageHeight~~~
// <rssMesh:feedImageWidth> =>  ~~~ItemRssMeshFeedImageWidth~~~
//
// Revision 2.58  2006/12/22 16:30:21  housley
// Add a check to see if cURL is allowed to follow redirects
//
// Revision 2.57  2006/11/06 14:59:22  housley
// Minor text changes in buildURL
//
// Revision 2.56  2006/11/06 14:39:24  housley
// Create a new method of including rss2html.php that will work on servers
// with remote URL restrictions (allow_url_fopen) that many ISPs are currently
// using.
//
// Revision 2.55  2006/10/17 16:05:05  housley
// Since some of the newer versions of the XML parser look at the encoding
// in the feed and ignore the one passed in on the call, change the encoding
// in the feed before parsing.
//
// Revision 2.54  2006/09/29 19:50:33  housley
// Add a function to convert &amp; in a certian RSS fields to &amp;amp;, so it will be proper HTML
//
// Revision 2.53  2006/09/22 20:21:55  housley
// Fix the problem of displaying an invalid date with an odd number of items
//
// Revision 2.51  2006/09/04 12:33:17  housley
// Exit after a parser error.  The parser stopped, so should we.
//
// Revision 2.50  2006/08/29 18:58:38  housley
// Changes to handle when there are not string conversion modules
//
// Revision 2.49  2006/08/25 15:09:22  housley
// Add hooks for a new feature in rss2html-pro
//
// Revision 2.48  2006/08/25 11:36:37  housley
// * Add the capability to change the character set that feeds are converted to
// * Allow specifying the encoding to use for feeds that don't specify the encoding
//
// Revision 2.46  2006/08/24 20:23:56  housley
// Over come a well meaning, but very misguided ISP removing file:// from
// all scripts.  Not only did the remove it in a place that was doing good,
// it was extremely simple to bypass.
//
// Revision 2.45  2006/08/21 20:19:32  housley
// Use special routines so that rss2html-pro will work with RSS fields that
// have quotes in them.
//
// Revision 2.43  2006/08/18 23:42:16  housley
// Add hooks for rss2html-pro post processing
//
// Revision 2.42  2006/08/11 17:15:45  housley
// Add the ability to restrict the use of the rss2html.php script.
//
// Revision 2.41  2006/08/09 23:57:35  housley
// If <?xml ... is missing add it
//
// Revision 2.40  2006/08/09 15:32:58  housley
// If mb_string_convert fails, try iconv
//
// Revision 2.39  2006/08/04 19:59:02  housley
// Assuming 0xa9 is (c) was bad
//
// Revision 2.38  2006/08/03 11:06:45  housley
// * Don't change the encoding string in the header
// * Give access to the first category in a feed
//
// Revision 2.37  2006/07/29 14:29:40  housley
// Add support for <category> in items.  If there are more then one <category>
// element, only the first is accessable.  The 2 new tags are
// ~~~ItemCategory~~~ and ~~~ItemCategoryDomain~~~
//
// Revision 2.36  2006/07/29 13:19:23  housley
// Trim any leading BOM because some PHP5 installations have problems if it
// is there.
//
// Revision 2.35  2006/07/27 00:27:03  housley
// * Add support for <source> and <comments> in <item>
// * Add support for <rssMesh:extra>
//
// Revision 2.34  2006/07/21 12:23:36  housley
// * If there is no encoding, default to ISO-8859-1
// * Modify the XML to show the encoding we used
//
// Revision 2.33  2006/07/16 10:33:23  housley
// Force $useFopenURL if cURL is not installed
//
// Revision 2.32  2006/07/13 17:05:08  housley
// Remove space that causes problems
//
// Revision 2.31  2006/07/12 12:48:27  housley
// Try the iconv() conversion option if mb_string_encode() doesn't exist
//
// Revision 2.30  2006/05/28 17:52:10  housley
// Handle no encoding specified in the feed
//
// Revision 2.29  2006/05/28 17:51:28  housley
// Allow displaying of the Creative Commons License URL
//
// Revision 2.28  2006/05/28 14:21:47  housley
// Add additional capabilities to work with enclosures.  The 3 new fields are
// ~~~ItemEnclosureType~~~, ~~~ItemEnclosureLength~~~ and ~~~ItemEnclosureLengthFormatted~~~
//
// Revision 2.27  2006/05/27 19:27:45  housley
// * Show a more universal TZ offset example
// * Make setting contentEncoded more robust
//
// Revision 2.26  2006/04/08 23:17:22  housley
// A "%" should not be encoded to "%2525", but to "%25"
//
// Revision 2.25  2006/04/08 23:16:17  housley
// Indicate that this is the last parse of XML
//
// Revision 2.24  2006/03/23 12:10:30  housley
// Add a simple way to change the timezone of produced times and dates
//
// Revision 2.23  2006/03/10 14:21:04  housley
// Update the licenses
//
// Revision 2.22  2006/03/06 15:01:57  housley
// Trim white space before and after the XML
//
// Revision 2.21  2006/03/05 15:15:11  housley
// Rename rss2html_CachingExtension.php to FeedForAll_Scripts_CachingExtension.php
//
// Revision 2.20  2006/03/05 14:43:59  housley
// Fix the testing for the character set conversion function
//
// Revision 2.19  2006/02/28 02:00:04  housley
// Add support for ~~~FeedXMLFilename~~~
//
// Revision 2.18  2006/02/26 15:24:15  housley
// Add the capability to limit the length of feed and item titles and descriptions
//
// Revision 2.17  2006/02/13 18:00:27  housley
// Fix the initialization of the item arrays
//
// Revision 2.16  2006/02/12 14:43:18  housley
// If possible convert the feed to UTF-8, for uniformity
//
// Revision 2.15  2006/02/12 00:21:13  housley
// Fix the offsetting of the time
//
// Revision 2.14  2006/01/26 15:52:37  housley
// Fix the error message for opening a feed, it was displaying the template filename.
//
// Revision 2.13  2006/01/08 23:25:44  housley
// Move all user configuration options at the top of the file to make them
// easier to find
//
// Revision 2.12  2005/12/12 16:27:26  housley
// Add an interface to allow FeedForAll_scripts_readFile() to be replaced
// by one that does caching of the XML files
//
// Revision 2.11  2005/12/09 19:08:26  housley
// Remove the first "banner" since IE barfs
//
// Revision 2.10  2005/10/22 18:51:47  housley
// Improve the formatting
//
// Revision 2.9  2005/10/22 14:27:57  housley
// Fix label in buildURL
//
// Revision 2.8  2005/10/22 14:20:31  housley
// Add buildURL to assist in creating properly encoded links.  Show proper
// include methods and contents of the files.
//
// Revision 2.7  2005/10/16 17:54:10  housley
// Improvements when using CURL:
// - Use the requested file as the REFERER, for sites that might require one
// - Allow to follow up to 10 redirects, some sites redirect to real content
//
// Revision 2.6  2005/10/16 17:32:27  housley
// Use lastBuildDate as another possible source if pubDate is empty at the
// <channel> level.
//
// Revision 2.5  2005/09/28 02:08:15  housley
// Fix the storage of pubDate at the feed level
//
// Revision 2.4  2005/09/12 18:56:31  housley
// Set a user agent for both fopen and curl transerfers
//
// Revision 2.3  2005/09/06 22:55:27  housley
// GUID doesn't need urlencode()
//
// Revision 2.2  2005/08/16 19:53:15  housley
// Add the ~~~ItemAuthor~~~ subsitution that uses first <author> and then
// <dc:creator> for its contents
//
// Revision 2.1  2005/08/15 14:49:24  housley
// Convert &amp;apos; to ' since &amp;apos; is not HTML
//
// Revision 2.0  2005/07/30 14:09:38  housley
// Allow "allow_url_fopen" to be sellected, incase CURL is not available.
//
//

//
// If using cURL, make sure it exists
if (($useFopenURL == 0) &amp;&amp; !function_exists("curl_init")) {
$useFopenURL = -1;
if (isset($debugLevel) &amp;&amp; ($debugLevel >= 3)) {
echo "DIAG: setting \$useFopenURL=-1 because curl_init() doesn't exist<br>\n";
}
}

if (($useFopenURL == -1) &amp;&amp; !function_exists("fsockopen")) {
$useFopenURL = 1;
if (isset($debugLevel) &amp;&amp; ($debugLevel >= 3)) {
echo "DIAG: setting \$useFopenURL=1 because fsockopen() doesn't exist<br>\n";
}
}

if ($useFopenURL == 1) {
ini_set("allow_url_fopen", "1");
ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1;) Gecko/2008070208 Firefox/3.0.1");
}

$FeedMaxItems = 10000;
$NoFutureItems = FALSE;

@include("FeedForAll_rss2html_pro.php");

if (function_exists("FeedForAll_rss2html_pro") === FALSE) {
Function FeedForAll_rss2html_pro($source) {
//
// This is the place to do any processing that is desired
return $source;
}
}

if (function_exists("FeedForAll_parseExtensions") === FALSE) {
Function FeedForAll_parseExtensions() {
return FALSE;
}
}

@include("FeedForAll_Scripts_CachingExtension.php");

@include_once("FeedForAll_XMLParser.inc.php");

if (function_exists("FeedForAll_rss2html_limitLength") === FALSE) {
Function FeedForAll_rss2html_limitLength($initialValue, $limit = 0) {
if (($limit == 0) || (strlen($initialValue) <= $limit )) {
// ZERO is for not limited
return $initialValue;
}

// Cut the text at the exact point, ignoring if it is in a word.
$result = substr($initialValue, 0, $limit);

// Check to see if there are any space we can trim at and if it is not
// too far from where we are
$lastSpace = strrchr($result,' ');
if (($lastSpace !== FALSE) &amp;&amp; (strlen($lastSpace) < 20)) {
// lose any incomplete word at the end
$result = substr($result, 0, -(strlen($lastSpace)));

// Append elipses, ... , to show it was truncated
$result .= " ...";
}

return $result;
}
}

if (function_exists("FeedForAll_rss2html_sizeToString") === FALSE) {
Function FeedForAll_rss2html_sizeToString($filesize) {
if ($filesize == "") {
return "";
}
elseif ($filesize >= 1073741824) {
return number_format($filesize/1073741824, 1, ".", ",")." GBytes";
}
elseif ($filesize >= 1048576) {
return number_format($filesize/1048576, 1, ".", ",")." MBytes";
}
elseif ($filesize >= 1024) {
return number_format($filesize/1024, 1, ".", ",")." KBytes";
}
else {
return $filesize." Bytes";
}
}
}

if (function_exists("FeedForAll_rss2html_isTemplate") === FALSE) {
Function FeedForAll_rss2html_isTemplate($templateData) {
if ((strstr($templateData, "~~~Feed") !== FALSE) || (strstr($templateData, "~~~Item") !== FALSE)) {
return TRUE;
}
return FALSE;
}
}

if (function_exists("FeedForAll_rss2html_validExtension") === FALSE) {
Function FeedForAll_rss2html_validExtension($filename, $extensions) {
$foundValid = FALSE;
foreach ($extensions as $value) {
if (strtolower($value) == strtolower(substr($filename, -strlen($value)))) {
$foundValid = TRUE;
break;
}
}
return $foundValid;
}
}

if (function_exists("FeedForAll_rss2html_str_replace") === FALSE) {
Function FeedForAll_rss2html_str_replace($search, $replace, $subject) {
return str_replace($search, $replace, $subject);
}
}

if (function_exists("FeedForAll_rss2html_encodeURL") === FALSE) {
Function FeedForAll_rss2html_encodeURL($URLstring, $includePND = 0) {
$result = "";
for ($x = 0; $x < strlen($URLstring); $x++) {
if ($URLstring[$x] == '%') {
$result = $result."%25";
}
elseif ($URLstring[$x] == '?') {
$result = $result."%3f";
}
elseif ($URLstring[$x] == '&amp;') {
$result = $result."%26";
}
elseif ($URLstring[$x] == '=') {
$result = $result."%3d";
}
elseif ($URLstring[$x] == '+') {
$result = $result."%2b";
}
elseif ($URLstring[$x] == ' ') {
$result = $result."%20";
}
elseif ($includePND &amp;&amp; ($URLstring[$x] == '#')) {
$result = $result."%23";
}else {
$result = $result.$URLstring[$x];
}
}
return $result;
}
}

if (function_exists("FeedForAll_rss2html_CreateUniqueLink") === FALSE) {
Function FeedForAll_rss2html_CreateUniqueLink($title, $description, $link, $guid, $XMLfilename, $itemTemplate) {
GLOBAL $TEMPLATEfilename;
$match = Array();

while (preg_match("/~~~ItemUniqueLinkWithTemplate=.*~~~/", $itemTemplate, $match) !== FALSE) {
if ((count($match) == 0) || ($match[0] == "")) {
// All done
return $itemTemplate;
}

$replace = "http://$_SERVER[SERVER_NAME]$_SERVER[SCRIPT_NAME]?XMLFILE=".FeedForAll_rss2html_encodeURL($XMLfilename)."&amp;amp;TEMPLATE=".FeedForAll_rss2html_encodeURL($TEMPLATEfilename);
$itemTemplate = FeedForAll_rss2html_str_replace($match[0], $replace, $itemTemplate);
}
if ($title);
if ($description);
if ($link);
if ($guid);
return $itemTemplate;
}
}

if (function_exists("FeedForAll_rss2html_UseUniqueLink") === FALSE) {
Function FeedForAll_rss2html_UseUniqueLink($title, $description, $link, $guid) {
if ($title);
if ($description);
if ($link);
if ($guid);
return -1;
}
}

if (function_exists("FeedForAll_rss2html_EscapeLink") === FALSE) {
Function FeedForAll_rss2html_EscapeLink($link) {
GLOBAL $escapeAmpInLinks;

if ((strstr($link, "://") !== FALSE) &amp;&amp; $escapeAmpInLinks) {
// In HTML a link with an &amp; must be converted to &amp;amp;
// And for here without :// it is not a link, since relative
// URLs are not allowed
$link = str_replace("&amp;", "&amp;amp;", $link);
}
return $link;
}
}

if (function_exists("FeedForAll_rss2html_AddIdentity") === FALSE) {
Function FeedForAll_rss2html_AddIdentity($itemString) {
return "<!-- HTML generated from an RSS Feed by rss2html.php, http://www.FeedForAll.com/ a NotePage, Inc. product (http://www.notepage.com/) -->".$itemString;
}
}

if (!isset($_REQUEST["buildURL"])) {
//
// Check variables that could be used if URL wrapper are disable or not working
if (isset($GLOBALS["XMLFILE"])) {
$XMLfilename = $GLOBALS["XMLFILE"];
}
if (isset($GLOBALS["TEMPLATE"])) {
$TEMPLATEfilename = $GLOBALS["TEMPLATE"];
}
if (isset($GLOBALS["FeedTitleLength"])) {
$limitFeedTitleLength = abs($GLOBALS["FeedTitleLength"]);
}
if (isset($GLOBALS["FeedDescriptionLength"])) {
$limitFeedDescriptionLength = abs($GLOBALS["FeedDescriptionLength"]);
}
if (isset($GLOBALS["ItemTitleLength"])) {
$limitItemTitleLength = abs($GLOBALS["ItemTitleLength"]);
}
if (isset($GLOBALS["ItemDescriptionLength"])) {
$limitItemDescriptionLength = abs($GLOBALS["ItemDescriptionLength"]);
}
if (isset($GLOBALS["MAXITEMS"])) {
$FeedMaxItems = $GLOBALS["MAXITEMS"];
}
if (isset($GLOBALS["NOFUTUREITEMS"])) {
$NoFutureItems = TRUE;
}


if (isset($_REQUEST["XMLFILE"])) {
if (stristr($_REQUEST["XMLFILE"], "file"."://")) {
// Not allowed
;
}
elseif (stristr($_REQUEST["XMLFILE"], "://")) {
if ($fileAccessLevel == -1) {
echo "Configuration setting prohibit using remote files, exiting\n";
return;
} else {
// URL files are allowed
$XMLfilename = $_REQUEST["XMLFILE"];
}
} else {
if (($fileAccessLevel == 1) || ($fileAccessLevel == -1)) {
if (FeedForAll_rss2html_validExtension(basename($_REQUEST["XMLFILE"]), $allowedFeedExtensions) === FALSE) {
echo "Configuration setting prohibit using the specified feed file, exiting\n";
return;
}
$XMLfilename = basename($_REQUEST["XMLFILE"]);
}
elseif ($fileAccessLevel == 2) {
echo "Configuration setting prohibit using local files, exiting\n";
return;
} else {
// It is local and must be in the same directory
$XMLfilename = basename($_REQUEST["XMLFILE"]);
}
}
}

if (isset($_REQUEST["TEMPLATE"])) {
if (stristr($_REQUEST["TEMPLATE"], "file"."://")) {
// Not allowed
;
}
elseif (stristr($_REQUEST["TEMPLATE"], "://")) {
if ($fileAccessLevel == -1) {
echo "Configuration setting prohibit using remote files, exiting\n";
return;
} else {
// URL files are allowed
$TEMPLATEfilename = $_REQUEST["TEMPLATE"];
}
} else {
if (($fileAccessLevel == 1) || ($fileAccessLevel == -1)) {
if (FeedForAll_rss2html_validExtension(basename($_REQUEST["TEMPLATE"]), $allowedTemplateExtensions) === FALSE) {
echo "Configuration setting prohibit using the specified template file, exiting\n";
return;
}
$TEMPLATEfilename = basename($_REQUEST["TEMPLATE"]);
}
elseif ($fileAccessLevel == 2) {
echo "Configuration setting prohibit using local files, exiting\n";
return;
} else {
// It is local and must be in the same directory
$TEMPLATEfilename = basename($_REQUEST["TEMPLATE"]);
}
}
}

if (isset($_REQUEST["FeedTitleLength"])) {
$limitFeedTitleLength = abs($_REQUEST["FeedTitleLength"]);
}
if (isset($_REQUEST["FeedDescriptionLength"])) {
$limitFeedDescriptionLength = abs($_REQUEST["FeedDescriptionLength"]);
}
if (isset($_REQUEST["ItemTitleLength"])) {
$limitItemTitleLength = abs($_REQUEST["ItemTitleLength"]);
}
if (isset($_REQUEST["ItemDescriptionLength"])) {
$limitItemDescriptionLength = abs($_REQUEST["ItemDescriptionLength"]);
}

//
// Maximum number of items to be displayed
//
if (isset($_REQUEST["MAXITEMS"])) {
$FeedMaxItems = $_REQUEST["MAXITEMS"];
}
if (isset($_REQUEST["NOFUTUREITEMS"])) {
$NoFutureItems = TRUE;
}

if (isset($outputCacheTTL) &amp;&amp; function_exists("FeedForAll_scripts_readOutputCacheFile") &amp;&amp; (($cacheContents = FeedForAll_scripts_readOutputCacheFile($XMLfilename, $TEMPLATEfilename)) !== FALSE)) {
if (!headers_sent()) {
// Send the Content-Type to force $destinationEncoding
header("Content-Type: text/html; charset=$destinationEncoding");
}
echo $cacheContents;
} else {
if (($template = FeedForAll_scripts_readFile($TEMPLATEfilename, $useFopenURL)) === FALSE) {
if (!isset($hideErrors)) {
if ($ReadErrorString == "") {
echo "Unable to open template $TEMPLATEfilename, exiting\n";
} else {
echo "Unable to open template $TEMPLATEfilename with error <b>$ReadErrorString</b>, exiting\n";
}
}
return;
}
if (FeedForAll_rss2html_isTemplate($template) === FALSE) {
if (!isset($hideErrors)) {
echo "$TEMPLATEfilename is not a valid rss2html.php template file, exiting\n";
}
return;
}

if (strstr($template, "~~~NoFutureItems~~~")) {
$NoFutureItems = TRUE;
}

if (($XML = FeedForAll_scripts_readFile($XMLfilename, $useFopenURL, $allowCachingXMLFiles)) === FALSE) {
if (!isset($hideErrors)) {
if ($ReadErrorString == "") {
echo "Unable to open RSS Feed $XMLfilename, exiting\n";
} else {
echo "Unable to open RSS Feed $XMLfilename with error <b>$ReadErrorString</b>, exiting\n";
}
}
return;
}

if (strstr(trim($XML), "<?xml") === FALSE) {
$XML = "<?xml version=\"1.0\"?>\n$XML";
}
$XML = strstr(trim($XML), "<?xml");
$XML = FeedForAll_preProcessXML($XML);
if (($convertedXML = FeedForAll_scripts_convertEncoding($XML, $missingEncodingDefault, $destinationEncoding)) === FALSE) {
// Conversions failed, probably becasue it was wrong or the routines were missing
$convertedXML = $XML;
$xml_parser = xml_parser_create();
} else {
$xml_parser = xml_parser_create($destinationEncoding);
}

$rss_parser = new baseParserClass("rss2html");
$rss_parser->noFutureItems = $NoFutureItems;
$rss_parser->wholeString = $convertedXML;
xml_set_object($xml_parser, $rss_parser);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING,1);
$parseResult = xml_parse($xml_parser, $convertedXML, TRUE);
if ($parseResult == 0) {
if (!isset($hideErrors)) {
$errorCode = xml_get_error_code($xml_parser);
echo "\$errorCode = $errorCode<br>\n";
echo "xml_error_string() = ".xml_error_string($errorCode)."<br>\n";
echo "xml_get_current_line_number() = ".xml_get_current_line_number($xml_parser)."<br>\n";
echo "xml_get_current_column_number() = ".xml_get_current_column_number($xml_parser)."<br>\n";
echo "xml_get_current_byte_index() = ".xml_get_current_byte_index($xml_parser)."<br>\n";
}
} else {
xml_parser_free($xml_parser);

// make sure the channel contentEncoded is not blank
if ($rss_parser->FeedContentEncoded == "") {
$rss_parser->FeedContentEncoded = $rss_parser->FeedDescription;
}
$template = FeedForAll_rss2html_str_replace("~~~FeedXMLFilename~~~", FeedForAll_rss2html_EscapeLink($XMLfilename), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedTitle~~~", FeedForAll_rss2html_limitLength($rss_parser->FeedTitle, $limitFeedTitleLength), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedDescription~~~", FeedForAll_rss2html_limitLength($rss_parser->FeedDescription, $limitFeedDescriptionLength), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedContentEncoded~~~", $rss_parser->FeedContentEncoded, $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedLink~~~", FeedForAll_rss2html_EscapeLink($rss_parser->FeedLink), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedPubDate~~~", $rss_parser->FeedPubDate, $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedPubLongDate~~~", date($LongDateFormat, $rss_parser->FeedPubDate_t), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedPubShortDate~~~", date($ShortDateFormat, $rss_parser->FeedPubDate_t), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedPubLongTime~~~", date($LongTimeFormat, $rss_parser->FeedPubDate_t), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedPubShortTime~~~", date($ShortTimeFormat, $rss_parser->FeedPubDate_t), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedImageUrl~~~", FeedForAll_rss2html_EscapeLink($rss_parser->FeedImageURL), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedImageTitle~~~", $rss_parser->FeedImageTitle, $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedImageLink~~~", FeedForAll_rss2html_EscapeLink($rss_parser->FeedImageLink), $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedImageDescription~~~", $rss_parser->FeedImageDescription, $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedImageHeight~~~", $rss_parser->FeedImageWidth, $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedImageWidth~~~", $rss_parser->FeedImageWidth, $template);
$template = FeedForAll_rss2html_str_replace("~~~FeedCreativeCommons~~~", FeedForAll_rss2html_EscapeLink($rss_parser->FeedCreativeCommons), $template);
if (FeedForAll_parseExtensions() === TRUE) {
$template = FeedForAll_parseExtensions_replaceInChannel($rss_parser, $template);
}

$match = NULL;

$template = str_replace("~~~NoFutureItems~~~", "", $template);

//
// Sort by PubDate if requested
if (strstr($template, "~~~SortByPubDate~~~")) {
$template = str_replace("~~~SortByPubDate~~~", "", $template);

for ($x = 0; $x < count($rss_parser->Items)-1; $x++) {
for ($y = $x+1; $y < count($rss_parser->Items); $y++) {
if ($rss_parser->Items[$x]->pubDate_t < $rss_parser->Items[$y]->pubDate_t) {
// Swap them
$swapTemp = $rss_parser->Items[$x]; $rss_parser->Items[$x] = $rss_parser->Items[$y]; $rss_parser->Items[$y] = $swapTemp;
}
}
}
}

if (isset($debugLevel) &amp;&amp; ($debugLevel >= 3)) {
echo "DIAG: adding to items, count=".count($rss_parser->Items)."<br>\n";
}

// The the maximum items requested
if (strstr($template, "~~~FeedMaxItems=")) {
// Limit the maximun number of items displayed
if (preg_match("/~~~FeedMaxItems=([0-9-]*)~~~/", $template, $match) !== FALSE) {
if (($match[0] != "") &amp;&amp; ($match[1] != "")) {
$FeedMaxItems = $match[1];
$template = str_replace("~~~FeedMaxItems=$match[1]~~~", "", $template);
}
}
}
if (abs($FeedMaxItems) > count($rss_parser->Items)) {
if ($FeedMaxItems > 0) {
$FeedMaxItems = count($rss_parser->Items);
} else {
$FeedMaxItems = -count($rss_parser->Items);
}
}

if (!function_exists("FeedForALL_rss2html_replaceInItem")) {
Function FeedForALL_rss2html_replaceInItem($source, $currentItem) {
GLOBAL $limitFeedTitleLength;
GLOBAL $limitFeedDescriptionLength;
GLOBAL $limitItemTitleLength;
GLOBAL $limitItemDescriptionLength;
GLOBAL $LongDateFormat;
GLOBAL $ShortDateFormat;
GLOBAL $LongTimeFormat;
GLOBAL $ShortTimeFormat;
GLOBAL $XMLfilename;

$item = FeedForAll_rss2html_str_replace("~~~ItemTitle~~~", FeedForAll_rss2html_limitLength($currentItem->title, $limitItemTitleLength), $source);
$item = FeedForAll_rss2html_str_replace("~~~ItemDescription~~~", FeedForAll_rss2html_limitLength($currentItem->description, $limitItemDescriptionLength), $item);
$item = FeedForAll_rss2html_str_replace("~~~ItemEnclosureLengthFormatted~~~", FeedForAll_rss2html_sizeToString($currentItem->enclosureLength), $item);
$item = FeedForAll_rss2html_str_replace("~~~ItemPubLongDate~~~", date($LongDateFormat, $currentItem->pubDate_t), $item);
$item = FeedForAll_rss2html_str_replace("~~~ItemPubShortDate~~~", date($ShortDateFormat, $currentItem->pubDate_t), $item);
$item = FeedForAll_rss2html_str_replace("~~~ItemPubLongTime~~~", date($LongTimeFormat, $currentItem->pubDate_t), $item);
$item = FeedForAll_rss2html_str_replace("~~~ItemPubShortTime~~~", date($ShortTimeFormat, $currentItem->pubDate_t), $item);

$knownFields = $currentItem->getArrayOfFields();
foreach ($knownFields as $field) {
$item = FeedForAll_rss2html_str_replace($field, $currentItem->getValueOf($field), $item);
}

$item = FeedForAll_rss2html_CreateUniqueLink($currentItem->title, $currentItem->description, $currentItem->link, $currentItem->guid, $XMLfilename, $item);
if (FeedForAll_parseExtensions() === TRUE) {
$item = FeedForAll_parseExtensions_replaceInItem($currentItem, $item);
}
return FeedForAll_rss2html_AddIdentity($item);
}
}

//
// Allow access to the number of times that will be processed in the feed
$template = FeedForAll_rss2html_str_replace("~~~NumberOfFeedItems~~~", min(abs($FeedMaxItems), count($rss_parser->Items)), $template);

//
// Find the string, if it exists, between the ~~~EndItemsRecord~~~ and ~~~BeginItemsRecord~~~
//
while ((strstr($template, "~~~BeginItemsRecord~~~")) !== FALSE) {
$match = NULL;
$allitems = NULL;
$loop_limit = min(abs($FeedMaxItems), count($rss_parser->Items));
if (($parts = explode("~~~BeginItemsRecord~~~", $template)) !== FALSE) {
if (($parts = explode("~~~EndItemsRecord~~~", $parts[1])) !== FALSE) {
$WholeBlock = $parts[0];
//
// Check for ~~~BeginAlternateItemsRecord~~~
//
if (strstr($WholeBlock, "~~~BeginAlternateItemsRecord~~~")) {
$parts = explode("~~~BeginAlternateItemsRecord~~~", $WholeBlock);
$block1 = $parts[0];
$block2 = $parts[1];
} else {
$block1 = $WholeBlock;
$block2 = $WholeBlock;
}
if ($FeedMaxItems < 0) {
for ($x = count($rss_parser->Items)-1; $x >= count($rss_parser->Items) + $FeedMaxItems; $x--) {
$allitems .= FeedForALL_rss2html_replaceInItem($block1, $rss_parser->Items[$x]);
$x--;
if ($x >= count($rss_parser->Items) + $FeedMaxItems) {
//
// This is at least one more item so use the Alternate definition
//
$allitems .= FeedForALL_rss2html_replaceInItem($block2, $rss_parser->Items[$x]);
}
}
} else {
for ($x = 0; $x < $loop_limit; $x++) {
if (isset($debugLevel) &amp;&amp; ($debugLevel >= 2)) {
echo "DIAG: Doing item fillin, \$x = $x; \$loop_limit = $loop_limit<br>\n";
}

$allitems .= FeedForALL_rss2html_replaceInItem($block1, $rss_parser->Items[$x]);
$x++;
if ($x < $loop_limit) {
//
// This is at least one more item so use the Alternate definition
//
if (isset($debugLevel) &amp;&amp; ($debugLevel >= 2)) {
echo "DIAG: Doing item fillin, \$x = $x; \$loop_limit = $loop_limit<br>\n";
}

$allitems .= FeedForALL_rss2html_replaceInItem($block2, $rss_parser->Items[$x]);
}
}
}
$template = str_replace("~~~BeginItemsRecord~~~".$WholeBlock."~~~EndItemsRecord~~~", $allitems, $template);
}
}
}

// Since &amp;apos; is not HTML, but is XML convert.
$template = str_replace("&amp;apos;", "'", $template);

if (!headers_sent()) {
// Send the Content-Type to force $destinationEncoding
header("Content-Type: text/html; charset=$destinationEncoding");
}
$resultHTML = FeedForAll_rss2html_pro($template);
echo $resultHTML;
if (isset($outputCacheTTL) &amp;&amp; function_exists("FeedForAll_scripts_writeOutputCacheFile")) {
FeedForAll_scripts_writeOutputCacheFile($XMLfilename, $TEMPLATEfilename, $resultHTML);
}
}
}
} else {
if (!headers_sent()) {
// Send the Content-Type to force $destinationEncoding
header("Content-Type: text/html; charset=$destinationEncoding");
}
echo "<html><head><title>rss2html.php URL tool</title><meta http-equiv=\"content-type\" content=\"text/html;charset=$destinationEncoding\"></head><body bgcolor=\"#EEEEFF\">\n";
//
// We are in "buildURL" mode to help create properly encoded URLs to pass to rss2html.php

$_xml = "";
if (isset($_POST["XML"])) {
$_xml = $_POST["XML"];
}
$_template = "";
if (isset($_POST["TEMPLATE"])) {
$_template = $_POST["TEMPLATE"];
}
$_maxitems = "";
if (isset($_POST["MAXITEMS"])) {
$_maxitems = $_POST["MAXITEMS"];
}
$_nofutureitems = "";
if (isset($_POST["NOFUTUREITEMS"])) {
$_nofutureitems = $_POST["NOFUTUREITEMS"];
}
if (function_exists("FeedForAll_scripts_contentOfCache")) {
$_cacheTTL = "";
if (isset($_POST["XMLCACHETTL"])) {
$_cacheTTL = $_POST["XMLCACHETTL"];
}
$_allowCachingXMLFiles = "";
if (isset($_POST["ALLOWXMLCACHE"])) {
$_allowCachingXMLFiles = $_POST["ALLOWXMLCACHE"];
}
$_outputCacheTTL = "";
if (isset($_POST["OUTCACHETTL"])) {
$_outputCacheTTL = $_POST["OUTCACHETTL"];
}
$_outputCacheFileName = "";
if (isset($_POST["OUTCACHENAME"])) {
$_outputCacheFileName = $_POST["OUTCACHENAME"];
}
}

// Display the entry form
echo "<center><h1>RSS2HTML.PHP LINK TOOL</h1></center>\n";
echo "<p>To assist with the with the creation of properly encoded URLs for use with rss2html.php this tool has been created.  Fill in the URLs or file paths for both the XML file and your template file in the boxes below and then click &amp;quot;Submit&amp;quot;.  The program will then return the URLs properly encoded in a string that calls rss2html.php.  You can click on this link to test the results.  The program will also indicate if it was unable to open either of the URLs it was given.</p>\n";
echo "<form action=\"$_SERVER[PHP_SELF]\" method=\"POST\">\n";
echo "<input type=\"hidden\" name=\"buildURL\" value=\"1\">\n";
echo "URL for the XML file: (ie. http://www.myserver.com/file.xml)<br><input type=\"text\" name=\"XML\" size=\"100\" value=\"$_xml\"><br>\n";
echo "URL for the template file: (ie. http://www.myserver.com/template.html)<br><input type=\"text\" name=\"TEMPLATE\" size=\"100\" value=\"$_template\"><br>\n";
echo "<b>Optional items:</b><br>\n";
echo "Maximum items: <input type=\"text\" name=\"MAXITEMS\" size=\"5\" value=\"$_maxitems\"> (Use negative numbers for the last X items)<br>\n";
echo "No future items: <input type=\"checkbox\" name=\"NOFUTUREITEMS\" ";
if ($_nofutureitems == "on") {
echo "CHECKED";
}
echo "><br>\n";
if (function_exists("FeedForAll_scripts_contentOfCache")) {
echo "<table cellpadding=\"2\" cellspacing=\"2\" width=\"100%\" border=\"1\"><tr><td>\n";
echo "<strong>XML (input) Cache Settings</strong><br>\n";
echo "Allow Caching of the feed: <input type=\"checkbox\" name=\"ALLOWXMLCACHE\" ";
if ($_allowCachingXMLFiles == "on") {
echo "CHECKED";
}
echo "><br>\n";
echo "Cache Time: <input type=\"text\" name=\"XMLCACHETTL\" size=\"5\" value=\"$_cacheTTL\"> (The number of seconds a file may be cached for before being fetched again)<br>\n";
echo "<hr>\n";
echo "<strong>HTML (output) Cache Settings</strong><br>\n";
echo "Output Cache Time: <input type=\"text\" name=\"OUTCACHETTL\" size=\"5\" value=\"$_outputCacheTTL\"> (The number of seconds the output may be cached for before being recreated)<br>\n";
echo "Output Cache Name: <input type=\"text\" name=\"OUTCACHENAME\" size=\"40\" value=\"$_outputCacheFileName\"> (This should be a unique name to prevent conflicts)<br>\n";
echo "</td></tr></table>\n";
}
echo "<input type=\"submit\" name=\"submit\" value=\"Submit\">\n";
echo "</form>\n";

$xmlContents = "";
$templateContents = "";

if (isset($_POST["submit"])) {
if ($_SERVER["REQUEST_METHOD"] != "POST") {
return;
}
echo "<hr>\n";

$answer = "";
$answerAlt = "";
$ssi = "";
$xmlurl = "";
$templateurl = "";
if ((isset($_POST["XML"]) &amp;&amp; $_POST["XML"] != "") || (isset($_POST["TEMPLATE"]) &amp;&amp; $_POST["TEMPLATE"] != "")) {
$answer .= "http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF]?";
}
if (isset($_POST["XML"]) &amp;&amp; $_POST["XML"] != "") {
$answer .= "XMLFILE=".FeedForAll_rss2html_encodeURL($_POST["XML"]);
$answerAlt .= "\$XMLFILE = \"".str_replace("&amp;", "&amp;amp;", $_POST["XML"])."\";<br>";
$ssi .= "XMLFILE=".FeedForAll_rss2html_encodeURL($_POST["XML"]);
$xmlurl = FeedForAll_rss2html_encodeURL($_POST["XML"]);
}
if ((isset($_POST["XML"]) &amp;&amp; $_POST["XML"] != "") &amp;&amp; (isset($_POST["TEMPLATE"]) &amp;&amp; $_POST["TEMPLATE"] != "")) {
$answer .=  "&amp;amp;";
$ssi .=  "&amp;amp;";
}
if (isset($_POST["TEMPLATE"]) &amp;&amp; $_POST["TEMPLATE"] != "") {
$answer .=  "TEMPLATE=".FeedForAll_rss2html_encodeURL($_POST["TEMPLATE"]);
$answerAlt .= "\$TEMPLATE = \"".str_replace("&amp;", "&amp;amp;", $_POST["TEMPLATE"])."\";<br>";
$ssi .=  "TEMPLATE=".FeedForAll_rss2html_encodeURL($_POST["TEMPLATE"]);
$templateurl = FeedForAll_rss2html_encodeURL($_POST["TEMPLATE"]);
}
if (isset($_POST["MAXITEMS"]) &amp;&amp; $_POST["MAXITEMS"] != "" &amp;&amp; intval($_POST["MAXITEMS"] != 0)) {
$answer .=  "&amp;amp;MAXITEMS=$_POST[MAXITEMS]";
$answerAlt .= "\$MAXITEMS = \"$_POST[MAXITEMS]\";<br>\n";
$ssi .=  "&amp;amp;MAXITEMS=$_POST[MAXITEMS]";
}
if (isset($_POST["NOFUTUREITEMS"]) &amp;&amp; $_POST["NOFUTUREITEMS"] == "on") {
$answer .=  "&amp;amp;NOFUTUREITEMS=1";
$answerAlt .= "\$NOFUTUREITEMS = \"1\";<br>\n";
$ssi .=  "&amp;amp;NOFUTUREITEMS=1";
}
if (function_exists("FeedForAll_scripts_contentOfCache")) {
if (isset($_POST["ALLOWXMLCACHE"]) &amp;&amp; $_POST["ALLOWXMLCACHE"] == "on") {
$answerAlt .= "\$ALLOWXMLCACHE = \"1\";<br>\n";
}
if (isset($_POST["XMLCACHETTL"]) &amp;&amp; ($_POST["XMLCACHETTL"] != "") &amp;&amp; (intval($_POST["XMLCACHETTL"]) != 0)) {
$answerAlt .= "\$XMLCACHETTL = \"$_POST[XMLCACHETTL]\";<br>\n";
}
if (isset($_POST["OUTCACHETTL"]) &amp;&amp; isset($_POST["OUTCACHENAME"])) {
if (($_POST["OUTCACHETTL"] != "") &amp;&amp; (intval($_POST["OUTCACHETTL"]) != 0) &amp;&amp; ($_POST["OUTCACHENAME"] != "")) {
$answerAlt .= "\$OUTCACHETTL = \"$_POST[OUTCACHETTL]\";<br>\n";
$answerAlt .= "\$OUTCACHENAME = \"$_POST[OUTCACHENAME]\";<br>\n";
}
}
}

echo "<h1>Results</h1>\n";

if (isset($_POST["XML"]) &amp;&amp; $_POST["XML"] != "") {
$XMLfilename = "";
if (stristr($_POST["XML"], "file"."://")) {
// Not allowed
;
}
elseif (stristr($_POST["XML"], "://")) {
if ($fileAccessLevel == -1) {
echo "<p style=\"color: red;\">Configuration setting prohibit using remote files</p>\n";
} else {
// URL files are allowed
$XMLfilename = $_POST["XML"];
}
} else {
if (($fileAccessLevel == 1) || ($fileAccessLevel == -1)) {
if (FeedForAll_rss2html_validExtension(basename($_POST["XML"]), $allowedFeedExtensions) === FALSE) {
echo "<p style=\"color: red;\">Configuration setting prohibit using the specified feed file</p>\n";
} else {
$XMLfilename = basename($_POST["XML"]);
}
}
elseif ($fileAccessLevel == 2) {
echo "<p style=\"color: red;\">Configuration setting prohibit using local files</p>\n";
} else {
// It is local and must be in the same directory
$XMLfilename = basename($_POST["XML"]);
}
}
if ($XMLfilename != "") {
if (($xmlContents = FeedForAll_scripts_readFile($XMLfilename, $useFopenURL)) === FALSE) {
if ($ReadErrorString == "") {
echo "<p>The XML file <b>$_POST[XML]</b> could not be opened.</p>\n";
} else {
echo "<p>The XML file <b>$_POST[XML]</b> could not be opened with the error <b>$ReadErrorString</b>.</p>\n";
}
} else {
echo "<p>The XML file <b>$_POST[XML]</b> was SUCCESSFULLY opened</p>\n";
}
}
}

if (isset($_POST["TEMPLATE"]) &amp;&amp; $_POST["TEMPLATE"] != "") {
$TEMPLATEfilename = "";
if (stristr($_POST["TEMPLATE"], "file"."://")) {
// Not allowed
;
}
elseif (stristr($_POST["TEMPLATE"], "://")) {
if ($fileAccessLevel == -1) {
echo "<p style=\"color: red;\">Configuration setting prohibit using remote files</p>\n";
} else {
// URL files are allowed
$TEMPLATEfilename = $_POST["TEMPLATE"];
}
} else {
if (($fileAccessLevel == 1) || ($fileAccessLevel == -1)) {
if (FeedForAll_rss2html_validExtension(basename($_POST["TEMPLATE"]), $allowedTemplateExtensions) === FALSE) {
echo "<p style=\"color: red;\">Configuration setting prohibit using the specified template file</p>\n";
} else {
$TEMPLATEfilename = basename($_POST["TEMPLATE"]);
}
}
elseif ($fileAccessLevel == 2) {
echo "<p style=\"color: red;\">Configuration setting prohibit using local files</p>\n";
} else {
// It is local and must be in the same directory
$TEMPLATEfilename = basename($_POST["TEMPLATE"]);
}
}
if ($TEMPLATEfilename != "") {
if (($templateContents = FeedForAll_scripts_readFile($TEMPLATEfilename, $useFopenURL)) === FALSE) {
if ($ReadErrorString == "") {
echo "<p>The template file <b>$_POST[TEMPLATE]</b> could not be opened.</p>\n";
} else {
echo "<p>The template file <b>$_POST[TEMPLATE]</b> could not be opened with the error <b>$ReadErrorString</b>.</p>\n";
}
}
elseif (FeedForAll_rss2html_isTemplate($templateContents) === FALSE) {
echo "$_POST[TEMPLATE] is not a valid rss2html.php template file\n";
$templateContents = "";
} else {
echo "<p>The template file <b>$_POST[TEMPLATE]</b> was SUCCESSFULLY opened</p>\n";
}
}
}

if ($xmlurl != "") {
echo "<p>URL for the XML file properly encoded:<br><pre>$xmlurl</pre></p>\n";
}

if ($templateurl != "") {
echo "<p>URL for the template file properly encoded:<br><pre>$templateurl</pre></p>\n";
}

echo "<h2>Test Link</h2>\n";

echo "<p>Click on link to view results: <a href=\"$answer\" target=\"_blank\">$answer</a></p>\n";

echo "<h2>Example Usage</h2>\n";

echo "<p>Server Side Include:<br><nobr style=\"font-weight: bolder; color: red;\">&amp;lt!--#INCLUDE VIRTUAL=&amp;quot;".basename($_SERVER["PHP_SELF"])."?$ssi&amp;quot; --&amp;gt;</nobr></p>\n";

echo "<p>Prefered PHP Include:<br><nobr style=\"font-weight: bolder; color: red;\">&amp;lt;?php<br>$answerAlt\ninclude(&amp;quot;".basename($_SERVER["PHP_SELF"])."&amp;quot;);<br>?&amp;gt;</nobr></p>\n";

echo "<p>PHP Include (Due to security concerns many ISP have configured their servers to prevent this from working):<br><nobr style=\"font-weight: bolder; color: red;\">&amp;lt;?php<br>include(&amp;quot;$answer&amp;quot;);<br>?&amp;gt;</nobr></p>\n";

}

if ($xmlContents != "" || $templateContents != "") {
echo "<br><hr><br>\n";
if ($xmlContents != "") {
echo "<h1>XML file</h1>\n";
if (($convertedXML = FeedForAll_scripts_convertEncoding($xmlContents, $missingEncodingDefault, $destinationEncoding)) === FALSE) {
// Conversions failed, probably becasue it was wrong or the routines were missing
$convertedXML = $xmlContents;
}
$convertedXML = str_replace("&amp;", "&amp;amp;", $convertedXML);
$convertedXML = str_replace("<", "&amp;lt;", $convertedXML);
$convertedXML = str_replace(">", "&amp;gt;", $convertedXML);
echo "<pre>$convertedXML</pre><br>\n";
}
if ($templateContents != "") {
echo "<h1>Template file</h1>\n";
$templateContents = str_replace("&amp;", "&amp;amp;", $templateContents);
$templateContents = str_replace("<", "&amp;lt;", $templateContents);
$templateContents = str_replace(">", "&amp;gt;", $templateContents);
echo "<pre>$templateContents</pre><br>\n";
}
}
}

?>

&amp;nbsp;

PHP Ultimate Web Counter Chat Scripts

The Ultimate Web Counter is a Freeware tool to can add to your web site that will allow visitors to choose counters to add to their own sites. One of the only scripts of its kind! – Written in HTML and JavaScript, so the page is platform-independent (works on any kind of hosting account, even free ones!) – Easy to install, just upload the page with some images and you’re done! – Counter images are remotely hosted, so you don’t lose any bandwidth
,- Over 130 high-quality counter styles for your visitors to choose from, – Super easy way to add extra FUN-ctionality to your site! – Spyware and adware free.

 

 

<?php
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 Old Guy's version of Akismet PHP4 class
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 Original PHP5 class by Alex Potsides, http://www.achingbrain.net
 Converted to PHP4 by Bret Kuhns, http://www.l33thaxor.com
 Enhanced by Richard Williamson (aka Old Guy), http://www.scripts.oldguy.us, June 2006

 Copyright Alex Potsides
 Licensed under the terms of the GNU General Public License, June 1991.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

This class allows use of the Akismet (http://akismet.com) anti-comment spam service in any PHP4 application. The service performs a number of checks on submitted data and returns whether or not the data is likely to be spam. It takes the functionality from the Akismet WordPress plugin written by Matt Mullenweg (http://photomatt.net) and allows it to be integrated into any PHP4 application or website.

To use this class, you must have a vaild WordPress API key (http://wordpress.com/api-keys). They are free for non-commercial use and getting one will only take a couple of minutes. For commercial. use there are Akismet commercial licenses (http://akismet.com/commercial).

Changes made by Old Guy:
- Replaced trigger_error() on fsockopen failure with status code that is retrieved via isKeyValid(). This allows your script to handle the error instead of having execution halt and your visitor seeing an ugly error message. Disabled PHP error display before the fsockopen to prevent the PHP error message and re-enabled error display after the error is trapped.
- Replaced trigger_error() on invalid key with status code that is returned by isCommentSpam().

The basic usage structure in your script will be something like the following:

 // Initialize and verify API key
 $akismet = new Akismet($your_site_url, $your_akismet_key]);
 $result = $akismet->isKeyValid();
 // Possible values: 'valid', 'invalid', 'no connect'
 if ($result != 'valid') {
 if (($result == 'invalid')) {
 // Invalid key
 store the comment in the moderation queue
 error email to administrator
 return
 } else {
 // Could not connect to the Akismet server
 store the comment in the moderation queue
 error email to administrator
 return
 }
 }
 // Pass comment info to the class
 $akismet->setCommentAuthorEmail($author_email);
 $akismet->setCommentAuthor($author_name);
 $akismet->setCommentAuthorURL($author_url);
 $akismet->setCommentContent($comment_text);
 $akismet->setPermalink($your_site_url . $path_to_page);
 $akismet->setCommentType('Comment');
 // Check the comment for spam
 $result = $akismet->isCommentSpam();
 // Possible values: 'false' (not spam), 'true' (spam), 'no connect'
 if ($result != 'false') {
 if ($result == 'true') {
 // The comment is spam
 mark as spam, store the comment, delete after n days
 (you should review these in case of a mis-diagnosis)
 } else {
 // Could not connect to the Akismet server
 store the comment in the moderation queue
 error email to administrator
 return
 }
 } else {
 store the comment normally
 }

Other functions you may use are:
 $akismet->setUserIP($userip)                    defaults to $_SERVER['REMOTE_ADDR'];
 $akismet->setReferrer($referrer)                defaults to $_SERVER['HTTP_REFERER'];
 $akismet->setAPIPort($apiPort)                    defaults to 80
 $akismet->setAkismetServer($akismetServer)        defaults to 'rest.akismet.com'
 $akismet->setAkismetVersion($akismetVersion)    defaults to '1.1'
 $akismet->submitSpam()                            no status returned
 $akismet->submitHam()                            no status returned

*/

class Akismet {
 var $version = '0.3';
 var $wordPressAPIKey;
 var $blogURL;
 var $comment;
 var $apiPort;
 var $akismetServer;
 var $akismetVersion;

 // This prevents some potentially sensitive information from being sent accross the wire.
 var $ignore = array('HTTP_COOKIE',
 'HTTP_X_FORWARDED_FOR',
 'HTTP_X_FORWARDED_HOST',
 'HTTP_MAX_FORWARDS',
 'HTTP_X_FORWARDED_SERVER',
 'REDIRECT_STATUS',
 'SERVER_PORT',
 'PATH',
 'DOCUMENT_ROOT',
 'SERVER_ADMIN',
 'QUERY_STRING',
 'PHP_SELF' );

 // Initialize Akismet and verify API key
 function Akismet($blogURL, $wordPressAPIKey) {
 $this->blogURL = $blogURL;
 $this->wordPressAPIKey = $wordPressAPIKey;
 $this->apiPort = 80;
 $this->akismetServer = 'rest.akismet.com';
 $this->akismetVersion = '1.1';
 $this->comment['blog'] = $blogURL;
 $this->comment['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
 $this->comment['referrer'] = $_SERVER['HTTP_REFERER'];
 $this->comment['user_ip'] = $_SERVER['REMOTE_ADDR'];
 // Check to see if the key is valid
 $response = $this->http_post('key=' . $this->wordPressAPIKey . '&amp;blog=' . $this->blogURL, $this->akismetServer, '/' . $this->akismetVersion . '/verify-key');
 if($response[1] == 'valid') {
 $this->keyStatus = 'valid';
 } elseif ($response[1] == 'no connect') {
 $this->keyStatus = 'no connect';
 } else {
 $this->keyStatus = 'invalid';
 }
 }

 // Use this after initializing Akismet
 function isKeyValid() {
 return $this->keyStatus;
 }

 // Checks the comment for spam
 function isCommentSpam() {
 $response = $this->http_post($this->getQueryString(), $this->wordPressAPIKey . '.rest.akismet.com', '/' . $this->akismetVersion . '/comment-check');
 return ($response[1]);
 }

 // Used if Akismet should have flagged a comment as spam but did not
 function submitSpam() {
 $this->http_post($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-spam');
 }

 // Used if Akismet flagged a comment as spam but it is not spam
 function submitHam() {
 $this->http_post($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-ham');
 }

 function http_post($request, $host, $path) {
 $http_request  = "POST " . $path . " HTTP/1.1\r\n";
 $http_request .= "Host: " . $host . "\r\n";
 $http_request .= "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n";
 $http_request .= "Content-Length: " . strlen($request) . "\r\n";
 $http_request .= "User-Agent: Akismet PHP4 Class (modified by RMW) " . $this->version . " | Akismet/1.11\r\n";
 $http_request .= "\r\n";
 $http_request .= $request;
 $socketWriteRead = new SocketWriteRead($host, $this->apiPort, $http_request);
 $socketWriteRead->send();
 $response = explode("\r\n\r\n", $socketWriteRead->getResponse(), 2);
 $sendStatus = $socketWriteRead->getsendStatus();
 if ($sendStatus == 'no connect') {
 $response[1] = 'no connect';
 }
 return $response;
 }

 // Formats the data for transmission
 function getQueryString() {
 foreach($_SERVER as $key => $value) {
 if(!in_array($key, $this->ignore)) {
 if($key == 'REMOTE_ADDR') {
 $this->comment[$key] = $this->comment['user_ip'];
 } else {
 $this->comment[$key] = $value;
 }
 }
 }
 $query_string = '';
 foreach($this->comment as $key => $data) {
 $query_string .= $key . '=' . urlencode(stripslashes($data)) . '&amp;';
 }
 return $query_string;
 }

 function setUserIP($userip) {
 $this->comment['user_ip'] = $userip;
 }

 function setReferrer($referrer) {
 $this->comment['referrer'] = $referrer;
 }

 function setPermalink($permalink) {
 $this->comment['permalink'] = $permalink;
 }

 function setCommentType($commentType) {
 $this->comment['comment_type'] = $commentType;
 }

 function setCommentAuthor($commentAuthor) {
 $this->comment['comment_author'] = $commentAuthor;
 }

 function setCommentAuthorEmail($authorEmail) {
 $this->comment['comment_author_email'] = $authorEmail;
 }

 function setCommentAuthorURL($authorURL) {
 $this->comment['comment_author_url'] = $authorURL;
 }

 function setCommentContent($commentBody) {
 $this->comment['comment_content'] = $commentBody;
 }

 function setAPIPort($apiPort) {
 $this->apiPort = $apiPort;
 }

 function setAkismetServer($akismetServer) {
 $this->akismetServer = $akismetServer;
 }

 function setAkismetVersion($akismetVersion) {
 $this->akismetVersion = $akismetVersion;
 }
}


// Utility class used by Akismet
class SocketWriteRead {
 var $host;
 var $port;
 var $request;
 var $response;
 var $responseLength;
 var $errorNumber;
 var $errorString;

 function SocketWriteRead($host, $port, $request, $responseLength = 1160) {
 $this->host = $host;
 $this->port = $port;
 $this->request = $request;
 $this->responseLength = $responseLength;
 $this->errorNumber = 0;
 $this->errorString = '';
 }

 // Sends the data to the remote host.
 function send() {
 $this->response = '';
 $this->sendStatus = '';
 /*ini_set('display_errors','false');*/
 $fs = fsockopen($this->host, $this->port, $this->errorNumber, $this->errorString, 3);
 if($this->errorNumber != 0) {
 $this->sendStatus = 'no connect';
 }
 /*ini_set('display_errors','true');*/
 if($fs !== false) {
 @fwrite($fs, $this->request);
 while(!feof($fs)) {
 $this->response .= fgets($fs, $this->responseLength);
 }
 fclose($fs);
 }
 }

 function getsendStatus() {
 return $this->sendStatus;
 }

 function getResponse() {
 return $this->response;
 }

 function getErrorNumner() {
 return $this->errorNumber;
 }

 function getErrorString() {
 return $this->errorString;
 }
}
?>

&amp;nbsp;

PHP x64 Simple Counter Chat Scripts

x64 Simple Counter can be used to count site visits using flat files to store visit statistics.It logs the visiting users IP address in order to know if the visitor was already counted. It may also be used to know if a visitor already voted in a poll.

 

 

<?php

/**
 * x64 Simple Counter
 *
 * A simple visits counter, it uses a flat
 * file as database, and it logs the IP
 * in order to know if the visitor already
 * was counted.
 * It can even be used to know if a visitor already
 * voted, or whatever you want to do.
 *
 * @author Atomo64 - www.atomo64.tk
 * @version 0.1
 * @copyright Atomo64 2006
 * @license GNU GPL
 * @example $counter=new x64_simple_counter(); $counter->auto();
 *
 */

class x64_simple_counter
{
 /**
 * The name of the file used as DB
 *
 * @var string
 */

 var $db;
 /**
 * The number of seconds when the IP expires
 *
 * @var int
 */

 var $expire;
 /**
 * If the visitor already was counted(filled when calling count(), get_count() or the function of the name of the var)
 *
 * @var bool
 */

 var $already_counted;
 /**
 * This is the number of visits counted
 * This value is used for caching pourposes, preventing from re-opening
 * the file if we already opened it once.
 * Only two functions sets the value of this var, count() (after counting) and get_count()
 * It is going to be null if none of both functions were called yet
 *
 * @var int,null null if count() or get_count() were not called yet
 */

 var $count;
 /**
 * This is the time of since when we are counting
 * For more information about this var see $count
 * The only exception is that the value of this var is set
 * by these functions: count(), get_count(), install(), reset_ips() and clean_expired_ips()
 *
 * @var int,null null if the value has not been set yet.
 */

 var $since_time;

 /**
 * Class initiator
 * Checks if the file used ad DB already exists,
 * if not, then it creates it.
 *
 * @param string $file The file name of the file used as DB
 * @param int $expire The expiration time of an IP (in seconds, default is a day)
 * @return x64_simple_counter
 */

 function x64_simple_counter($file='counter_data.php',$expire=86400)
 {
 $this->db=$file;
 $this->expire=$expire;
 if(!file_exists($file))
 $this->install();
 }

 /**
 * Counts the visitor
 *
 * @return bool if the file could be found/open or not
 */

 function count()
 {
 if(!file_exists($this->db))
 return false;

 $data=file($this->db);
 $ips=unserialize($data[1]);
 $count=unserialize($data[2]);
 $date=unserialize($data[3]);
 $this->since_time=$date;

 if(isset($ips[$_SERVER['REMOTE_ADDR']]))
 {
 $ips[$_SERVER['REMOTE_ADDR']]=time();
 $this->already_counted=true;
 }
 else
 {
 $count++;
 $ips[$_SERVER['REMOTE_ADDR']]=time();
 $this->already_counted=false;
 }

 $this->count=$count;

 $flat_file="<?php /* \n".serialize($ips)."\n".serialize($count)."\n".serialize($date)."\n */ ?>";

 $fp=fopen($this->db,"w");

 if(!$fp)
 return false;

 fwrite($fp,$flat_file,strlen($flat_file));
 fclose($fp);

 return true;
 }

 /**
 * Get the number of visits
 *
 * @return false,int false when the file could not be found/open or an int with the visits
 */

 function get_count()
 {
 if(!file_exists($this->db))
 return false;

 if($this->count!==null)
 return $this->count;

 $data=file($this->db);
 $ips=unserialize($data[1]);
 $count=unserialize($data[2]);
 $date=unserialize($data[3]);

 $this->already_counted=isset($ips[$_SERVER['REMOTE_ADDR']]);
 $this->count=$count;
 $this->since_time=$date;

 return $count;
 }

 /**
 * Creates the file used as DB
 *
 * @return bool if the file could be found/open or not
 */

 function install()
 {
 $time=time();
 $flat_file="<?php /* \n".serialize(array())."\n".serialize(0)."\n".serialize($time)."\n */ ?>";
 $this->since_time=$time;

 $fp=fopen($this->db,"w");

 if(!$fp)
 return false;

 fwrite($fp,$flat_file,strlen($flat_file));
 fclose($fp);

 return true;
 }

 /**
 * Alias of install(); resets all the data
 *
 * @return bool if the file could be found/open or not
 */

 function reset_all(){ return $this->install(); }

 /**
 * This removes all the IPs from the database
 *
 * @return bool if the file could be found/open or not
 */

 function reset_ips()
 {
 if(!file_exists($this->db))
 return false;

 $data=file($this->db);

 $count=unserialize($data[2]);
 $date=unserialize($data[3]);
 $this->since_time=$date;
 $flat_file="<?php /* \n".serialize(array())."\n".serialize($count)."\n".serialize($date)."\n */ ?>";

 $fp=fopen($this->db,"w");

 if(!$fp)
 return false;

 fwrite($fp,$flat_file,strlen($flat_file));
 fclose($fp);

 return true;
 }

 /**
 * Cleans the DB from expired IPs
 *
 * @param bool $reduce_count if the counter should decrease for each expired IP
 * @return bool if the file could be found/open or not
 */

 function clean_expired_ips($reduce_count=false)
 {
 if(!file_exists($this->db))
 return false;

 if($this->expire==0)
 return true;

 $data=file($this->db);
 $ips=unserialize($data[1]);
 $count=unserialize($data[2]);
 $date=unserialize($data[2]);

 $this->since_time=$date;

 $new_array=array();
 $modified=false;

 foreach ($ips as $key=>$date)
 {
 if((time()-$date)<$this->expire)
 $new_array[$key]=$date;
 else
 {
 if($reduce_count)
 $count--;
 $modified=true;
 }
 }

 if($modified)
 {
 $flat_file="<?php /* \n".serialize($new_array)."\n".serialize($count)."\n".serialize($date)."\n */ ?>";

 $fp=fopen($this->db,"w");

 if(!$fp)
 return false;

 fwrite($fp,$flat_file,strlen($flat_file));
 fclose($fp);
 }
 return true;
 }

 /**
 * Use this and forget about calling any other function
 * It is necessary that you initiate a class before calling
 *
 * @param bool $reduce_count if the counter should decrease for each expired IP
 * @return false,int False when DB couldn't be created/open or an int saying the number of visits on the DB.
 */

 function auto($reduce_count=false)
 {
 if(!file_exists($this->db)&amp;&amp;!$this->install())
 {
 return false;
 }

 $this->clean_expired_ips($reduce_count);
 $this->count();

 return $this->get_count();
 }

 /**
 * Returns if the visitor was already counted
 * This function fills the value of $already_counted
 *
 * @return bool,null null when the DB doesn't exists
 */

 function already_counted()
 {
 if($this->already_counted!=null)
 return $this->already_counted;

 if(!file_exists($this->db))
 return null;

 $data=file($this->db);
 $ips=unserialize($data[1]);
 $count=unserialize($data[2]);
 $date=unserialize($data[3]);

 $this->already_counted=isset($ips[$_SERVER['REMOTE_ADDR']]);
 $this->count=$count;
 $this->since_time=$date;

 return $this->already_counted;
 }
}
?>

&amp;nbsp;

AGTC PHP – Simple Hits Counter Chat Scripts

Well its a very simple hits counter that only logs individual hits, in other words one hit per person per visit. Its work simply by checking the visitors Remote Address and logs it as a SESSION. Once the visitor enters your site the session is then logged with their Remote Address and the hits counter logs one hit. For as long as there on your site they will not add anymore hits to the counter until they re-visit in a new session. The idea of this script came to me from some of the poor or lazy examples of hits counters I have seen, which each time you refreshed the page it would log another hit, this is no good if you want to see the true value of visitors to your site. Great, simple, and easy to integrate into any PHP script. Try the demo…

 

 

<?php  session_start(); // This line must go at the top of the page you wish to display the hits counter on ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Sample Index Page For AGTC Unique Hits Counter</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h4>This is a sample index page displaying the unique hits counter result</h4>
<p>So whats unique about it ?</p>
<p>Well its a very simple hits counter that only logs individual hits, in other words one hit per person per visit.<br>
 Its work simply by checking the visitors Remote Address and logs it as a SESSION.<br>
 Once the visitor enters your site the session is then logged with their Remote Address and the hits counter logs one hit.<br>
 For as long as there on your site they will not add anymore hits to the counter until they re-visit in a new session.<br>
 The idea of this script came to me from some of the poor or lazy examples of hits counters I have seen, which each time you refreshed the page<br>
 it would log another hit.<br>
 This is no good for your true site traffic data, yes it does looks good to visitors to see so many hits but you will never know the true value of<br>
 the visitors to your site. Why not run this script along side any other hits counter you have and put the hits counter display in your own<br>
 admin page or a page that your visitors will never see then you can still impress your visitors while you can keep an eye on your true hits.</p>
<?php
// This code must be inserted somewhere in your index page to display the hits counter
include"check.php";
echo "<b><font face='arial'>".$data." Unique Visitors</b></font><br>";
?>

<p><a href="http://www.agtc.co.uk"><img src="http://www.agtc.co.uk/images/agtcbanner1.gif" alt="AGTC Web Solutions" width="468" height="60" border="1"></a></p>
</body>
</html>

&amp;nbsp;

PHP Page Counter for Chat scripts

Page Counter can be used to display a graphical page hit counter. It read, update and stores the page hit counts in text files.The counter is displayed a sequence of HTML tags for images that represent each digit of the current page hit count. The counter digits may display trailing zeros. The width and height of the digit images can also be configured. Page Counter comes with a set of digit image files but it can also be configured to use a set of the digit files from custom image directory.

 

 

<?php
class PageCounter {
 var $_FileCounter;        // Text file for storing count
 var $_MinLen;            // Minimum length of counter ie trailing zeros
 var $_ImgSizeH;            // height of the digit image
 var $_ImgSizeW;            // width of the digit image
 var $_IDigitDir;        // Location of digit images
// Create a outset border for digit images that don't use  borders in themselves
 var $_UseBorder        =    false;
 var $_BorderColor;
 var $_UseTriger        =    false;
 var $_TrigerURL;
 function SetFileCounter($x)
 {
 $this->_FileCounter        = $x;
 }
 function SetMinLen($x)
 {
 $this->_MinLen            = $x;
 }
 function SetImgSize($xHeight, $xWidth)
 {
 $this->_ImgSizeH        = $xHeight;
 $this->_ImgSizeW        = $xWidth;
 }
 function SetDigitDir($x)
 {
 $this->_DigitDir        = $x;
 }
 function SetBorder($useBool, $bColour)
 {
 $this->_UseBorder        = $useBool;
 $this->_BorderColor        = $bColour;
 }
 function SetTrigerPage($useBool, $url)
 {
 $this->_UseTriger        = $useBool;
 $this->_TrigerURL        = $url;
 }
 function HitCount()
 {
 if (!file_exists($this->_FileCounter)) {
 $fp_Count = fopen($this->_FileCounter, "w+");
 fwrite($fp_Count,0);
 fclose($fp_Count);
 }
 $i_Count = file_get_contents ($this->_FileCounter, "r");
 if($this->_UseTriger) {
 $ActiveURL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ."?". $_SERVER['QUERY_STRING'];
 if($ActiveURL == $this->_TrigerURL) {
 $i_Count++;
 $fp = fopen($this->_FileCounter,'w+');
 fwrite($fp,$i_Count);
 }
 } else {
 $i_Count++;
 $fp = fopen($this->_FileCounter,'w+');
 fwrite($fp,$i_Count);
 }
 if (strlen($i_Count) < $this->_MinLen) {
 $i_Countz = $this->AddZeros($i_Count);
 }else {
 $i_Countz = $i_Count;
 }
 for ($x = 0; $x < strlen($i_Countz); $x++) {
 $Cur = substr($i_Countz,$x,1);
 $Ret .=    "<img src=\"". $this->_DigitDir . $Cur .".gif\" height=$this->_ImgSizeH";
 $Ret .= " width=$this->_ImgSizeW>";
 }
 if($this->_UseBorder) { $Ret = $this->CreateBorder($Ret); }
 return $Ret;
 }
 function CreateBorder($imgTags)
 {
 $bTags = "<table><tr>\n<td title=\"Evil Wizard Hit Counters\" style=\"border: 3px outset ". $this->_BorderColor ."; padding:0;\">";
 $bTags .= $imgTags;
 $bTags .= "</td></tr></table>\n";
 return $bTags;
 }
 function AddZeros($i)
 {
 $f = "%0";
 $f .= $this->_MinLen;
 $f .= "d";
 $i = sprintf($f,$i);
 return $i;
 }
}
?>

&amp;nbsp;

PHP Access Pattern Counter Chat Scripts

Access Pattern Counter is meant to keep track of the count of users access to the pages of a site. The counter class can also output the current access count in an HTML table.Page accesses are considered by the remote user computer IP address only if sufficient time has passed, by default one hour. During this access window, a count is kept of the accesses to the page by a specific ip address.Access Pattern Counter allows possible detection of denial of service attacks by keeping data useful for tracking access patterns by specific hosts. All data is kept in a MySQL database. This class is officially compatible with PHP 5.

 

 

<?php

//
// Class: Counter
// Table: counter
// Database: counter
/*
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      |      | PRI | NULL    | auto_increment |
| counter   | int(11)      |      |     | 0       |                |
| host      | varchar(255) | YES  |     | NULL    |                |
| page      | longtext     | YES  |     | NULL    |                |
| timestamp | datetime     | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
*/

// Generated by buildClass.php, written by Dick Munroe (munroe@csworks.com)
//
// Edit History:
//
//    Dick Munroe (munroe@csworks.com) 03-Nov-2005
//        Semantics of select changed.  Errors now require testing with "hasErrors" in order to sort out
//        the case between that and no data.
//
//    Dick Munroe (munroe@csworks.com) 12-Jun-2006
//        The format of timestamps changed from sql V3 to V4.
//

include_once("class.counterUser.php") ;
include_once("SDD/class.SDD.php") ;
include_once("SQLData/class.SQLData.php") ;

class Counter extends SQLData
{

 //
 // Private (or constant) varibles.
 //

 var $m__current = 60 ;                              // Number of minutes a user is considered to be "current"
 var $m__host ;                    // name of the host (allows multiple sites per database).
 var $m__page ;                    // page on the host.
 var $m__remoteAddr ;                // fqdn or ip address of the accessing host.
 var $m__tableName = 'counter' ;

 //
 // Constructor
 //
 //  Create and, if necessary, increment a counter for a page.
 //
 // Parameters:
 //
 //     $_database    Name of the database containing the counter tables.
 //    $_host        Name of the host running the MySQL server.  (Default: localhost)
 //    $_login        SQL user name.  (Default: "")
 //  $_password    SQL user password.  (Default: "")
 //  $_page         Name of the counter.  (Default: $_SERVER['SCRIPT_NAME'])
 //    $_current    Number of minues this accessor is considered current for
 //            access to the page.  (Default: 60)
 //

 function Counter($_dataBase,
 $_host="localhost",
 $_login="",
 $_password="",
 $_page = null,
 $_current = null)
 {
 if ($_page == null)
 {
 $this->m__page = $_SERVER['SCRIPT_NAME'] ;
 }
 else
 {
 $this->m__page = $_page ;
 }

 if ($_current != null)
 {
 $this->m__current = $_current ;
 }

 $this->m__host = $_SERVER['HTTP_HOST'] ;

 $this->m__remoteAddr = (empty($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_ADDR'] : $_SERVER['REMOTE_HOST']) ;

 $this->SQLData($this->m__tableName, $_dataBase, $_host, $_login, $_password) ;

 //
 // Create a counter in the table if one hasn't been implemented.
 //

 if (!$this->select("where host = '" . $this->escape_string($this->m__host) .
 "' and page = '" . $this->escape_string($this->m__page) . "'"))
 {
 if ($this->hasErrors())
 {
 $this->showErrors() ;
 die("Can't select counter") ;
 }
 }

 if ($this->eof())
 {
 $this->setHost($this->m__host) ;
 $this->setPage($this->m__page) ;
 $this->setCounter(0) ;
 $this->setTimestamp(date("YmdHis")) ;
 if (!$this->insert())
 {
 $this->showErrors() ;
 die("Can't insert counter") ;
 }
 $this->initId($this->fetchLastInsertId()) ;
 }

 $u = new CounterUser($this->getId(), $this->m__remoteAddr, $_dataBase, $_host, $_login, $_password) ;

 $ts = $u->getTimestamp() ;

 //
 // Convert MySQL V4 timestamps into canonical form.
 //

 $ts = preg_replace('/[: -.]+/', '', $ts) ;

 if (preg_match("/^0+$/", $ts))
 {
 //
 // This is a brand new user of the page, so belt out the timestamp.
 //

 $this->setCounter($this->getCounter()+1) ;

 if (!$this->update("where id = '" . $this->getId() . "'"))
 {
 $this->showErrors() ;
 die("Can't update counter") ;
 }

 $u->setTimestamp(null) ;

 if (!$u->update("where id = '" . $u->escape_string($u->getId()) . "'"))
 {
 $u->showErrors() ;
 die("Can't update user") ;
 }
 }
 else
 {
 $localTs = array(substr($ts, 8, 2),
 substr($ts, 10, 2),
 substr($ts, 12, 2),
 substr($ts, 4, 2),
 substr($ts, 6, 2),
 substr($ts, 0, 4)) ;

 //
 // Add the increment of current to get when the timestamp expires.
 //

 $localTs[1] += $this->m__current ;
 $localTs = mktime($localTs[0], $localTs[1], $localTs[2], $localTs[3], $localTs[4], $localTs[5]) ;

 if (time() > $localTs)
 {
 //
 // It's been long enough, so increment another counter.
 //

 $this->setCounter($this->getCounter()+1) ;

 if (!$this->update("where id = '" . $this->getId() . "'"))
 {
 $this->showErrors() ;
 die("Can't update counter") ;
 }
 }

 //
 // Since this user has made yet another hit on the page, move his
 // window for a "new" hit into the future by remarking his
 // timestamp.  This avoids repeated hits on the page from being
 // incorrectly counted.  Keep track of the repeats in case of some
 // form of abuse.
 //

 $u->setTimestamp(null) ;

 $u->setRepeat($u->getRepeat()+1) ;

 if (!$u->update("where id = '" . $u->escape_string($u->getId()) . "'"))
 {
 $u->showErrors() ;
 die("Can't update user") ;
 }
 }
 }

 //
 // Accessor Functions
 //

 function setId($theValue)
 {
 $this->set('id', $theValue) ;
 }

 function getId()
 {
 return $this->get('id') ;
 }

 function initId($theValue)
 {
 $this->init('id', $theValue) ;
 }

 function setCounter($theValue)
 {
 $this->set('counter', $theValue) ;
 }

 function getCounter()
 {
 return $this->get('counter') ;
 }

 function initCounter($theValue)
 {
 $this->init('counter', $theValue) ;
 }

 function setHost($theValue)
 {
 $this->set('host', $theValue) ;
 }

 function getHost()
 {
 return $this->get('host') ;
 }

 function initHost($theValue)
 {
 $this->init('host', $theValue) ;
 }

 function setPage($theValue)
 {
 $this->set('page', $theValue) ;
 }

 function getPage()
 {
 return $this->get('page') ;
 }

 function initPage($theValue)
 {
 $this->init('page', $theValue) ;
 }

 function setTimestamp($theValue)
 {
 $this->set('timestamp', $theValue) ;
 }

 function getTimestamp()
 {
 return $this->get('timestamp') ;
 }

 function initTimestamp($theValue)
 {
 $this->init('timestamp', $theValue) ;
 }

 //
 // Return counter as a table, one digit per cell.
 //

 function oneDigitTable($theTableAttr = "", $theTDAttr = "", $theLength=0)
 {
 $theTable = "" ;

 $theCounter = sprintf("%0{$theLength}d", $this->getCounter()) ;

 for ($i = 0; $i < strlen($theCounter) ; $i++)
 {
 $theTable .= sprintf("<td%s>%s</td>",
 ($theTDAttr == "" ? "" : " " . $theTDAttr),
 substr($theCounter, $i, 1)) ;
 }

 return sprintf("<table%s>%s</table>", ($theTableAttr == "" ? "" : " " . $theTableAttr), $theTable) ;
 }

 //
 // Debugging Functions
 //

 function print_r()
 {
 print("class " . get_class($this) . " ") ;
 parent::print_r() ;
 }
}

?>

&amp;nbsp;

PHP for RTCounter Chat Scripts

RTCounter is a very simple php counter that doesn’t requires mysql and keeps track of how many unique pageviews your site has.

 

 

<?php
/**********************************************
* Copyright (c) 2006 Roberto Toldo
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
***********************************************/


//User counter
$file = fopen("counter.txt","r+");
$EXPIRE_DATE = 600;
$count = fread($file, filesize("counter.txt"));
fclose($file);
 if ($tivisited == "") {
 $count += 1;
 $file = fopen("counter.txt","w+");
 fputs($file, $count);
 fclose($file);
 setcookie("tivisited", "RTcounter cookie", time()+$EXPIRE_DATE , "/", $SERVER_NAME);
 }
?>

&amp;nbsp;