#/*
# *  Copyright 2007 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: upload.pm 1107 2007-09-10 14:37:37Z hikarin $
#

package Zeromin2::App::upload;

use strict;

sub load_poll {
    my ($zApp) = @_;
    $zApp->privilege( 'can_abone_res', 1 )
        or return $zApp->return_value( 1, [] );

    require Img0ch::Setting;
    require Img0ch::Subject;
    require Img0ch::Upload;
    require Img0ch::Upload::Poll;
    require Zeromin2::Util;
    my $iKernel   = $zApp->kernel();
    my $iBBS      = $zApp->bbs();
    my $iConfig   = $iKernel->get_config();
    my $key       = $zApp->key();
    my $resno     = $zApp->request()->param_int('resno');
    my $encoding  = $iKernel->get_encoding(1);
    my $iSetting  = Img0ch::Setting->new($iBBS);
    my $iSubject  = Img0ch::Subject->new($iBBS);
    my $iUpload   = Img0ch::Upload->new( $iBBS, $key );
    my $iUPoll    = Img0ch::Upload::Poll->new( $iBBS, $key );
    my $bad       = $iUPoll->get( $resno, 'BAD' );
    my $privilege = $zApp->privilege('can_view_thread_log');

    $iSubject->load();
    for my $one (@$bad) {
        $one->{comment}
            = $iKernel->get_encoded_str( $one->{comment}, 'utf8', $encoding );
        $one->{polled} = Zeromin2::Util::format_date( $one->{polled} );
    }

    my $extension = $iUpload->get($resno)->[0];
    my ( $width, $height, $is_image, $file_url ) = ( 0, 0, 0, '' );
    if ( $extension eq 'jpg' or $extension eq 'gif' or $extension eq 'png' ) {
        $is_image = 1;
        if ( $iUpload->get_thumbnail_size( $resno, \$width, \$height ) ) {
            $file_url = $iUpload->url( "t${resno}", $extension );
        }
        else {
            $file_url = $iUpload->url( $resno, $extension );
            ( $width, $height ) = $iUpload->scale(
                $width, $height,
                $iSetting->get('BBS_IMG_THUMBNAIL_X'),
                $iSetting->get('BBS_IMG_THUMBNAIL_Y')
            );
        }
    }
    else {
        $file_url = $iUpload->url( $resno, $extension );
    }

    $zApp->add_template_param(
        {   BBS_TITLE => $iKernel->get_encoded_str(
                $iSetting->get('BBS_TITLE'),
                'utf8', $encoding
            ),
            DisplayPolledIP =>
                ( $privilege or !$iConfig->get('ufm.no_polled_ip') ),
            FileExtension   => $extension,
            FileURL         => $file_url,
            KEY             => $key,
            ImageHeight     => $height,
            ImageWidth      => $width,
            IsImage         => $is_image,
            PollForBad      => $bad,
            PollForBadCount => scalar @$bad,
            PollForBadTag   => 'BAD',
            Resno           => $resno,
            Subject         => $iKernel->get_encoded_str(
                $iSubject->get($key)->[0],
                'utf8', $encoding
            ),
        }
    );
    return $zApp->return_value( 0, $bad );
}

sub load_removed_file_hash {
    my ($zApp) = @_;
    $zApp->privilege('can_remove_thread') or return $zApp->return_value(1);

    require Img0ch::Upload::Removed;
    require Zeromin2::Util;

    my $iURemoved = Img0ch::Upload::Removed->new( $zApp->kernel() );
    my ( $hashes, $page )
        = $iURemoved->get_all_hash_with_page(
        $zApp->page_param('removed_file_hash') );
    my $ret = [];
    for my $hash (@$hashes) {
        my ( $bbs_name, $thread_key, $resno, $removed )
            = @{ $iURemoved->get($hash) };
        push @$ret,
            {
            id      => $hash,
            hash    => $hash,
            board   => $bbs_name,
            key     => $thread_key,
            resno   => $resno,
            removed => Zeromin2::Util::format_date($removed),
            };
    }

    return $zApp->return_value( 0, $ret, $page );
}

