#!/usr/bin/perl -w --

#
# written by gecon - finalized on 31/1/2011
# enjoy!
#
# 
#

use strict;


BEGIN {
package DissertsViewer;
use vars qw($VERSION);

$VERSION = '0.5';

use base 'CGI::Application';
use CGI::Application::Plugin::Forward;

use LWP::UserAgent;
use HTTP::Request;

#cap setup
 sub setup {
        my $c = shift;

        $c->start_mode('parse_request');
        $c->run_modes([qw/ parse_request show_pdf show_pdf_error show_access_restrict 			show_disclaimer show_pdf        /]);
}
  
sub cgiapp_postrun {
    my $c = shift;
    my $output_ref = shift;
    $c->header_add( -charset => 'utf-8' );
    return 1;
}
  
  #main logic
sub parse_request {
        my $c = shift;
        my $q = $c->query();

        my $fileid = $q->param('i');
        
        #proper call
        if (!defined($fileid) || $fileid eq '') {
        		return $c->forward('show_access_restrict');
        }
        
        #ip check (in uoa range)
				if (not $c->ip_check) { 
					return $c->forward('show_access_restrict');
        }
        
        #proper referer
        if (not $c->proper_referer) { 
					return $c->forward('show_access_restrict');
        }
        
        return $c->forward('show_disclaimer');
        	
  }
  
  #checks our request to see if we've got a proper referer
  sub proper_referer {
  	my $c = shift;
  	my $q = $c->query();
  	my $good_url_1 = 'http://efessos.lib.uoa.gr/applications/';
  	my $good_url_2 = 'http://hippo.lib.uoa.gr/';
		my $self_url = $q->url(-path_info=>1);
		
  	my $referer = $q->referer(); #$ENV{'HTTP_REFERER'};
  	print STDERR "Self: $self_url --- Referer: $referer" ."\n";
  	
  	return 0 unless defined($referer);
  	
  	#from self ...
  	if ($referer =~ /^\Q$self_url/i) {
  		return 1;
  	}
  	
  	#from efessos	...
  	if ($referer =~ /^\Q$good_url_1/i) {
  		return 1;
  	}
  	
  	#from hippo	...
  	if ($referer =~ /^\Q$good_url_2/i) {
  		return 1;
  	}
  	
  	
  	#bad boys ...
  	return 0;
  	
  }
  
  #shows access restriction
  sub show_access_restrict { 
  		my $c = shift;
  			
  				#my $t = $c->load_tmpl;
        	#$t->param($errs) if $errs;
        	#return $t->output;
       return "<div align='center' style='color:red;font-size:140%'>ERROR - No access</div>";		
  }
  
  #shows disclaimer before proceeding
  sub show_disclaimer {
       my $c = shift;
			 my $q = $c->query();
			 
			 if (defined $q->param('d') && $q->param('d')==1) { #aggreed
			 	$c->forward('show_pdf');
			 } else {
       	return '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" />' . 
       	"<title>ΕΚΠΑ ΥΚΒ | Πρόσβαση σε ψηφιακό υλικό</title></head><body><div align='center'><h2>Όροι χρήσης και πρόσβασης ψηφιακού υλικού που υπόκειται σε καθεστώς πνευματικής ιδιοκτησίας</h2></div><div><p>
Η πλήρης πρόσβαση στο ψηφιακό υλικό επιτρέπεται κατόπιν συναίνεσης των συγγραφέων και προσφέρεται αποκλειστικά για προσωπική, εκπαιδευτική ή ερευνητική χρήση. Απαγορεύεται η συστηματική αποθήκευση ή/και εκτύπωση του υλικού  καθώς και οποιαδήποτε εμπορική χρήση του. </p></div><div align='center'><a href='" .$q->self_url ."&d=1'>Αποδέχομαι</a></div></body>";
       }
       
  }
  
  #sends the final pdf to user
  sub show_pdf {
      my $c = shift;
      my $q = $c->query();
      
			my $file = "";
			
			my $url_prefix = 'http://efessos.lib.uoa.gr/Applications/disserts.nsf/0/';
			my $url_suffix = '/%24File/document.pdf';
			
			my $ua = new LWP::UserAgent;
			$ua->credentials('efessos.lib.uoa.gr:443','/Applications','greylitviewer' => 'm0n0bl1epow');

			$ua->agent('YKB - disserts pdf reader');
      $ua->timeout(15);
      my $request = HTTP::Request->new('GET');
      my $url = $url_prefix . $q->param('i') . $url_suffix;
			$request->url($url);
			my $response = $ua->request($request);
			print STDERR "got res: 		" .	$response->code ;
			print STDERR "for url: $url";
			
			if ($response->code == 200) {
					my $body =  $response->content;
				  $c->header_add(
 		        -type              =>      'application/pdf',
						 -Content_Length   =>      length($body), # bytes
					   -Content_disposition => 'inline',
					   -filename => 'dissertsFile.pdf',
					 );
					
					return $body;
			}
			else {
				$c->forward('show_pdf_error');
			}
	}

  sub show_pdf_error {
  	my $c = shift;
  	return "pdf error";
  }
  
  #checks ip range for uoa access
  sub ip_check {
  		my $c = shift;
  		return 1;
  }
  
  1;


} #BEGIN


  
  #use DissertsViewer;
  my $c = DissertsViewer->new();
  $c->run();
