summaryrefslogtreecommitdiff
path: root/fml/lib/Mail/ThreadTrack/Analyze.pm
blob: ec395f2bd5711d95c6265c7b6c223dde52ff4ab8 (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
#-*- perl -*-
#
#  Copyright (C) 2001 Ken'ichi Fukamachi
#   All rights reserved. This program is free software; you can
#   redistribute it and/or modify it under the same terms as Perl itself. 
#
# $FML: @template.pm,v 1.1 2001/08/07 12:23:48 fukachan Exp $
#

package Mail::ThreadTrack::Analyze;
use strict;
use vars qw(@ISA @EXPORT @EXPORT_OK $AUTOLOAD);
use Carp;

=head1 NAME

Mail::ThreadTrack::Analyze - analyze mail thread relation

=head1 SYNOPSIS

    my $ticket = $pkg->new($args);
    if (defined $ticket) {
	$ticket->analyze($msg);
	$ticket->rewrite_header($msg);
    }

=head1 DESCRIPTION

=head1 METHODS

=cut


=head2 C<analyze($mesg)>

C<$mesg> is Mail::Message object.

1) assign a new ticket or extract the existing ticket-id from the subject.

2) update ticket status if needed.

=cut


sub analyze
{
    my ($self, $msg) = @_;
    $self->_assign($msg);
    $self->update_ticket_status($msg);
    $self->update_db($msg);
}


=head2 assign($msg)

=cut


sub _is_reply
{
    my ($subject) = @_;

    use Mail::Message::Language::Japanese::Subject;
    return Mail::Message::Language::Japanese::Subject::is_reply($subject);
}


# Descriptions: assign a new ticket or 
#               extract the existing ticket-id from the subject
#    Arguments: $self $curproc $args
# Side Effects: a new ticket_id may be assigned
#               article header is rewritten
# Return Value: none
sub _assign
{
    my ($self, $msg) = @_;
    my $config   = $self->{ _config };
    my $header   = $msg->rfc822_message_header();
    my $subject  = $header->get('subject');
    my $pcb      = $self->{ _pcb };
    my $is_reply = _is_reply($subject);

    # 1. try to extract $ticket_id from subject: field
    my $ticket_id = $self->_extract_ticket_id_in_subject($header, $config);
    unless ($ticket_id) {
	# 1.1 hmm, we tail to but we try to speculate ticket_id 
	#     from other header information.
	$ticket_id = $self->_speculate_ticket_id($msg);
	if ($ticket_id) {
	    $is_reply = 1;
	    $self->{ _ticket_id } = $ticket_id;
	    Log("speculated id=$ticket_id");
	}
	else {
	    Log("(debug) fail to spelucate ticket_id");
	}
    }

    # 2. check "X-Ticket-Pragma:" field, 
    #    we ignore this mail if the pragma is specified as "ignore".
    if (defined $header->get('x-ticket-pragma')) {
	my $pragma = $header->get('x-ticket-pragma') || '';
	if ($pragma =~ /ignore/i) {
	    $self->{ _pragma } = 'ignore';
	    $self->_append_ticket_status_info("ignored");
	    return undef;
	}
    }
    
    # if the header carries "Subject: Re: ..." with ticket-id, 
    # we do not rewrite the subject but save the extracted $ticket_id.
    if ($is_reply && $ticket_id) {
	Log("reply message with ticket_id=$ticket_id");
	$self->{ _ticket_id } = $ticket_id;
	$self->{ _status    } = 'analyzed';
	$self->_append_ticket_status_info('analyzed');
    }
    elsif ($ticket_id) {
	Log("usual message with ticket_id=$ticket_id");
	$self->{ _ticket_id } = $ticket_id;
	$self->_append_ticket_status_info("found");
    }
    else {
	Log("message with no ticket_id");

	# assign a new ticket number for a new message
	my $id = $self->increment_id();

	# O.K. rewrite Subject: of the article to distribute
	unless ($self->error) {
	    $pcb->{'article'}->{'id'} = $id; # save $id info in PCB

	    my $header = $msg->rfc822_message_header();
	    $self->_get_ticket_id($header, $config, $id);
	    $self->_rewrite_header($header, $config, $id);
	    $self->_append_ticket_status_info("newly assigned");
	}
	else {
	    Log( $self->error );
	}
    }
}


# For example, consider a posting to both elena ML and rudo (DM) from kenken.
#
#     From: kenken 
#     To: elena-ml
#     Cc: rudo
#
# The reply to this DM (direct message) from rudo is
#
#     From: rudo
#     To: elena-ml
#
# This reply message has no ticket_id since the message from kenken to
# rudo comes directly from kenken not through fml driver.
# In this case, we try to speculdate the reply relation and the ticket_id
# of this thread by using _speculate_ticket_id().
#
sub _speculate_ticket_id
{
    my ($self, $msg) = @_;
    my $header  = $msg->rfc822_message_header();
    my $midlist = _extract_message_id_references( $header );
    my $result  = '';

    for (@$midlist) { Log("(debug) mid=$_");}

    if (defined $midlist) {
	$self->db_open();

	# prepare hash table tied to db_dir/*db's
	my $rh = $self->{ _hash_table };

	for my $mid (@$midlist) { 
	    $result = $rh->{ _message_id }->{ $mid };
	    last if $result;
	}

	$self->db_close();
    }

    Log("(debug) not speculated") unless $result;
    $result;
}


