/[suikacvs]/test/cvs
Suika

Diff of /test/cvs

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

revision 1.14 by wakaba, Wed Apr 3 13:31:36 2002 UTC revision 1.24 by wakaba, Tue Jun 11 13:01: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);  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{WSP}     = qr/[\x09\x20]/;          $REG{M_field} = qr/^([^\x3A]+):$REG{FWS}([\x00-\xFF]*)$/;
17  $REG{FWS}     = qr/[\x09\x20]*/;          $REG{M_fromline} = qr/^\x3E?From$REG{WSP}+([\x00-\xFF]*)$/;
18  $REG{M_field} = qr/^([^\x3A]+):$REG{FWS}([\x00-\xFF]*)$/;          $REG{ftext} = qr/[\x21-\x39\x3B-\x7E]+/;        ## [2]822
19  $REG{M_fromline} = qr/^\x3E?From$REG{WSP}+([\x00-\xFF]*)$/;          $REG{NON_ftext} = qr/[^\x21-\x39\x3B-\x7E]/;    ## [2]822
20  $REG{UNSAFE_field_name} = qr/[\x00-\x20\x3A\x7F-\xFF]/;          $REG{NON_ftext_usefor} = qr/[^0-9A-Za-z-]/;     ## name-character
21            $REG{NON_ftext_http} = $REG{NON_http_token};
22  =head2 options  
23    ## Namespace support
24  These options can be getten/set by C<get_option>/C<set_option>          our %NS_phname2uri;     ## PH-namespace name -> namespace URI
25  method.          our %NS_uri2phpackage;  ## namespace URI -> PH-package name
26            require Message::Header::Default;       ## Default namespace
27  =head3 capitalize = 0/1  
28    ## Initialize of this class -- called by constructors
29  (First character of) C<field-name> is capitalized  %DEFAULT = (
30  when C<stringify>.  (Default = 1)      -_HASH_NAME => 'value',
31        -_METHODS   => [qw|field field_exist field_type add replace count delete subject id is|],
32  =head3 fold_length = numeric value      -_MEMBERS   => [qw|value|],
33        -M_namsepace_prefix_regex => qr/(?!)/,
34  Length of line used to fold.  (Default = 70)      -_VALTYPE_DEFAULT   => ':default',
35        -by => 'name',      ## (Reserved for method level option)
36  =head3 mail_from = 0/1      -field_format_pattern       => '%s: %s',
37        -field_name_case_sensible   => 0,
38  Outputs "From " line (known as Un*x From, Mail-From, and so on)      -field_name_unsafe_rule     => 'NON_ftext',
39  when C<stringify>.  (Default = 0)      -field_name_validation      => 1,   ## Method level option.
40        -field_sort => 0,
41  =cut      #-format    => 'mail-rfc2822',
42        -linebreak_strict   => 0,   ## Not implemented completely
43  my %DEFAULT = (      -line_length_max    => 60,  ## For folding
44    capitalize    => 1,      -ns_default_uri     => $Message::Header::Default::OPTION{namespace_uri},
45    fold_length   => 70,      -output_bcc => 0,
46    #field_type   => {},      -output_folding     => 1,
47    format        => 'mail-rfc2822',      -output_mail_from   => 0,
48    mail_from     => 0,      #-parse_all => 0,
49    output_bcc    => 0,      -translate_underscore       => 1,
50    parse_all     => 0,      #-uri_mailto_safe
51    sort  => 'none',      -uri_mailto_safe_level      => 4,
52    translate_underscore  => 1,      -use_folding        => 1,
53    validate      => 1,      #-value_type
54  );  );
55  $DEFAULT{field_type} = {  
56          ':DEFAULT'      => 'Message::Field::Unstructured',  $DEFAULT{-value_type} = {
57                    ':default'      => ['Message::Field::Unstructured'],
         received        => 'Message::Field::Received',  
         'x-received'    => 'Message::Field::Received',  
           
         'content-type'  => 'Message::Field::ContentType',  
         'content-disposition'   => 'Message::Field::ContentDisposition',  
         link    => 'Message::Field::ValueParams',  
         archive => 'Message::Field::ValueParams',  
         'x-face-type'   => 'Message::Field::ValueParams',  
           
         subject => 'Message::Field::Subject',  
         'x-nsubject'    => 'Message::Field::Subject',  
           
         'list-software' => 'Message::Field::UA',  
         'user-agent'    => 'Message::Field::UA',  
         server  => 'Message::Field::UA',  
58                    
59          'content-length'        => 'Message::Field::Numval',          p3p     => ['Message::Field::Params'],
60          lines   => 'Message::Field::Numval',          link    => ['Message::Field::ValueParams'],
         'max-forwards'  => 'Message::Field::Numval',  
         'mime-version'  => 'Message::Field::Numval',  
61                    
62          path    => 'Message::Field::Path',          'list-software' => ['Message::Field::UA'],
63            'user-agent'    => ['Message::Field::UA'],
64            server  => ['Message::Field::UA'],
65  };  };
66  for (qw(cancel-lock importance   precedence list-id  for (qw(pics-label list-id status))
67    x-face x-mail-count x-msmail-priority x-priority xref))    {$DEFAULT{-value_type}->{$_} = ['Message::Field::Structured']}
68    {$DEFAULT{field_type}->{$_} = 'Message::Field::Structured'}          ## Not supported yet, but to be supported...
69  for (qw(approved bcc cc delivered-to disposition-notification-to envelope-to          # x-list: unstructured, ml name
70    errors-to fcc from mail-followup-to mail-followup-cc reply-to resent-bcc  for (qw(date expires))
71    resent-cc resent-to resent-from resent-sender return-path    {$DEFAULT{-value_type}->{$_} = ['Message::Field::Date']}
72    return-receipt-to sender to x-approved x-beenthere  for (qw(accept accept-charset accept-encoding accept-language uri))
73    x-complaints-to x-envelope-from x-envelope-sender    {$DEFAULT{-value_type}->{$_} = ['Message::Field::CSV']}
74    x-envelope-to x-ml-address x-ml-command x-ml-to x-nfrom x-nto))  for (qw(location referer))
75    {$DEFAULT{field_type}->{$_} = 'Message::Field::Address'}    {$DEFAULT{-value_type}->{$_} = ['Message::Field::URI']}
76  for (qw(date date-received delivery-date expires  
77    expire-date nntp-posting-date posted reply-by resent-date x-tcup-date))  my %header_goodcase = (
78    {$DEFAULT{field_type}->{$_} = 'Message::Field::Date'}          'article-i.d.'  => 'Article-I.D.',
79  for (qw(article-updates client-date content-id in-reply-to message-id          etag    => 'ETag',
80    references resent-message-id see-also supersedes))          'pics-label'    => 'PICS-Label',
81    {$DEFAULT{field_type}->{$_} = 'Message::Field::MsgID'}          te      => 'TE',
82  for (qw(accept accept-charset accept-encoding accept-language          url     => 'URL',
83    content-language          'www-authenticate'      => 'WWW-Authenticate',
84    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'}  
85    
86  ## taken from L<HTTP::Header>  ## taken from L<HTTP::Header>
87  # "Good Practice" order of HTTP message headers:  # "Good Practice" order of HTTP message headers:
# Line 140  my @header_order = qw( Line 113  my @header_order = qw(
113  );  );
114  my %header_order;  my %header_order;
115    
116    =head1 CONSTRUCTORS
117    
118    The following methods construct new C<Message::Header> objects:
119    
120    =over 4
121    
122    =cut
123    
124  sub _init ($;%) {  sub _init ($;%) {
125    my $self = shift;    my $self = shift;
126    my %options = @_;    my %options = @_;
127    $self->{field} = [];    my $DEFAULT = Message::Util::make_clone (\%DEFAULT);
128    $self->{option} = \%DEFAULT;    $self->SUPER::_init (%$DEFAULT, %options);
129      $self->{value} = [];
130      $self->_ns_load_ph ('default');
131      $self->{ns}->{default_phuri} = $self->{ns}->{phname2uri}->{'default'};
132      $self->_ns_load_ph ('rfc822');
133      $self->{ns}->{default_phuri} = $self->{ns}->{phname2uri}->{'rfc822'};
134      
135    my @new_fields = ();    my @new_fields = ();
136    for my $name (keys %options) {    for my $name (keys %options) {
137      if (substr ($name, 0, 1) eq '-') {      unless (substr ($name, 0, 1) eq '-') {
       $self->{option}->{substr ($name, 1)} = $options{$name};  
     } else {  
138        push @new_fields, ($name => $options{$name});        push @new_fields, ($name => $options{$name});
139      }      }
140    }    }
141    $self->add (@new_fields, -parse => $self->{option}->{parse_all})    $self->_init_by_format ($self->{option}->{format}, $self->{option});
     if $#new_fields > -1;  
     
   my $format = $self->{option}->{format};  
   if ($format =~ /^cgi/) {  
     unshift @header_order, qw(content-type location);  
     $self->{option}->{sort} = 'good-practice';  
   } elsif ($format =~ /^http/) {  
     $self->{option}->{sort} = 'good-practice';  
   }  
     
142    # Make alternative representations of @header_order.  This is used    # Make alternative representations of @header_order.  This is used
143    # for sorting.    # for sorting.
144    my $i = 1;    my $i = 1;
145    for (@header_order) {    for (@header_order) {
146        $header_order{$_} = $i++ unless $header_order{$_};        $header_order{$_} = $i++ unless $header_order{$_};
147    }    }
148      
149      $self->add (@new_fields, -parse => $self->{option}->{parse_all})
150        if $#new_fields > -1;
151  }  }
152    
153  =head2 Message::Header->new ([%initial-fields/options])  sub _init_by_format ($$\%) {
154      my $self = shift;
155      my ($format, $option) = @_;
156      if ($format =~ /cgi/) {
157        unshift @header_order, qw(content-type location);
158        $option->{field_sort} = 'good-practice';
159        $option->{use_folding} = 0;
160      } elsif ($format =~ /http/) {
161        $option->{field_sort} = 'good-practice';
162      }
163      if ($format =~ /uri-url-mailto/) {
164        $option->{output_bcc} = 0;
165        $option->{field_format_pattern} = '%s=%s';
166        $option->{output_folding} = sub {
167          $_[1] =~ s/([^:@+\$A-Za-z0-9\-_.!~*])/sprintf('%%%02X', ord $1)/ge;
168          $_[1];
169        };  ## Yes, this is not folding!
170      }
171    }
172    
173    =item $msg = Message::Header->new ([%initial-fields/options])
174    
175  Constructs a new C<Message::Headers> object.  You might pass some initial  Constructs a new C<Message::Headers> object.  You might pass some initial
176  C<field-name>-C<field-body> pairs and/or options as parameters to the constructor.  C<field-name>-C<field-body> pairs and/or options as parameters to the constructor.
177    
178  =head3 example  Example:
179    
180   $hdr = new Message::Headers   $hdr = new Message::Headers
181          Date         => 'Thu, 03 Feb 1994 00:00:00 +0000',          Date         => 'Thu, 03 Feb 1994 00:00:00 +0000',
# Line 188  C<field-name>-C<field-body> pairs and/or Line 186  C<field-name>-C<field-body> pairs and/or
186    
187  =cut  =cut
188    
189  sub new ($;%) {  ## Inherited
   my $class = shift;  
   my $self = bless {}, $class;  
   $self->_init (@_);  
   $self;  
 }  
190    
191  =head2 Message::Header->parse ($header, [%initial-fields/options])  =item $msg = Message::Header->parse ($header, [%initial-fields/options])
192    
193  Parses given C<header> and constructs a new C<Message::Headers>  Parses given C<header> and constructs a new C<Message::Headers>
194  object.  You might pass some additional C<field-name>-C<field-body> pairs  object.  You might pass some additional C<field-name>-C<field-body> pairs
# Line 207  sub parse ($$;%) { Line 200  sub parse ($$;%) {
200    my $class = shift;    my $class = shift;
201    my $header = shift;    my $header = shift;
202    my $self = bless {}, $class;    my $self = bless {}, $class;
203    $self->_init (@_);    $self->_init (@_);    ## BUG: don't check linebreak_strict
204    $header =~ s/\x0D?\x0A$REG{WSP}/\x20/gos;     ## unfold    $header =~ s/\x0D?\x0A$REG{WSP}/\x20/gos if $self->{option}->{use_folding};
205    for my $field (split /\x0D?\x0A/, $header) {    for my $field (split /\x0D?\x0A/, $header) {
206      if ($field =~ /$REG{M_fromline}/) {      if ($field =~ /$REG{M_fromline}/) {
207        my $body = $1;        my ($s,undef,$value) = $self->_value_to_arrayitem
208        $body = $self->_field_body ($body, 'mail-from')          ('mail-from' => $1, $self->{option});
209          if $self->{option}->{parse_all};        push @{$self->{value}}, $value if $s;
       push @{$self->{field}}, {name => 'mail-from', body => $body};  
210      } elsif ($field =~ /$REG{M_field}/) {      } elsif ($field =~ /$REG{M_field}/) {
211        my ($name, $body) = (lc $1, $2);        my ($name, $body) = ($1, $2);
       $name =~ s/$REG{WSP}+$//;  
212        $body =~ s/$REG{WSP}+$//;        $body =~ s/$REG{WSP}+$//;
213        $body = $self->_field_body ($body, $name) if $self->{option}->{parse_all};        my ($s,undef,$value) = $self->_value_to_arrayitem
214        push @{$self->{field}}, {name => $name, body => $body};          ($name => $body, $self->{option});
215          push @{$self->{value}}, $value if $s;
216        } elsif (length $field) {
217          my ($s,undef,$value) = $self->_value_to_arrayitem
218            ('x-unknown' => $field, $self->{option});
219          push @{$self->{value}}, $value if $s;
220      }      }
221    }    }
222    $self;    $self;
223  }  }
224    
225    =item $msg = Message::Header->parse_array (\@header, [%initial-fields/options])
226    
227    Parses given C<header> and constructs a new C<Message::Headers>
228    object.  Same as C<Message::Header-E<lt>parse> but this method
229    is given an array reference.  You might pass some additional
230    C<field-name>-C<field-body> pairs or/and initial options
231    as parameters to the constructor.
232    
233    =cut
234    
235  sub parse_array ($\@;%) {  sub parse_array ($\@;%) {
236    my $class = shift;    my $class = shift;
237    my $header = shift;    my $header = shift;
# Line 235  sub parse_array ($\@;%) { Line 241  sub parse_array ($\@;%) {
241    $self->_init (@_);    $self->_init (@_);
242    while (1) {    while (1) {
243      my $field = shift @$header;      my $field = shift @$header;
244      while (1) {      if ($self->{option}->{use_folding}) {
245        if ($$header[0] =~ /^$REG{WSP}/) {        while (1) {
246          $field .= shift @$header;          if ($$header[0] =~ /^$REG{WSP}/) {
247        } else {last}            $field .= shift @$header;
248            } else {last}
249          }
250      }      }
251      $field =~ tr/\x0D\x0A//d;   ## BUG: not safe for bar CR/LF      if ($self->{option}->{linebreak_strict}) {
252          $field =~ s/\x0D\x0A//g;
253        } else {
254          $field =~ tr/\x0D\x0A//d;
255        }
256        local $self->{option}->{parse} = $self->{option}->{parse_all};
257      if ($field =~ /$REG{M_fromline}/) {      if ($field =~ /$REG{M_fromline}/) {
258        my $body = $1;        my ($s,undef,$value) = $self->_value_to_arrayitem
259        $body = $self->_field_body ($body, 'mail-from')          ('mail-from' => $1, $self->{option});
260          if $self->{option}->{parse_all};        push @{$self->{value}}, $value if $s;
       push @{$self->{field}}, {name => 'mail-from', body => $body};  
261      } elsif ($field =~ /$REG{M_field}/) {      } elsif ($field =~ /$REG{M_field}/) {
262        my ($name, $body) = (lc $1, $2);        my ($name, $body) = ($self->_n11n_field_name ($1), $2);
       $name =~ s/$REG{WSP}+$//;  
263        $body =~ s/$REG{WSP}+$//;        $body =~ s/$REG{WSP}+$//;
264        $body = $self->_field_body ($body, $name) if $self->{option}->{parse_all};        my ($s,undef,$value) = $self->_value_to_arrayitem
265        push @{$self->{field}}, {name => $name, body => $body};          ($name => $body, $self->{option});
266          push @{$self->{value}}, $value if $s;
267        } elsif (length $field) {
268          my ($s,undef,$value) = $self->_value_to_arrayitem
269            ('x-unknown' => $field, $self->{option});
270          push @{$self->{value}}, $value if $s;
271      }      }
272      last if $#$header < 0;      last if $#$header < 0;
273    }    }
274    $self;    $self;
275  }  }
276    
277    =back
278    
279    =head1 METHODS
280    
281  =head2 $self->field ($field_name)  =head2 $self->field ($field_name)
282    
283  Returns C<field-body> of given C<field-name>.  Returns C<field-body> of given C<field-name>.
# Line 267  context, only first one is returned.) Line 287  context, only first one is returned.)
287    
288  =cut  =cut
289    
290  sub field ($$) {  sub field ($@) {shift->SUPER::item (@_)}
291    sub field_exist ($@) {shift->SUPER::item_exist (@_)}
292    
293    ## item-by?, \$checked-item, {item-key => 1}, \%option
294    sub _item_match ($$\$\%\%) {
295    my $self = shift;    my $self = shift;
296    my $name = lc shift;    my ($by, $i, $list, $option) = @_;
297    my @ret;    return 0 unless ref $$i;  ## Already removed
298    for my $field (@{$self->{field}}) {    if ($by eq 'name') {
299      if ($field->{name} eq $name) {      my %o = %$option; $o{parse} = 0;
300        unless (wantarray) {      my %l;
301          $field->{body} = $self->_field_body ($field->{body}, $name);      for (keys %$list) {
302          return $field->{body};        my ($s, undef, $v) = $self->_value_to_arrayitem ($_, '', %o);
303          if ($s) {
304            $l{$v->{name} . ':' . ( $option->{ns} || $v->{ns} ) } = 1;
305        } else {        } else {
306          $field->{body} = $self->_field_body ($field->{body}, $name);          $l{$v->{name} .':'. ( $option->{ns} || $self->{ns}->{default_phuri} ) } = 1;
         push @ret, $field->{body};  
307        }        }
308      }      }
309        return 1 if $l{$$i->{name} . ':' . $$i->{ns}};
310      } elsif ($by eq 'ns') {
311        my %o = %$option; $o{parse} = 0;
312        my %l;
313        for (keys %$list) {
314          my ($s, undef, $v) = $self->_value_to_arrayitem ($_, '', %o);
315          if ($s) {
316            $l{ $v->{ns} } = 1;
317          } else {
318            $l{ $self->{ns}->{default_phuri} } = 1;
319          }
320        }
321        return 1 if $l{ $$i->{ns} };
322    }    }
323    if ($#ret < 0) {    0;
     return $self->add ($name);  
   }  
   @ret;  
324  }  }
325    *_delete_match = \&_item_match;
326    
327  sub field_exist ($$) {  ## Returns returned item value    \$item-value, \%option
328    my $self = shift;  sub _item_return_value ($\$\%) {
329    my $name = lc shift;    if (ref ${$_[1]}->{body}) {
330    my @ret;      ${$_[1]}->{body};
331    for my $field (@{$self->{field}}) {    } else {
332      return 1 if ($field->{name} eq $name);      ${$_[1]}->{body} = $_[0]->_parse_value (${$_[1]}->{name} => ${$_[1]}->{body},
333          ns => ${$_[1]}->{ns});
334        ${$_[1]}->{body};
335    }    }
   0;  
336  }  }
337    
338  =head2 $self->field_name ($index)  ## Returns returned (new created) item value    $name, \%option
339    sub _item_new_value ($$\%) {
340  Returns C<field-name> of $index'th C<field>.      my ($s,undef,$value) = $_[0]->_value_to_arrayitem
341            ($_[1] => '', $_[2]);
342  =head2 $self->field_body ($index)      $s? $value: undef;
343    }
344    
 Returns C<field-body> of $index'th C<field>.  
