File: Trackback.pm

package info (click to toggle)
movabletype-opensource 4.2.3-1%2Blenny3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 21,268 kB
  • ctags: 15,862
  • sloc: perl: 178,892; php: 26,178; sh: 161; makefile: 82
file content (662 lines) | stat: -rw-r--r-- 19,628 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
# Movable Type (r) Open Source (C) 2001-2008 Six Apart, Ltd.
# This program is distributed under the terms of the
# GNU General Public License, version 2.
#
# $Id: Trackback.pm 2890 2008-08-04 11:28:44Z fumiakiy $

package MT::App::Trackback;

use strict;
use base qw( MT::App );

use File::Spec;
use MT::TBPing;
use MT::Trackback;
use MT::Util qw( first_n_words encode_xml is_valid_url
    start_background_task );
use MT::JunkFilter qw(:constants);
use MT::I18N
    qw( encode_text guess_encoding const length_text wrap_text substr_text first_n_text );

sub id {'tb'}

sub init {
    my $app = shift;
    $app->SUPER::init(@_) or return;
    $app->add_methods(
        ping => \&ping,
        view => \&view,
        rss  => \&rss,
    );
    $app->{default_mode} = 'ping';
    $app;
}

sub validate_request_params {
    my $app = shift;

    my $q = $app->param;

    # attempt to determine character set encoding based on
    # 'charset' parameter:
    my $enc = $q->param('charset');
    local $app->{charset} = $enc if $enc;
    return $app->SUPER::validate_request_params();
}

sub view {
    my $app = shift;
    my $q   = $app->param;
    require MT::Template;
    require MT::Template::Context;
    require MT::Entry;
    my $entry_id = $q->param('entry_id');
    my $entry
        = MT::Entry->load(
        { id => $entry_id, status => MT::Entry::RELEASE() } )
        or return $app->error(
        $app->translate( "Invalid entry ID '[_1]'", $entry_id ) );
    my $ctx = MT::Template::Context->new;
    $ctx->stash( 'entry', $entry );
    $ctx->{current_timestamp} = $entry->authored_on;
    my $tmpl = MT::Template->load(
        {   type    => 'pings',
            blog_id => $entry->blog_id
        }
        )
        or return $app->error(
        $app->translate(
            "You must define a Ping template in order to display pings.")
        );
    defined( my $html = $tmpl->build($ctx) )
        or return $app->error( $tmpl->errstr );
    $html;
}

## The following subroutine strips the UTF8 flag from a string, thus
## forcing it into a series of bytes. "pack 'C0'" is a magic way of
## forcing the following string to be packed as bytes, not as UTF8.
sub no_utf8 {
    for (@_) {
        next if !defined $_;
        $_ = pack 'C0A*', $_;
    }
}

my %map = ( '&' => '&amp;', '"' => '&quot;', '<' => '&lt;', '>' => '&gt;' );

sub _response {
    my $app   = shift;
    my %param = @_;
    $app->response_code( $param{Code} );
    $app->send_http_header('text/xml; charset=utf-8');
    $app->{no_print_body} = 1;

    if ( my $err = $param{Error} ) {
        my $re = join '|', keys %map;
        $err =~ s!($re)!$map{$1}!g;
        $err = encode_text( $err, undef, 'utf-8' );
        print <<XML;
<?xml version="1.0" encoding="utf-8"?>
<response>
<error>1</error>
<message>$err</message>
</response>
XML
    }
    else {
        print <<XML;
<?xml version="1.0" encoding="utf-8"?>
<response>
<error>0</error>
XML
        if ( my $rss = $param{RSS} ) {
            $rss = encode_text( $rss, undef, 'utf-8' );
            print $rss;
        }
        print <<XML;
</response>
XML
    }

    1;
}

sub _get_params {
    my $app = shift;
    my ( $tb_id, $pass );
    if ( $tb_id = $app->param('tb_id') ) {
        $pass = $app->param('pass');
    }
    else {
        if ( my $pi = $app->path_info ) {
            $pi =~ s!^/!!;
            my $tbscript = $app->config('TrackbackScript');
            $pi =~ s!.*\Q$tbscript\E/!!;
            ( $tb_id, $pass ) = split /\//, $pi;
        }
    }
    ( $tb_id, $pass );
}

