Space separators in tags are optional.
[gruta.git] / Gruta / CGI.pm
blob08878e7a06651dc20091c1b32c6c9a92e6a7152a
1 package Gruta::CGI;
3 use CGI;
4 use Carp;
6 sub vars { return $_[0]->{cgi}->Vars(); }
7 sub upload_dirs { return @{ $_[0]->{upload_dirs} }; }
9 sub http_headers {
10 my $self = shift;
11 my %headers = @_;
13 foreach my $k (keys(%headers)) {
14 $self->{http_headers}->{$k} = $headers{$k};
17 return $self->{http_headers};
20 sub cookie {
21 my $self = shift;
23 if (@_) {
24 $self->http_headers( 'Set-Cookie', shift );
27 return $ENV{HTTP_COOKIE};
30 sub redirect { $_[0]->http_headers( 'Location', $_[1] ); }
32 sub data {
33 my $self = shift;
34 my $data = shift;
36 if (defined($data)) {
37 $self->{data} = $data;
40 return $self->{data};
44 sub upload {
45 my $self = shift;
46 my $dir = shift;
47 my $field = shift;
49 my $file = $self->{cgi}->param($field);
50 my ($basename) = ($file =~ /([^\/\\]+)$/);
52 if (! grep(/^$dir$/, $self->upload_dirs())) {
53 croak "Unauthorized upload directory $dir";
56 my $filename = $dir . '/' . $basename;
58 open F, '>' . $filename or croak "Can't write $filename";
59 while(<$file>) {
60 print F $_;
63 close F;
67 sub new {
68 my $class = shift;
70 my $obj = bless( { @_ }, $class );
72 $obj->{http_headers} = {
73 'Content-Type' => 'text/html; charset=ISO-8859-1',
74 'X-Powered-By' => 'Gruta',
75 'X-Gateway-Interface' => $ENV{'GATEWAY_INTERFACE'},
76 'X-Server-Name' => $ENV{'SERVER_NAME'}
79 $obj->{upload_dirs} ||= [];
81 $obj->{cgi} = CGI->new();
83 return $obj;
87 sub run {
88 my $self = shift;
90 my $data = $self->data();
91 my $vars = $self->vars();
93 $data->template->cgi_vars($vars);
95 if ($ENV{REMOTE_USER} and my $u = $data->user($ENV{REMOTE_USER})) {
96 $data->auth( $u );
98 elsif (my $cookie = $self->cookie()) {
99 if (my ($sid) = ($cookie =~ /^sid\s*=\s*(\d+)$/)) {
100 $data->auth_from_sid( $sid );
104 my $st = 'INDEX';
106 if ($vars->{t}) {
107 $st = uc($vars->{t});
110 $st = 'INDEX' unless $st =~ /^[-\w0-9_]+$/;
112 my $body = undef;
114 eval { $body = $data->template->process( $st ) };
116 if ($@) {
117 $data->log($@);
118 # $self->redirect('?t=INDEX');
119 $body = "<pre>$@</pre>";
122 $body = $data->special_uris($body);
124 my $h = $self->http_headers();
125 foreach my $k (keys(%{ $h })) {
126 print $k, ': ', $h->{$k}, "\n";
128 print "\n";
130 print $body;