#!/usr/bin/perl

# Fresh News Updater Version 1.0 by Webfresh (TM)
# Copyright  ©1999-2000 Webfresh All Rights Reserved
#
# This program is being distributed as shareware.  It may be used and
# modified by anyone, so long as this copyright notice and the header
# above remain intact, but any usage should be registered.  (See the
# program documentation for registration information.)  Selling the
# code for this program without prior written consent is expressly
# forbidden.  Obtain permission before redistributing this program
# over the Internet or in any other medium.  In all cases copyright
# and header must remain intact.
#
# VERSIONS OF SOFTWARE
#-----------------------------------------------------------------------
# Only one copy of the shareware or registered version of Fresh News
# Updater may be used on one web site owned by one owner or an entity.
#
# LICENSE TO REDISTRIBUTE
#-----------------------------------------------------------------------
# Distributing the software and/or documentation with other products
# (commercial or otherwise) or by other than electronic means without
# Webfresh prior written permission is forbidden.
# All rights to the Fresh News Updater software and documentation not 
# expressly granted under this Agreement are reserved to Webfresh.
#
# DISCLAIMER OR WARRANTY
#-----------------------------------------------------------------------
# THIS SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE PROVIDED "AS IS" AND
# WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR ANY OTHER
# WARRANTIES WHETHER EXPRESSED OR IMPLIED.   BECAUSE OF THE VARIOUS HARDWARE
# AND SOFTWARE ENVIRONMENTS INTO WHICH THE FRESH NEWS UPDATER MAY BE USED, 
# NO WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE IS OFFERED. THE USER MUST
# ASSUME THE ENTIRE RISK OF USING THIS PROGRAM. ANY LIABILITY OF WEBFRESH WILL BE
# LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
# IN NO CASE SHALL WEBFRESH BE LIABLE FOR ANY INCIDENTAL, SPECIAL OR
# CONSEQUENTIAL DAMAGES OR LOSS, INCLUDING, WITHOUT LIMITATION, LOST PROFITS
# OR THE INABILITY TO USE EQUIPMENT OR ACCESS DATA, WHETHER SUCH DAMAGES ARE
# BASED UPON A BREACH OF EXPRESS OR IMPLIED WARRANTIES, BREACH OF CONTRACT,
# NEGLIGENCE, STRICT TORT, OR ANY OTHER LEGAL THEORY. THIS IS TRUE EVEN IF
# WEBFRESH IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL
# WEBFRESH'S LIABILITY EXCEED THE AMOUNT OF THE LICENSE FEE ACTUALLY PAID
# BY LICENSEE TO WEBFRESH.
#
#################################################################################

#########################################################
# DEFINE THIS CONFIGURATION VARIABLE!

# Message listed when no news are stored.
# Any HTML allowed (note the backslash in front of quotation marks \")

$no_news = "<font face=\"arial, verdana\" size=\"2\"><b>There are currently no news to display.<P>Please check back soon for news in and around Marina Bay.</b></font>";

#########################################################
# NO EDITING REQUIRED BELOW

#########################################################
# PATH INFO

