/[suikacvs]/test/cvs
Suika

Diff of /test/cvs

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.10 by wakaba, Tue Mar 26 05:41:16 2002 UTC revision 1.26 by wakaba, Sun Jun 16 10:45:54 2002 UTC
# Line 1  Line 1 
1    
2  =head1 NAME  =head1 NAME
3    
4  Message::Header Perl module  Message::Header --- A Perl Module for Internet Message Headers
   
 =head1 DESCRIPTION  
   
 Perl module for RFC 822/2822 message C<header>.  
5    
6  =cut  =cut
7    
8  package Message::Header;  package Message::Header;
9  use strict;  use strict;
10  use vars qw($VERSION %REG %DEFAULT);  use vars qw(%DEFAULT @ISA %REG $VERSION);
11  $VERSION = '1.00';  $VERSION=do{my @r=(q$Revision$=~/\d+/g);sprintf "%d."."%02d" x $#r,@r};
12    require Message::Field::Structured;     ## This may seem silly:-)
13    push @ISA, qw(Message::Field::Structured);
14    
15    %REG = %Message::Util::REG;
16            $REG{M_field} = qr/^([^\x3A]+):$REG{FWS}([\x00-\xFF]*)$/;
17            $REG{M_fromline} = qr/^\x3E?From$REG{WSP}+([\x00-\xFF]*)$/;
18            $REG{ftext} = qr/[\x21-\x39\x3B-\x7E]+/;        ## [2]822
19            $REG{NON_ftext} = qr/[^\x21-\x39\x3B-\x7E]/;    ## [2]822
20            $REG{NON_ftext_usefor} = qr/[^0-9A-Za-z-]/;     ## name-character
21            $REG{NON_ftext_http} = $REG{NON_http_token};
22    
23    ## Namespace support
24            our %NS_phname2uri;     ## PH-namespace name -> namespace URI
25            our %NS_uri2phpackage;  ## namespace URI -> PH-package name
26            require Message::Header::Default;       ## Default namespace
27    
28  use overload '@{}' => sub {shift->_delete_empty_field()->{field}},  ## Initialize of this class -- called by constructors
29               '""' => sub {shift->stringify};  %DEFAULT = (
30        -_HASH_NAME => 'value',
31        -_METHODS   => [qw|field field_exist field_type add replace count delete subject id is|],
32        -_MEMBERS   => [qw|value|],
33        -_VALTYPE_DEFAULT   => ':default',
34        -by => 'name',      ## (Reserved for method level option)
35        -field_format_pattern       => '%s: %s',
36        -field_name_case_sensible   => 0,
37        -field_name_unsafe_rule     => 'NON_ftext',
38        -field_name_validation      => 1,   ## Method level option.
39        -field_sort => 0,
40        #-format    => 'mail-rfc2822',
41        -linebreak_strict   => 0,   ## Not implemented completely
42        -line_length_max    => 60,  ## For folding
43        #ns_default_phuri
44        -output_bcc => 0,
45        -output_folding     => 1,
46        -output_mail_from   => 0,
47        #-parse_all => 0,
48        -translate_underscore       => 1,
49        #-uri_mailto_safe
50        -uri_mailto_safe_level      => 4,
51        -use_folding        => 1,
52        #-value_type
53    );
54    
55  $REG{WSP}     = qr/[\x09\x20]/;  $DEFAULT{-value_type} = {
56  $REG{FWS}     = qr/[\x09\x20]*/;          ':default'      => ['Message::Field::Unstructured'],
57  $REG{M_field} = qr/^([^\x3A]+):$REG{FWS}([\x00-\xFF]*)$/;          
58  $REG{M_fromline} = qr/^\x3E?From$REG{WSP}+([\x00-\xFF]*)$/;          p3p     => ['Message::Field::Params'],
59  $REG{UNSAFE_field_name} = qr/[\x00-\x20\x3A\x7F-\xFF]/;          link    => ['Message::Field::ValueParams'],
60            
61            'user-agent'    => ['Message::Field::UA'],
62            server  => ['Message::Field::UA'],
63    };
64    for (qw(date expires))
65      {$DEFAULT{-value_type}->{$_} = ['Message::Field::Date']}
66    for (qw(accept accept-charset accept-encoding accept-language uri))
67      {$DEFAULT{-value_type}->{$_} = ['Message::Field::CSV']}
68    for (qw(location referer))
69      {$DEFAULT{-value_type}->{$_} = ['Message::Field::URI']}
70    
71    my %header_goodcase = (
72            'article-i.d.'  => 'Article-I.D.',
73            etag    => 'ETag',
74            'pics-label'    => 'PICS-Label',
75            te      => 'TE',
76            url     => 'URL',
77            'www-authenticate'      => 'WWW-Authenticate',
78    );
79    
80  =head2 options  ## taken from L<HTTP::Header>
81    # "Good Practice" order of HTTP message headers:
82    #    - General-Headers
83    #    - Request-Headers
84    #    - Response-Headers
85    #    - Entity-Headers
86    # (From draft-ietf-http-v11-spec-rev-01, Nov 21, 1997)
87    my @header_order = qw(
88      mail-from x-envelope-from relay-version path status
89    
90       cache-control connection date pragma transfer-encoding upgrade trailer via
91    
92       accept accept-charset accept-encoding accept-language
93       authorization expect from host
94       if-modified-since if-match if-none-match if-range if-unmodified-since
95       max-forwards proxy-authorization range referer te user-agent
96    
97       accept-ranges age location proxy-authenticate retry-after server vary
98       warning www-authenticate
99    
100       mime-version
101       allow content-base content-encoding content-language content-length
102       content-location content-md5 content-range content-type
103       etag expires last-modified content-style-type content-script-type
104       link
105    
106  These options can be getten/set by C<get_option>/C<set_option>    xref
107  method.  );
108    my %header_order;
109    
110  =head3 capitalize = 0/1  =head1 CONSTRUCTORS
111    
112  (First character of) C<field-name> is capitalized  The following methods construct new C<Message::Header> objects:
 when C<stringify>.  (Default = 1)  
113    
114  =head3 fold_length = numeric value  =over 4
115    
116  Length of line used to fold.  (Default = 70)  =cut
117    
118  =head3 mail_from = 0/1  sub _init ($;%) {
119      my $self = shift;
120      my %options = @_;
121      my $DEFAULT = Message::Util::make_clone (\%DEFAULT);
122      $self->SUPER::_init (%$DEFAULT, %options);
123      $self->{value} = [];
124      $self->_ns_load_ph ('default');
125      $self->_ns_load_ph ('rfc822');
126      $self->{option}->{ns_default_phuri} = $self->{ns}->{phname2uri}->{'rfc822'}
127        unless $self->{option}->{ns_default_phuri};
128      
129      my @new_fields = ();
130      for my $name (keys %options) {
131        unless (substr ($name, 0, 1) eq '-') {
132          push @new_fields, ($name => $options{$name});
133        }
134      }
135      $self->_init_by_format ($self->{option}->{format}, $self->{option});
136      # Make alternative representations of @header_order.  This is used
137      # for sorting.
138      my $i = 1;
139      for (@header_order) {
140          $header_order{$_} = $i++ unless $header_order{$_};
141      }
142      
143      $self->add (@new_fields, -parse => $self->{option}->{parse_all})
144        if $#new_fields > -1;
145    }
146    
147    sub _init_by_format ($$\%) {
148      my $self = shift;
149      my ($format, $option) = @_;
150      if ($format =~ /cgi/) {
151        unshift @header_order, qw(content-type location);
152        $option->{field_sort} = 'good-practice';
153        $option->{use_folding} = 0;
154      } elsif ($format =~ /http/) {
155        $option->{field_sort} = 'good-practice';
156      }
157      if ($format =~ /uri-url-mailto/) {
158        $option->{output_bcc} = 0;
159        $option->{field_format_pattern} = '%s=%s';
160        $option->{output_folding} = sub {
161          $_[1] =~ s/([^:@+\$A-Za-z0-9\-_.!~*])/sprintf('%%%02X', ord $1)/ge;
162          $_[1];
163        };  ## Yes, this is not folding!
164      }
165    }
166    
167  Outputs "From " line (known as Un*x From, Mail-From, and so on)  =item $msg = Message::Header->new ([%initial-fields/options])
168  when C<stringify>.  (Default = 0)  
169    Constructs a new C<Message::Headers> object.  You might pass some initial
170    C<field-name>-C<field-body> pairs and/or options as parameters to the constructor.
171    
172    Example:
173    
174     $hdr = new Message::Headers
175            Date         => 'Thu, 03 Feb 1994 00:00:00 +0000',
176            Content_Type => 'text/html',
177            Content_Location => 'http://www.foo.example/',
178            -format => 'mail-rfc2822'       ## not to be header field
179            ;
180    
181  =cut  =cut
182    
183  %DEFAULT = (  ## Inherited
   capitalize    => 1,  
   fold_length   => 70,  
   field_type    => {':DEFAULT' => 'Message::Field::Unstructured'},  
   mail_from     => -1,  
   output_bcc    => -1,  
   parse_all     => -1,  
 );  
 my @field_type_Structured = qw(cancel-lock  
   importance mime-version path precedence x-cite  
   x-face x-mail-count x-msmail-priority x-priority x-uidl xref);  
 for (@field_type_Structured)  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Structured'}  
 my @field_type_Address = qw(approved bcc cc delivered-to disposition-notification-to  
   envelope-to  
   errors-to fcc from mail-followup-to mail-followup-cc mail-from reply-to resent-bcc  
   resent-cc resent-to resent-from resent-sender return-path  
   return-receipt-to sender to x-approved x-beenthere  
   x-complaints-to x-envelope-from x-envelope-sender  
   x-envelope-to x-ml-address x-ml-command x-ml-to x-nfrom x-nto);  
 for (@field_type_Address)  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Address'}  
 my @field_type_Date = qw(date date-received delivery-date expires  
   expire-date nntp-posting-date posted reply-by resent-date x-tcup-date);  
 for (@field_type_Date)  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Date'}  
 my @field_type_MsgID = qw(content-id in-reply-to message-id  
   references resent-message-id see-also supersedes);  
 for (@field_type_MsgID)  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::MsgID'}  
 for (qw(received x-received))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Received'}  
 $DEFAULT{field_type}->{'content-type'} = 'Message::Field::ContentType';  
 $DEFAULT{field_type}->{'content-disposition'} = 'Message::Field::ContentDisposition';  
 for (qw(x-face-type))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::ValueParams'}  
 for (qw(accept accept-charset accept-encoding accept-language  
   content-language  
   content-transfer-encoding encrypted followup-to keywords newsgroups  
   x-brother x-daughter x-respect x-moe x-syster x-wife))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::CSV'}  
 my @field_type_URI = qw(list-archive list-help list-owner  
   list-post list-subscribe list-unsubscribe uri url x-home-page x-http_referer  
   x-info x-pgp-key x-ml-url x-uri x-url x-web);  
 for (@field_type_URI)  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Structured'}  
 for (qw(list-id))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Structured'}  
 for (qw(subject title x-nsubject))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Subject'}  
 for (qw(list-software user-agent server))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::UA'}  
184    
185  =head2 Message::Header->new ([%option])  =item $msg = Message::Header->parse ($header, [%initial-fields/options])
186    
187  Returns new Message::Header instance.  Some options can be  Parses given C<header> and constructs a new C<Message::Headers>
188  specified as hash.  object.  You might pass some additional C<field-name>-C<field-body> pairs
189    or/and initial options as parameters to the constructor.
190    
191  =cut  =cut
192    
193  sub new ($;%) {  sub parse ($$;%) {
194    my $class = shift;    my $class = shift;
195    my $self = bless {option => {@_}}, $class;    my $header = shift;
196    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}    my $self = bless {}, $class;
197      $self->_init (@_);    ## BUG: don't check linebreak_strict
198      $header =~ s/\x0D?\x0A$REG{WSP}/\x20/gos if $self->{option}->{use_folding};
199      for my $field (split /\x0D?\x0A/, $header) {
200        if ($field =~ /$REG{M_fromline}/) {
201          my ($s,undef,$value) = $self->_value_to_arrayitem
202            ('mail-from' => $1, $self->{option});
203          push @{$self->{value}}, $value if $s;
204        } elsif ($field =~ /$REG{M_field}/) {
205          my ($name, $body) = ($1, $2);
206          $body =~ s/$REG{WSP}+$//;
207          my ($s,undef,$value) = $self->_value_to_arrayitem
208            ($name => $body, $self->{option});
209          push @{$self->{value}}, $value if $s;
210        } elsif (length $field) {
211          my ($s,undef,$value) = $self->_value_to_arrayitem
212            ('x-unknown' => $field, $self->{option});
213          push @{$self->{value}}, $value if $s;
214        }
215      }
216    $self;    $self;
217  }  }
218    
219  =head2 Message::Header->parse ($header, [%option])  =item $msg = Message::Header->parse_array (\@header, [%initial-fields/options])
220    
221  Parses given C<header> and return a new Message::Header  Parses given C<header> and constructs a new C<Message::Headers>
222  object.  Some options can be specified as hash.  object.  Same as C<Message::Header-E<lt>parse> but this method
223    is given an array reference.  You might pass some additional
224    C<field-name>-C<field-body> pairs or/and initial options
225    as parameters to the constructor.
226    
227  =cut  =cut
228    
229  sub parse ($$;%) {  sub parse_array ($\@;%) {
230    my $class = shift;    my $class = shift;
231    my $header = shift;    my $header = shift;
232    my $self = bless {option => {@_}}, $class;    Carp::croak "parse_array: first argument is not an array reference"
233    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}      unless ref $header eq 'ARRAY';
234    $header =~ s/\x0D?\x0A$REG{WSP}+/\x20/gos;    ## unfold    my $self = bless {}, $class;
235    for my $field (split /\x0D?\x0A/, $header) {    $self->_init (@_);
236      while (1) {
237        my $field = shift @$header;
238        if ($self->{option}->{use_folding}) {
239          while (1) {
240            if ($$header[0] =~ /^$REG{WSP}/) {
241              $field .= shift @$header;
242            } else {last}
243          }
244        }
245        if ($self->{option}->{linebreak_strict}) {
246          $field =~ s/\x0D\x0A//g;
247        } else {
248          $field =~ tr/\x0D\x0A//d;
249        }
250        local $self->{option}->{parse} = $self->{option}->{parse_all};
251      if ($field =~ /$REG{M_fromline}/) {      if ($field =~ /$REG{M_fromline}/) {
252        my $body = $1;        my ($s,undef,$value) = $self->_value_to_arrayitem
253        $body = $self->_field_body ($body, 'mail-from')          ('mail-from' => $1, $self->{option});
254          if $self->{option}->{parse_all}>0;        push @{$self->{value}}, $value if $s;
       push @{$self->{field}}, {name => 'mail-from', body => $body};  
255      } elsif ($field =~ /$REG{M_field}/) {      } elsif ($field =~ /$REG{M_field}/) {
256        my ($name, $body) = (lc $1, $2);        my ($name, $body) = ($self->_n11n_field_name ($1), $2);
       $name =~ s/$REG{WSP}+$//;  
257        $body =~ s/$REG{WSP}+$//;        $body =~ s/$REG{WSP}+$//;
258        $body = $self->_field_body ($body, $name) if $self->{option}->{parse_all}>0;        my ($s,undef,$value) = $self->_value_to_arrayitem
259        push @{$self->{field}}, {name => $name, body => $body};          ($name => $body, $self->{option});
260          push @{$self->{value}}, $value if $s;
261        } elsif (length $field) {
262          my ($s,undef,$value) = $self->_value_to_arrayitem
263            ('x-unknown' => $field, $self->{option});
264          push @{$self->{value}}, $value if $s;
265      }      }
266        last if $#$header < 0;
267    }    }
268    $self;    $self;
269  }  }
270    
271    =back
272    
273    =head1 METHODS
274    
275  =head2 $self->field ($field_name)  =head2 $self->field ($field_name)
276    
277  Returns C<field-body> of given C<field-name>.  Returns C<field-body> of given C<field-name>.
# Line 150  context, only first one is returned.) Line 281  context, only first one is returned.)
281    
282  =cut  =cut
283    
284  sub field ($$) {  sub field ($@) {shift->SUPER::item (@_)}
285    sub field_exist ($@) {shift->SUPER::item_exist (@_)}
286    
287    ## item-by?, \$checked-item, {item-key => 1}, \%option
288    sub _item_match ($$\$\%\%) {
289    my $self = shift;    my $self = shift;
290    my $name = lc shift;    my ($by, $i, $list, $option) = @_;
291    my @ret;    return 0 unless ref $$i;  ## Already removed
292    for my $field (@{$self->{field}}) {    if ($by eq 'name') {
293      if ($field->{name} eq $name) {      my %o = %$option; $o{parse} = 0;
294        unless (wantarray) {      my %l;
295          $field->{body} = $self->_field_body ($field->{body}, $name);      for (keys %$list) {
296          return $field->{body};        my ($s, undef, $v) = $self->_value_to_arrayitem ($_, '', %o);
297          if ($s) {
298            $l{$v->{name} . ':' . ( $option->{ns} || $v->{ns} ) } = 1;
299        } else {        } else {
300          $field->{body} = $self->_field_body ($field->{body}, $name);          $l{$v->{name} .':'. ( $option->{ns} || $self->{option}->{ns_default_phuri} ) } = 1;
         push @ret, $field->{body};  
301        }        }
302      }      }
303        return 1 if $l{$$i->{name} . ':' . $$i->{ns}};
304      } elsif ($by eq 'ns') {
305        return 1 if $list->{ $$i->{ns} };
306    }    }
307    if ($#ret < 0) {    0;
     return $self->add ($name);  
   }  
   @ret;  
308  }  }
309    *_delete_match = \&_item_match;
310    
311  sub field_exist ($$) {  ## Returns returned item value    \$item-value, \%option
312    my $self = shift;  sub _item_return_value ($\$\%) {
313    my $name = lc shift;    if (ref ${$_[1]}->{body}) {
314    my @ret;      ${$_[1]}->{body};
315    for my $field (@{$self->{field}}) {    } else {
316      return 1 if ($field->{name} eq $name);      ${$_[1]}->{body} = $_[0]->_parse_value (${$_[1]}->{name} => ${$_[1]}->{body},
317          ns => ${$_[1]}->{ns});
318        ${$_[1]}->{body};
319    }    }
   0;  
320  }  }
321    *_add_return_value = \&_item_return_value;
322    *_replace_return_value = \&_item_return_value;
323    
324  =head2 $self->field_name ($index)  ## Returns returned (new created) item value    $name, \%option
325    sub _item_new_value ($$\%) {
326  Returns C<field-name> of $index'th C<field>.      my ($s,undef,$value) = $_[0]->_value_to_arrayitem
327            ($_[1] => '', $_[2]);
328  =head2 $self->field_body ($index)      $s? $value: undef;
329    }
330    
 Returns C<field-body> of $index'th C<field>.  
