#/*
# *  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$
#

package Img0ch::Plugin::Filter::URLWhiteList;

use strict;
use Img0ch::Util::Trie qw();

sub check {
    my ($iApp) = @_;
    defined $Unicode::Japanese::VERSION or require Unicode::Japanese;
    my $unijp = Unicode::Japanese->new( $iApp->get_comment(),
        $iApp->bbs()->get_encoding() );
    $unijp->z2h();
    my $comment = $unijp->get();

    my $trie    = Img0ch::Util::Trie->new();
    my $iKernel = $iApp->kernel();
    my $iConfig = $iKernel->get_config();
    my $path    = $iConfig->get('SystemPath') . '/URL-whitelist.txt';
    if ( -r $path ) {
        my $fh = $iKernel->get_read_file_handle($path)
            or $iKernel->throw_io_exception($path);
        while ( my $url = <$fh> ) {
            chomp $url;
            $url or next;
            $trie->add($url);
            $url !~ m{https?://} and $trie->add( '.' . $url );
        }
        close $fh or $iKernel->throw_io_exception($path);
    }
    my $server = $iConfig->get('Server');
    $server =~ s{\Ahttp://}{}xms;
    $trie->add($server);

    my $url_re = qr{
        (h?t?tps?://
        [A-Za-z0-9\-\.]+/?
        [-_.!~*'()a-zA-Z0-9;/?:\@\&=+\$,%#]*/?)
    }xms;
    my $white_re = $trie->regexp();
    my @urls = $comment =~ /$url_re/g;

    foreach my $url (@urls) {
        if ( $url !~ /$white_re/xms ) {
            $iApp->set_error('URL_NOT_ALLOWED');
            return 0;
        }
    }

    return 1;
}

1;
__END__

