/[suikacvs]/test/cvs
Suika

Diff of /test/cvs

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

revision 1.13 by wakaba, Mon Apr 1 05:32:37 2002 UTC revision 1.30 by wakaba, Thu Jul 4 06:38:21 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  use Carp;  require Message::Field::Structured;     ## This may seem silly:-)
13  use overload '@{}' => sub {shift->_delete_empty_field()->{field}},  push @ISA, qw(Message::Field::Structured);
14               '""' => sub {shift->stringify};  
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    ## Initialize of this class -- called by constructors
29    %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',
35        -field_format_pattern       => '%s: %s',
36        -field_name_case_sensible   => 0,
37        -field_name_unsafe_rule     => 'NON_ftext',
38        -field_name_validation      => 0,
39        -field_sort => 0,
40        -format     => 'mail-rfc2822',
41        -header_default_charset     => 'iso-2022-int-1',
42        -header_default_charset_input       => 'iso-2022-int-1',
43        -linebreak_strict   => 0,
44        -line_length_max    => 60,  ## For folding
45        #ns_default_phuri
46        -output_bcc => 0,
47        -output_folding     => 1,
48        -output_mail_from   => 0,
49        #parse_all
50        -translate_underscore       => 1,
51        #uri_mailto_safe
52        -uri_mailto_safe_level      => 4,
53        -use_folding        => 1,
54        #value_type
55    );
56    
57  $REG{WSP}     = qr/[\x09\x20]/;  ## taken from L<HTTP::Header>
58  $REG{FWS}     = qr/[\x09\x20]*/;  # "Good Practice" order of HTTP message headers:
59  $REG{M_field} = qr/^([^\x3A]+):$REG{FWS}([\x00-\xFF]*)$/;  #    - General-Headers
60  $REG{M_fromline} = qr/^\x3E?From$REG{WSP}+([\x00-\xFF]*)$/;  #    - Request-Headers
61  $REG{UNSAFE_field_name} = qr/[\x00-\x20\x3A\x7F-\xFF]/;  #    - Response-Headers
62    #    - Entity-Headers
63    # (From draft-ietf-http-v11-spec-rev-01, Nov 21, 1997)
64    my @header_order = qw(
65      mail-from x-envelope-from relay-version path status
66    
67       cache-control connection date pragma transfer-encoding upgrade trailer via
68    
69       accept accept-charset accept-encoding accept-language
70       authorization expect from host
71       if-modified-since if-match if-none-match if-range if-unmodified-since
72       max-forwards proxy-authorization range referer te user-agent
73    
74       accept-ranges age location proxy-authenticate retry-after server vary
75       warning www-authenticate
76    
77       mime-version
78       allow content-base content-encoding content-language content-length
79       content-location content-md5 content-range content-type
80       etag expires last-modified content-style-type content-script-type
81       link
82    
83  =head2 options    xref
84    );
85    my %header_order;
86    
87  These options can be getten/set by C<get_option>/C<set_option>  =head1 CONSTRUCTORS
 method.  
88    
89  =head3 capitalize = 0/1  The following methods construct new C<Message::Header> objects:
90    
91  (First character of) C<field-name> is capitalized  =over 4
 when C<stringify>.  (Default = 1)  