sub _append_ticket_status_info
{
    my ($self, $s) = @_;
    $self->{ _status_info } .= $self->{ _status_info } ? " -> ".$s : $s;
}


=head2 update_ticket_status($msg)

=cut


sub update_ticket_status
{
    my ($self, $msg) = @_;

    return if $self->{ _pragma } eq 'ignore';

    # entries to check
    my $header  = $msg->rfc822_message_header();
    my $subject = $header->get('subject');
    my $pragma  = $header->get('x-ticket-pragma') || '';

    my $content = '';
    my $message = $msg->get_first_plaintext_message();
    if (ref($message) eq 'Mail::Message') {
	$content = $message->data_in_body_part();
    }
    else {
	croak("invalid object");
    }

    if ($content =~ /^\s*close/ || 
	$subject =~ /^\s*close/ || 
	$pragma  =~ /close/      ) {
	$self->{ _status } = "closed";
	$self->_append_ticket_status_info("closed");
	Log("ticket is closed");
    }
    else {
	Log("ticket status not changed");
    }
}


# Descriptions: create regexp for a subject tag, for example
#               "[%s %05d]" => "\[\S+ \d+\]"
#    Arguments: a subject tag string
#               XXX non OO type function
# Side Effects: none
# Return Value: a regexp for the given tag
sub _regexp_compile
{
    my ($s) = @_;

    $s = quotemeta( $s );
    $s =~ s@\\\%@\%@g;
    $s =~ s@\%s@\\S+@g;
    $s =~ s@\%d@\\d+@g;
    $s =~ s@\%0\d+d@\\d+@g;
    $s =~ s@\%\d+d@\\d+@g;
    $s =~ s@\%\-\d+d@\\d+@g;

    # quote for regexp substitute: [ something ] -> \[ something \]
    # $s =~ s/^(.)/quotemeta($1)/e;
    # $s =~ s/(.)$/quotemeta($1)/e;

    return $s;
}


sub _extract_message_id_references
{
    my ($header) = @_;
    my $buf = 
        $header->get('in-reply-to') ."\n". $header->get('references');

    use Mail::Address;
    my @addrs = Mail::Address->parse($buf);

    my @r    = ();
    my %uniq = ();
    foreach my $addr (@addrs) { 
        my $a = $addr->address;
        unless ($uniq{ $a }) {
            push(@r, $addr->address);
            $uniq{ $a } = 1;
        }
    }

    \@r;
}


sub _extract_ticket_id_in_subject
{
    my ($self, $header, $config) = @_;
    my $tag     = $config->{ ticket_subject_tag };
    my $subject = $header->get('subject');
    my $regexp  = _regexp_compile($tag);

    # Subject: ... [ticket_id]
    if (($config->{ ticket_subject_tag_location } eq 'appended') &&
	($subject =~ /($regexp)\s*$/)) {
	my $id = $1;
	$id =~ s/^(\[|\(|\{)//;
	$id =~ s/(\]|\)|\})$//;
	return $id;
    }
    # XXX incomplete, we check subject after cutting off "Re:" et. al.
    # Subject: [ticket_id] ...
    # Subject: Re: [ticket_id] ...
    elsif (($config->{ ticket_subject_tag_location } eq 'appended') &&
	   ($subject =~ /^\s*($regexp)/)) {
	my $id = $1;
	$id =~ s/^(\[|\(|\{)//;
	$id =~ s/(\]|\)|\})$//;
	return $id;
    }
    else {
	Log("no ticket id /$regexp/ in subject");
	return 0;
    }
}


sub _get_ticket_id
{
    my ($self, $header, $config, $id) = @_;
    my $subject_tag = $config->{ ticket_subject_tag };
    my $id_syntax   = $config->{ ticket_id_syntax };

    # ticket_id in subject
    my $ticket_id = sprintf($subject_tag, $id);
    $self->{ _ticket_subject_tag } = $ticket_id;

    $ticket_id = sprintf($id_syntax, $id);
    $self->{ _ticket_id } = $ticket_id;

    return $ticket_id;
}


sub _rewrite_header
{
    my ($self, $header, $config, $id) = @_;

    # append the ticket tag to the subject
    my $subject = $header->get('subject') || '';
    $header->replace('Subject', 
		     $subject." " . $self->{ _ticket_subject_tag });
}