sub remove_removed_file_hash {
    my ($zApp) = @_;
    $zApp->check_csrf()                   or return $zApp->return_value(1);
    $zApp->privilege('can_remove_thread') or return $zApp->return_value(1);

    my @param = $zApp->request()->param('hash');
    scalar @param or return $zApp->return_value(2);

    require Img0ch::Upload::Removed;
    my $iURemoved = Img0ch::Upload::Removed->new( $zApp->kernel() );
    my $status    = {};

    for my $hash (@param) {
        if ( $iURemoved->remove($hash) ) {
            $zApp->logger( 1, 'REMOVED FILE HASH: %s', [$hash] );
            $status->{$hash} = 1;
        }
        else {
            $zApp->logger( 0, 'TRIED REMOVING FILE HASH: %s', [$hash] );
            $status->{$hash} = 0;
        }
    }

    $iURemoved->save();
    return $zApp->return_value( 0, $status );
}

sub remove_poll {
    my ($zApp) = @_;
    $zApp->check_csrf()                 or return $zApp->return_value(1);
    $zApp->privilege('can_remove_poll') or return $zApp->return_value(1);

    my $iRequest = $zApp->request();
    my @param    = $iRequest->param('id');
    scalar @param or return $zApp->return_value(2);

    my $resno = $iRequest->param_int('resno');
    my $tag   = $iRequest->param('tag');

    require Img0ch::Upload::Poll;
    my $zBBS   = $zApp->bbs();
    my $bbs    = $zBBS->get_name();
    my $key    = $zApp->key();
    my $iUPoll = Img0ch::Upload::Poll->new( $zBBS, $key );
    my $status = {};

    for my $id (@param) {
        if ( $iUPoll->remove( $resno, $tag, $id ) ) {
            $zApp->logger(
                1,
                'REMOVED POLL %s at %s/dat/%s.dat',
                [ $id, $bbs, $key ]
            );
            $status->{$id} = 1;
        }
        else {
            $zApp->logger(
                0,
                'TRIED REMOVING POLL %s at %s/dat/%s.dat',
                [ $id, $bbs, $key ]
            );
            $status->{$id} = 0;
        }
    }

    $iUPoll->save();
    return $zApp->return_value( 0, $status );
}

sub remove_all_poll {
    my ($zApp) = @_;
    $zApp->check_csrf()                 or return $zApp->return_value(1);
    $zApp->privilege('can_remove_poll') or return $zApp->return_value(1);

    my $iRequest = $zApp->request();
    my $resno    = $iRequest->param_int('resno');
    my $tag      = $iRequest->param('tag');

    require Img0ch::Upload::Poll;
    my $zBBS   = $zApp->bbs();
    my $bbs    = $zBBS->get_name();
    my $key    = $zApp->key();
    my $iUPoll = Img0ch::Upload::Poll->new( $zBBS, $key );
    $iUPoll->remove( $resno, $tag );
    $iUPoll->save();
    $zApp->logger(
        1,
        'REMOVED ALL POLL at %s/dat/%s.dat',
        [ $zBBS->get_name, $key ]
    );

    return $zApp->return_value(0);
}

sub freeze_file {
    _task(
        shift, 'can_freeze_file',
        'FREEZED UPLOADED FILE',
        'TRIED FREEZING UPLOADED FILE', 'freeze'
    );
}

sub release_file {
    _task(
        shift, 'can_release_file',
        'RELEASED UPLOADED FILE',
        'TRIED RELEASING UPLOADED FILE', 'release'
    );
}

sub _task {
    my ( $zApp, $priv_meth, $success, $fail, $method ) = @_;
    $zApp->check_csrf() or return $zApp->return_value(1);
    $zApp->privilege( $priv_meth, 1 ) or return $zApp->return_value(1);

    my $key = $zApp->key() || return $zApp->return_value(3);
    my @param = $zApp->request()->param('resno');
    scalar @param or return $zApp->return_value(2);

    require Img0ch::Upload;
    my $zBBS    = $zApp->bbs();
    my $bbs     = $zBBS->get_name();
    my $status  = {};
    my $iUpload = Img0ch::Upload->new( $zBBS, $key );

    for my $resno (@param) {
        Img0ch::Kernel::intval($resno) or next;
        if ( $iUpload->$method($resno) ) {
            $zApp->logger(
                1,
                ( $success . ' %d at %s/dat/%s.dat' ),
                [ $resno, $bbs, $key ]
            );
            $status->{$resno} = 1;
        }
        else {
            $zApp->logger(
                1,
                ( $fail . ' %d at %s/dat/%s.dat' ),
                [ $resno, $bbs, $key ]
            );
            $status->{$resno} = 1;
        }
    }

    return $zApp->return_value( 0, $status );
}

1;
__END__