92    
93  =head3 fold_length = numeric value  =cut
94    
95  Length of line used to fold.  (Default = 70)  sub _init ($;%) {
96      my $self = shift;
97      my %options = @_;
98      my $DEFAULT = Message::Util::make_clone (\%DEFAULT);
99      $self->SUPER::_init (%$DEFAULT, %options);
100      $self->{value} = [];
101      $self->_ns_load_ph ('default');
102      $self->_ns_load_ph ('rfc822');
103      $self->{option}->{ns_default_phuri} = $self->{ns}->{phname2uri}->{'rfc822'}
104        unless $self->{option}->{ns_default_phuri};
105      
106      ## For text/rfc822-headers
107      if (ref $options{entity_header}) {
108        $self->{entity_header} = $options{entity_header};
109        delete $options{entity_header};
110      }
111      my @new_fields = ();
112      for my $name (keys %options) {
113        unless (substr ($name, 0, 1) eq '-') {
114          push @new_fields, ($name => $options{$name});
115        }
116      }
117      $self->_init_by_format ($self->{option}->{format}, $self->{option});
118      # Make alternative representations of @header_order.  This is used
119      # for sorting.
120      my $i = 1;
121      for (@header_order) {
122          $header_order{$_} = $i++ unless $header_order{$_};
123      }
124      
125      $self->add (@new_fields, -parse => $self->{option}->{parse_all})
126        if $#new_fields > -1;
127    }
128    
129    sub _init_by_format ($$\%) {
130      my $self = shift;
131      my ($format, $option) = @_;
132      if ($format =~ /cgi/) {
133        unshift @header_order, qw(content-type location);
134        $option->{field_sort} = 'good-practice';
135        $option->{use_folding} = 0;
136      } elsif ($format =~ /http/) {
137        $option->{field_sort} = 'good-practice';
138      }
139      if ($format =~ /uri-url-mailto/) {
140        $option->{output_bcc} = 0;
141        $option->{field_format_pattern} = '%s=%s';
142        $option->{output_folding} = sub {
143          $_[1] =~ s/([^:@+\$A-Za-z0-9\-_.!~*])/sprintf('%%%02X', ord $1)/ge;
144          $_[1];
145        };  ## Yes, this is not folding!
146      }
147    }
148    
149  =head3 mail_from = 0/1  =item $msg = Message::Header->new ([%initial-fields/options])
150    
151  Outputs "From " line (known as Un*x From, Mail-From, and so on)  Constructs a new C<Message::Headers> object.  You might pass some initial
152  when C<stringify>.  (Default = 0)  C<field-name>-C<field-body> pairs and/or options as parameters to the constructor.
153    
154    Example:
155    
156     $hdr = new Message::Headers
157            Date         => 'Thu, 03 Feb 1994 00:00:00 +0000',
158            Content_Type => 'text/html',
159            Content_Location => 'http://www.foo.example/',
160            -format => 'mail-rfc2822'       ## not to be header field
161            ;
162    
163  =cut  =cut
164    
165  %DEFAULT = (  ## Inherited
   capitalize    => 1,  
   fold_length   => 70,  
   field_type    => {':DEFAULT' => 'Message::Field::Unstructured'},  
   format        => 'rfc2822',   ## rfc2822, usefor, http  
   mail_from     => -1,  
   output_bcc    => -1,  
   parse_all     => -1,  
 );  
 my @field_type_Structured = qw(cancel-lock  
   importance path precedence  
   x-face x-mail-count x-msmail-priority x-priority 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(article-updates 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(archive link 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  
   list-archive list-digest list-help list-owner  
   list-post list-subscribe list-unsubscribe list-url uri newsgroups  
   x-brother x-daughter x-respect x-moe x-syster x-wife))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::CSV'}  
 for (qw(content-alias content-base content-location location referer  
   url x-home-page x-http_referer  
   x-info x-pgp-key x-ml-url x-uri x-url x-web))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::URI'}  
 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'}  
 for (qw(content-length lines max-forwards mime-version))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Numval'}  
166    
167  =head2 Message::Header->new ([%option])  =item $msg = Message::Header->parse ($header, [%initial-fields/options])
168    
169  Returns new Message::Header instance.  Some options can be  Parses given C<header> and constructs a new C<Message::Headers>
170  specified as hash.  object.  You might pass some additional C<field-name>-C<field-body> pairs
171    or/and initial options as parameters to the constructor.
172    
173  =cut  =cut
174    
175  sub new ($;%) {  sub parse ($$;%) {
176    my $class = shift;    my $class = shift;
177    my $self = bless {option => {@_}}, $class;    my $header = shift;
178    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}    my $self = bless {}, $class;
179      $self->_init (@_);
180      if ($self->{option}->{linebreak_strict}) {
181        $header =~ s/\x0D\x0A$REG{WSP}/\x20/gos if $self->{option}->{use_folding};
182      } else {
183        $header =~ s/\x0D?\x0A$REG{WSP}/\x20/gos if $self->{option}->{use_folding};
184      }
185      for my $field (split /\x0D?\x0A/, $header) {
186        if ($field =~ /$REG{M_fromline}/) {
187          my ($s,undef,$value) = $self->_value_to_arrayitem
188            ('mail-from' => $1, $self->{option});
189          push @{$self->{value}}, $value if $s;
190        } elsif ($field =~ /$REG{M_field}/) {
191          my ($name, $body) = ($1, $2);
192          $body =~ s/$REG{WSP}+$//;
193          my ($s,undef,$value) = $self->_value_to_arrayitem
194            ($name => $body, $self->{option});
195          push @{$self->{value}}, $value if $s;
196        } elsif (length $field) {
197          my ($s,undef,$value) = $self->_value_to_arrayitem
198            ('x-unknown' => $field, $self->{option});
199          push @{$self->{value}}, $value if $s;
200        }
201      }
202    $self;    $self;
203  }  }
204    
205  =head2 Message::Header->parse ($header, [%option])  =item $msg = Message::Header->parse_array (\@header, [%initial-fields/options])
206    
207  Parses given C<header> and return a new Message::Header  Parses given C<header> and constructs a new C<Message::Headers>
208  object.  Some options can be specified as hash.  object.  Same as C<Message::Header-E<lt>parse> but this method
209    is given an array reference.  You might pass some additional
210    C<field-name>-C<field-body> pairs or/and initial options
211    as parameters to the constructor.
212    
213  =cut  =cut
214    
215  sub parse ($$;%) {  sub parse_array ($\@;%) {
216    my $class = shift;    my $class = shift;
217    my $header = shift;    my $header = shift;
218    my $self = bless {option => {@_}}, $class;    Carp::croak "parse_array: first argument is not an array reference"
219    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}      unless ref $header eq 'ARRAY';
220    $header =~ s/\x0D?\x0A$REG{WSP}+/\x20/gos;    ## unfold    my $self = bless {}, $class;
221    for my $field (split /\x0D?\x0A/, $header) {    $self->_init (@_);
222      while (1) {
223        my $field = shift @$header;
224        if ($self->{option}->{use_folding}) {
225          while (1) {
226            if ($$header[0] =~ /^$REG{WSP}/) {
227              $field .= shift @$header;
228            } else {last}
229          }
230        }
231        if ($self->{option}->{linebreak_strict}) {
232          $field =~ s/\x0D\x0A//g;
233        } else {
234          $field =~ tr/\x0D\x0A//d;
235        }
236        local $self->{option}->{parse} = $self->{option}->{parse_all};
237      if ($field =~ /$REG{M_fromline}/) {      if ($field =~ /$REG{M_fromline}/) {
238        my $body = $1;        my ($s,undef,$value) = $self->_value_to_arrayitem
239        $body = $self->_field_body ($body, 'mail-from')          ('mail-from' => $1, $self->{option});
240          if $self->{option}->{parse_all}>0;        push @{$self->{value}}, $value if $s;
       push @{$self->{field}}, {name => 'mail-from', body => $body};  
241      } elsif ($field =~ /$REG{M_field}/) {      } elsif ($field =~ /$REG{M_field}/) {
242        my ($name, $body) = (lc $1, $2);        my ($name, $body) = ($self->_n11n_field_name ($1), $2);
       $name =~ s/$REG{WSP}+$//;  
243        $body =~ s/$REG{WSP}+$//;        $body =~ s/$REG{WSP}+$//;
244        $body = $self->_field_body ($body, $name) if $self->{option}->{parse_all}>0;        my ($s,undef,$value) = $self->_value_to_arrayitem
245        push @{$self->{field}}, {name => $name, body => $body};          ($name => $body, $self->{option});
246          push @{$self->{value}}, $value if $s;
247        } elsif (length $field) {
248          my ($s,undef,$value) = $self->_value_to_arrayitem
249            ('x-unknown' => $field, $self->{option});
250          push @{$self->{value}}, $value if $s;
251      }      }
252        last if $#$header < 0;
253    }    }
254    $self;    $self;
255  }  }
256    
257    =back
258    
259    =head1 METHODS
260    
261  =head2 $self->field ($field_name)  =head2 $self->field ($field_name)
262    
263  Returns C<field-body> of given C<field-name>.  Returns C<field-body> of given C<field-name>.
# Line 154  context, only first one is returned.) Line 267  context, only first one is returned.)
267    
268  =cut  =cut
269    
270  sub field ($$) {  sub field ($@) {shift->SUPER::item (@_)}
271    sub field_exist ($@) {shift->SUPER::item_exist (@_)}
272    
273    ## item-by?, \$checked-item, {item-key => 1}, \%option
274    sub _item_match ($$\$\%\%) {
275    my $self = shift;    my $self = shift;
276    my $name = lc shift;    my ($by, $i, $list, $option) = @_;
277    my @ret;    return 0 unless ref $$i;  ## Already removed
278    for my $field (@{$self->{field}}) {    if ($by eq 'name') {
279      if ($field->{name} eq $name) {      my %o = %$option; $o{parse} = 0;
280        unless (wantarray) {      my %l;
281          $field->{body} = $self->_field_body ($field->{body}, $name);      for (keys %$list) {
282          return $field->{body};        my ($s, undef, $v) = $self->_value_to_arrayitem ($_, '', %o);
283          if ($s) {
284            $l{$v->{name} . ':' . ( $option->{ns} || $v->{ns} ) } = 1;
285        } else {        } else {
286          $field->{body} = $self->_field_body ($field->{body}, $name);          $l{$v->{name} .':'. ( $option->{ns} || $self->{option}->{ns_default_phuri} ) } = 1;
         push @ret, $field->{body};  
287        }        }
288      }      }
289        return 1 if $l{$$i->{name} . ':' . $$i->{ns}};
290      } elsif ($by eq 'ns') {
291        return 1 if $list->{ $$i->{ns} };
292    }    }
293    if ($#ret < 0) {    0;
     return $self->add ($name);  
   }  
   @ret;  
294  }  }
295    *_delete_match = \&_item_match;
296    
297  sub field_exist ($$) {  ## Returns returned item value    \$item-value, \%option
298    my $self = shift;  sub _item_return_value ($\$\%) {
299    my $name = lc shift;    if (ref ${$_[1]}->{body}) {
300    my @ret;      ${$_[1]}->{body};
301    for my $field (@{$self->{field}}) {    } else {
302      return 1 if ($field->{name} eq $name);      ${$_[1]}->{body} = $_[0]->_parse_value (${$_[1]}->{name} => ${$_[1]}->{body},
303          ns => ${$_[1]}->{ns});
304        ${$_[1]}->{body};
305    }    }
   0;  
306  }  }
307    *_add_return_value = \&_item_return_value;
308    *_replace_return_value = \&_item_return_value;
309    
310  =head2 $self->field_name ($index)  ## Returns returned (new created) item value    $name, \%option
311    sub _item_new_value ($$\%) {
312  Returns C<field-name> of $index'th C<field>.      my ($s,undef,$value) = $_[0]->_value_to_arrayitem
313            ($_[1] => '', $_[2]);
314  =head2 $self->field_body ($index)      $s? $value: undef;
315    }
316    
 Returns C<field-body> of $index'th C<field>.  