sub _builtin_throttle {
    my ( $eh, $app, $tb ) = @_;
    my $user_ip = $app->remote_ip;
    use MT::Util qw(offset_time_list);
    my @ts = offset_time_list( time - 3600, $tb->blog_id );
    my $from = sprintf(
        "%04d%02d%02d%02d%02d%02d",
        $ts[5] + 1900,
        $ts[4] + 1,
        @ts[ 3, 2, 1, 0 ]
    );
    require MT::TBPing;
    if ($app->config('OneHourMaxPings') <= MT::TBPing->count(
            {   blog_id    => $tb->blog_id,
                created_on => [$from]
            },
            { range => { created_on => 1 } }
        )
        )
    {
        return 0;
    }

    @ts = offset_time_list( time - $app->config('ThrottleSeconds') * 4000 - 1,
        $tb->blog_id );
    $from = sprintf(
        "%04d%02d%02d%02d%02d%02d",
        $ts[5] + 1900,
        $ts[4] + 1,
        @ts[ 3, 2, 1, 0 ]
    );
    my $terms = {
        blog_id    => $tb->blog_id,
        created_on => [$from]
    };
    my $count = MT::TBPing->count( $terms, { range => { created_on => 1 } } );
    if ( $count >= $app->config('OneDayMaxPings') ) {
        return 0;
    }
    return 1;
}

sub ping {
    my $app = shift;
    my $q   = $app->param;

    return $app->_response(
        Error => $app->translate("Trackback pings must use HTTP POST") )
        if $app->request_method() ne 'POST';

    my ( $tb_id, $pass ) = $app->_get_params;
    return $app->_response(
        Error => $app->translate("Need a TrackBack ID (tb_id).") )
        unless $tb_id;

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

    my $user_ip = $app->remote_ip;

    ## 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 } );
    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.")
            );
        }
    }

    my ( $blog_id, $entry, $cat );
    if ( $tb->entry_id ) {
        require MT::Entry;
        $entry = MT::Entry->load(
            { id => $tb->entry_id, status => MT::Entry::RELEASE() } );
        if ( !$entry ) {
            return $app->_response( Error =>
                    $app->translate( "Invalid TrackBack ID '[_1]'", $tb_id )
            );
        }
    }
    elsif ( $tb->category_id ) {
        require MT::Category;
        $cat = MT::Category->load( $tb->category_id );
    }
    $blog_id = $tb->blog_id;

    MT->add_callback( 'TBPingThrottleFilter', 1, undef,
        \&MT::App::Trackback::_builtin_throttle );

    my $passed_filter
        = MT->run_callbacks( 'TBPingThrottleFilter', $app, $tb );
    if ( !$passed_filter ) {
        return $app->_response(
            Error => $app->translate(
                "You are pinging trackbacks too quickly. Please try again later."
            ),
            Code => "403 Throttled"
        );
    }

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

    no_utf8( $tb_id, $title, $excerpt, $url, $blog_name );

    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::Blog;
    my $blog = MT::Blog->load( $tb->blog_id );
    my $cfg  = $app->config;

    return $app->_response(
        Error => $app->translate("This TrackBack item is disabled.") )
        if $tb->is_disabled
            || !$cfg->AllowPings
            || !$blog
            || !$blog->allow_pings;

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

    my $ping;

    # Check for duplicates...
    my @pings = MT::TBPing->load( { tb_id => $tb->id } );
    foreach (@pings) {
        if ( $_->source_url eq $url ) {
            return $app->_response();
        }
    }

    if ( !$ping ) {
        $ping ||= MT::TBPing->new;
        $ping->blog_id( $tb->blog_id );
        $ping->tb_id($tb_id);
        $ping->source_url($url);
        $ping->ip( $app->remote_ip || '' );
        $ping->visible(1);
    }
    my $excerpt_max_len = const('LENGTH_ENTRY_PING_EXCERPT');
    if ($excerpt) {
        if ( length_text($excerpt) > $excerpt_max_len ) {
            $excerpt
                = substr_text( $excerpt, 0, $excerpt_max_len - 3 ) . '...';
        }
        $title
            = first_n_text( $excerpt,
            const('LENGTH_ENTRY_PING_TITLE_FROM_TEXT') )
            unless defined $title;
        $ping->excerpt($excerpt);
    }
    $ping->title( defined $title && $title ne '' ? $title : $url );
    $ping->blog_name($blog_name);

    # strip of any null characters (done after junk checks so they can
    # monitor for that kind of activity)
    for my $field (qw(title excerpt source_url blog_name)) {
        my $val = $ping->column($field);
        if ( $val =~ m/\x00/ ) {
            $val =~ tr/\x00//d;
            $ping->column( $field, $val );
        }
    }

    if ( !MT->run_callbacks( 'TBPingFilter', $app, $ping ) ) {
        return $app->_response( Error => "", Code => 403 );
    }

    if ( !$ping->is_junk ) {
        MT::JunkFilter->filter($ping);
    }

    if ( !$ping->is_junk && $ping->visible && $blog->moderate_pings ) {
        $ping->visible(0);
    }

    $ping->save
        or return $app->_response( Error => "An internal error occured" );
    if ( $ping->id && !$ping->is_junk ) {
        my $msg = 'New TrackBack received.';
        if ($entry) {
            $msg = $app->translate( 'TrackBack on "[_1]" from "[_2]".',
                $entry->title, $ping->blog_name );
        }
        elsif ($cat) {
            $msg = $app->translate( "TrackBack on category '[_1]' (ID:[_2]).",
                $cat->label, $cat->id );
        }
        require MT::Log;
        $app->log(
            {   message  => $msg,
                class    => 'ping',
                category => 'new',
                blog_id  => $blog_id,
                metadata => $ping->id,
            }
        );
    }

    if ( !$ping->is_junk ) {
        if ( !$ping->visible ) {
            $app->_send_ping_notification( $blog, $entry, $cat, $ping );
        }
        else {
            start_background_task(
                sub {
                    ## 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.
                    $app->rebuild_indexes( Blog => $blog )
                        or return $app->_response(
                        Error => $app->translate(
                            "Publish failed: [_1]",
                            $app->errstr
                        )
                        );

                    if ( $tb->entry_id ) {
                        $app->rebuild_entry(
                            Entry             => $entry->id,
                            Blog              => $blog,
                            BuildDependencies => 1
                        );
                    }
                    if ( $tb->category_id ) {
                        $app->publisher->_rebuild_entry_archive_type(
                            Entry       => undef,
                            Blog        => $blog,
                            Category    => $cat,
                            ArchiveType => 'Category'
                        );
                    }

                    if ( $app->config('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
                            )
                            );
                    }
                    $app->_send_ping_notification( $blog, $entry, $cat,
                        $ping );
                }
            );
        }
    }
    else {
        $app->run_tasks('JunkExpiration');
    }

    return $app->_response;
}

