#!/usr/bin/perl
# ==================================================================
# Links SQL - enhanced directory management system
#   Plugins::Detailed_Page
#   Author  : PUGDOGŪ Enterprises, Inc.
#   Version : 2.0.5
#   Updated : June 20 2001
#   parts copyright Gossamer-Threads
# ==================================================================
# minor header update for Links 2.04
#

use strict;
use lib '/home/sites/home/web/perl/admin';
use Links qw/:objects :payment/; # I need these vars 
Links::init ('/home/sites/home/web/perl/admin'); # Required 
Links::init_user ('/home/sites/home/web/perl/admin'); # Optional 
use Apache2::Const ':common';
use Links::Build;
#use Encode qw(encode_utf8);
use Links::SiteHTML;
use utf8;
#use encoding 'utf8';


#use vars qw/$LINKDB $CATDB $DETAILED_CFG/;
use Links::Plugins;

#Links::reset_env( { load_user => 1 } ) if ($Links::PERSIST);
local $SIG{__DIE__} = \&Links::fatal;

main();

sub main {
# --------------------------------------------------------------
# Wrap in a subroutine to prevent possible mod_perl probs.
# 
# Create our database objects.
#	$LINKDB  ||= $DB->table('Links');
#	$CATDB   ||= $DB->table('Category');  
 
	if ($IN->param('ID')) {
			&generate_detailed_page ()
		} else { 
			&generate_detailed_page()
	}
}
 
sub generate_detailed_page {
# --------------------------------------------------------
# This routine build a single page for every link.
#
 my ($page, $id, $link);
 my $db   = $DB->table('Links');
 my $linkdb = $DB->table('Links');
 my $idtest = $IN->param('ID');	
 my $query = $IN->param('query');
 $query =~ s/(-|\||\/|<|>)/ /;
 $query = GT::CGI::html_escape($query);
# If we are choosing a random link, then get the total and go to one at random.
 if (lc $idtest eq "random") {
        require GT::SQL::Condition; 
        my $condition = GT::SQL::Condition->new('Priority', '<=', '3','isValidated','=','No');        
        $condition->bool ('OR'); 
        my $total  = $db->total() - $db->count($condition);
        my $offset = int rand $total;
        $linkdb->select_options ("LIMIT $offset, 1");
        my $condition1 = GT::SQL::Condition->new('Priority', '>', '3',VIEWABLE); 
        my $sth = $linkdb->select ($condition1,['ID']);
        $id = $sth->fetchrow_array;
 }
 else {
        my $sth2 = $db->select ( {ID => $idtest}, VIEWABLE, ['ID'] );
        $id = $sth2->fetchrow_array; 
 }
 if (! $id) {
       my $link = $db->get ($idtest, 'HASH');
       if (!$link){
        if ($query){
          my $altlink = $DB->table('Links')->select({Title=>"$query"})->fetchrow_hashref; 
          if ($altlink->{URL}){
            print $IN->header();
            print Links::SiteHTML::display ('detailed',$altlink);
            return;
          }
        } 
                print "Status: 404" . $GT::CGI::EOL;
		print $IN->header();
		print Links::SiteHTML::display ('error', { error => Links::language('PAGE_INVALIDDETAIL', $idtest) });
		return OK;
        
       } else {
                print $IN->header();
                print Links::SiteHTML::display ('detailed', $link);
                return;
       }
       return;
 } else {
	$link = $linkdb->get ($id, 'HASH');
	if (!$link) {
       		print "Status: 404" . $GT::CGI::EOL;
		print $IN->header();
		print Links::SiteHTML::display ('error', { error => Links::language('PAGE_INVALIDDETAIL', $idtest) } );
		return OK;
	} 
        unless ($IN->param('mylists')){
	        my $DETAILED_CFG  = Links::Plugins::get_plugin_user_cfg ('Detailed_Page');
	        my $column_name = $DETAILED_CFG->{'column_name'};
#		$linkdb->update (
#        	{ "$column_name" => \"$column_name + 1" },  ## set
#		{ ID => $id },				## where
#		{ GT_SQL_SKIP_INDEX => 1 }		## cut overhead
#		);
	}

	## need to do some housekeeping, and set up some variables:

	my ($cat_id, $cat_name) = %{$linkdb->get_categories ($link->{'ID'})};		##	Returns the category name & ID from link ID
	$link->{'title_linked'}	= Links::Build::build ('title_linked', "$cat_name/$link->{Title}");
        $link->{'title_loop'}   = Links::Build::build('title', "$cat_name/$link->{Title}"),

	## Fix up the HTML references
	my ($begin, $url, $output);		## setting up for a very, very complicated regex, taken from Links.pm clean_output
	$link->{'title_linked'} =~ s!(<a[^>]+href\s*=\s*["']*)$CFG->{build_root_url}/?([^"'>]*)!   
        ($begin, $url) = ($1, $2);
        $output = "$1$CFG->{db_cgi_url}/page.cgi?g=" . $IN->escape($2);
	$output;
	!eisog;

	print $IN->header();
	if ($IN->param('Pts') eq '2'){
        	print Links::SiteHTML::display ('detailed_specials', $link);
                return;
	} elsif ($IN->param('Pts') eq '3'){
        	print Links::SiteHTML::display ('detailed', $link);
		return;
	} else {
		print Links::SiteHTML::display ('detailed', $link);
		return;
	}
 }
}


## my $widget = "<select name=foo>" . &calc_date($day1, $day2) . "</select>"; 
sub calc_date {
	my ($time1, $time2) = @_;
	my @dates;
	while ($time2 > $time1) {
		push (@dates, GT::Date::date_get ($time2));
		$time2 = $time2 - 86400;
	}
	push (@dates, GT::Date::date_get ($time1));
	return join "<option>$_", reverse @dates;
}

1;