331    
 =cut  
332    
333  sub field_name ($$) {  ## $self->_parse_value ($type, $value, %options);
334    sub _parse_value ($$$;%) {
335    my $self = shift;    my $self = shift;
336    $self->{field}->[shift]->{name};    my $name = shift ;#|| $self->{option}->{_VALTYPE_DEFAULT};
337  }    my $value = shift;  return $value if ref $value;
338  sub field_body ($$) {    my %option = @_;
339    my $self = shift;    my $vtype; { no strict 'refs';
340    my $i = shift;      my $vt = ${&_NS_uri2phpackage ($option{ns}).'::OPTION'}{value_type};
341    $self->{field}->[$i]->{body}      if (ref $vt) {
342     = $self->_field_body ($self->{field}->[$i]->{body}, $self->{field}->[$i]->{name});        $vtype = $vt->{$name} || $vt->{$self->{option}->{_VALTYPE_DEFAULT}};
   $self->{field}->[$i]->{body};  
 }  
   
 sub _field_body ($$$) {  
   my $self = shift;  
   my ($body, $name) = @_;  
   unless (ref $body) {  
     my $type = $self->{option}->{field_type}->{$name}  
             || $self->{option}->{field_type}->{':DEFAULT'};  
     eval "require $type";  
     unless ($body) {  
       $body = $type->new (field_name => $name);  
     } else {  
       $body = $type->parse ($body, field_name => $name);  
343      }      }
344        ## For compatiblity.
345        unless (ref $vtype) { $vtype = $self->{option}->{value_type}->{$name}
346          || $self->{option}->{value_type}->{$self->{option}->{_VALTYPE_DEFAULT}} }
347      }
348      my $vpackage = $vtype->[0];
349      my %vopt = %{$vtype->[1]} if ref $vtype->[1];
350      if ($vpackage eq ':none:') {
351        return $value;
352      } elsif (defined $value) {
353        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
354        return $vpackage->parse ($value,
355          -format   => $self->{option}->{format},
356          -field_ns => $option{ns},
357          -field_name       => $name,
358          -parse_all        => $self->{option}->{parse_all},
359        %vopt);
360      } else {
361        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
362        return $vpackage->new (
363          -format   => $self->{option}->{format},
364          -field_ns => $option{ns},
365          -field_name       => $name,
366          -parse_all        => $self->{option}->{parse_all},
367        %vopt);
368    }    }
   $body;  
369  }  }
370    
371  =head2 $self->field_name_list ()  =head2 $self->field_name_list ()
# Line 229  returns ALL names.) Line 378  returns ALL names.)
378    
379  sub field_name_list ($) {  sub field_name_list ($) {
380    my $self = shift;    my $self = shift;
381    $self->_delete_empty_field ();    $self->_delete_empty ();
382    map {$_->{name}} @{$self->{field}};    map { $_->{name} . ':' . $_->{ns} } @{$self->{value}};
383  }  }
384    
385  =head2 $self->add ($field_name, $field_body)  sub namespace_ph_default ($;$) {
386      my $self = shift;
387      if (defined $_[0]) {
388        no strict 'refs';
389        $self->{option}->{ns_default_phuri} = $_[0];
390        $self->_ns_load_ph (${&_NS_uri2phpackage ($self->{option}->{ns_default_phuri}).'::OPTION'}{namespace_phname});
391      }
392      $self->{option}->{ns_default_phuri};
393    }
394    
395    =item $hdr->add ($field-name, $field-body, [$name, $body, ...])
396    
397    Adds some field name/body pairs.  Even if there are
398    one or more fields named given C<$field-name>,
399    given name/body pairs are ADDed.  Use C<replace>
400    to remove same-name-fields.
401    
402  Adds an new C<field>.  It is not checked whether  Instead of field name-body pair, you might pass some options.
403  the field which named $field_body is already exist or not.  Four options are available for this method.
404  If you don't want duplicated C<field>s, use C<replace> method.  
405    C<-parse>: Parses and validates C<field-body>, and returns
406    C<field-body> object.  (When multiple C<field-body>s are
407    added, returns only last one.)  (Default: C<defined wantarray>)
408    
409    C<-prepend>: New fields are not appended,
410    but prepended to current fields.  (Default: C<0>)
411    
412    C<-translate-underscore>: Do C<field-name> =~ tr/_/-/.  (Default: C<1>)
413    
414    C<-validate>: Checks whether C<field-name> is valid or not.
415    
416  =cut  =cut
417    
418  sub add ($$;$%) {  ## [Name: Value] pair -> internal array item
419    ## $self->_value_to_arrayitem ($name => $value, {%options})
420    ## or
421    ## $self->_value_to_arrayitem ($name => [$value, %value_options], {%options})
422    ##
423    ## Return: ((1 = success / 0 = failue), $full_name, $arrayitem)
424    sub _value_to_arrayitem ($$$\%) {
425    my $self = shift;    my $self = shift;
426    my ($name, $body) = (lc shift, shift);    my ($name, $value, $option) = @_;
427    my %option = @_;    my $value_option = {};
428    return 0 if $name =~ /$REG{UNSAFE_field_name}/;    if (ref $value eq 'ARRAY') {
429    $body = $self->_field_body ($body, $name);      ($value, %$value_option) = @$value;
430    if ($option{prepend}) {    }
431      unshift @{$self->{field}}, {name => $name, body => $body};    my $nsuri = $self->{option}->{ns_default_phuri};
432    } else {    
433      push @{$self->{field}}, {name => $name, body => $body};    no strict 'refs';
434      if ($value_option->{ns}) {
435        $nsuri = $value_option->{ns};
436      } elsif ($option->{ns}) {
437        $nsuri = $option->{ns};
438      } elsif ($name =~ s/^([Xx]-[A-Za-z]+|[A-Za-z]+)-//) {
439        my $oprefix = $1;
440        my $prefix
441          = &{${&_NS_uri2phpackage ($nsuri).'::OPTION'}{n11n_prefix}}
442            ($self, &_NS_uri2phpackage ($nsuri), $oprefix);
443        $self->_ns_load_ph ($prefix);
444        $nsuri = $self->{ns}->{phname2uri}->{$prefix};
445        unless ($nsuri) {
446          $name = $oprefix . '-' . $name;
447          $nsuri = $self->{option}->{ns_default_phuri};
448        }
449    }    }
450    $body;    $name
451        = &{${&_NS_uri2phpackage ($nsuri).'::OPTION'}{n11n_name}}
452          ($self, &_NS_uri2phpackage ($nsuri), $name);
453      Carp::croak "$name: invalid field-name"
454        if $option->{field_name_validation}
455          && $name =~ /$REG{$option->{field_name_unsafe_rule}}/;
456      $value = $self->_parse_value ($name => $value, ns => $nsuri)
457        if $$option{parse} || $$option{parse_all};
458      $$option{parse} = 0;
459      (1, $name.':'.$nsuri => {name => $name, body => $value, ns => $nsuri});
460  }  }
461    *_add_hash_check = \&_value_to_arrayitem;
462    *_replace_hash_check = \&_value_to_arrayitem;
463    
464  =head2 $self->relace ($field_name, $field_body)  =head2 $self->relace ($field_name, $field_body)
465    
# Line 265  first one is used and the others are not Line 471  first one is used and the others are not
471    
472  =cut  =cut
473    
474  sub replace ($$$) {  sub _replace_hash_shift ($\%$\%) {
475    my $self = shift;    shift; my $r = shift;  my $n = $_[0]->{name} . ':' . $_[0]->{ns};
476    my ($name, $body) = (lc shift, shift);    if ($$r{$n}) {
477    return 0 if $name =~ /$REG{UNSAFE_field_name}/;      my $d = $$r{$n};
478    $body = $self->_field_body ($body, $name);      delete $$r{$n};
479    for my $field (@{$self->{field}}) {      return $d;
     if ($field->{name} eq $name) {  
       $field->{body} = $body;  
       return $body;  
     }  
480    }    }
481    push @{$self->{field}}, {name => $name, body => $body};    undef;
   $body;  
482  }  }
483    
484  =head2 $self->delete ($field_name, [$index])  =head2 $self->delete ($field-name, [$name, ...])
485    
486  Deletes C<field> named as $field_name.  Deletes C<field> named as $field_name.
 If $index is specified, only $index'th C<field> is deleted.  
 If not, ($index == 0), all C<field>s that have the C<field-name>  
 $field_name are deleted.  
