#/*
# *  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: Util.pm 610 2007-05-09 14:49:15Z hikarin $
#

package Zeromin2::Util;

use strict;

sub format_date {
    my ($key) = @_;
    my @d = localtime($key);
    $d[5] += 1900;
    $d[4] += 1;
    return sprintf '%02d/%02d/%02d %02d:%02d:%02d', $d[5], $d[4], $d[3],
        $d[2], $d[1], $d[0];
}

sub get_rewriter {
    my ($zApp)   = @_;
    my $bbs_id   = $zApp->bbs()->get_id();
    my $iConfig  = $zApp->kernel()->get_config();
    my $url      = $iConfig->get('Static') . '/zeromin/redirect.html?';
    my $self_url = $iConfig->get('Server');
    my $cgi_url  = $iConfig->get('CGIServer');
    my $self_url_re
        = $cgi_url
        ? qr{\A(?:/|\.+|$self_url|$cgi_url)}xms
        : qr{\A(?:/|\.+|$self_url)}xms;

    return sub {
        my ($text) = @_;
        my $link_rewrite = sub {
            my ( $redirectTo, $caption ) = @_;
            $redirectTo =~ s/\A"//xms;
            $redirectTo =~ s/".*\z//xms;
            if ( $redirectTo =~ $self_url_re ) {
                return '<a href="' . $redirectTo . '">' . $caption . '</a>';
            }
            else {

                # from URI::Escape
                Img0ch::Request->escape_uri( \$redirectTo );
                return '<a href="' 
                    . $url
                    . $redirectTo . '">'
                    . $caption . '</a>';
            }
        };
        $$text =~ s{
            <a\s*href=([^>]+)>([^<]+)</a>
            }{$link_rewrite->( $1, $2 )}gxmse;
    };
}

sub ip2host {
    my ($ip) = @_;
    return gethostbyaddr( pack( 'C*', split( '\.', $ip ) ), 2 ) || $ip;
}

1;
__END__
