#!/usr/bin/perl
#
# DCLinks 2000 Version 1.000
# dclinks.cgi
# Released Date: Jan 20 2000
#
# Revision History
# DCLinks 1998 Release on 16 November 1997
#
##########  YOU MUST KEEP THIS COPYRIGHTS NOTICE INTACT ###############
# Copyright  ©1997-2000 DCScripts All Rights Reserved
# As part of the installation process, you will be asked
# to accept the terms of this Agreement. This Agreement is
# a legal contract, which specifies the terms of the license
# and warranty limitation between you and DCScripts and DCLinks.
# You should carefully read the following terms and conditions before
# installing or using this software.  Unless you have a different license
# agreement obtained from DCScripts, installation or use of this software
# indicates your acceptance of the license and warranty limitation terms
# contained in this Agreement. If you do not agree to the terms of this
# Agreement, promptly delete and destroy all copies of the Software.
#
# Versions of the Software 
# --------------------------------------------------------------------------
# You may install as many copies of DCLinks Script for free
# on personal and non-profit sites.  Otherwise, a single license
# of DCLinks is $35 (USD).
# 
# License to Redistribute
# --------------------------------------------------------------------------
# Distributing the software and/or documentation with other products
# (commercial or otherwise) or by other than electronic means without
# DCScripts's prior written permission is forbidden.
#
# All rights to the DCLinks software and documentation not expressly
# granted under this Agreement are reserved to DCScripts.
#
# Disclaimer of 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 HKDBOARD 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 DCSCRIPTS WILL BE
# LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
# IN NO CASE SHALL DCSCRIPTS 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
# DCSCRIPTS IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL
# DCSCRIPT'S LIABILITY EXCEED THE AMOUNT OF THE LICENSE FEE ACTUALLY PAID
# BY LICENSEE TO DCSCRIPTS.
#
###########################################################################

# Define directory path to this script
# If relative path will work leave it as is

$cgidir = ".";

# ----------------- Shouldn't have to change anything below here --------------#
require "$cgidir/dclinks.setup";
require "$cgidir/cgi-lib.pl";
require "$cgidir/dclinkslib.pl";

# OK Let's read in formdata
ReadParse();

$r_in = \%in;

# Cookie name
$in{'cookie_name'} = "DCProtectSessionID";

# OK, before we do anything, let's check the user's session ID
# If it exists then read in user data
$r_in->{'userdata'} = get_session();

$j = -1;
foreach (@link_fields) {
	$j++;
   $field_id{$_} = $j;
}

# Create files if not found
check_datafile($datafile,[]);
check_datafile($counter,[]);


if ($in{'action'} eq 'set_sort_index') {
   set_sort_index($in{'field'});
	exit;
}
elsif ($in{'action'} eq 'redirect') {
   update_view( $in{"id"} );
	print "Location: $in{'URL'}\n\n";
	exit;
}

# Send HTTP header to the server
print_header();

# Format Comment input so that it will fit nicely in the database

$in{'Description'} = form_to_text($in{'Description'});

# Depending on Form input:
#	1) Display add to links form
#	2) Add Link information to the database
# 	3) Display Links

$header = $title;

$cat1 = $in{'category'};
$cat1 =~ s/\s/+/g;
$menu = qq~
<a href="http://www.americas-fr.com">Retour vers Americas</a> |
<a href="$dcscript">Annuaire Principal</a> |
<a href="$dcscript?action=add_form&Category=$cat1">Ajouter un site</a>
~;

if ($r_in->{'userdata'}->{'Group'} eq 'admin') {
$menu .= qq~
| <a href="$dcadmin">DCLinks Admin</a>
| <a href="$dcadmin?az=login">Logout</a>
~;
}

$r_data = readdata($datafile);

if ($in{'action'} eq "add_form") {

	print_header_end();
	$sub_header = "Compléter le formulaire ci-dessous pour inscrire le site.";
	add_form();

}
elsif ($in{'action'} eq "add_links") {

	if (incomplete_form()) {
		print_header_end();
		$sub_header = "ERROR!  Incomplete form.";
		add_form();
	}
	elsif (duplicate_url()) {
		print_header_end();
		$sub_header = "ERROR!  Duplicate URL.";
		add_form();
	}
	else {
		print_header_end();
		add_links();
		$sub_header = "Votre lien a été enregistré.";
		$html_output = qq~
		Merci pour cette inscription.  Le site a été ajoué à la base de données.<br>
		<a href="$dcscript">Aller à la page principale</a>~;
	}
}
elsif ($in{'action'} eq "view_category") {

	$sub_header = "Listes dans $in{'category'}";
	print_header_end();
	view_category();
}
elsif ($in{'action'} eq 'update_rating') {
	update_rating($in{"id"},$in{'score'});
}
elsif ($in{'action'} eq 'rate') {
	rating_form($in{"id"});
}
else {

	print_header_end();
	display_main();
}