# clean up given C<address>.
# It parse it by C<Mail::Address::parse()> and nuke < and >.
sub _address_clean_up
{
    my ($self, $addr) = @_;

    use Mail::Address;
    my @addrlist = Mail::Address->parse($addr);

    # only the first element in the @addrlist array is effective.
    $addr = $addrlist[0]->address;
    $addr =~ s/^\s*<//;
    $addr =~ s/>\s*$//;

    # return the result.
    return $addr;
}


=head2 update_db($msg)

=cut


sub update_db
{
    my ($self, $msg) = @_;
    my $config  = $self->{ _config };
    my $ml_name = $config->{ ml_name };

    return if $self->{ _pragma } eq 'ignore';

    $self->db_open();

    # save $ticke_id et.al. in db_dir/$ml_name
    $self->_update_db($msg);

    # save cross reference pointers among $ml_name
    $self->_update_index_db();

    $self->db_close();
}


sub _update_db
{
    my ($self, $msg) = @_;
    my $config     = $self->{ _config };
    my $pcb        = $self->{ _pcb };
    my $article_id = $pcb->{'article'}->{'id'};
    my $ticket_id  = $self->{ _ticket_id };

    # 0. logging
    Log("article_id=$article_id ticket_id=$ticket_id");

    # prepare hash table tied to db_dir/*db's
    my $rh = $self->{ _hash_table };

    # 1. 
    $rh->{ _ticket_id }->{ $article_id }  = $ticket_id;
    $rh->{ _date      }->{ $article_id }  = time;
    $rh->{ _articles  }->{ $ticket_id  } .= $article_id . " ";

    # 2. record the sender information
    my $header = $msg->rfc822_message_header;
    $rh->{ _sender }->{ $article_id } = $header->get('from');

    # 3. update status information
    if (defined $self->{ _status }) {
	$self->_set_status($ticket_id, $self->{ _status });
    }
    else {
	# set the default status value for the first time.
	unless (defined $rh->{ _status }->{ $ticket_id }) {
	    $self->_set_status($ticket_id, 'open');
	}
    }

    # 4. save optional/additional information
    #    message_id hash is { message_id => ticket_id };
    my $mid = $header->get('message-id');
    $mid    = $self->_address_clean_up($mid);
    $rh->{ _message_id }->{ $mid } = $ticket_id;

    # 5. history
    my $buf    = '';
    my (@aid)  = split(/\s+/, $rh->{ _articles  }->{ $ticket_id });
    my $sender = $rh->{ _sender }->{ $aid[0] };
    my $when   = $rh->{ _date }->{ $aid[0] };

    # clean up
    $sender =~ s/[\s\n]*$//;
    $when   =~ s/[\s\n]*$//;

    use Mail::Message::Date;
    $when = Mail::Message::Date->new($when)->mail_header_style();
    
    $buf .= "\t\n";
    $buf .= "\tthis ticket/thread is opended at article $aid[0]\n";
    $buf .= "\tby $sender\n";
    $buf .= "\ton $when\n";
    $buf .= "\tarticle references: @aid\n";
    $self->{ _status_history } = $buf;
}


# register myself to index_db for further reference among mailing lists
sub _update_index_db
{
    my ($self) = @_;
    my $config    = $self->{ _config };
    my $ticket_id = $self->{ _ticket_id };
    my $rh        = $self->{ _hash_table };
    my $ml_name   = $config->{ ml_name };

    my $ref = $rh->{ _index }->{ $ticket_id } || '';
    if ($ref !~ /^$ml_name|\s$ml_name\s|$ml_name$/) {
	$rh->{ _index }->{ $ticket_id } .= $ml_name." ";
    }
}


=head2 C<set_status($args)>

set $status for $ticket_id. It rewrites DB (file).
C<$args>, HASH reference, must have two keys.

    $args = {
	ticket_id => $ticket_id,
	status    => $status,
    }

C<set_status()> calls db_open() an db_close() automatically within it.

=cut


# Descriptions: 
#    Arguments: $self $curproc $args
# Side Effects: 
# Return Value: none
sub set_status
{
    my ($self, $args) = @_;
    my $ticket_id = $args->{ ticket_id };
    my $status    = $args->{ status };

    Log("ticket.set_status($ticket_id, $status)");

    $self->db_open();
    $self->_set_status($ticket_id, $status);
    $self->db_close();
}


sub _set_status
{
    my ($self, $ticket_id, $value) = @_;
    $self->{ _hash_table }->{ _status }->{ $ticket_id } = $value;
}


sub Log
{
    print STDERR "Log> @_\n";
}


=head1 AUTHOR

Ken'ichi Fukamachi

=head1 COPYRIGHT

Copyright (C) 2001 Ken'ichi Fukamachi

All rights reserved. This program is free software; you can
redistribute it and/or modify it under the same terms as Perl itself. 

=head1 HISTORY

Mail::ThreadTrack::Analyze appeared in fml5 mailing list driver package.
See C<http://www.fml.org/> for more details.

=cut


1;