345    
 =cut  
346    
347  sub field_name ($$) {  ## $self->_parse_value ($type, $value, %options);
348    my $self = shift;  sub _parse_value ($$$;%) {
349    $self->{field}->[shift]->{name};    my $self = shift;
350  }    my $name = shift ;#|| $self->{option}->{_VALTYPE_DEFAULT};
351  sub field_body ($$) {    my $value = shift;  return $value if ref $value;
352    my $self = shift;    my %option = @_;
353    my $i = shift;    my $vtype; { no strict 'refs';
354    $self->{field}->[$i]->{body}      $vtype = ${&_NS_uri2phpackage ($option{ns}).'::OPTION'}{value_type};
355     = $self->_field_body ($self->{field}->[$i]->{body}, $self->{field}->[$i]->{name});      if (ref $vtype) { $vtype = $vtype->{$name} }
356    $self->{field}->[$i]->{body};      unless (ref $vtype) { $vtype = $vtype->{$self->{option}->{_VALTYPE_DEFAULT}} }
357  }      ## For compatiblity.
358        unless (ref $vtype) { $vtype = $self->{option}->{value_type}->{$name}
359  sub _field_body ($$$) {        || $self->{option}->{value_type}->{$self->{option}->{_VALTYPE_DEFAULT}} }
360    my $self = shift;    }
361    my ($body, $name) = @_;    my $vpackage = $vtype->[0];
362    unless (ref $body) {    my %vopt = %{$vtype->[1]} if ref $vtype->[1];
363      my $type = $self->{option}->{field_type}->{$name}    if ($vpackage eq ':none:') {
364              || $self->{option}->{field_type}->{':DEFAULT'};      return $value;
365      eval "require $type" or Carp::croak ("_field_body: $type: $@");    } elsif (defined $value) {
366      unless ($body) {      eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
367        $body = $type->new (-field_name => $name,      return $vpackage->parse ($value,
368          -format => $self->{option}->{format});        -format   => $self->{option}->{format},
369      } else {        -field_ns => $option{ns},
370        $body = $type->parse ($body, -field_name => $name,        -field_name       => $name,
371          -format => $self->{option}->{format});        -parse_all        => $self->{option}->{parse_all},
372      }      %vopt);
373      } else {
374        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
375        return $vpackage->new (
376          -format   => $self->{option}->{format},
377          -field_ns => $option{ns},
378          -field_name       => $name,
379          -parse_all        => $self->{option}->{parse_all},
380        %vopt);
381    }    }
   $body;  
382  }  }
383    
384  =head2 $self->field_name_list ()  =head2 $self->field_name_list ()
# Line 348  returns ALL names.) Line 391  returns ALL names.)
391    
392  sub field_name_list ($) {  sub field_name_list ($) {
393    my $self = shift;    my $self = shift;
394    $self->_delete_empty_field ();    $self->_delete_empty ();
395    map {$_->{name}} @{$self->{field}};    map { $_->{name} . ':' . $_->{ns} } @{$self->{value}};
396    }
397    
398    sub namespace_ph_default ($;$) {
399      my $self = shift;
400      if (defined $_[0]) {
401        no strict 'refs';
402        $self->{ns}->{default_phuri} = $_[0];
403        $self->_ns_load_ph (${&_NS_uri2phpackage ($self->{ns}->{default_phuri}).'::OPTION'}{namespace_phname});
404      }
405      $self->{ns}->{default_phuri};
406  }  }
407    
408  =head2 $self->add ($field-name, $field-body, [$name, $body, ...])  =item $hdr->add ($field-name, $field-body, [$name, $body, ...])
409    
410  Adds an new C<field>.  It is not checked whether  Adds some field name/body pairs.  Even if there are
411  the field which named $field_body is already exist or not.  one or more fields named given C<$field-name>,
412  If you don't want duplicated C<field>s, use C<replace> method.  given name/body pairs are ADDed.  Use C<replace>
413    to remove same-name-fields.
414    
415  Instead of field name-body pair, you might pass some options.  Instead of field name-body pair, you might pass some options.
416  Four options are available for this method.  Four options are available for this method.
# Line 374  C<-validate>: Checks whether C<field-nam Line 428  C<-validate>: Checks whether C<field-nam
428    
429  =cut  =cut
430    
431  sub add ($%) {  ## [Name: Value] pair -> internal array item
432    my $self = shift;  ## $self->_value_to_arrayitem ($name => $value, {%options})
433    my %fields = @_;  ## or
434    my %option = %{$self->{option}};  ## $self->_value_to_arrayitem ($name => [$value, %value_options], {%options})
435    $option{parse} = defined wantarray unless defined $option{parse};  ##
436    for (grep {/^-/} keys %fields) {$option{substr ($_, 1)} = $fields{$_}}  ## Return: ((1 = success / 0 = failue), $full_name, $arrayitem)
437    my $body;  sub _value_to_arrayitem ($$$\%) {
438    for (grep {/^[^-]/} keys %fields) {    my $self = shift;
439      my $name = lc $_;  $body = $fields{$_};    my ($name, $value, $option) = @_;
440      $name =~ tr/_/-/ if $option{translate_underscore};    my $value_option = {};
441      Carp::croak "add: $name: invalid field-name"    if (ref $value eq 'ARRAY') {
442        if $option{validate} && $name =~ /$REG{UNSAFE_field_name}/;      ($value, %$value_option) = @$value;
443      $body = $self->_field_body ($body, $name) if $option{parse};    }
444      if ($option{prepend}) {    my $nsuri = $self->{ns}->{default_phuri};
445        unshift @{$self->{field}}, {name => $name, body => $body};    no strict 'refs';
446      } else {    if ($option->{ns}) {
447        push @{$self->{field}}, {name => $name, body => $body};      $nsuri = $option->{ns};
448      }    } elsif ($name =~ s/^([Xx]-[A-Za-z]+|[A-Za-z]+)-//) {
449    }      my $oprefix = $1;
450    $body if $option{parse};      my $prefix
451          = &{${&_NS_uri2phpackage ($nsuri).'::OPTION'}{n11n_prefix}}
452            ($self, &_NS_uri2phpackage ($nsuri), $oprefix);
453        $self->_ns_load_ph ($prefix);
454        $nsuri = $self->{ns}->{phname2uri}->{$prefix};
455        unless ($nsuri) {
456          $name = $oprefix . '-' . $name;
457          $nsuri = $self->{ns}->{default_phuri};
458        }
459      }
460      $name
461        = &{${&_NS_uri2phpackage ($nsuri).'::OPTION'}{n11n_name}}
462          ($self, &_NS_uri2phpackage ($nsuri), $name);
463      Carp::croak "$name: invalid field-name"
464        if $option->{field_name_validation}
465          && $name =~ /$REG{$option->{field_name_unsafe_rule}}/;
466      $value = $self->_parse_value ($name => $value, ns => $nsuri) if $$option{parse};
467      $$option{parse} = 0;
468      (1, $name.':'.$nsuri => {name => $name, body => $value, ns => $nsuri});
469  }  }
470    *_add_hash_check = \&_value_to_arrayitem;
471    *_replace_hash_check = \&_value_to_arrayitem;
472    
473  =head2 $self->relace ($field_name, $field_body)  =head2 $self->relace ($field_name, $field_body)
474    
# Line 406  first one is used and the others are not Line 480  first one is used and the others are not
480    
481  =cut  =cut
482    
483  sub replace ($%) {  sub _replace_hash_shift ($\%$\%) {
484    my $self = shift;    shift; my $r = shift;  my $n = $_[0]->{name} . ':' . $_[0]->{ns};
485    my %params = @_;    if ($$r{$n}) {
486    my %option = %{$self->{option}};      my $d = $$r{$n};
487    $option{parse} = defined wantarray unless defined $option{parse};      delete $$r{$n};
488    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}      return $d;
   my (%new_field, $body);  
   for (grep {/^[^-]/} keys %params) {  
     my $name = lc $_;  
     $name =~ tr/_/-/ if $option{translate_underscore};  
     Carp::croak "replace: $name: invalid field-name"  
       if $option{validate} && $name =~ /$REG{UNSAFE_field_name}/;  
     $params{$_} = $self->_field_body ($params{$_}, $name) if $option{parse};  
     $new_field{$name} = $params{$_};  
   }  
   for my $field (@{$self->{field}}) {  
     if (defined $new_field{$field->{name}}) {  
       $body = $new_field {$field->{name}};  
       $field->{body} = $body;  
       $new_field{$field->{name}} = undef;  
     }  
489    }    }
490    for (keys %new_field) {    undef;
     push @{$self->{field}}, {name => $_, body => $new_field{$_}};  
   }  
   $body if $option{parse};  
491  }  }
492    
493  =head2 $self->delete ($field-name, [$name, ...])  =head2 $self->delete ($field-name, [$name, ...])
# Line 440  Deletes C<field> named as $field_name. Line 496  Deletes C<field> named as $field_name.
496    
497  =cut  =cut
498    
 sub delete ($@) {  
   my $self = shift;  
   my %delete;  
   for (@_) {$delete{lc $_} = 1}  
   for my $field (@{$self->{field}}) {  
     undef $field if $delete{$field->{name}};  
   }  
 }  