487    
488  =cut  =cut
489    
 sub delete ($$;$) {  
   my $self = shift;  
   my ($name, $index) = (lc shift, shift);  
   my $i = 0;  
   for my $field (@{$self->{field}}) {  
     if ($field->{name} eq $name) {  
       $i++;  
       if ($index == 0 || $i == $index) {  
         undef $field;  
         return $self if $i == $index;  
       }  
     }  
   }  
   $self;  
 }  
490    
491  =head2 $self->count ([$field_name])  =head2 $self->count ([$field_name])
492    
# Line 313  of fields.  (Same as $#$self+1) Line 496  of fields.  (Same as $#$self+1)
496    
497  =cut  =cut
498    
499  sub count ($;$) {  sub _count_by_name ($$\%) {
500    my $self = shift;    my $self = shift;
501    my ($name) = (lc shift);    my ($array, $option) = @_;
502    unless ($name) {    my $name = $self->_n11n_field_name ($$option{-name});
503      $self->_delete_empty_field ();    my @a = grep {$_->{name} eq $name} @{$self->{$array}};
504      return $#{$self->{field}}+1;    $#a + 1;
   }  
   my $count = 0;  
   for my $field (@{$self->{field}}) {  
     if ($field->{name} eq $name) {  
       $count++;  
     }  
   }  
   $count;  
505  }  }
506    
507  =head2 $self->stringify ([%option])  ## Delete empty items
508    sub _delete_empty ($) {
509      my $self = shift;
510      my $array = $self->{option}->{_HASH_NAME};
511      $self->{$array} = [grep {ref $_ && length $_->{name}} @{$self->{$array}}];
512    }
513    
514  Returns the C<header> as a string.  =head2 $self->rename ($field-name, $new-name, [$old, $new,...])
515    
516    Renames C<$field-name> as C<$new-name>.
517    
518  =cut  =cut
519    
520  sub stringify ($;%) {  sub rename ($%) {
521    my $self = shift;    my $self = shift;
522    my %OPT = @_;    my %params = @_;
523    my @ret;    my %option = %{$self->{option}};
524    $OPT{capitalize} ||= $self->{option}->{capitalize};    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
525    $OPT{mail_from} ||= $self->{option}->{mail_from};    my %new_name;
526    $OPT{output_bcc} ||= $self->{option}->{output_bcc};    for (grep {/^[^-]/} keys %params) {
527    push @ret, 'From '.$self->field ('mail-from') if $OPT{mail_from}>0;      my ($old => $new)
528    for my $field (@{$self->{field}}) {        = ($self->_n11n_field_name ($_) => $self->_n11n_field_name ($params{$_}));
529      my $name = $field->{name};      $old =~ tr/_/-/ if $option{translate_underscore};
530      next unless $name;      $new =~ tr/_/-/ if $option{translate_underscore};
531      next if $OPT{mail_from}<0 && $name eq 'mail-from';      Carp::croak "rename: $new: invalid field-name"
532      next if $OPT{output_bcc}<0 && ($name eq 'bcc' || $name eq 'resent-bcc');        if $option{field_name_validation}
533      my $fbody = scalar $field->{body};          && $new =~ /$REG{$option{field_name_unsafe_rule}}/;
534      next unless $fbody;      $new_name{$old} = $new;
535      $fbody =~ s/\x0D([^\x09\x0A\x20])/\x0D\x20$1/g;    }
536      $fbody =~ s/\x0A([^\x09\x20])/\x0A\x20$1/g;    for my $field (@{$self->{value}}) {
537      $name =~ s/((?:^|-)[a-z])/uc($1)/ge if $OPT{capitalize};      if (length $new_name{$field->{name}}) {
538      push @ret, $name.': '.$self->fold ($fbody);        $field->{name} = $new_name{$field->{name}};
539        }
540    }    }
541    my $ret = join ("\n", @ret);    $self if defined wantarray;
   $ret? $ret."\n": "";  
542  }  }
543    
 =head2 $self->get_option ($option_name)  