317    
 =cut  
318    
319  sub field_name ($$) {  ## $self->_parse_value ($type, $value, %options);
320    my $self = shift;  sub _parse_value ($$$;%) {
   $self->{field}->[shift]->{name};  
 }  
 sub field_body ($$) {  
321    my $self = shift;    my $self = shift;
322    my $i = shift;    my $name = shift ;#|| $self->{option}->{_VALTYPE_DEFAULT};
323    $self->{field}->[$i]->{body}    my $value = shift;  return $value if ref $value;
324     = $self->_field_body ($self->{field}->[$i]->{body}, $self->{field}->[$i]->{name});    my %option = @_;
325    $self->{field}->[$i]->{body};    my $vtype; { no strict 'refs';
326        my $vt = ${&_NS_uri2phpackage ($option{ns}).'::OPTION'}{value_type};
327        if (ref $vt) {
328          $vtype = $vt->{$name} || $vt->{$self->{option}->{_VALTYPE_DEFAULT}};
329        }
330        ## For compatiblity.
331        unless (ref $vtype) { $vtype = $self->{option}->{value_type}->{$name}
332          || $self->{option}->{value_type}->{$self->{option}->{_VALTYPE_DEFAULT}} }
333      }
334      my $vpackage = $vtype->[0];
335      my %vopt = %{$vtype->[1]} if ref $vtype->[1];
336      if ($vpackage eq ':none:') {
337        return $value;
338      } elsif (defined $value) {
339        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
340        return $vpackage->parse ($value,
341          -format   => $self->{option}->{format},
342          -field_ns => $option{ns},
343          -field_name       => $name,
344        -header_default_charset     => $self->{option}->{header_default_charset},
345        -header_default_charset_input       => $self->{option}->{header_default_charset_input},
346          -parse_all        => $self->{option}->{parse_all},
347        %vopt);
348      } else {
349        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
350        return $vpackage->new (
351          -format   => $self->{option}->{format},
352          -field_ns => $option{ns},
353          -field_name       => $name,
354        -header_default_charset     => $self->{option}->{header_default_charset},
355        -header_default_charset_input       => $self->{option}->{header_default_charset_input},
356          -parse_all        => $self->{option}->{parse_all},
357        %vopt);
358      }
359  }  }
360    
361  sub _field_body ($$$) {  ## Defined for text/rfc822-headers
362    my $self = shift;  sub entity_header ($;$) {
363    my ($body, $name) = @_;    my $self = shift;
364    unless (ref $body) {    my $new_header = shift;
365      my $type = $self->{option}->{field_type}->{$name}    if (ref $new_header) {
366              || $self->{option}->{field_type}->{':DEFAULT'};      $self->{header} = $new_header;
     eval "require $type";  
     unless ($body) {  
       $body = $type->new (field_name => $name, format => $self->{option}->{format});  
     } else {  
       $body = $type->parse ($body, field_name => $name,  
         format => $self->{option}->{format});  
     }  
367    }    }
368    $body;    $self->{header};
369  }  }
370    
371  =head2 $self->field_name_list ()  =head2 $self->field_name_list ()
# Line 234  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    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  =head2 $self->add ($field_name, $field_body)  =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    Instead of field name-body pair, you might pass some options.
403    Four options are available for this method.
404    
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  Adds an new C<field>.  It is not checked whether  C<-prepend>: New fields are not appended,
410  the field which named $field_body is already exist or not.  but prepended to current fields.  (Default: C<0>)
411  If you don't want duplicated C<field>s, use C<replace> method.  
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;
   if ($option{prepend}) {  
     unshift @{$self->{field}}, {name => $name, body => $body};  
   } else {  
     push @{$self->{field}}, {name => $name, body => $body};  
430    }    }
431    $body;    my $nsuri = $self->{option}->{ns_default_phuri};
432      
433      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      $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 270  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.  
 ($index of first field is C<1>, not C<0>.)  
 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 319  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;
