#!/usr/bin/perl
#  Copyright 2001-2022 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

my %lex = ('Main' => 'Main',
	   'Export' => 'Export',
	   'Error' => 'Error',
	   'Add Student Pictures' => 'Add Student Pictures',
	   'File Processing' => 'File Processing',
	   'Cannot open file' => 'Cannot open file',
	   'Resizing and Adding to picture folders Complete' =>
	     'Resizing and Adding to picture folders Complete',
	   'Maximum File Upload size exceeded!' => 'Maximum File Upload size exceeded!',
	   'Uploaded' => 'Uploaded',
	   'Library type not recognized' => 'Library type not recognized',
	   'Continue' => 'Continue',
	   'No Files Found' => 'No Files Found',
	   'Files Found' => 'Files Found',
	   'Move' => 'Move',
	   'Not Found' => 'Not Found',

	   );


use CGI;
use DBI;

my $self = 'imageadd.pl';

eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

eval require "../../etc/image.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

my $q = new CGI;
my %arr= $q->Vars;
print $q->header( -charset, $charset );

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);


my $title = $lex{'Add Student Pictures'};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" type="text/css" href="$css">\n};
print qq{$chartype\n</head><body>\n};

print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$exppage">$lex{Export}</a> ]\n};

# Processing Loop
if ( $arr{uploadflag} ){  # Now process the images
    delete $arr{uploadflag};
    doProcessing();
}

print qq{<h1>$title</h1>\n};

my $file = $q->param("filename"); 
my $name; my $ext; 