544    
545  Returns value of the option.  =item $self->scan(\&doit)
546    
547  =head2 $self->set_option ($option_name, $option_value)  Apply a subroutine to each header field in turn.  The callback routine is
548    called with two parameters; the name of the field and a single value.
549  Set new value of the option.  If the header has more than one value, then the routine is called once
550    for each value.
551    
552  =cut  =cut
553    
554  sub get_option ($$) {  sub _scan_sort ($\@\%) {
555    my $self = shift;    my $self = shift;
556    my ($name) = @_;    my ($array, $option) = @_;
557    $self->{option}->{$name};    my $sort;
558      $sort = \&_header_cmp if $option->{field_sort} eq 'good-practice';
559      $sort = {$a cmp $b} if $option->{field_sort} eq 'alphabetic';
560      return ( sort $sort @$array ) if ref $sort;
561      @$array;
562  }  }
563  sub set_option ($$$) {  
564    sub _n11n_field_name ($$) {
565    my $self = shift;    my $self = shift;
566    my ($name, $value) = @_;    my $s = shift;
567    $self->{option}->{$name} = $value;    $s =~ s/^$REG{WSP}+//; $s =~ s/$REG{WSP}+$//;
568    $self;    $s = lc $s unless ${&_NS_uri2phpackage ($self->{option}->{ns_default_phuri}).'::OPTION'}{case_sensible};
569      $s;
570  }  }
571    
572  sub field_type ($$;$) {  # Compare function which makes it easy to sort headers in the
573    # recommended "Good Practice" order.
574    ## taken from HTTP::Header
575    sub _header_cmp
576    {
577      my ($na, $nb) = ($a->{name}, $b->{name});
578        # Unknown headers are assign a large value so that they are
579        # sorted last.  This also helps avoiding a warning from -w
580        # about comparing undefined values.
581        $header_order{$na} = 999 unless defined $header_order{$na};
582        $header_order{$nb} = 999 unless defined $header_order{$nb};
583    
584        $header_order{$na} <=> $header_order{$nb} || $na cmp $nb;
585    }
586    
587    =head2 $self->stringify ([%option])
588    
589    Returns the C<header> as a string.
590    
591    =cut
592    
593    sub stringify ($;%) {
594    my $self = shift;    my $self = shift;
595    my $field_name = shift;    my %params = @_;
596    my $new_field_type = shift;    my %option = %{$self->{option}};
597    if ($new_field_type) {    $option{format} = $params{-format} if $params{-format};
598      $self->{option}->{field_type}->{$field_name} = $new_field_type;    $self->_init_by_format ($option{format}, \%option);
599      for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
600      my @ret;
601      my $_stringify = sub {
602        no strict 'refs';
603          my ($name, $body, $nsuri) = ($_[1]->{name}, $_[1]->{body}, $_[1]->{ns});
604          return unless length $name;
605          return if $option{output_mail_from} && $name eq 'mail-from';
606          return if !$option{output_bcc} && ($name eq 'bcc' || $name eq 'resent-bcc');
607          my $nspackage = &_NS_uri2phpackage ($nsuri);
608          my $oname;        ## Outputed field-name
609          my $prefix = ${$nspackage.'::OPTION'} {namespace_phname_goodcase}
610                    || $self->{ns}->{uri2phname}->{$nsuri};
611          $prefix = undef if $nsuri eq $self->{option}->{ns_default_phuri};
612          my $gc = ${$nspackage.'::OPTION'} {to_be_goodcase};
613          if (ref $gc) { $oname = &$gc ($self, $nspackage, $name, \%option) }
614          else { $oname = $name }
615          if ($prefix) { $oname = $prefix . '-' . $oname }
616          if ($option{format} =~ /uri-url-mailto/) {
617            return if (( ${$nspackage.'::OPTION'} {uri_mailto_safe}->{$name}
618                      || ${$nspackage.'::OPTION'} {uri_mailto_safe}->{':default'})
619                      < $option{uri_mailto_safe_level});
620            if ($name eq 'to') {
621              $body = $self->field ('to', -new_item_unless_exist => 0);
622              if (ref $body && $body->have_group) {
623                #
624              } elsif (ref $body && $body->count > 1) {
625                $body = $body->clone;
626                $body->delete ({-by => 'index'}, 0);
627              }
628            }
629          }
630          my $fbody;
631          if (ref $body) {
632            $fbody = $body->stringify (-format => $option{format});
633          } else {
634            $fbody = $body;
635          }
636          return unless length $fbody;
637          unless ($option{linebreak_strict}) {
638            ## bare \x0D and bare \x0A are unsafe
639            $fbody =~ s/\x0D(?=[^\x09\x0A\x20])/\x0D\x20/g;
640            $fbody =~ s/\x0A(?=[^\x09\x20])/\x0A\x20/g;
641          } else {
642            $fbody =~ s/\x0D\x0A(?=[^\x09\x20])/\x0D\x0A\x20/g;
643          }
644          if ($option{use_folding}) {
645            if (ref $option{output_folding}) {
646              $fbody = &{$option{output_folding}} ($self, $fbody,
647                -initial_length => length ($oname) +2);
648            } elsif ($option{output_folding}) {
649              $fbody = $self->_fold ($fbody, -initial_length => length ($oname) +2);
650            }
651          }
652          push @ret, sprintf $option{field_format_pattern}, $oname, $fbody;
653        };
654      if ($option{format} =~ /uri-url-mailto/) {
655        if ($option{format} =~ /uri-url-mailto-to/) {
656          my $to = $self->field ('to', -new_item_unless_exist => 0);
657          if ($to) {
658            unless ($to->have_group) {
659              my $fbody = $to->stringify (-format => $option{format}, -max => 1);
660              return &{$option{output_folding}} ($self, $fbody);
661            }
662          }
663          '';
664        } elsif ($option{format} =~ /uri-url-mailto-rfc1738/) {
665          my $to = $self->field ('to', -new_item_unless_exist => 0);
666          if ($to) {
667            my $fbody = $to->addr_spec (-format => $option{format});
668            return &{$option{output_folding}} ($self, $fbody);
669          }
670          '';
671        } else {
672          $self->scan ($_stringify);
673          my $ret = join ('&', @ret);
674          $ret;
675        }
676      } else {
677        if ($option{output_mail_from}) {
678          my $fromline = $self->field ('mail-from', -new_item_unless_exist => 0);
679          push @ret, 'From '.$fromline if $fromline;
680        }
681        $self->scan ($_stringify);
682        my $ret = join ("\x0D\x0A", @ret);
683        $ret? $ret."\x0D\x0A": '';
684    }    }
   $self->{option}->{field_type}->{$field_name}  
   || $self->{option}->{field_type}->{':DEFAULT'};  
685  }  }
686    *as_string = \&stringify;
687    
688    =head2 $self->option ($option_name, [$option_value])
689    
690    Set/gets new value of the option.
691    
692  sub _delete_empty_field ($) {  =cut
693    
694    sub option ($@) {
695    my $self = shift;    my $self = shift;
696    my @ret;    if (@_ == 1) {
697    for my $field (@{$self->{field}}) {      return $self->{option}->{ shift (@_) };
698      push @ret, $field if $field->{name};    }
699      while (my ($name, $value) = splice (@_, 0, 2)) {
700        $self->{option}->{$name} = $value;
701        if ($name eq 'format') {
702          for my $f (@{$self->{field}}) {
703            if (ref $f->{body}) {
704              $f->{body}->option (-format => $value);
705            }
706          }
707        }
708    }    }
   $self->{field} = \@ret;  
   $self;  
709  }  }
710    
711  sub fold ($$;$) {  sub field_type ($@) {shift->SUPER::value_type (@_)}
712    
713    ## $self->_fold ($string, %option = (-max, -initial_length(for field-name)) )
714    sub _fold ($$;%) {
715    my $self = shift;    my $self = shift;
716    my $string = shift;    my $string = shift;
717    my $len = shift || $self->{option}->{fold_length};    my %option = @_;
718    $len = 60 if $len < 60;    my $max = $self->{option}->{line_length_max};
719        $max = 20 if $max < 20;
   ## This code is taken from Mail::Header 1.43 in MailTools,  
   ## by Graham Barr (Maintained by Mark Overmeer <mailtools@overmeer.net>).  
   my $max = int($len - 5);         # 4 for leading spcs + 1 for [\,\;]  
   my $min = int($len * 4 / 5) - 4;  
   my $ml = $len;  
720        
721    if (length($string) > $ml) {    my $l = $option{-initial_length} || 0;
722       #Split the line up    $string =~ s{((?:^|[\x09\x20])[^\x09\x20]+)}{
723       # first bias towards splitting at a , or a ; >4/5 along the line      my $s = $1;
724       # next split a whitespace      if ($l + length $s > $max) {
725       # else we are looking at a single word and probably don't want to split        $s = "\x0D\x0A\x20" . $s;
726       my $x = "";        $l = length ($s) - 2;
727       $x .= "$1\n    "      } else { $l += length $s }
728         while($string =~ s/^$REG{WSP}*(      $s;
729                            [^"]{$min,$max}?[\,\;]    }gex;
                           |[^"]{1,$max}$REG{WSP}  
                           |[^\s"]*(?:"[^"]*"[^\s"]*)+$REG{WSP}  
                           |[^\s"]+$REG{WSP}  
                           )  
                         //x);  
      $x .= $string;  
      $string = $x;  
      $string =~ s/(\A$REG{WSP}+|$REG{WSP}+\Z)//sog;  
      $string =~ s/\s+\n/\n/sog;  
   }  
730    $string;    $string;
731  }  }
732    
733    sub _ns_load_ph ($$) {
734      my $self = shift;
735      my $name = shift;     ## normalized prefix (without HYPHEN-MINUS)
736      return if $self->{ns}->{phname2uri}->{$name};
737      $self->{ns}->{phname2uri}->{$name} = $NS_phname2uri{$name};
738      return unless $self->{ns}->{phname2uri}->{$name};
739      $self->{ns}->{uri2phname}->{$self->{ns}->{phname2uri}->{$name}} = $name;
740    }
741    
742    sub _NS_uri2phpackage ($) {
743      $NS_uri2phpackage{$_[0]}
744      || $NS_uri2phpackage{$Message::Header::Default::OPTION{namespace_uri}};
745    }
746    
747    =head2 $self->clone ()
748    
749    Returns a copy of Message::Header object.
750    
751    =cut
752    
753    ## Inhreited
754    
755    =head1 NOTE
756    
757    =head2 C<field-name>
758    
759    The header field name is not case sensitive.  To make the life
760    easier for perl users who wants to avoid quoting before the => operator,
761    you can use '_' as a synonym for '-' in header field names
762    (this behaviour can be suppressed by setting
763    C<translate_underscore> option to C<0> value).
764    
765  =head1 EXAMPLE  =head1 EXAMPLE
766    
767    ## Print field list    ## Print field list
# Line 443  sub fold ($$;$) { Line 769  sub fold ($$;$) {
769    use Message::Header;    use Message::Header;
770    my $header = Message::Header->parse ($header);    my $header = Message::Header->parse ($header);
771        
   ## Next sample is better.  
   #for my $field (@$header) {  
   #  print $field->{name}, "\t=> ", $field->{body}, "\n";  
   #}  
     
772    for my $i (0..$#$header) {    for my $i (0..$#$header) {
773      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";
774    }    }
# Line 470  sub fold ($$;$) { Line 791  sub fold ($$;$) {
791    $header->add ('References' => '<hoge.msgid%foo@foo.example>');    $header->add ('References' => '<hoge.msgid%foo@foo.example>');
792    print $header;    print $header;
793    
794    =head1 ACKNOWLEDGEMENTS
795    
796    Some of codes are taken from other modules such as
797    HTTP::Header, Mail::Header.
798    
799  =head1 LICENSE  =head1 LICENSE
800    
801  Copyright 2002 wakaba E<lt>w@suika.fam.cxE<gt>.  Copyright 2002 wakaba E<lt>w@suika.fam.cxE<gt>.

Legend:
Removed from v.1.10  
changed lines
  Added in v.1.26

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24