501      my ($array, $option) = @_;
502      my $name = $self->_n11n_field_name ($$option{-name});
503      my @a = grep {$_->{name} eq $name} @{$self->{$array}};
504      $#a + 1;
505    }
506    
507    ## 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    =head2 $self->rename ($field-name, $new-name, [$old, $new,...])
515    
516    Renames C<$field-name> as C<$new-name>.
517    
518    =cut
519    
520    sub rename ($%) {
521    my $self = shift;    my $self = shift;
522    my ($name) = (lc shift);    my %params = @_;
523    unless ($name) {    my %option = %{$self->{option}};
524      $self->_delete_empty_field ();    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
525      return $#{$self->{field}}+1;    my %new_name;
526      for (grep {/^[^-]/} keys %params) {
527        my ($old => $new)
528          = ($self->_n11n_field_name ($_) => $self->_n11n_field_name ($params{$_}));
529        $old =~ tr/_/-/ if $option{translate_underscore};
530        $new =~ tr/_/-/ if $option{translate_underscore};
531        Carp::croak "rename: $new: invalid field-name"
532          if $option{field_name_validation}
533            && $new =~ /$REG{$option{field_name_unsafe_rule}}/;
534        $new_name{$old} = $new;
535    }    }
536    my $count = 0;    for my $field (@{$self->{value}}) {
537    for my $field (@{$self->{field}}) {      if (length $new_name{$field->{name}}) {
538      if ($field->{name} eq $name) {        $field->{name} = $new_name{$field->{name}};
       $count++;  
539      }      }
540    }    }
541    $count;    $self if defined wantarray;
542  }  }
543    
 =head2 $self->rename ($field_name, [$index])  