display_output();
exit;

#======================================================================#
# function display_main
# displays the main categories
#======================================================================#

sub display_main {

	# Sort data according to category
	foreach (@{$r_data}) {
		my @data = split /\|/;
		$category_num{$data[$cat_id]}++;
	}

	$html_output = qq~
	<table border="0" width="$table_width" cellpadding="5" cellspacing="1">
	<tr class="heading">
	<td class="heading" colspan="2">Catégorie et description</td>
	</tr>
	~;

	toggle('reset');
   my $num_cat = @Category_list;
   for ($j=0;$j<$num_cat/2;$j++) {
		toggle();
      my $cat = $Category_list[2*$j];
		$cat1 = $cat;
		$cat =~ tr/ /+/;

		if ($category_num{"$cat1"} eq "" ) {
			$category_num{"$cat1"} = "0";
		}

      $html_output .= qq~
		<tr class="$style_class">
		<td class="$style_class"><b><a href="$dcscript?action=view_category&category=$cat">$cat1</a></b>
		($category_num{"$cat1"})
		<br>$Category_desc{$cat1}</td>
		~;

      $cat = $Category_list[2*$j+1];
		$cat1 = $cat;
		$cat =~ tr/ /+/;

		if ($category_num{"$cat1"} eq "" ) {
			$category_num{"$cat1"} = "0";
		}

      if ($Category_desc{$cat1}) {
	      $html_output .= qq~
			<td class="$style_class"><b><a href="$dcscript?action=view_category&category=$cat">$cat1</a></b>
			($category_num{"$cat1"})
			<br>$Category_desc{$cat1}</td>
			~;
      }
      else {
	      $html_output .= qq~
			<td class="$style_class">&nbsp;</td>
			~;
		}
		$html_output .= "</tr>";
	}

	$html_output .= "</table>";

}

#======================================================================#
# function view_category
# displays links in one categorie
#======================================================================#

sub view_category {

	$category = $in{"category"};	
	$category =~ tr/+/ /;
	
	my $r_links = [];

	# Ok, first pull off all the links in this category
	foreach $record (@{$r_data}) {
		chomp($record);
		my @row = split (/\|/,$record);
		if ($row[$cat_id] eq $category) {
			push(@{$r_links},$record);
		}
	}
		
   my $sort_by_field = get_cookie($sort_by_field_cookie);
	if ($sort_by_field > 0) {
	   $r_links = sort_topics($r_links,$sort_by_field);
	}
	
   my $num_links = @{$r_links};
   # stuff for next and previous pages
   my $num_next = int(($num_links - 1)/$max_links) + 1;
   my $start = $in{'mm'} + 1;
   my $stop = $in{'mm'} + $max_links;
	$stop = $num_links if ($stop > $num_links);
   # Construct links to additional topics
   $stop--;
   $start--;

   my @temp_out;
   for ($j=1;$j<=$num_next;$j++) {
      my $marker = ($j-1)*$max_links;
      my $j_start = ($j-1)*$max_links + 1;
      my $j_stop = $j*$max_links;
      $j_stop=$num_links if ($j_stop > $num_links);
      if ($marker == $start) {
         push(@temp_out,$j);
      }
      else {
			my $cat = $category;
			$cat =~ s/ /+/g;
         push(@temp_out, "<a href=\"$dcscript?action=view_category&category=$cat&mm=$marker\">$j</a>" );
      }
   }
	
	my $pages = join(" \| ",@temp_out);

	$html_output = qq~
	<center>
	<table border="0" width="$table_width" cellpadding="3" cellspacing="0">
	<tr>
	<td class="menu">Page $pages</td>
	</tr>
	</table>
	<table border="0" width="$table_width" cellpadding="4" cellspacing="1">
	<tr class="heading">
	<td class="heading" colspan="6">Liste rangée par $sorted_by{$sort_by_field}<br>
	Classement par : 
	<a href="$dcscript?action=set_sort_index&field=$name_index" 
	class="heading">Nom</a> |
	<a href="$dcscript?action=set_sort_index&field=$id_index" 
	class="heading">Date d'entrée</a> |
	<a href="$dcscript?action=set_sort_index&field=$date_index" 
	class="heading">Nouveaux&nbsp;Sites</a> |
	<a href="$dcscript?action=set_sort_index&field=$view_index" 
	class="heading">Visites</a> |
	<a href="$dcscript?action=set_sort_index&field=$vote_index" 
	class="heading">Votes</a> |
	<a href="$dcscript?action=set_sort_index&field=$rating_index" 
	class="heading">Note</a></td>
	</tr></table>
	~;

	foreach (@$r_links[$start..$stop]) {
		toggle();
		my @link = split /\|/;
		my ($ltime,$ldate) = split (/\s/,$link[$field_id{"Date"}]);
      $ltime = time_format($ltime);
      $ldate = date_format($ldate);

		my $score = rating( $link[$field_id{"Rating"}] );
		unless ($score eq "NA") {
			$score = sprintf("%.1f",$score);
		}
		
		my $votes = votes( $link[$field_id{"Rating"}] );

		$link[$field_id{"Homepage"}] =~ s/http:\/\///g;
		$html_output .= qq~
		<table border="0" width="$table_width" cellpadding="2" cellspacing="1">		
		<tr>
		<td class="datecol" rowspan="3">
		$link[$field_id{"ID"}]~;
		
		if ($r_in->{'userdata'}->{'Group'} eq 'admin') {
		$html_output .= qq~
		<a href="$dcadmin?action=remove_links&selected=$link[$field_id{"ID"}]&command=remove" class="admin">D</a><br>
		<a href="$dcadmin?action=edit_links&selected=$link[$field_id{"ID"}]&command=edit" class="admin">E</a><br>
		~;
		}

		$html_output .= qq~
		</td>
		<td class="dark" colspan="5" width="100%">
		<a href="$dcscript?action=redirect&id=$link[$field_id{"ID"}]&URL=http://$link[$field_id{"Homepage"}]" 
		target="_blank">$link[$field_id{"Name"}]</a><br>
		<font class="small">http://$link[$field_id{"Homepage"}]</font><br></td>
		</tr>
		<tr>
		<td class="lite" colspan="5" width="100%">
		<p>
		$link[$field_id{"Description"}]
		<p>
		</td>
		</tr>
		<tr>
		<td class="datecol">
		$ldate&nbsp;$ltime
		</td>
		<td class="datecol">
		$link[$field_id{"Views"}] Visites
		</td>
		<td class="datecol">
		$votes Votes
		</td>
		<td class="datecol"">
		Note : $score 
		</td>
		<td class="ratecol">
		<a href="$dcscript?action=rate&id=$link[$field_id{"ID"}]" class="rate">Noter&nbsp;ce&nbsp;site</a>
		</td>
		</tr>
		<tr>
		<td class="lite" colspan="4">&nbsp;
		</td>
		</tr>
	</table>
		~;
	}

	$html_output .= qq~
	<table border="0" width="$table_width" cellpadding="3" cellspacing="0">
	<tr>
	<td class="menu">Page $pages</td>
	</tr>
	</table>
	</center>
	~;
	
}

