package MT::Plugin::Trackback::Ja;

use MT::Util qw( first_n_words encode_xml is_valid_url );

*{"MT::App::Trackback::ping"} = \&ping_ja;
*{"MT::Plugin::Trackback::Ja::no_utf8"} = \&MT::App::Trackback::no_utf8;
*{"MT::Plugin::Trackback::Ja::_generate_rss"} = \&MT::App::Trackback::_generate_rss;

sub ping_ja {
    my $app = shift;
    my $q = $app->{query};
    my($tb_id, $pass) = $app->_get_params;
    return $app->_response(Error =>
           $app->translate("Need a TrackBack ID (tb_id)."))
        unless $tb_id;

    my($title, $excerpt, $url, $blog_name, $icode) = map scalar $q->param($_),
                                             qw( title excerpt url blog_name charset);

    no_utf8($tb_id, $title, $excerpt, $url, $blog_name);
    require Jcode;
    my $charset = {'Shift_JIS'=>'sjis','ISO-2022-JP'=>'jis','EUC-JP'=>'euc',
                   'UTF-8'=>'utf8'}->{$app->{cfg}->PublishCharset} || 'utf8';
    $icode = Jcode::getcode($excerpt . $title . $blog_name) unless $icode;
    $title = Jcode->new($title, $icode)->$charset();
    $excerpt = Jcode->new($excerpt, $icode)->$charset();
    $blog_name = Jcode->new($blog_name, $icode)->$charset();

    return $app->_response(Error => $app->translate("Need a Source URL (url)."))
        unless $url;

    if (my $fixed = MT::Util::is_valid_url($url)) {
        $url = $fixed; 
    } else {
        return $app->_response(Error =>
            $app->translate("Invalid URL '[_1]'", $url));
    }

    require MT::TBPing;
    require MT::Trackback;

    my $tb = MT::Trackback->load($tb_id)
        or return $app->_response(Error =>
            $app->translate("Invalid TrackBack ID '[_1]'", $tb_id));

    return $app->_response(Error =>
        $app->translate("This TrackBack item is disabled."))
        if $tb->is_disabled;

    if ($tb->passphrase && (!$pass || $pass ne $tb->passphrase)) {
        return $app->_response(Error =>
          $app->translate("This TrackBack item is protected by a passphrase."));
    }

    ## Check if this user has been banned from sending TrackBack pings.
    require MT::IPBanList;
    my $iter = MT::IPBanList->load_iter({ blog_id => $tb->blog_id });
    my $user_ip = $app->remote_ip;
    while (my $ban = $iter->()) {
        my $banned_ip = $ban->ip;
        if ($user_ip =~ /$banned_ip/) {
            return $app->_response(Error =>
              $app->translate("You are not allowed to send TrackBack pings."));
        }
    }

    ## Check if user has pinged recently
    #my @past = MT::TBPing->load({ tb_id => $tb_id, ip => $host_ip });
    #if (@past) {
    #    @past = sort { $b->created_on cmp $a->created_on } @past;
    #}

    my $ping = MT::TBPing->new;
    $ping->blog_id($tb->blog_id);
    $ping->tb_id($tb_id);
    $ping->source_url($url);
    $ping->ip($app->remote_ip || '');
    if ($excerpt) {
        if (length($excerpt) > 255) {
            $excerpt = substr($excerpt, 0, 252) . '...';
        }
        $title = first_n_words($excerpt, 5)
            unless defined $title;
        $ping->excerpt($excerpt);
    }
    $ping->title(defined $title && $title ne '' ? $title : $url);
    $ping->blog_name($blog_name);
    $ping->save;

    ## If this is a trackback item for a particular entry, we need to
    ## rebuild the indexes in case the <$MTEntryTrackbackCount$> tag
    ## is being used. We also want to place the RSS files inside of the
    ## Local Site Path.
    my($blog_id, $entry, $cat);
    if ($tb->entry_id) {
        require MT::Entry;
        $entry = MT::Entry->load($tb->entry_id);
        $blog_id = $entry->blog_id;
    } elsif ($tb->category_id) {
        require MT::Category;
        $cat = MT::Category->load($tb->category_id);
        $blog_id = $cat->blog_id;
    }
    require MT::Blog;
    my $blog = MT::Blog->load($blog_id);
    $app->rebuild_indexes( Blog => $blog )
        or return $app->_response(Error =>
            $app->translate("Rebuild failed: [_1]", $app->errstr));

    if ($app->{cfg}->GenerateTrackBackRSS) {
        ## Now generate RSS feed for this trackback item.
        my $rss = _generate_rss($tb, 10);
        my $base = $blog->archive_path;
        my $feed = File::Spec->catfile($base, $tb->rss_file || $tb->id . '.xml');
        my $fmgr = $blog->file_mgr;
        $fmgr->put_data($rss, $feed)
            or return $app->_response(Error =>
                $app->translate("Can't create RSS feed '[_1]': ", $feed,
                $fmgr->errstr));
    }

    if ($blog->email_new_pings) {
        require MT::Mail;
        my($author, $subj, $body);
        if ($entry) {
            $author = $entry->author;
            $app->set_language($author->preferred_language)
                if $author && $author->preferred_language;
            $subj = $app->translate('New TrackBack Ping to Entry [_1] ([_2])',
                $entry->id, $entry->title);
            $body = $app->translate('A new TrackBack ping has been sent to your weblog, on the entry [_1] ([_2]).', $entry->id, $entry->title);
        } elsif ($cat) {
            require MT::Author;
            $author = MT::Author->load($cat->created_by);
            $app->set_language($author->preferred_language)
                if $author && $author->preferred_language;
            $subj = $app->translate('New TrackBack Ping to Category [_1] ([_2])',
                $cat->id, $cat->label);
            $body = $app->translate('A new TrackBack ping has been sent to your weblog, on the category [_1] ([_2]).', $cat->id, $cat->label);
        }
        if ($author && $author->email) {
            my %head = ( To => $author->email,
                         From => $author->email,
                         Subject => '[' . $blog->name . '] ' . $subj );
            my $charset = $app->{cfg}->PublishCharset || 'iso-8859-1';
            $head{'Content-Type'} = qq(text/plain; charset="$charset");
            require Text::Wrap;
            $Text::Wrap::cols = 72;
            $body = Text::Wrap::wrap('', '', $body) . "\n\n" .
                 $app->translate('IP Address:') . ' ' . $ping->ip . "\n" .
                 $app->translate('URL:') . ' ' . $ping->source_url . "\n" .
                 $app->translate('Title:') . ' ' . $ping->title . "\n" .
                 $app->translate('Weblog:') . ' ' . $ping->blog_name . "\n\n" .
                 $app->translate('Excerpt:') . "\n" . $ping->excerpt . "\n";
            MT::Mail->send(\%head, $body);
        }
    }

    return $app->_response;
}

1;