if ( $file ) {
    $filename = $file;  # filename is output filename, file is input.
    $filename =~ s!^.*(\\|\/)!!;
    $filename =~ s/\s*//g; # strip any spaces.
    $filename = lc($filename);
    @name = split(/\./, $filename); # split on dots.
    $ext = $name[$#name];  # last element is the extension.

    unless ( $ext eq 'jpg' or $ext eq 'zip' or $ext eq 'tgz' ) {
	print qq{<h3>The file must be a jpg, zip, or tgz file!</h3>};
	print qq{</body></html>\n};
	exit;
    }

    pop(@name); # pull off extension.
    foreach $n (@name){ $name .= "$n.";} # assemble name 
    chop; # remove trailing dot
    
    # print qq{Name: $name Extension: $ext<br>\n};

    open (OUTFILE, ">$filename") || 
	die $lex{'Cannot open file'}. " $filename\n"; 
    my $bufcount = 0;
    while (my $bytesread = read($file, my $buffer, 1024)) { 
        print OUTFILE $buffer;
        $bufcount++;
        if ($bufcount > $maxbufcount){
           print qq{<h1>$lex{'Maximum File Upload size exceeded!'}\n};
	   print qq{($maxbufcount K)</h1>\n};
	   print qq{</body></html>\n};
	   exit;
        }
    } 

    close (OUTFILE);
}

# Process Library Files
if ( $ext eq 'zip' or $ext eq 'tgz' ) {
    doLibrary($ext, $filename); # put any jpg's in compressed library into working dir.

} elsif ($ext eq 'jpg') {  # move single jpg into working.
    system("mv $filename ./working");

} else {
    print qq{$lex{Error} $lex{'Cannot open file'}: $ext\n};
    print qq{</body></html>\n};
    exit;
}


print qq{<p style="font-size: 150%;">$filename $lex{Uploaded}</p><p>\n};

print qq{<form action="$self" method="post">
<input type="hidden" name="filename" value="$filename">
<input type="hidden" name="uploadflag" value="1">
<input type="submit" value="$lex{Continue}">\n};
print qq{</form></p></body></html>\n};



#------------
sub doLibrary { # uncompress lib and place any .jpg files into working folder.
#------------

    my ($extension,  $filename ) = @_;
    # Create a folder to do the zip in.
    my $tempdir = "templib$$";
    mkdir $tempdir;

    if ( $extension eq 'zip' ){
	system("unzip $filename -d $tempdir >/dev/null");

    } elsif ($extension eq 'tgz'){
	system("tar xvz -C  $tempdir -f $filename >/dev/null");

    # } elsif ($extension eq 'bz2'){
    # system("bunzip2 xvj -C  $tempdir -f $filename ");

    } else {
	print qq{<b>$lex{Error}: $lex{'Library type not recognized'}</b>\n};
	print qq{</body></html>\n};
	exit;
    }

    # Count the number of .jpg files...
    my $filecount;
    opendir(DH,"$tempdir") or die "Cannot open dir $tempdir!: $!";
    my @files = readdir(DH);

    foreach my $fn ( @files ) {
        if ($fn eq '.' or $fn eq '..'){ next;}
	my $newname = $fn;
	$newname =~ s/\s//g; # strip space.
        $newname = lc($newname); # rename them to lowercase.
        rename("$tempdir/$fn","$tempdir/$newname") or 
	    warn "Could not rename files because $!<br>\n";
	if ($newname =~ m/\.jpg/){ $filecount++;}
    }

    closedir(DH);
    print qq{<h3>$filecount jpg $lex{'Files Found'}.<h3>\n};
    if ( not $filecount ) {
	print qq{<p>$lex{'No Files Found'}</p>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $res = system("cp $tempdir/*.jpg ./working");
    if ( $res ) {
	print qq{$lex{Error}: $!<br>\n};
	exit;
    }  

    print qq{Done the copy<br>\n};

    system("rm -f $tempdir/*");
    rmdir $tempdir;
    unlink $filename;

}


#--------
sub doTgz {  # uncompress tgz and replace jpg's into working dir.
#--------
    # Create a folder to do the zip in.
    my $tempdir = "temptgz$$";
    mkdir $tempdir;


    # Count the number of .jpg files...
    my $filecount;
    opendir(DH,"$tempdir") or die "Cannot open dir $tempdir!: $!";
    while ( defined ($filename = readdir(DH))){
	if ($filename =~ m/\.jpg/){ $filecount++;}
    }
    closedir(DH);
    print qq{$filecount jpg files found.<br>\n};

    system("cp $tempdir/*.jpg ./working");
    system("rm -f $tempdir/*");
    rmdir $tempdir;
    unlink $filename;

}

#---------------
sub doProcessing {  # Process any images in the working directory
#---------------

    my $tempimage = "temp$$.jpg";

    print qq{<h1>$lex{'File Processing'}</h1>\n};

    if ( not -e $convertprog ) {
	print qq{<h3>$convertprog $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    # Read Files in working folder (skip dot files)
    opendir (DH,"working") || die $lex{'Cannot open file'}. " $!\n";
    my @files = grep !/^\./, readdir DH;
    close DH;

    foreach my $file (@files){ # Do files one after another.

	print qq{$file<br>};

	# Process image
	$res = system("$convertprog ./working/$file -resize x$imageheight ./working/$tempimage");
	if ($res){ print qq{$lex{Error}: Convert Image: $res<br>\n};}

	$res = system("mv ./working/$tempimage  $picdir/$file");
	if ($res){ print qq{$lex{Error}: $lex{Move} $res<br>\n};}

	# Now process thumbnail
	system("$convertprog ./working/$file -resize x$thumbheight ./working/$tempimage");
	$res = system("mv ./working/$tempimage  $tndir/$file");
	if ($res){ print qq{Move: $res<br>\n};}

	
	print qq{<div style="float:left; margin:2px; border:1px solid gray; padding:3px;">\n};
	print qq{<img src="$tndirurl/$file"><br>$file</div>\n};

	unlink("./working/$file");

    }

    print qq{<br clear="left"><b>$lex{'Resizing and Adding to picture folders Complete'}\n};;
    print qq{</p></body></html>\n};

    exit;

}
