summaryrefslogtreecommitdiff
path: root/rt/lib/RT/Attachment_Overlay.pm
blob: 8dcf56ea6af719326837e153424b1102270cf67f (plain)
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
# {{{ BEGIN BPS TAGGED BLOCK
# 
# COPYRIGHT:
#  
# This software is Copyright (c) 1996-2004 Best Practical Solutions, LLC 
#                                          <jesse@bestpractical.com>
# 
# (Except where explicitly superseded by other copyright notices)
# 
# 
# LICENSE:
# 
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
# 
# This work is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# 
# 
# CONTRIBUTION SUBMISSION POLICY:
# 
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
# 
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
# 
# }}} END BPS TAGGED BLOCK
=head1 SYNOPSIS

  use RT::Attachment;


=head1 DESCRIPTION

This module should never be instantiated directly by client code. it's an internal 
module which should only be instantiated through exported APIs in Ticket, Queue and other 
similar objects.


=head1 METHODS


=begin testing

ok (require RT::Attachment);

=end testing

=cut

use strict;
no warnings qw(redefine);

use MIME::Base64;
use MIME::QuotedPrint;


# {{{ sub _OverlayAccessible 
sub _OverlayAccessible {
    {
    TransactionId   => { 'read'=>1, 'public'=>1, 'write' => 0 },
    MessageId       => { 'read'=>1, 'write' => 0 },
    Parent          => { 'read'=>1, 'write' => 0 },
    ContentType     => { 'read'=>1, 'write' => 0 },
    Subject         => { 'read'=>1, 'write' => 0 },
    Content         => { 'read'=>1, 'write' => 0 },
    ContentEncoding => { 'read'=>1, 'write' => 0 },
    Headers         => { 'read'=>1, 'write' => 0 },
    Filename        => { 'read'=>1, 'write' => 0 },
    Creator         => { 'read'=>1, 'auto'=>1, },
    Created         => { 'read'=>1, 'auto'=>1, },
  };
}
# }}}

# {{{ sub TransactionObj 

=head2 TransactionObj

Returns the transaction object asscoiated with this attachment.

=cut

sub TransactionObj {
    require RT::Transaction;
    my $self=shift;
    unless (exists $self->{_TransactionObj}) {
	$self->{_TransactionObj}=RT::Transaction->new($self->CurrentUser);
	$self->{_TransactionObj}->Load($self->TransactionId);
    }
    unless ($self->{_TransactionObj}->Id) {
        $RT::Logger->crit("Attachment ".$self->id." can't find transaction ".$self->TransactionId." which it is ostensibly part of. That's bad");
    }
    return $self->{_TransactionObj};
}

# }}}

# {{{ sub Create 

=head2 Create

Create a new attachment. Takes a paramhash:
    
    'Attachment' Should be a single MIME body with optional subparts
    'Parent' is an optional Parent RT::Attachment object
    'TransactionId' is the mandatory id of the Transaction this attachment is associated with.;

=cut