544    
545  Renames C<field> named as $field_name.  =item $self->scan(\&doit)
546  If $index is specified, only $index'th C<field> is renamed.  
547  ($index of first field is C<1>, not C<0>.)  Apply a subroutine to each header field in turn.  The callback routine is
548  If not, ($index == 0), all C<field>s that have the C<field-name>  called with two parameters; the name of the field and a single value.
549  $field_name are renamed.  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 rename ($$$;$) {  sub _scan_sort ($\@\%) {
555    my $self = shift;    my $self = shift;
556    my ($name, $newname, $index) = (lc shift, lc shift, shift);    my ($array, $option) = @_;
557    my $i = 0;    my $sort;
558    croak "rename: new field-name contains of unsafe character: $newname"    $sort = \&_header_cmp if $option->{field_sort} eq 'good-practice';
559      if !$newname || $newname =~ /$REG{UNSAFE_field_name}/;    $sort = {$a cmp $b} if $option->{field_sort} eq 'alphabetic';
560    for my $field (@{$self->{field}}) {    return ( sort $sort @$array ) if ref $sort;
561      if ($field->{name} eq $name) {    @$array;
562        $i++;  }
563        if ($index == 0 || $i == $index) {  
564          $field->{name} = $newname;  sub _n11n_field_name ($$) {
565          return $self if $i == $index;    no strict 'refs';
566        }    my $self = shift;
567      }    my $s = shift;
568    }    $s =~ s/^$REG{WSP}+//; $s =~ s/$REG{WSP}+$//;
569    $self;    $s = lc $s unless ${&_NS_uri2phpackage ($self->{option}->{ns_default_phuri}).'::OPTION'}{case_sensible};
570      $s;
571    }
572    
573    # Compare function which makes it easy to sort headers in the
574    # recommended "Good Practice" order.
575    ## taken from HTTP::Header
576    sub _header_cmp
577    {
578      my ($na, $nb) = ($a->{name}, $b->{name});
579        # Unknown headers are assign a large value so that they are
580        # sorted last.  This also helps avoiding a warning from -w
581        # about comparing undefined values.
582        $header_order{$na} = 999 unless defined $header_order{$na};
583        $header_order{$nb} = 999 unless defined $header_order{$nb};
584    
585        $header_order{$na} <=> $header_order{$nb} || $na cmp $nb;
586  }  }
587    
588  =head2 $self->stringify ([%option])  =head2 $self->stringify ([%option])
# Line 371  Returns the C<header> as a string. Line 593  Returns the C<header> as a string.
593    
594  sub stringify ($;%) {  sub stringify ($;%) {
595    my $self = shift;    my $self = shift;
596    my %OPT = @_;    my %params = @_;
597      my %option = %{$self->{option}};
598      $option{format} = $params{-format} if $params{-format};
599      $self->_init_by_format ($option{format}, \%option);
600      for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
601    my @ret;    my @ret;
602    $OPT{capitalize} ||= $self->{option}->{capitalize};    my $_stringify = sub {
603    $OPT{mail_from} ||= $self->{option}->{mail_from};      no strict 'refs';
604    $OPT{output_bcc} ||= $self->{option}->{output_bcc};        my ($name, $body, $nsuri) = ($_[1]->{name}, $_[1]->{body}, $_[1]->{ns});
605    $OPT{format} ||= $self->{option}->{format};        return unless length $name;
606    push @ret, 'From '.$self->field ('mail-from') if $OPT{mail_from}>0;        return if $option{output_mail_from} && $name eq 'mail-from';
607    for my $field (@{$self->{field}}) {        $body = '' if !$option{output_bcc} && $name eq 'bcc';
608      my $name = $field->{name};        my $nspackage = &_NS_uri2phpackage ($nsuri);
609      next unless $name;        my $oname;        ## Outputed field-name
610      next if $OPT{mail_from}<0 && $name eq 'mail-from';        my $prefix = ${$nspackage.'::OPTION'} {namespace_phname_goodcase}
611      next if $OPT{output_bcc}<0 && ($name eq 'bcc' || $name eq 'resent-bcc');                  || $self->{ns}->{uri2phname}->{$nsuri};
612      my $fbody;        $prefix = undef if $nsuri eq $self->{option}->{ns_default_phuri};
613      if (ref $field->{body}) {        my $gc = ${$nspackage.'::OPTION'} {to_be_goodcase};
614        $fbody = $field->{body}->stringify (format => $OPT{format});        if (ref $gc) { $oname = &$gc ($self, $nspackage, $name, \%option) }
615          else { $oname = $name }
616          if ($prefix) { $oname = $prefix . '-' . $oname }
617          if ($option{format} =~ /uri-url-mailto/) {
618            return if (( ${$nspackage.'::OPTION'} {uri_mailto_safe}->{$name}
619                      || ${$nspackage.'::OPTION'} {uri_mailto_safe}->{':default'})
620                      < $option{uri_mailto_safe_level});
621            if ($name eq 'to') {
622              $body = $self->field ('to', -new_item_unless_exist => 0);
623              if (ref $body && $body->have_group) {
624                #
625              } elsif (ref $body && $body->count > 1) {
626                $body = $body->clone;
627                $body->delete ({-by => 'index'}, 0);
628              }
629            }
630          }
631          my $fbody;
632          if (ref $body) {
633            $fbody = $body->stringify (-format => $option{format});
634          } else {
635            $fbody = $body;
636          }
637          unless (${$nspackage.'::OPTION'} {field}->{$name}->{empty_body}) {
638            return unless length $fbody;
639          }
640          unless ($option{linebreak_strict}) {
641            ## bare \x0D and bare \x0A are unsafe
642            $fbody =~ s/\x0D(?=[^\x09\x0A\x20])/\x0D\x20/g;
643            $fbody =~ s/\x0A(?=[^\x09\x20])/\x0A\x20/g;
644          } else {
645            $fbody =~ s/\x0D\x0A(?=[^\x09\x20])/\x0D\x0A\x20/g;
646          }
647          if ($option{use_folding}) {
648            if (ref $option{output_folding}) {
649              $fbody = &{$option{output_folding}} ($self, $fbody,
650                -initial_length => length ($oname) +2);
651            } elsif ($option{output_folding}) {
652              $fbody = $self->_fold ($fbody, -initial_length => length ($oname) +2);
653            }
654          }
655          push @ret, sprintf $option{field_format_pattern}, $oname, $fbody;
656        };
657      if ($option{format} =~ /uri-url-mailto/) {
658        if ($option{format} =~ /uri-url-mailto-to/) {
659          my $to = $self->field ('to', -new_item_unless_exist => 0);
660          if ($to) {
661            unless ($to->have_group) {
662              my $fbody = $to->stringify (-format => $option{format}, -max => 1);
663              return &{$option{output_folding}} ($self, $fbody);
664            }
665          }
666          '';
667        } elsif ($option{format} =~ /uri-url-mailto-rfc1738/) {
668          my $to = $self->field ('to', -new_item_unless_exist => 0);
669          if ($to) {
670            my $fbody = $to->addr_spec (-format => $option{format});
671            return &{$option{output_folding}} ($self, $fbody);
672          }
673          '';
674      } else {      } else {
675        $fbody = $field->{body};        $self->scan ($_stringify);
676          my $ret = join ('&', @ret);
677          $ret;
678        }
679      } else {
680        if ($option{output_mail_from}) {
681          my $fromline = $self->field ('mail-from', -new_item_unless_exist => 0);
682          push @ret, 'From '.$fromline if $fromline;
683      }      }
684      next unless $fbody;      $self->scan ($_stringify);
685      $fbody =~ s/\x0D([^\x09\x0A\x20])/\x0D\x20$1/g;      my $ret = join ("\x0D\x0A", @ret);
686      $fbody =~ s/\x0A([^\x09\x20])/\x0A\x20$1/g;      $ret? $ret."\x0D\x0A": '';
     $name =~ s/((?:^|-)[a-z])/uc($1)/ge if $OPT{capitalize};  
     push @ret, $name.': '.$self->fold ($fbody);  
687    }    }
   my $ret = join ("\n", @ret);  
   $ret? $ret."\n": "";  
688  }  }
689    *as_string = \&stringify;
690    
691  =head2 $self->option ($option_name, [$option_value])  =head2 $self->option ($option_name, [$option_value])
692    
# Line 405  Set/gets new value of the option. Line 694  Set/gets new value of the option.
694    
695  =cut  =cut
696    
697  sub option ($$;$) {  sub option ($@) {
698    my $self = shift;    my $self = shift;
699    my ($name, $value) = @_;    if (@_ == 1) {
700    if (defined $value) {      return $self->{option}->{ shift (@_) };
701      }
702      while (my ($name, $value) = splice (@_, 0, 2)) {
703      $self->{option}->{$name} = $value;      $self->{option}->{$name} = $value;
704      if ($name eq 'format') {      if ($name eq 'format') {
705        for my $f (@{$self->{field}}) {        for my $f (@{$self->{field}}) {
706          if (ref $f) {          if (ref $f->{body}) {
707            $f->option (format => $value);            $f->{body}->option (-format => $value);
708          }          }
709        }        }
710      }      }
711    }    }
   $self->{option}->{$name};  
712  }  }
713    
714  sub field_type ($$;$) {  sub field_type ($@) {shift->SUPER::value_type (@_)}
715    
716    ## $self->_fold ($string, %option = (-max, -initial_length(for field-name)) )
717    sub _fold ($$;%) {
718    my $self = shift;    my $self = shift;
719    my $field_name = shift;    my $string = shift;
720    my $new_field_type = shift;    my %option = @_;
721    if ($new_field_type) {    my $max = $self->{option}->{line_length_max};
722      $self->{option}->{field_type}->{$field_name} = $new_field_type;    $max = 20 if $max < 20;
723    }    
724    $self->{option}->{field_type}->{$field_name}    my $l = $option{-initial_length} || 0;
725    || $self->{option}->{field_type}->{':DEFAULT'};    $l += length $1 if $string =~ /^([^\x09\x20]+)/;
726      $string =~ s{([\x09\x20][^\x09\x20]+)}{
727        my $s = $1;
728        if (($l + length $s) > $max) {
729          $s = "\x0D\x0A\x20" . $s;
730          $l = 1 + length $s;
731        } else { $l += length $s }
732        $s;
733      }gex;
734      $string;
735  }  }
736    
737  sub _delete_empty_field ($) {  sub _ns_load_ph ($$) {
738    my $self = shift;    my $self = shift;
739    my @ret;    my $name = shift;     ## normalized prefix (without HYPHEN-MINUS)
740    for my $field (@{$self->{field}}) {    return if $self->{ns}->{phname2uri}->{$name};
741      push @ret, $field if $field->{name};    $self->{ns}->{phname2uri}->{$name} = $NS_phname2uri{$name};
742    }    return unless $self->{ns}->{phname2uri}->{$name};
743    $self->{field} = \@ret;    $self->{ns}->{uri2phname}->{$self->{ns}->{phname2uri}->{$name}} = $name;
   $self;  
744  }  }
745    
746  sub fold ($$;$) {  sub _NS_uri2phpackage ($) {
747    my $self = shift;    $NS_uri2phpackage{$_[0]}
748    my $string = shift;    || $NS_uri2phpackage{$Message::Header::Default::OPTION{namespace_uri}};
   my $len = shift || $self->{option}->{fold_length};  
   $len = 60 if $len < 60;  
     
   ## 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;  
     
   if (length($string) > $ml) {  
      #Split the line up  
      # first bias towards splitting at a , or a ; >4/5 along the line  
      # next split a whitespace  
      # else we are looking at a single word and probably don't want to split  
      my $x = "";  
      $x .= "$1\n "  
        while($string =~ s/^$REG{WSP}*(  
                           [^"]{$min,$max}?[\,\;]  
                           |[^"]{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;  
   }  
   $string;  
749  }  }
750    
751    =head2 $self->clone ()
752    
753    Returns a copy of Message::Header object.
754    
755    =cut
756    
757    ## Inhreited
758    
759    =head1 NOTE
760    
761    =head2 C<field-name>
762    
763    The header field name is not case sensitive.  To make the life
764    easier for perl users who wants to avoid quoting before the => operator,
765    you can use '_' as a synonym for '-' in header field names
766    (this behaviour can be suppressed by setting
767    C<translate_underscore> option to C<0> value).
768    
769  =head1 EXAMPLE  =head1 EXAMPLE
770    
771    ## Print field list    ## Print field list
# Line 483  sub fold ($$;$) { Line 773  sub fold ($$;$) {
773    use Message::Header;    use Message::Header;
774    my $header = Message::Header->parse ($header);    my $header = Message::Header->parse ($header);
775        
   ## Next sample is better.  
   #for my $field (@$header) {  
   #  print $field->{name}, "\t=> ", $field->{body}, "\n";  
   #}  
     
776    for my $i (0..$#$header) {    for my $i (0..$#$header) {
777      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";
778    }    }
# Line 510  sub fold ($$;$) { Line 795  sub fold ($$;$) {
795    $header->add ('References' => '<hoge.msgid%foo@foo.example>');    $header->add ('References' => '<hoge.msgid%foo@foo.example>');
796    print $header;    print $header;
797    
798    =head1 ACKNOWLEDGEMENTS
799    
800    Some of codes are taken from other modules such as
801    HTTP::Header, Mail::Header.
802    
803  =head1 LICENSE  =head1 LICENSE
804    
805  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.13  
changed lines
  Added in v.1.30

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24