# one of $entry or $cat must be passed.
sub _send_ping_notification {
    my $app = shift;
    my ( $blog, $entry, $cat, $ping ) = @_;

    return unless $blog->email_new_pings;

    my $attn_reqd = $ping->is_moderated();
    if ( $blog->email_attn_reqd_pings && !$attn_reqd ) {
        return;
    }

    require MT::Mail;

    my ( $author, $subj );
    if ($entry) {
        $author = $entry->author;
    }
    elsif ($cat) {
        require MT::Author;
        $author = MT::Author->load( $cat->author_id ) if $cat->author_id;
    }
    $app->set_language( $author->preferred_language )
        if $author && $author->preferred_language;

    if ( $author && $author->email ) {
        if ($entry) {
            $subj
                = $app->translate( 'New TrackBack Ping to Entry [_1] ([_2])',
                $entry->id, $entry->title );
        }
        elsif ($cat) {
            $subj
                = $app->translate(
                'New TrackBack Ping to Category [_1] ([_2])',
                $cat->id, $cat->label );
        }
        my %head = (
            id   => 'new_ping',
            To   => $author->email,
            From => $app->config('EmailAddressMain')
                || (
                  $author->nickname
                ? $author->nickname . ' <' . $author->email . '>'
                : $author->email
                ),
            Subject => '[' . $blog->name . '] ' . $subj
        );
        my $base;
        {
            local $app->{is_admin} = 1;
            $base = $app->base . $app->mt_uri;
        }
        if ( $base =~ m!^/! ) {
            my ($blog_domain) = $blog->site_url =~ m|(.+://[^/]+)|;
            $base = $blog_domain . $base;
        }
        my $nonce
            = MT::Util::perl_sha1_digest_hex( $ping->id
                . $ping->created_on
                . $blog->id
                . $app->config->SecretToken );
        my $approve_link = $base
            . $app->uri_params(
            'mode' => 'approve_item',
            args   => {
                blog_id => $blog->id,
                '_type' => 'ping',
                id      => $ping->id,
                nonce   => $nonce
            }
            );
        my $spam_link = $base
            . $app->uri_params(
            'mode' => 'handle_junk',
            args   => {
                blog_id => $blog->id,
                '_type' => 'ping',
                id      => $ping->id,
                nonce   => $nonce
            }
            );
        my $edit_link = $base
            . $app->uri_params(
            'mode' => 'view',
            args =>
                { blog_id => $blog->id, '_type' => 'ping', id => $ping->id }
            );
        my $ban_link = $base
            . $app->uri_params(
            'mode' => 'save',
            args   => {
                '_type' => 'banlist',
                blog_id => $blog->id,
                ip      => $ping->ip
            }
            );
        my %param = (
            blog           => $blog,
            approve_url    => $approve_link,
            spam_url       => $spam_link,
            edit_url       => $edit_link,
            ban_url        => $ban_link,
            ping           => $ping,
            unapproved     => !$ping->visible(),
            state_editable => (
                $author->is_superuser()
                    || (
                       $author->permissions( $blog->id )->can_manage_feedback
                    || $author->permissions( $blog->id )->can_publish_post )
                ) ? 1 : 0,
        );
        $param{entry}    = $entry if $entry;
        $param{category} = $cat   if $cat;

        my $charset = $app->config('MailEncoding') || $app->charset;
        $head{'Content-Type'} = qq(text/plain; charset="$charset");
        my $body = MT->build_email( 'new-ping.tmpl', \%param );
        MT::Mail->send( \%head, $body );
    }
}

sub rss {
    my $app = shift;
    my ( $tb_id, $pass ) = $app->_get_params;
    my $tb = MT::Trackback->load($tb_id)
        or return $app->_response(
        Error => $app->translate( "Invalid TrackBack ID '[_1]'", $tb_id ) );
    if ( my $eid = $tb->entry_id ) {
        my $entry = $app->model('entry')->load($eid);
        return $app->_response(
            Error => $app->translate( "Invalid TrackBack ID '[_1]'", $tb_id )
        ) unless $entry && ( MT::Entry::RELEASE() == $entry->status );
    }
    elsif ( my $cid = $tb->category_id ) {
        my $exist = $app->model('entry')->exist(
            { status => MT::Entry::RELEASE() },
            {   join => MT::Placement->join_on(
                    'entry_id', { category_id => $cid }
                )
            }
        );
        return $app->_response(
            Error => $app->translate( "Invalid TrackBack ID '[_1]'", $tb_id )
        ) unless $exist;
    }
    my $rss = _generate_rss($tb);
    $app->_response( RSS => $rss );
}

sub _generate_rss {
    my ( $tb, $lastn ) = @_;
    my $lang = MT->config->DefaultLanguage || 'en-us';
    my $rss = <<RSS;
<rss version="0.91"><channel>
<title>@{[ $tb->title ]}</title>
<link>@{[ $tb->url || '' ]}</link>
<description>@{[ $tb->description || '' ]}</description>
<language>$lang</language>
RSS
    my %arg;
    if ($lastn) {
        %arg = (
            'sort'    => 'created_on',
            direction => 'descend',
            limit     => $lastn
        );
    }
    my $iter = MT::TBPing->load_iter(
        {   tb_id       => $tb->id,
            junk_status => MT::TBPing::NOT_JUNK(),
            visible     => 1
        },
        \%arg
    );
    while ( my $ping = $iter->() ) {
        $rss .= sprintf qq(<item>\n<title>%s</title>\n<link>%s</link>\n),
            encode_xml( $ping->title ), encode_xml( $ping->source_url );
        if ( $ping->excerpt ) {
            $rss .= sprintf qq(<description>%s</description>\n),
                encode_xml( $ping->excerpt );
        }
        $rss .= qq(</item>\n);
    }
    $rss .= qq(</channel>\n</rss>);
    my $enc = MT->config->PublishCharset || 'utf-8';
    $rss = MT::I18N::encode_text( $rss, $enc, 'utf-8' ) if $enc ne 'utf-8';
    $rss;
}

sub blog {
    my $app = shift;
    return $app->{_blog} if $app->{_blog};
    if ( my ($tb_id) = $app->_get_params() ) {
        require MT::Trackback;
        my $tb = MT::Trackback->load($tb_id);
        return undef unless $tb;
        $app->{_blog} = MT::Blog->load( $tb->blog_id ) if $tb;
    }
    return $app->{_blog};
}

1;
__END__

=head1 NAME

MT::App::Trackback

=head1 METHODS

=head2 init

Call L<MT::App/init>, register the C<ping>, C<view> and C<rss>
callbacks and set the application default_mode to C<ping>.

=head2 view

Build the trackback page for viewing.

=head2 rss

Generate and return RSS text for the trackback.

=head2 blog

Return the blog of the trackback.

=head2 no_utf8

This function removes UTF-8 from scalars.

=head1 AUTHOR & COPYRIGHT

Please see L<MT/AUTHOR & COPYRIGHT>.

=cut