#======================================================================#
# addd_links                                                           #
#======================================================================#

sub add_links {

	my $r_data = readdata($datafile);

	my $id = get_number();
	my ($ltime,$ldate) = get_date();
	$ldate = $ltime. " " . $ldate;

	$in{'ID'} = $id;
	$in{'Date'} = $ldate;
	$in{'Views'} = 0;

	foreach $field (@link_fields){
		$in{$field} =~ s/\|/\s/g;
		push(@fields,$in{$field});
	}

	my $newline = join("\|",@fields);
	$newline .= "\n";

	unshift(@{$r_data},$newline);

	writedata("$datafile",$r_data);	
}

#======================================================================#
# duplicate_url                                                        #
#======================================================================#

sub duplicate_url {
	foreach (@{$r_data}) {
		if ($_ =~ /$in{'Homepage'}/) {
			return 1;
		}
	}
	return 0;
}

#======================================================================#
# incomplete_form                                                      #
#======================================================================#

sub incomplete_form {

	print "\n";

	foreach $field (@link_fields) {
		if ($in{$field} eq "" || $in{$field} eq " ") {
			unless ($field eq "ID" or 
				$field eq "Views" or 
				$field eq "Rating" or 
				$field eq "Date") {

				push(@ERROR,$field);
				return 1;

			}
		}
	}
	return 0;
}

#======================================================================#
# add_form                                                           #
#======================================================================#

sub add_form {	
	$html_output = qq~
	<form method="post">
	<input type="hidden" name="action" value="add_links">
	<table border="0" width="$table_width" cellpadding="5" cellspacing="1">
	<tr class="heading">
	<td class="heading" colspan="2">Ajouter le lien</td>
	</tr>~;
	foreach (@link_fields) {
		$html_output .= table_row($_,$field_input_type{$_});
	}

	$html_output .= qq~
	<tr>
	<td class="lite" colspan="2"><input type="submit" value="Ajouter le lien">
	<input type="reset"></td>
	</tr>
	</table>
	</form>
	~;
}

#======================================================================#
# get_number                                                           #
# get next counter number for a new link                               #
#======================================================================#

sub get_number {
	my $num;
	open(F,"$counter") or my_die ("Can't read from $counter",$!);
	flock(F,2);
   $num = <F>;
	flock(F,8);
	close(F);
	if ($num eq "" or $num < 1) {
		$num = 1;
	} else {
		$num++;
	}
	open(F,">$counter") or my_die ("Can't write to $counter",$!);
	flock(F,2);
   		print F $num;
	flock(F,8);
	close(F);
	$num;
}


1;