#/*
# *  Copyright 2007-2010 hkrn <hikarin@users.sourceforge.jp>
# *
# *  Licensed under the Apache License, Version 2.0 (the "License");
# *  you may not use this file except in compliance with the License.
# *  You may obtain a copy of the License at
# *
# *      http://www.apache.org/licenses/LICENSE-2.0
# *
# *  Unless required by applicable law or agreed to in writing, software
# *  distributed under the License is distributed on an "AS IS" BASIS,
# *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# *  See the License for the specific language governing permissions and
# *  limitations under the License.
# */
#
# $Id: MIME.pm 1901 2009-12-31 02:40:20Z hikarin $
#

package Img0ch::Plugin::Upload::MIME;

use strict;

sub check {
    my ($iApp)   = @_;
    my $iKernel  = $iApp->kernel();
    my $iRequest = $iApp->request();
    my ( $expected, $got );
    my $additional_extensions = {
        'jpg' => 'image/jpeg',
        'gif' => 'image/gif',
        'png' => 'image/png',
        'wav' => 'audio/x-wav',
        'mpg' => 'video/mpeg',
        'rar' => 'application/x-rar',
    };

    #    if ( defined $File::MMagic::XS::VERSION
    #        or eval 'use File::MMagic::XS qw(); 1' ) {
    #        my $mime = File::MMagic::XS->new();
    #        while ( my ( $ext, $mimetype ) = each %$additional_extensions ) {
    #            $mime->add_file_ext( $ext, $mimetype );
    #        }
    #        $expected = $mime->fsmagic($iRequest->filename());
    #        local ( *FH, $! );
    #        my $path = $iRequest->tempfile();
    #        open *FH, "<${path}" ## no critic
    #            or $iKernel->throw_io_exception($path);
    #        $got = $mime->fsmagic(\*FH);
    #        close *FH or $iKernel->throw_io_exception($path);
    #    }
    #    else {
    defined $File::MMagic::VERSION or require File::MMagic;
    my $mime = File::MMagic->new();
    while ( my ( $ext, $mimetype ) = each %$additional_extensions ) {
        $mime->addFileExts( qr/\.$ext\z/xms, $mimetype );
    }

    $expected = $mime->checktype_byfilename( $iRequest->filename() );
    my $path = $iRequest->tempfile();
    my $fh   = $iKernel->get_read_file_handle( $iRequest->tempfile() );
    $got = $mime->checktype_filehandle($fh);
    close $fh or $iKernel->throw_io_exception($path);

    #    }

    if ( $got ne $expected ) {
        $iApp->set_error('UPLOAD_FAKED_FILE');
        return 0;
    }
    return 1;
}

1;
__END__