sub Create {
    my $self = shift;
    my ($id);
    my %args = ( id            => 0,
                 TransactionId => 0,
                 Parent        => 0,
                 Attachment    => undef,
                 @_ );

    #For ease of reference
    my $Attachment = $args{'Attachment'};

	    #if we didn't specify a ticket, we need to bail
	    if ( $args{'TransactionId'} == 0 ) {
        $RT::Logger->crit( "RT::Attachment->Create couldn't, as you didn't specify a transaction\n" );
        return (0);

    }

    #If we possibly can, collapse it to a singlepart
    $Attachment->make_singlepart;

    #Get the subject
    my $Subject = $Attachment->head->get( 'subject', 0 );
    defined($Subject) or $Subject = '';
    chomp($Subject);

    #Get the filename
    my $Filename = $Attachment->head->recommended_filename || eval {
	${ $Attachment->head->{mail_hdr_hash}{'Content-Disposition'}[0] }
	    =~ /^.*\bfilename="(.*)"$/ ? $1 : ''
    };

    # If a message has no bodyhandle, that means that it has subparts (or appears to)
    # and we should act accordingly.  
    unless ( defined $Attachment->bodyhandle ) {
        $id = $self->SUPER::Create(
            TransactionId => $args{'TransactionId'},
            Parent        => 0,
            ContentType   => $Attachment->mime_type,
            Headers => $Attachment->head->as_string,
            Subject => $Subject);

        foreach my $part ( $Attachment->parts ) {
            my $SubAttachment = new RT::Attachment( $self->CurrentUser );
            $SubAttachment->Create(
                TransactionId => $args{'TransactionId'},
                Parent        => $id,
                Attachment    => $part,
                ContentType   => $Attachment->mime_type,
                Headers       => $Attachment->head->as_string(),

            );
        }
        return ($id);
    }

    #If it's not multipart
    else {


        my $Body = $Attachment->bodyhandle->as_string;


	my ($ContentEncoding, $Body) = $self->_EncodeLOB($Attachment->bodyhandle->as_string, $Attachment->mime_type);


        my $id = $self->SUPER::Create( TransactionId => $args{'TransactionId'},
                                       ContentType   => $Attachment->mime_type,
                                       ContentEncoding => $ContentEncoding,
                                       Parent          => $args{'Parent'},
                                       Headers       =>  $Attachment->head->as_string, 
                                       Subject       =>  $Subject,
                                       Content         => $Body,
                                       Filename => $Filename, );
        return ($id);
    }
}

# }}}


=head2 Import

Create an attachment exactly as specified in the named parameters.

=cut


sub Import {
    my $self = shift;
    my %args = ( ContentEncoding => 'none',

		 @_ );
    return($self->SUPER::Create(@_));
}

# {{{ sub Content

=head2 Content

Returns the attachment's content. if it's base64 encoded, decode it 
before returning it.

=cut

sub Content {
  my $self = shift;
  my $decode_utf8 = (($self->ContentType =~ qr{^text/plain}i) ? 1 : 0);

  if ( $self->ContentEncoding eq 'none' || ! $self->ContentEncoding ) {
      return $self->_Value(
	  'Content',
	  decode_utf8 => $decode_utf8,
      );
  } elsif ( $self->ContentEncoding eq 'base64' ) {
      return ( $decode_utf8
        ? Encode::decode_utf8(MIME::Base64::decode_base64($self->_Value('Content')))
        : MIME::Base64::decode_base64($self->_Value('Content'))
      );
  } elsif ( $self->ContentEncoding eq 'quoted-printable' ) {
      return ( $decode_utf8
        ? Encode::decode_utf8(MIME::QuotedPrint::decode($self->_Value('Content')))
        : MIME::QuotedPrint::decode($self->_Value('Content'))
      );
  } else {
      return( $self->loc("Unknown ContentEncoding [_1]", $self->ContentEncoding));
  }
}


# }}}


# {{{ sub OriginalContent

=head2 OriginalContent

Returns the attachment's content as octets before RT's mangling.
Currently, this just means restoring text/plain content back to its
original encoding.

=cut

sub OriginalContent {
  my $self = shift;

  return $self->Content unless $self->ContentType eq 'text/plain';
  my $enc = $self->OriginalEncoding;

  my $content;
  if ( $self->ContentEncoding eq 'none' || ! $self->ContentEncoding ) {
      $content = $self->_Value('Content', decode_utf8 => 0);
  } elsif ( $self->ContentEncoding eq 'base64' ) {
      $content = MIME::Base64::decode_base64($self->_Value('Content', decode_utf8 => 0));
  } elsif ( $self->ContentEncoding eq 'quoted-printable' ) {
      return MIME::QuotedPrint::decode($self->_Value('Content', decode_utf8 => 0));
  } else {
      return( $self->loc("Unknown ContentEncoding [_1]", $self->ContentEncoding));
  }

  # Encode::_utf8_on($content);
  if (!$enc || $enc eq '' ||  $enc eq 'utf8' || $enc eq 'utf-8') {
    # If we somehow fail to do the decode, at least push out the raw bits
    eval {return( Encode::decode_utf8($content))} || return ($content);
  }
  
  eval { Encode::from_to($content, 'utf8' => $enc);};
  if ($@) {
	$RT::Logger->error("Could not convert attachment from assumed utf8 to '$enc' :".$@);
  }
  return $content;
}

