#! /usr/bin/perl
use strict;
use warnings;
use CGI;
use DBI;
use Apache::Session::Postgres;
use Encode;
use HTML::Entities;
use locale;
use utf8;

require 'config.pm';

package itkaclcommon;

our $cgi;
our $dbh;
our $last_modified = '$Date: 2011-11-19 11:08:01 $';
our %session;

sub init {
	$cgi = new CGI;
	$dbh = DBI->connect("dbi:Pg:dbname=$itkaclconfig::db_name;host=$itkaclconfig::db_host",
		$itkaclconfig::db_user, $itkaclconfig::db_pass)
		or die "Couldn't connect to database";
	$dbh->{pg_enable_utf8} = 1;
	$last_modified = '$Date: 2011-11-19 11:08:01 $';
	%session = ();
}

sub print_header {
	init();

	# Find the cookie, if any
	my $session_id = $cgi->cookie('itkaclsession');
	tie %session, 'Apache::Session::Postgres', $session_id, {
		DataSource => "dbi:Pg:dbname=$itkaclconfig::sessiondb_name;host=$itkaclconfig::sessiondb_host",
		UserName   => $itkaclconfig::sessiondb_user,
		Password   => $itkaclconfig::sessiondb_pass,
		Commit     => 1
	};

	# Update with open/close
	my $open = $cgi->param('open');
	my $close = $cgi->param('close');
	if (defined($open)) {
		$session{$open} = 1;
	} elsif (defined($close)) {
		undef $session{$close};
	}

	my $cookie = $cgi->cookie(-name=>'itkaclsession',
			-value=>$session{_session_id},
			-expires=>'+1h');

	binmode STDOUT, ":utf8";
	print $cgi->header(-type=>'application/xhtml+xml; charset=utf-8', cookie=>$cookie, -expires=>'now');
	
	open HEADER, "<", $itkaclconfig::header
		or die "Couldn't open $itkaclconfig::header: $!";

	# Find out if we're using SSO.
	my $sso = "";
	if (defined($ENV{'AUTH_TYPE'}) && $ENV{'AUTH_TYPE'} eq 'Negotiate') {
		$sso = '<img src="https://itk.samfundet.no/images/ssso-button.png" alt="Samfundet single sign-on" title="Samfundet single sign-on"/>';
	}

	# Set secure path.
	local @ENV;
	delete @ENV{qw(IFS CDPATH ENV BASH_ENV PATH)};

	my $quote;
	if (defined($itkaclconfig::quotescript)) {
		# Hent inn quotes. Stygt, jodal! =)
		$quote = `$itkaclconfig::quotescript`;
		$quote = Encode::decode_utf8($quote);
	}

	while (<HEADER>) {
		s/\%QUOTES\%/$quote/ if defined($quote);
		s/\%SSO\%/$sso/;
		s/\%META\%//;
		s/\%TITLE\%/ITKACL-tre/;
		s/"http:\/\/([^"]*\.(css|png))"/"https:\/\/$1"/;
		print;
	}

	close HEADER;
}

sub print_footer {
	untie %session;
	
	# Print footer
	open FOOTER, "<", $itkaclconfig::footer
		or die "Couldn't open $itkaclconfig::footer: $!";

	# Strip RCS stuff from $::last_modified
	(my $lm = $last_modified) =~ s/^\$[D]ate: (.*) \$$/$1/;

	while (<FOOTER>) {
		s/\%LAST_MODIFIED\%/$lm/;
		print;
	}

	close FOOTER;
}

sub print_tree {
	my ($fulltree, $boldelem) = @_;
	if ($fulltree) {
		print "    <div class=\"tree\">\n";
	} else {
		print "    <div class=\"tree floatingtree\">\n";
	}
	
	print "      <p><img src=\"/img/base-folder.png\" alt=\"\" width=\"21\" height=\"18\" />Samfundet</p>\n";

	print_tree_element($dbh, undef, 0, [], $fulltree, $boldelem);

	print "    </div>\n";
}

sub print_tree_element {
	my ($dbh, $curr_obj, $level, $vbars, $fulltree, $boldelem) = @_;
	
	my $refs;
	if (defined($curr_obj)) {
		$refs = $dbh->selectall_arrayref('SELECT id,name,description FROM objects WHERE parent=? ORDER BY name', undef, $curr_obj);
	} else {
		$refs = $dbh->selectall_arrayref('SELECT id,name,description FROM objects WHERE parent IS NULL ORDER BY name');
	}

	my $i = 0;
	my $count = (scalar @{$refs}) - 1;
	for my $ref (@{$refs}) {
		# More siblings?
		my $msb;
		my @vbarscopy = @{$vbars};
		if ($i == $count) {
			$msb = "";
			push @vbarscopy, 0;
		} else {
			$msb = "-moresiblings";
			push @vbarscopy, 1;
		}

		print "    <p>";

		# Stuff to the left of folder
		for my $i (1..$level) {
			if ($vbars->[$i - 1]) {
				print '<img src="/img/verticalbar.png" alt="|" width="18" height="18" />';
			} else {
				print '<img src="/img/whitespace.png" alt="&nbsp;" width="18" height="18" />';
			}
		}

		# The folder itself
		my $countref = $dbh->selectrow_hashref('SELECT COUNT(*) AS num FROM objects WHERE parent=?', undef, $ref->[0]);
		if ($countref->{'num'} == 0) {
			if ($i == $count) {
				print "<img src=\"/img/folder-nochildren.png\" alt=\"\" width=\"39\" height=\"18\" />";
			} else {
				print "<img src=\"/img/folder-nochildren-moresiblings.png\" alt=\"|\" width=\"39\" height=\"18\" />";
			}
		} else {
			my $url = $cgi->url(-absolute=>1) . "?";
			my @params = ();
			for my $p ($cgi->param()) {
				next if ($p eq 'open');
				next if ($p eq 'close');
				push @params, "$p=" . $cgi->param($p);
			}
			if (scalar @params > 0) {
				$url .= join('&amp;', @params) . "&amp;";
			}
							 
			if (defined($session{$ref->[0]})) {
				print "<a href=\"${url}close=$ref->[0]\"><img src=\"/img/folder-open$msb.png\" alt=\"-\" width=\"39\" height=\"18\" /></a>";
			} else {
				print "<a href=\"${url}open=$ref->[0]\"><img src=\"/img/folder-closed$msb.png\" alt=\"+\" width=\"39\" height=\"18\" /></a>";
			}
		}

		if (defined($boldelem) && $boldelem == $ref->[0]) {
			print "<strong>";
		}
	
		my $e_entity = HTML::Entities::encode_entities($ref->[1]);
		my $e_description = HTML::Entities::encode_entities($ref->[2]);
	
		if ($fulltree) {
			print "<a href=\"/view.pl?entry=$ref->[0]\">$e_entity: $e_description</a>";
		} else {
			print "<a href=\"/view.pl?entry=$ref->[0]\" title=\"$e_description\">$e_entity</a>";
		}
		
		if (defined($boldelem) && $boldelem == $ref->[0]) {
			print "</strong>";
		}
		print "</p>\n";
		
		if ($countref->{'num'} > 0 && defined($session{$ref->[0]})) {
			print_tree_element($dbh, $ref->[0], $level + 1, \@vbarscopy, $fulltree, $boldelem);
		}
		++$i;
	}
}

1;
