# Copyright (C) 2006 Affelio Inc.
#
# This program 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

package Diary;
{
    use strict;
    use Affelio::misc::Debug qw( debug_print);

    ######################################################################
    #run_upload
    ######################################################################
    sub run_upload{
	my $self = shift;
	my $afap = $self->{afap};
	my $cgi = $self->{cgi};
	my $wi = $self->{wi};
	
	debug_print("Diary::UploadImage: start");

	###########################
	#Check DF_access
	###########################
	unless ($afap->check_access("DF_access")) {
	    $self->accessErrorExit('Access Denied. You don\'t have permission to this application.');
	}   
	unless ($afap->check_access("write_diary")) {
	    $self->accessErrorExit('Access Denied. You don\'t have permission to this application.');
	}


	##############################################################
	#Model invocation
	##############################################################
	my %output_data = ("tmpl_path", Cwd::getcwd()."/templates/",
			   "style_path", $afap->{af}->{site__web_root} . "/skins/" . $afap->{af}->{userpref__skin}."/style.css");
	my $tmpl = new HTML::Template(filename => "templates/uploader.tmpl",
				      die_on_bad_params => 0);
	if ($cgi->param("upload")){
	    $self->saveUploadedImage($cgi->param("upload"),\%output_data);
	}
	$tmpl->param(%output_data);
	
	print "Content-type: text/html; charset=UTF-8\n";
	print "Pragma: no-cache", "\n\n";
	print $self->translate_templateL10N($tmpl->output);

	debug_print("Diary::UploadImage: end");

}

##############################################
# saveUploadedImage
##############################################

sub saveUploadedImage {
    use Image::Magick;
    use File::Basename;
    my ($self, $filehandle, $output_data, $id) = @_;
    my $afap = $self->{afap};
    my $file;
    my $buf;
    my $filesize = 0;
    my $bytesread;
    my $basename;

  	if ($filehandle){
	    fileparse_set_fstype("MSDOS"); #For IE user
	    $basename  = basename($filehandle,"");
	    if ($basename =~ /^[a-zA-Z0-9\.\-\_]{1,32}$/ ){ #Check Filename
		unless ($basename =~ /^[a-zA-Z0-9\.\-\_]{1,28}\.(jpg|jpeg|png|gif|bmp)$/i) {
		    print "Uploaded file had invalid MIME type";
		}
		while ($bytesread = read($filehandle, $buf, 1024)) {
		    $file .= $buf;
#		    $self->errorExit('Uploaded file was too big') if (++$filesize >= 300);
		}
		my $imgdir = "$self->{datadir}img/";
		unless (-d $imgdir) {
		    mkdir $imgdir;
		}
		my $tmp_imgdir = "$self->{datadir}tmp/";
		unless (-d $tmp_imgdir) {
		    mkdir $tmp_imgdir;
		}

		my $thumbdir = $tmp_imgdir."thumb/";
		unless (-d $thumbdir) {
		    mkdir $thumbdir;
		}

		my $distfile = $tmp_imgdir.$basename;
		my $thumbfile = $thumbdir.$basename;
		# Save file
		local (*OUT);
		open(OUT, "> $distfile") or $output_data->{err}= "Failed to open file";
		binmode OUT;
		print OUT $file;
		close(OUT);

#		(eval 'use Image::Magick; 1;' ) ? ( $tmpl->param(IMAGEMAGICK => 0) ) : ( $tmpl->param(IMAGEMAGICK =>1) );                  
		my $image = Image::Magick->new;
		$image->Read( $distfile );
		my ($wg,$hg) = $image->Get('Width','Height');
		if ($wg>300 || $hg>300){
		    $image->Resize( geometry=>"300x300" );
		}
		$image->Set( quality=>75 );
		$image->Write( $thumbfile );

	    }else{
		$output_data->{err}= "You can only use ascii character in your file name";
	    }
  	}
        else{
	    $output_data->{err}= "Please select a file.";
      	}
	$output_data->{img}= $basename;
}


}
1;
