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

#  This file is part of Open Admin for Schools.


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;
use File::Find;
use Cwd;

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 $currdir = getcwd();

my (@dirs, %options);
$options{wanted} = \&processFiles;

my $checkfile; # file to check for.

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};

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



if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    uploadPics();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    doProcessing();
    
} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    confirmDelete();
    
} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    deletePictures();
}


#-----------------
sub deletePictures {
#-----------------

    my $path = qq{$currdir/../../admin};
    
    # Remove the files from admin big pic and thumbnail
    my $res = system("rm -fr $path/pic-big/*");
    if ($res) {
	print qq{<div>$lex{Error} removing Large Pictures $!</div>\n};
    }
    
    my $res = system("rm -fr $path/pic-sm/*");
    if ($res) {
	print qq{<div>$lex{Error} removing Small Thumbnail Pictures $!</div>\n};
    }

    print qq{<h3>Picture Files Removed</h3>\n};


    # remove any pic field values in the student records.
    my $sth = $dbh->prepare("update student set pic = NULL");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}

    print qq{<h3>Picture Field in student table cleared</h3>\n};

    # Starting Page
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="submit" value="Back to Starting Page">\n};
    print qq{</form>\n};

    exit;
}


#----------------
sub confirmDelete {
#----------------

    print qq{<h3>This will remove all student/staff pictures! Are you sure?</h3>\n};
    
    print qq{<form action="$self" method="post" style="margin:2em 1em;">\n};
    print qq{<input type="submit" value="Yes, remove all pictures">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<input type="hidden" name="confirm" value="1"></form>\n};

    exit;
}
    

#----------------
sub showStartPage {
#----------------
    
    print qq{<form action="$self" method="post" enctype="multipart/form-data" style="margin:2em 1em;">\n};
    print qq{<input type="submit" value="Upload Pictures (jpg,zip)">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="file" name="filename"></form>\n};

    print qq{<hr style="width:50ch;margin-left:0;">\n};

    
    print qq{<div style="margin:1em;background-color:red;width:35ch;border:1px solid black;">\n};
    print qq{<form action="$self" method="post" style="margin:1em;padding:0.5em;">\n};
    print qq{<input type="submit" value="Remove Previous Year Pictures">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{</form></div>\n};
    
    exit;
    
}


#--------------
sub uploadPics {
#--------------

    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);
    }

    # Uncompress 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">\n};
    print qq{<input type="hidden" name="filename" value="$filename">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="submit" value="$lex{Continue}">\n};
    print qq{</form></p></body></html>\n};

    exit;
} # end of uploadPics

    
#---------------
sub processFiles {  # convert and put into working.
#---------------

    my $file = $_;
    my $path = $File::Find::dir;

    # skip any non jpg files
    if ( $file !~ m/\.jpg/i ) { 
	# print qq{<div>No Match:$file</div>\n};
	return;
    }

    my $originalfile = $file;
    
    # Strip trailing .jpg extension
    $file =~ s/\.jpg$//;
    my $name = $file; # to avoid confusion.
    
    # Rename file if it has any single quotes 
    if ( $name =~ m/\'/ ) {

	$name =~ s/\'//; # remove the quote or dot
	$file = $name . q{.jpg}; # put the extension back on
	
	my $fullnew = qq{$currdir/$path/$file};
	my $fullorig = qq{$currdir/$path/$originalfile};
	rename( $fullorig, $fullnew);
	if ( $! ) {
	    print qq{<div>Rename Error: $! - \n};
	    print qq{NAME:$name NEW:$fullnew ORIG:$fullorig</div>\n};
	    exit;
	}
    } else { # just put the ending back on
	$file = $name . q{.jpg};
    }

    
    my $fullpath = qq{$currdir/$path/$file};

    # Copy file into working
    my $res = system("cp $fullpath $currdir/working");
    if ($res){
	print qq{<div>Error:$!</div>\n};
	exit;
    }
    print qq{<div>$file Imported</div>\n};

    return;

};


#------------
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");

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

    # All files/folders now put into tempdir.

    
    find(\%options, $tempdir);  # get all the files and put into working (with process files)

    # All jpg files should now be in working directory
    
    
    # Remove temporary directory
    my $res = system("rm -fr $tempdir/*");
    if ($res) {
	print qq{$lex{Error} removing $tempdir<br>\n};
    }
    
    rmdir $tempdir;
    unlink $filename;  # uploaded file removed

    return;

}


#--------
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;

    print qq{<h3>Pictures resized and added to Picture Directories</h3>\n};
    
    foreach my $file ( sort @files){ # Do files one after another.

#	print qq{$file<br>};

	
	# Process image
	my $res = system("$convertprog ./working/$file -resize x$imageheight ./working/$tempimage");
	if ($res){ print qq{$lex{Error}: Convert Image: $!<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{Error in Thumbnail Move: $!<br>\n};}

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

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

    }

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

    exit;

}