# }}}


# {{{ sub OriginalEncoding

=head2 OriginalEncoding

Returns the attachment's original encoding.

=cut

sub OriginalEncoding {
  my $self = shift;
  return $self->GetHeader('X-RT-Original-Encoding');
}

# }}}

# {{{ sub Children

=head2 Children

  Returns an RT::Attachments object which is preloaded with all Attachments objects with this Attachment\'s Id as their 'Parent'

=cut

sub Children {
    my $self = shift;
    
    my $kids = new RT::Attachments($self->CurrentUser);
    $kids->ChildrenOf($self->Id);
    return($kids);
}

# }}}

# {{{ UTILITIES

# {{{ sub Quote 



sub Quote {
    my $self=shift;
    my %args=(Reply=>undef, # Prefilled reply (i.e. from the KB/FAQ system)
	      @_);

    my ($quoted_content, $body, $headers);
    my $max=0;

    # TODO: Handle Multipart/Mixed (eventually fix the link in the
    # ShowHistory web template?)
    if ($self->ContentType =~ m{^(text/plain|message)}i) {
	$body=$self->Content;

	# Do we need any preformatting (wrapping, that is) of the message?

	# Remove quoted signature.
	$body =~ s/\n-- \n(.*)$//s;

	# What's the longest line like?
	foreach (split (/\n/,$body)) {
	    $max=length if ( length > $max);
	}

	if ($max>76) {
	    require Text::Wrapper;
	    my $wrapper=new Text::Wrapper
		(
		 columns => 70, 
		 body_start => ($max > 70*3 ? '   ' : ''),
		 par_start => ''
		 );
	    $body=$wrapper->wrap($body);
	}

	$body =~ s/^/> /gm;

	$body = '[' . $self->TransactionObj->CreatorObj->Name() . ' - ' . $self->TransactionObj->CreatedAsString()
	            . "]:\n\n"
   	        . $body . "\n\n";

    } else {
	$body = "[Non-text message not quoted]\n\n";
    }
    
    $max=60 if $max<60;
    $max=70 if $max>78;
    $max+=2;

    return (\$body, $max);
}
# }}}

# {{{ sub NiceHeaders - pulls out only the most relevant headers

=head2 NiceHeaders

Returns the To, From, Cc, Date and Subject headers.

It is a known issue that this breaks if any of these headers are not
properly unfolded.

=cut

sub NiceHeaders {
    my $self = shift;
    my $hdrs = "";
    my @hdrs = split(/\n/,$self->Headers);
    while (my $str = shift @hdrs) {
	    next unless $str =~ /^(To|From|RT-Send-Cc|Cc|Bcc:Date|Subject): /i;
	    $hdrs .= $str . "\n";
	    $hdrs .= shift( @hdrs ) . "\n" while ($hdrs[0] =~ /^[ \t]+/);
    }
    return $hdrs;
}
# }}}

# {{{ sub Headers

=head2 Headers

