package PhotoPub::CGIBase;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&init $query &printheader);

use PhotoPub::Global qw($error &register_init &finit);
use PhotoPub::ParallelLimit qw(&enter &leave LIM_CGI);
use PhotoPub::Utils qw(%errorstrings &getparallellimit);
use PhotoPub::Ages qw(&initage &getage);

use strict;
use vars qw($query);
use CGI qw(-debug);
use HTML::Entities;
use Carp;


sub cgierror {
  my ($type,$message);
  if (scalar @_==1) {
    &carp("Old parameter format sent to error handler");
    ($message)=@_;
    $type='unknown';
  } else {
    my %options=@_;
    $message=$options{'message'};
    $type=$options{'type'} || 'unknown';
  }
  return if $type eq 'warning';
  if(!defined $query) {
    $query=new CGI;
    if(!defined $query) {
      &finit();
      &croak("Couldn't make CGI query while handling error ".
	     "type $type message $message");
    }
  }
  print $query->header('text/html');
  my $errorstring=$errorstrings{$type} || 'unknown';
  $type eq 'unknown' and &carp("Didn't specify error type");
  print $query->start_html($errorstring);
  print $query->h1($errorstring);
  $message=&encode_entities($message);
  $message=~s/\n/\<br\>/gs;
  print $message;
  print $query->end_html;
  &finit();
  exit;
}

sub printheader {
  print $query->header(-"Last-Modified" => 
		       CGI::expires(getage()-time(),'http'),@_);
}

BEGIN {
  $error=\&cgierror;
}

&register_init('startup',sub {
		$query=new CGI;
		&enter(LIM_CGI,&getparallellimit('cgi'));
	      });

&register_init('config',sub {
		 &initage();
	       });

&register_init('shutdown',sub {
		 &leave(LIM_CGI);
	       });

1;