499    
500  =head2 $self->count ([$field_name])  =head2 $self->count ([$field_name])
501    
# Line 457  of fields.  (Same as $#$self+1) Line 505  of fields.  (Same as $#$self+1)
505    
506  =cut  =cut
507    
508  sub count ($;$) {  sub _count_by_name ($$\%) {
509    my $self = shift;    my $self = shift;
510    my ($name) = (lc shift);    my ($array, $option) = @_;
511    unless ($name) {    my $name = $self->_n11n_field_name ($$option{-name});
512      $self->_delete_empty_field ();    my @a = grep {$_->{name} eq $name} @{$self->{$array}};
513      return $#{$self->{field}}+1;    $#a + 1;
514    }  }
515    my $count = 0;  
516    for my $field (@{$self->{field}}) {  ## Delete empty items
517      if ($field->{name} eq $name) {  sub _delete_empty ($) {
518        $count++;    my $self = shift;
519      }    my $array = $self->{option}->{_HASH_NAME};
520    }    $self->{$array} = [grep {ref $_ && length $_->{name}} @{$self->{$array}}];
   $count;  
521  }  }
522    
523  =head2 $self->rename ($field-name, $new-name, [$old, $new,...])  =head2 $self->rename ($field-name, $new-name, [$old, $new,...])
# Line 486  sub rename ($%) { Line 533  sub rename ($%) {
533    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
534    my %new_name;    my %new_name;
535    for (grep {/^[^-]/} keys %params) {    for (grep {/^[^-]/} keys %params) {
536      my ($old => $new) = (lc $_ => lc $params{$_});      my ($old => $new)
537          = ($self->_n11n_field_name ($_) => $self->_n11n_field_name ($params{$_}));
538        $old =~ tr/_/-/ if $option{translate_underscore};
539      $new =~ tr/_/-/ if $option{translate_underscore};      $new =~ tr/_/-/ if $option{translate_underscore};
540      Carp::croak "rename: $new: invalid field-name"      Carp::croak "rename: $new: invalid field-name"
541        if $option{validate} && $new =~ /$REG{UNSAFE_field_name}/;        if $option{field_name_validation}
542            && $new =~ /$REG{$option{field_name_unsafe_rule}}/;
543      $new_name{$old} = $new;      $new_name{$old} = $new;
544    }    }
545    for my $field (@{$self->{field}}) {    for my $field (@{$self->{value}}) {
546      if (length $new_name{$field->{name}}) {      if (length $new_name{$field->{name}}) {
547        $field->{name} = $new_name{$field->{name}};        $field->{name} = $new_name{$field->{name}};
548      }      }
# Line 510  for each value. Line 560  for each value.
560    
561  =cut  =cut
562    
563  sub scan ($&) {  sub _scan_sort ($\@\%) {
564    my ($self, $sub) = @_;    my $self = shift;
565      my ($array, $option) = @_;
566    my $sort;    my $sort;
567    $sort = \&_header_cmp if $self->{option}->{sort} eq 'good-practice';    $sort = \&_header_cmp if $option->{field_sort} eq 'good-practice';
568    $sort = {$a cmp $b} if $self->{option}->{sort} eq 'alphabetic';    $sort = {$a cmp $b} if $option->{field_sort} eq 'alphabetic';
569    my @field = @{$self->{field}};    return ( sort $sort @$array ) if ref $sort;
570    if (ref $sort) {    @$array;
571      @field = sort $sort @{$self->{field}};  }
572    }  
573    for my $field (@field) {  sub _n11n_field_name ($$) {
574      next if $field->{name} =~ /^_/;    my $self = shift;
575      &$sub($field->{name} => $field->{body});    my $s = shift;
576    }    $s =~ s/^$REG{WSP}+//; $s =~ s/$REG{WSP}+$//;
577      $s = lc $s ;#unless $self->{option}->{field_name_case_sensible};
578      $s;
579  }  }
580    
581  # Compare function which makes it easy to sort headers in the  # Compare function which makes it easy to sort headers in the
# Line 550  sub stringify ($;%) { Line 603  sub stringify ($;%) {
603    my $self = shift;    my $self = shift;
604    my %params = @_;    my %params = @_;
605    my %option = %{$self->{option}};    my %option = %{$self->{option}};
606      $option{format} = $params{-format} if $params{-format};
607      $self->_init_by_format ($option{format}, \%option);
608    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
609    my @ret;    my @ret;
610    if ($option{mail_from}) {    my $_stringify = sub {
611      my $fromline = $self->field ('mail-from');      no strict 'refs';
612      push @ret, 'From '.$fromline if $fromline;        my ($name, $body, $nsuri) = ($_[1]->{name}, $_[1]->{body}, $_[1]->{ns});
613    }        return unless length $name;
614    $self->scan (sub {        return if $option{output_mail_from} && $name eq 'mail-from';
615      my ($name, $body) = (@_);        return if !$option{output_bcc} && ($name eq 'bcc' || $name eq 'resent-bcc');
616      return unless length $name;        my $nspackage = &_NS_uri2phpackage ($nsuri);
617      return if $option{mail_from} && $name eq 'mail-from';        my $oname;        ## Outputed field-name
618      return if !$option{output_bcc} && ($name eq 'bcc' || $name eq 'resent-bcc');        my $prefix = ${$nspackage.'::OPTION'} {namespace_phname_goodcase}
619      my $fbody;                  || $self->{ns}->{uri2phname}->{$nsuri};
620      if (ref $body) {        $prefix = undef if $nsuri eq $self->{ns}->{default_phuri};
621        $fbody = $body->stringify (-format => $option{format});        my $gc = ${$nspackage.'::OPTION'} {to_be_goodcase};
622          if (ref $gc) { $oname = &$gc ($self, $nspackage, $name, \%option) }
623          else { $oname = $name }
624          if ($prefix) { $oname = $prefix . '-' . $oname }
625          if ($option{format} =~ /uri-url-mailto/) {
626            return if (( ${$nspackage.'::OPTION'} {uri_mailto_safe}->{$name}
627                      || ${$nspackage.'::OPTION'} {uri_mailto_safe}->{':default'})
628                      < $option{uri_mailto_safe_level});
629            if ($name eq 'to') {
630              $body = $self->field ('to', -new_item_unless_exist => 0);
631              if (ref $body && $body->have_group) {
632                #
633              } elsif (ref $body && $body->count > 1) {
634                $body = $body->clone;
635                $body->delete ({-by => 'index'}, 0);
636              }
637            }
638          }
639          my $fbody;
640          if (ref $body) {
641            $fbody = $body->stringify (-format => $option{format});
642          } else {
643            $fbody = $body;
644          }
645          return unless length $fbody;
646          unless ($option{linebreak_strict}) {
647            ## bare \x0D and bare \x0A are unsafe
648            $fbody =~ s/\x0D(?=[^\x09\x0A\x20])/\x0D\x20/g;
649            $fbody =~ s/\x0A(?=[^\x09\x20])/\x0A\x20/g;
650          } else {
651            $fbody =~ s/\x0D\x0A(?=[^\x09\x20])/\x0D\x0A\x20/g;
652          }
653          if ($option{use_folding}) {
654            if (ref $option{output_folding}) {
655              $fbody = &{$option{output_folding}} ($self, $fbody,
656                -initial_length => length ($oname) +2);
657            } elsif ($option{output_folding}) {
658              $fbody = $self->_fold ($fbody, -initial_length => length ($oname) +2);
659            }
660          }
661          push @ret, sprintf $option{field_format_pattern}, $oname, $fbody;
662        };
663      if ($option{format} =~ /uri-url-mailto/) {
664        if ($option{format} =~ /uri-url-mailto-to/) {
665          my $to = $self->field ('to', -new_item_unless_exist => 0);
666          if ($to) {
667            unless ($to->have_group) {
668              my $fbody = $to->stringify (-format => $option{format}, -max => 1);
669              return &{$option{output_folding}} ($self, $fbody);
670            }
671          }
672          '';
673        } elsif ($option{format} =~ /uri-url-mailto-rfc1738/) {
674          my $to = $self->field ('to', -new_item_unless_exist => 0);
675          if ($to) {
676            my $fbody = $to->addr_spec (-format => $option{format});
677            return &{$option{output_folding}} ($self, $fbody);
678          }
679          '';
680      } else {      } else {
681        $fbody = $body;        $self->scan ($_stringify);
682      }        my $ret = join ('&', @ret);
683      return unless length $fbody;        $ret;
684      $fbody =~ s/\x0D(?=[^\x09\x0A\x20])/\x0D\x20/g;      }
685      $fbody =~ s/\x0A(?=[^\x09\x20])/\x0A\x20/g;    } else {
686      $name =~ s/((?:^|-)[a-z])/uc($1)/ge if $option{capitalize};      if ($option{output_mail_from}) {
687      push @ret, $name.': '.$self->fold ($fbody);        my $fromline = $self->field ('mail-from', -new_item_unless_exist => 0);
688    });        push @ret, 'From '.$fromline if $fromline;
689    my $ret = join ("\n", @ret);      }
690    $ret? $ret."\n": '';      $self->scan ($_stringify);
691        my $ret = join ("\x0D\x0A", @ret);
692        $ret? $ret."\x0D\x0A": '';
693      }
694  }  }
695  *as_string = \&stringify;  *as_string = \&stringify;
696    
# Line 590  sub option ($@) { Line 706  sub option ($@) {
706      return $self->{option}->{ shift (@_) };      return $self->{option}->{ shift (@_) };
707    }    }
708    while (my ($name, $value) = splice (@_, 0, 2)) {    while (my ($name, $value) = splice (@_, 0, 2)) {
     $name =~ s/^-//;  
709      $self->{option}->{$name} = $value;      $self->{option}->{$name} = $value;
710      if ($name eq 'format') {      if ($name eq 'format') {
711        for my $f (@{$self->{field}}) {        for my $f (@{$self->{field}}) {
# Line 602  sub option ($@) { Line 717  sub option ($@) {
717    }    }
718  }  }
719    
720  sub field_type ($$;$) {  sub field_type ($@) {shift->SUPER::value_type (@_)}
721    
722    ## $self->_fold ($string, %option = (-max, -initial_length(for field-name)) )
723    sub _fold ($$;%) {
724    my $self = shift;    my $self = shift;
725    my $field_name = shift;    my $string = shift;
726    my $new_field_type = shift;    my %option = @_;
727    if ($new_field_type) {    my $max = $self->{option}->{line_length_max};
728      $self->{option}->{field_type}->{$field_name} = $new_field_type;    $max = 20 if $max < 20;
729    }    
730    $self->{option}->{field_type}->{$field_name}    my $l = $option{-initial_length} || 0;
731    || $self->{option}->{field_type}->{':DEFAULT'};    $string =~ s{([\x09\x20][^\x09\x20]+)}{
732        my $s = $1;
733        if ($l + length $s > $max) {
734          $s = "\x0D\x0A\x20" . $s;
735          $l = length ($s) - 2;
736        } else { $l += length $s }
737        $s;
738      }gex;
739      $string;
740  }  }
741    
742  sub _delete_empty_field ($) {  sub _ns_load_ph ($$) {
743    my $self = shift;    my $self = shift;
744    my @ret;    my $name = shift;     ## normalized prefix (without HYPHEN-MINUS)
745    for my $field (@{$self->{field}}) {    return if $self->{ns}->{phname2uri}->{$name};
746      push @ret, $field if $field->{name};    $self->{ns}->{phname2uri}->{$name} = $NS_phname2uri{$name};
747    }    return unless $self->{ns}->{phname2uri}->{$name};
748    $self->{field} = \@ret;    $self->{ns}->{uri2phname}->{$self->{ns}->{phname2uri}->{$name}} = $name;
   $self;  
749  }  }
750    
751  sub fold ($$;$) {  sub _NS_uri2phpackage ($) {
752    my $self = shift;    $NS_uri2phpackage{$_[0]}
753    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;  
754  }  }
755    
756  =head2 $self->clone ()  =head2 $self->clone ()
# Line 663  Returns a copy of Message::Header object Line 759  Returns a copy of Message::Header object
759    
760  =cut  =cut
761    
762  sub clone ($) {  ## Inhreited
   my $self = shift;  
   my $clone = new Message::Header;  
   for my $name (%{$self->{option}}) {  
     if (ref $self->{option}->{$name} eq 'HASH') {  
       $clone->{option}->{$name} = {%{$self->{option}->{$name}}};  
     } elsif (ref $self->{option}->{$name} eq 'ARRAY') {  
       $clone->{option}->{$name} = [@{$self->{option}->{$name}}];  
     } else {  
       $clone->{option}->{$name} = $self->{option}->{$name};  
     }  
   }  
   for (@{$self->{field}}) {  
     $clone->add ($_->{name}, scalar $_->{body});  
   }  
   $clone;  
 }  
763    
764  =head1 NOTE  =head1 NOTE
765    

Legend:
Removed from v.1.14  
changed lines
  Added in v.1.24

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24