if ($0=~m#^(.*)(\\|/)#)	{ $dir = $1; }
else { $dir = `pwd`; chomp $dir; }

$script_url  = $ENV{'SCRIPT_NAME'};
$data_dir = "$dir/data";
$news_dat = "$data_dir/news.dat";
$news_info = "$data_dir/info.dat";

%in = &ReadForm;

#########################################################
# GET CONTENT

if($news) {

   	open(NEWS,"<$news_dat");
   	while(<NEWS>) {
            	($ID,$news_date,$news_head,$news_body) = split(/\|/,$_);
            	$push = "$ID\|$news_date\|$news_head\|$news_body\n";
            	push(@reprint,$_);
    	}
  	 close(NEWS);

}

#########################################################
# NEWS HEADLINE

&Template("$data_dir/news.temp");

open(INFO,"$news_info");
@info = <INFO>;
close(INFO);

$content_info = @info[0];
($news_name, $news_per_page) = split(/\|/,$content_info);

open(NEWS_DAT,"<$news_dat");
@news_dat_content = <NEWS_DAT>;
close(NEWS_DAT);

foreach$content(@news_dat_content) {
($ID,$news_date,$news_head,$news_body) = split(/\|/,$content);
$push = "$ID\|$news_date\|$news_head\|$news_body";
push(@news_dat,$push);
}

#########################################################
# NEWS BODY

if($news ne "") {

	foreach$news_content(sort { $b <=> $a } @news_dat) {
      	($ID,$news_date,$news_head,$news_body) = split(/\|/,$news_content);
	if($news == $ID) {
       	$display_body .= &Cell('news_body');
        	}   
     	}

}

#########################################################
# GENERATE NEWS HEADLINE

$show_max = $news_per_page;

if($news eq "") {

	for($news_content = $show; $news_content < scalar @news_dat;) {
      	($ID,$news_date,$news_head,$news_body) = split(/\|/,$news_dat[$news_content]);
	if($ID ne "") {
              	$display_headline .= &Cell('news_headline');
	}
      	$news_content++;
      	last if $news_content-$show == $show_max;
   	}

	if($news_content > $show_max || $news_content < @news_dat) {
	
	if($news_content > $show_max) {
  	$show_back = $show-$show_max;
  	$back_span = "<td align=\"left\"><font face=\"verdana,arial\" Size=2><b><a href=\"$script_url\?show=$show_back\">Back</a></b></font></td>";
	}

	if($news_content < @news_dat) {
	if($news_content-$show == $show_max) { 
  	$show_next = $show+$show_max;
  	$next_span = "<td align=\"right\"><font face=\"verdana,arial\" Size=2><b><a href=\"$script_url\?show=$show_next\">Next</a></b></font></td>";
 	}
	}

	$display_span .= &Cell("show_span");
	}

	if(!$display_headline) { $display_headline = "$no_news" };

}

print &Template("$data_dir/news.temp",'temp');

#########################################################
# TEMPLATE

sub Template {  

  	local(*FILE);

  	if    ($_[1] eq 'temp') { print "Content-type: text/html\n\n"  unless ($ContentType++ > 0); }
  	elsif ($_[1] eq 'text') { print "Content-type: text/plain\n\n" unless ($ContentType++ > 0); }

  	if    (!$_[0])	{ return "<br>\nTemplate : No file was specified<br>\n"; }
  	elsif (!-e "$_[0]")	{ return "<br>\nTemplate : File '$_[0]' does not exist<br>\n"; }
  	else {
    	open(FILE, "<$_[0]") || return "<br>\nTemplate : Could open $_[0]<br>\n";
    	while (<FILE>) { $FILE .= $_; }
    	close(FILE);
    	for ($FILE) {
      	s/<!-- ins : (.*?) -->/\1/gi;				# show hidden inserts
      	s/<!-- def : (\w+) -->(?:\r\n|\n)?(.*?)<!-- \/def : \1 -->/
	$CELL{$1}=$2;''/ges;					# read/remove template cells
      	s/\%(\w+)\%/${$1}/g;					# translate %%
      	}
    	}
  	return $FILE;

}

#########################################################
# TRANSLATE CELL

sub Cell {  

  	my($CELL);
  	for (0..$#_) { if ($_[$_]) { $CELL .= $CELL{$_[$_]}; }}

  	if    (!$_[0]) { return "<br>\nCell : No cell was specified<br>\n"; }
  	elsif (!$CELL) { return "<br>\nCell : Cell '$_[0]' is not defined<br>\n"; }
  	else		 { $CELL =~ s/\%(\w+)\%/${$1}/g; }		# translate %%
  
  	return $CELL;

}

#########################################################
# PARSE FORM

sub ReadForm {

  	my($max) = $_[1];					# Max Input Size
  	my($name,$value,$pair,@pairs,$buffer,%hash);		# localize variables

  	# Check input size if max input size is defined
  	if ($max && ($ENV{'CONTENT_LENGTH'}||length $ENV{'QUERY_STRING'}) > $max) {
    	die("ReadForm : Input exceeds max input limit of $max bytes\n");
    	}

  	# Read GET or POST form into $buffer
 	if    ($ENV{'REQUEST_METHOD'} eq 'POST') { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }
 	if    ($ENV{'QUERY_STRING'}) { $buffer .= $ENV{'QUERY_STRING'}; }

  	@pairs = split(/&/, $buffer);				# Split into name/value pairs
  	foreach $pair (@pairs) {		

   	($name, $value) = split(/=/, $pair);		# split into $name and $value
    	$value =~ tr/+/ /;					# replace "+" with " "
    	$value =~ s/%([A-F0-9]{2})/pack("C", hex($1))/egi;	# replace %hex with char
	$$name = $value;
    	}

  	return %hash;

  }