Returns this object's headers as a string.  This method specifically
removes the RT-Send-Bcc: header, so as to never reveal to whom RT sent a Bcc.
We need to record the RT-Send-Cc and RT-Send-Bcc values so that we can actually send
out mail. (The mailing rules are separated from the ticket update code by
an abstraction barrier that makes it impossible to pass this data directly

=cut

sub Headers {
    my $self = shift;
    my $hdrs="";
    for ($self->_SplitHeaders) {
	    $hdrs.="$_\n" unless /^(RT-Send-Bcc):/i
    }
    return $hdrs;
}


# }}}

# {{{ sub GetHeader

=head2 GetHeader ( 'Tag')

Returns the value of the header Tag as a string. This bypasses the weeding out
done in Headers() above.

=cut

sub GetHeader {
    my $self = shift;
    my $tag = shift;
    foreach my $line ($self->_SplitHeaders) {
        if ($line =~ /^\Q$tag\E:\s+(.*)$/si) { #if we find the header, return its value
            return ($1);
        }
    }
    
    # we found no header. return an empty string
    return undef;
}
# }}}

# {{{ sub SetHeader

=head2 SetHeader ( 'Tag', 'Value' )

Replace or add a Header to the attachment's headers.

=cut

sub SetHeader {
    my $self = shift;
    my $tag = shift;
    my $newheader = '';

    foreach my $line ($self->_SplitHeaders) {
        if (defined $tag and $line =~ /^\Q$tag\E:\s+(.*)$/i) {
	    $newheader .= "$tag: $_[0]\n";
	    undef $tag;
        }
	else {
	    $newheader .= "$line\n";
	}
    }

    $newheader .= "$tag: $_[0]\n" if defined $tag;
    $self->__Set( Field => 'Headers', Value => $newheader);
}
# }}}

# {{{ sub _Value 

=head2 _Value

Takes the name of a table column.
Returns its value as a string, if the user passes an ACL check

=cut

sub _Value {

    my $self  = shift;
    my $field = shift;

    #if the field is public, return it.
    if ( $self->_Accessible( $field, 'public' ) ) {
        return ( $self->__Value( $field, @_ ) );
    }

    #If it's a comment, we need to be extra special careful
    elsif ( $self->TransactionObj->Type =~ /^Comment/ ) {
        if ( $self->TransactionObj->CurrentUserHasRight('ShowTicketComments') )
        {
            return ( $self->__Value( $field, @_ ) );
        }
    }
    elsif ( $self->TransactionObj->CurrentUserHasRight('ShowTicket') ) {
        return ( $self->__Value( $field, @_ ) );
    }

    #if they ain't got rights to see, don't let em
    else {
        return (undef);
    }

}

# }}}

=head2 _SplitHeaders

Returns an array of this attachment object's headers, with one header 
per array entry. multiple lines are folded

=begin testing

my $test1 = "From: jesse";
my @headers = RT::Attachment->_SplitHeaders($test1);
is ($#headers, 0, $test1 );

my $test2 = qq{From: jesse
To: bobby
Subject: foo
};

@headers = RT::Attachment->_SplitHeaders($test2);
is ($#headers, 2, "testing a bunch of singline multiple headers" );


my $test3 = qq{From: jesse
To: bobby,
 Suzie,
    Sally,
    Joey: bizzy,
Subject: foo
};

@headers = RT::Attachment->_SplitHeaders($test3);
is ($#headers, 2, "testing a bunch of singline multiple headers" );


=end testing

=cut

sub _SplitHeaders {
    my $self = shift;
    my $headers = (shift || $self->SUPER::Headers());
    my @headers;
    for (split(/\n(?=\w|\z)/,$headers)) {
        push @headers, $_;

    }
    return(@headers);
}


sub ContentLength {
    my $self = shift;

    unless ( (($self->TransactionObj->CurrentUserHasRight('ShowTicketComments')) and
	     ($self->TransactionObj->Type eq 'Comment') )  or
	    ($self->TransactionObj->CurrentUserHasRight('ShowTicket'))) {
	return undef;
    }

    if (my $len = $self->GetHeader('Content-Length')) {
	return $len;
    }

    {
	use bytes;
	my $len = length($self->Content);
	$self->SetHeader('Content-Length' => $len);
	return $len;
    }
}

# }}}

# Transactions don't change. by adding this cache congif directiove, we don't lose pathalogically on long tickets.
sub _CacheConfig {
    {
        'cache_p'         => 1,
          'fast_update_p' => 1,
          'cache_for_sec' => 180,
    }
}

1;