/[suikacvs]/test/cvs
Suika

Diff of /test/cvs

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

revision 1.8 by wakaba, Sat Mar 23 11:43:06 2002 UTC revision 1.25 by wakaba, Wed Jun 12 11:38:56 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        -M_namsepace_prefix_regex => qr/(?!)/,
34        -_VALTYPE_DEFAULT   => ':default',
35        -by => 'name',      ## (Reserved for method level option)
36        -field_format_pattern       => '%s: %s',
37        -field_name_case_sensible   => 0,
38        -field_name_unsafe_rule     => 'NON_ftext',
39        -field_name_validation      => 1,   ## Method level option.
40        -field_sort => 0,
41        #-format    => 'mail-rfc2822',
42        -linebreak_strict   => 0,   ## Not implemented completely
43        -line_length_max    => 60,  ## For folding
44        -ns_default_uri     => $Message::Header::Default::OPTION{namespace_uri},
45        -output_bcc => 0,
46        -output_folding     => 1,
47        -output_mail_from   => 0,
48        #-parse_all => 0,
49        -translate_underscore       => 1,
50        #-uri_mailto_safe
51        -uri_mailto_safe_level      => 4,
52        -use_folding        => 1,
53        #-value_type
54    );
55    
56  $REG{WSP}     = qr/[\x09\x20]/;  $DEFAULT{-value_type} = {
57  $REG{FWS}     = qr/[\x09\x20]*/;          ':default'      => ['Message::Field::Unstructured'],
58  $REG{M_field} = qr/^([^\x3A]+):$REG{FWS}([\x00-\xFF]*)$/;          
59  $REG{M_fromline} = qr/^\x3E?From$REG{WSP}+([\x00-\xFF]*)$/;          p3p     => ['Message::Field::Params'],
60  $REG{UNSAFE_field_name} = qr/[\x00-\x20\x3A\x7F-\xFF]/;          link    => ['Message::Field::ValueParams'],
61            
62            'list-software' => ['Message::Field::UA'],
63            'user-agent'    => ['Message::Field::UA'],
64            server  => ['Message::Field::UA'],
65    };
66    for (qw(pics-label list-id status))
67      {$DEFAULT{-value_type}->{$_} = ['Message::Field::Structured']}
68            ## Not supported yet, but to be supported...
69            # x-list: unstructured, ml name
70    for (qw(date expires))
71      {$DEFAULT{-value_type}->{$_} = ['Message::Field::Date']}
72    for (qw(accept accept-charset accept-encoding accept-language uri))
73      {$DEFAULT{-value_type}->{$_} = ['Message::Field::CSV']}
74    for (qw(location referer))
75      {$DEFAULT{-value_type}->{$_} = ['Message::Field::URI']}
76    
77    my %header_goodcase = (
78            'article-i.d.'  => 'Article-I.D.',
79            etag    => 'ETag',
80            'pics-label'    => 'PICS-Label',
81            te      => 'TE',
82            url     => 'URL',
83            'www-authenticate'      => 'WWW-Authenticate',
84    );
85    
86  =head2 options  ## taken from L<HTTP::Header>
87    # "Good Practice" order of HTTP message headers:
88    #    - General-Headers
89    #    - Request-Headers
90    #    - Response-Headers
91    #    - Entity-Headers
92    # (From draft-ietf-http-v11-spec-rev-01, Nov 21, 1997)
93    my @header_order = qw(
94      mail-from x-envelope-from relay-version path status
95    
96       cache-control connection date pragma transfer-encoding upgrade trailer via
97    
98       accept accept-charset accept-encoding accept-language
99       authorization expect from host
100       if-modified-since if-match if-none-match if-range if-unmodified-since
101       max-forwards proxy-authorization range referer te user-agent
102    
103       accept-ranges age location proxy-authenticate retry-after server vary
104       warning www-authenticate
105    
106       mime-version
107       allow content-base content-encoding content-language content-length
108       content-location content-md5 content-range content-type
109       etag expires last-modified content-style-type content-script-type
110       link
111    
112  These options can be getten/set by C<get_option>/C<set_option>    xref
113  method.  );
114    my %header_order;
115    
116  =head3 capitalize = 0/1  =head1 CONSTRUCTORS
117    
118  (First character of) C<field-name> is capitalized  The following methods construct new C<Message::Header> objects:
 when C<stringify>.  (Default = 1)  
119    
120  =head3 fold_length = numeric value  =over 4
121    
122  Length of line used to fold.  (Default = 70)  =cut
123    
124  =head3 mail_from = 0/1  sub _init ($;%) {
125      my $self = shift;
126      my %options = @_;
127      my $DEFAULT = Message::Util::make_clone (\%DEFAULT);
128      $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 = ();
136      for my $name (keys %options) {
137        unless (substr ($name, 0, 1) eq '-') {
138          push @new_fields, ($name => $options{$name});
139        }
140      }
141      $self->_init_by_format ($self->{option}->{format}, $self->{option});
142      # Make alternative representations of @header_order.  This is used
143      # for sorting.
144      my $i = 1;
145      for (@header_order) {
146          $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    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  Outputs "From " line (known as Un*x From, Mail-From, and so on)  =item $msg = Message::Header->new ([%initial-fields/options])
174  when C<stringify>.  (Default = 0)  
175    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.
177    
178    Example:
179    
180     $hdr = new Message::Headers
181            Date         => 'Thu, 03 Feb 1994 00:00:00 +0000',
182            Content_Type => 'text/html',
183            Content_Location => 'http://www.foo.example/',
184            -format => 'mail-rfc2822'       ## not to be header field
185            ;
186    
187  =cut  =cut
188    
189  %DEFAULT = (  ## Inherited
   capitalize    => 1,  
   fold_length   => 70,  
   mail_from     => 0,  
   field_type    => {':DEFAULT' => 'Message::Field::Unstructured'},  
 );  
 my @field_type_Structured = qw(cancel-lock  
   importance mime-version path precedence user-agent 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(content-description subject title x-nsubject))  
   {$DEFAULT{field_type}->{$_} = 'Message::Field::Subject'}  
190    
191  =head2 Message::Header->new ([%option])  =item $msg = Message::Header->parse ($header, [%initial-fields/options])
192    
193  Returns new Message::Header instance.  Some options can be  Parses given C<header> and constructs a new C<Message::Headers>
194  specified as hash.  object.  You might pass some additional C<field-name>-C<field-body> pairs
195    or/and initial options as parameters to the constructor.
196    
197  =cut  =cut
198    
199  sub new ($;%) {  sub parse ($$;%) {
200    my $class = shift;    my $class = shift;
201    my $self = bless {option => {@_}}, $class;    my $header = shift;
202    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}    my $self = bless {}, $class;
203      $self->_init (@_);    ## BUG: don't check linebreak_strict
204      $header =~ s/\x0D?\x0A$REG{WSP}/\x20/gos if $self->{option}->{use_folding};
205      for my $field (split /\x0D?\x0A/, $header) {
206        if ($field =~ /$REG{M_fromline}/) {
207          my ($s,undef,$value) = $self->_value_to_arrayitem
208            ('mail-from' => $1, $self->{option});
209          push @{$self->{value}}, $value if $s;
210        } elsif ($field =~ /$REG{M_field}/) {
211          my ($name, $body) = ($1, $2);
212          $body =~ s/$REG{WSP}+$//;
213          my ($s,undef,$value) = $self->_value_to_arrayitem
214            ($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  =head2 Message::Header->parse ($header, [%option])  =item $msg = Message::Header->parse_array (\@header, [%initial-fields/options])
226    
227  Parses given C<header> and return a new Message::Header  Parses given C<header> and constructs a new C<Message::Headers>
228  object.  Some options can be specified as hash.  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  =cut
234    
235  sub parse ($$;%) {  sub parse_array ($\@;%) {
236    my $class = shift;    my $class = shift;
237    my $header = shift;    my $header = shift;
238    my $self = bless {option => {@_}}, $class;    Carp::croak "parse_array: first argument is not an array reference"
239    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}      unless ref $header eq 'ARRAY';
240    $header =~ s/\x0D?\x0A$REG{WSP}+/\x20/gos;    ## unfold    my $self = bless {}, $class;
241    for my $field (split /\x0D?\x0A/, $header) {    $self->_init (@_);
242      while (1) {
243        my $field = shift @$header;
244        if ($self->{option}->{use_folding}) {
245          while (1) {
246            if ($$header[0] =~ /^$REG{WSP}/) {
247              $field .= shift @$header;
248            } else {last}
249          }
250        }
251        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        push @{$self->{field}}, {name => 'mail-from', body => $1};        my ($s,undef,$value) = $self->_value_to_arrayitem
259            ('mail-from' => $1, $self->{option});
260          push @{$self->{value}}, $value if $s;
261      } elsif ($field =~ /$REG{M_field}/) {      } elsif ($field =~ /$REG{M_field}/) {
262        my ($name, $body) = ($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        push @{$self->{field}}, {name => lc $name, body => $body};        my ($s,undef,$value) = $self->_value_to_arrayitem
265            ($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;
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 142  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        return 1 if $list->{ $$i->{ns} };
312      }
313      0;
314    }
315    *_delete_match = \&_item_match;
316    
317    ## Returns returned item value    \$item-value, \%option
318    sub _item_return_value ($\$\%) {
319      if (ref ${$_[1]}->{body}) {
320        ${$_[1]}->{body};
321      } else {
322        ${$_[1]}->{body} = $_[0]->_parse_value (${$_[1]}->{name} => ${$_[1]}->{body},
323          ns => ${$_[1]}->{ns});
324        ${$_[1]}->{body};
325    }    }
   @ret;  
326  }  }
327    
328  =head2 $self->field_name ($index)  ## Returns returned (new created) item value    $name, \%option
329    sub _item_new_value ($$\%) {
330  Returns C<field-name> of $index'th C<field>.      my ($s,undef,$value) = $_[0]->_value_to_arrayitem
331            ($_[1] => '', $_[2]);
332  =head2 $self->field_body ($index)      $s? $value: undef;
333    }
334    
 Returns C<field-body> of $index'th C<field>.  
335    
 =cut  
336    
337  sub field_name ($$) {  ## $self->_parse_value ($type, $value, %options);
338    my $self = shift;  sub _parse_value ($$$;%) {
   $self->{field}->[shift]->{name};  
 }  
 sub field_body ($$) {  
339    my $self = shift;    my $self = shift;
340    my $i = shift;    my $name = shift ;#|| $self->{option}->{_VALTYPE_DEFAULT};
341    $self->{field}->[$i]->{body}    my $value = shift;  return $value if ref $value;
342     = $self->_field_body ($self->{field}->[$i]->{body}, $self->{field}->[$i]->{name});    my %option = @_;
343    $self->{field}->[$i]->{body};    my $vtype; { no strict 'refs';
344  }      $vtype = ${&_NS_uri2phpackage ($option{ns}).'::OPTION'}{value_type};
345        if (ref $vtype) { $vtype = $vtype->{$name} }
346  sub _field_body ($$$) {      unless (ref $vtype) { $vtype = $vtype->{$self->{option}->{_VALTYPE_DEFAULT}} }
347    my $self = shift;      ## For compatiblity.
348    my ($body, $name) = @_;      unless (ref $vtype) { $vtype = $self->{option}->{value_type}->{$name}
349    unless (ref $body) {        || $self->{option}->{value_type}->{$self->{option}->{_VALTYPE_DEFAULT}} }
350      my $type = $self->{option}->{field_type}->{$name}    }
351              || $self->{option}->{field_type}->{':DEFAULT'};    my $vpackage = $vtype->[0];
352      eval "require $type";    my %vopt = %{$vtype->[1]} if ref $vtype->[1];
353      unless ($body) {    if ($vpackage eq ':none:') {
354        $body = $type->new (field_name => $name);      return $value;
355      } else {    } elsif (defined $value) {
356        $body = $type->parse ($body, field_name => $name);      eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
357      }      return $vpackage->parse ($value,
358          -format   => $self->{option}->{format},
359          -field_ns => $option{ns},
360          -field_name       => $name,
361          -parse_all        => $self->{option}->{parse_all},
362        %vopt);
363      } else {
364        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
365        return $vpackage->new (
366          -format   => $self->{option}->{format},
367          -field_ns => $option{ns},
368          -field_name       => $name,
369          -parse_all        => $self->{option}->{parse_all},
370        %vopt);
371    }    }
   $body;  
372  }  }
373    
374  =head2 $self->field_name_list ()  =head2 $self->field_name_list ()
# Line 208  returns ALL names.) Line 381  returns ALL names.)
381    
382  sub field_name_list ($) {  sub field_name_list ($) {
383    my $self = shift;    my $self = shift;
384    $self->_delete_empty_field ();    $self->_delete_empty ();
385    map {$_->{name}} @{$self->{field}};    map { $_->{name} . ':' . $_->{ns} } @{$self->{value}};
386  }  }
387    
388  =head2 $self->add ($field_name, $field_body)  sub namespace_ph_default ($;$) {
389      my $self = shift;
390      if (defined $_[0]) {
391        no strict 'refs';
392        $self->{ns}->{default_phuri} = $_[0];
393        $self->_ns_load_ph (${&_NS_uri2phpackage ($self->{ns}->{default_phuri}).'::OPTION'}{namespace_phname});
394      }
395      $self->{ns}->{default_phuri};
396    }
397    
398    =item $hdr->add ($field-name, $field-body, [$name, $body, ...])
399    
400    Adds some field name/body pairs.  Even if there are
401    one or more fields named given C<$field-name>,
402    given name/body pairs are ADDed.  Use C<replace>
403    to remove same-name-fields.
404    
405    Instead of field name-body pair, you might pass some options.
406    Four options are available for this method.
407    
408  Adds an new C<field>.  It is not checked whether  C<-parse>: Parses and validates C<field-body>, and returns
409  the field which named $field_body is already exist or not.  C<field-body> object.  (When multiple C<field-body>s are
410  If you don't want duplicated C<field>s, use C<replace> method.  added, returns only last one.)  (Default: C<defined wantarray>)
411    
412    C<-prepend>: New fields are not appended,
413    but prepended to current fields.  (Default: C<0>)
414    
415    C<-translate-underscore>: Do C<field-name> =~ tr/_/-/.  (Default: C<1>)
416    
417    C<-validate>: Checks whether C<field-name> is valid or not.
418    
419  =cut  =cut
420    
421  sub add ($$$;%) {  ## [Name: Value] pair -> internal array item
422    ## $self->_value_to_arrayitem ($name => $value, {%options})
423    ## or
424    ## $self->_value_to_arrayitem ($name => [$value, %value_options], {%options})
425    ##
426    ## Return: ((1 = success / 0 = failue), $full_name, $arrayitem)
427    sub _value_to_arrayitem ($$$\%) {
428    my $self = shift;    my $self = shift;
429    my ($name, $body) = (lc shift, shift);    my ($name, $value, $option) = @_;
430    my %option = @_;    my $value_option = {};
431    return 0 if $name =~ /$REG{UNSAFE_field_name}/;    if (ref $value eq 'ARRAY') {
432    $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};  
433    }    }
434    $body;    my $nsuri = $self->{ns}->{default_phuri};
435      no strict 'refs';
436      if ($value_option->{ns}) {
437        $nsuri = $value_option->{ns};
438      } elsif ($option->{ns}) {
439        $nsuri = $option->{ns};
440      } elsif ($name =~ s/^([Xx]-[A-Za-z]+|[A-Za-z]+)-//) {
441        my $oprefix = $1;
442        my $prefix
443          = &{${&_NS_uri2phpackage ($nsuri).'::OPTION'}{n11n_prefix}}
444            ($self, &_NS_uri2phpackage ($nsuri), $oprefix);
445        $self->_ns_load_ph ($prefix);
446        $nsuri = $self->{ns}->{phname2uri}->{$prefix};
447        unless ($nsuri) {
448          $name = $oprefix . '-' . $name;
449          $nsuri = $self->{ns}->{default_phuri};
450        }
451      }
452      $name
453        = &{${&_NS_uri2phpackage ($nsuri).'::OPTION'}{n11n_name}}
454          ($self, &_NS_uri2phpackage ($nsuri), $name);
455      Carp::croak "$name: invalid field-name"
456        if $option->{field_name_validation}
457          && $name =~ /$REG{$option->{field_name_unsafe_rule}}/;
458      $value = $self->_parse_value ($name => $value, ns => $nsuri) if $$option{parse};
459      $$option{parse} = 0;
460      (1, $name.':'.$nsuri => {name => $name, body => $value, ns => $nsuri});
461  }  }
462    *_add_hash_check = \&_value_to_arrayitem;
463    *_replace_hash_check = \&_value_to_arrayitem;
464    
465  =head2 $self->relace ($field_name, $field_body)  =head2 $self->relace ($field_name, $field_body)
466    
# Line 244  first one is used and the others are not Line 472  first one is used and the others are not
472    
473  =cut  =cut
474    
475  sub replace ($$$) {  sub _replace_hash_shift ($\%$\%) {
476    my $self = shift;    shift; my $r = shift;  my $n = $_[0]->{name} . ':' . $_[0]->{ns};
477    my ($name, $body) = (lc shift, shift);    if ($$r{$n}) {
478    return 0 if $name =~ /$REG{UNSAFE_field_name}/;      my $d = $$r{$n};
479    for my $field (@{$self->{field}}) {      delete $$r{$n};
480      if ($field->{name} eq $name) {      return $d;
       $field->{body} = $body;  
       return $body;  
     }  
481    }    }
482    push @{$self->{field}}, {name => $name, body => $body};    undef;
   $self;  
483  }  }
484    
485  =head2 $self->delete ($field_name, [$index])  =head2 $self->delete ($field-name, [$name, ...])
486    
487  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.  
488    
489  =cut  =cut
490    
 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;  
 }  
491    
492  =head2 $self->count ([$field_name])  =head2 $self->count ([$field_name])
493    
# Line 291  of fields.  (Same as $#$self+1) Line 497  of fields.  (Same as $#$self+1)
497    
498  =cut  =cut
499    
500  sub count ($;$) {  sub _count_by_name ($$\%) {
501    my $self = shift;    my $self = shift;
502    my ($name) = (lc shift);    my ($array, $option) = @_;
503    unless ($name) {    my $name = $self->_n11n_field_name ($$option{-name});
504      $self->_delete_empty_field ();    my @a = grep {$_->{name} eq $name} @{$self->{$array}};
505      return $#{$self->{field}}+1;    $#a + 1;
   }  
   my $count = 0;  
   for my $field (@{$self->{field}}) {  
     if ($field->{name} eq $name) {  
       $count++;  
     }  
   }  
   $count;  
506  }  }
507    
508  =head2 $self->stringify ([%option])  ## Delete empty items
509    sub _delete_empty ($) {
510      my $self = shift;
511      my $array = $self->{option}->{_HASH_NAME};
512      $self->{$array} = [grep {ref $_ && length $_->{name}} @{$self->{$array}}];
513    }
514    
515  Returns the C<header> as a string.  =head2 $self->rename ($field-name, $new-name, [$old, $new,...])
516    
517    Renames C<$field-name> as C<$new-name>.
518    
519  =cut  =cut
520    
521  sub stringify ($;%) {  sub rename ($%) {
522    my $self = shift;    my $self = shift;
523    my %OPT = @_;    my %params = @_;
524    my @ret;    my %option = %{$self->{option}};
525    $OPT{capitalize} ||= $self->{option}->{capitalize};    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
526    $OPT{mail_from} ||= $self->{option}->{mail_from};    my %new_name;
527    push @ret, 'From '.$self->field ('mail-from') if $OPT{mail_from};    for (grep {/^[^-]/} keys %params) {
528    for my $field (@{$self->{field}}) {      my ($old => $new)
529      my $name = $field->{name};        = ($self->_n11n_field_name ($_) => $self->_n11n_field_name ($params{$_}));
530      next unless $field->{name};      $old =~ tr/_/-/ if $option{translate_underscore};
531      next if !$OPT{mail_from} && $name eq 'mail-from';      $new =~ tr/_/-/ if $option{translate_underscore};
532      my $fbody = scalar $field->{body};      Carp::croak "rename: $new: invalid field-name"
533      next unless $fbody;        if $option{field_name_validation}
534      $name =~ s/((?:^|-)[a-z])/uc($1)/ge if $OPT{capitalize};          && $new =~ /$REG{$option{field_name_unsafe_rule}}/;
535      push @ret, $name.': '.$self->fold ($fbody);      $new_name{$old} = $new;
536      }
537      for my $field (@{$self->{value}}) {
538        if (length $new_name{$field->{name}}) {
539          $field->{name} = $new_name{$field->{name}};
540        }
541    }    }
542    my $ret = join ("\n", @ret);    $self if defined wantarray;
   $ret? $ret."\n": "";  
543  }  }
544    
 =head2 $self->get_option ($option_name)  
   
 Returns value of the option.  
545    
546  =head2 $self->set_option ($option_name, $option_value)  =item $self->scan(\&doit)
547    
548  Set new value of the option.  Apply a subroutine to each header field in turn.  The callback routine is
549    called with two parameters; the name of the field and a single value.
550    If the header has more than one value, then the routine is called once
551    for each value.
552    
553  =cut  =cut
554    
555  sub get_option ($$) {  sub _scan_sort ($\@\%) {
556    my $self = shift;    my $self = shift;
557    my ($name) = @_;    my ($array, $option) = @_;
558    $self->{option}->{$name};    my $sort;
559      $sort = \&_header_cmp if $option->{field_sort} eq 'good-practice';
560      $sort = {$a cmp $b} if $option->{field_sort} eq 'alphabetic';
561      return ( sort $sort @$array ) if ref $sort;
562      @$array;
563  }  }
564  sub set_option ($$$) {  
565    sub _n11n_field_name ($$) {
566    my $self = shift;    my $self = shift;
567    my ($name, $value) = @_;    my $s = shift;
568    $self->{option}->{$name} = $value;    $s =~ s/^$REG{WSP}+//; $s =~ s/$REG{WSP}+$//;
569    $self;    $s = lc $s ;#unless $self->{option}->{field_name_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  sub field_type ($$;$) {  =head2 $self->stringify ([%option])
589    
590    Returns the C<header> as a string.
591    
592    =cut
593    
594    sub stringify ($;%) {
595    my $self = shift;    my $self = shift;
596    my $field_name = shift;    my %params = @_;
597    my $new_field_type = shift;    my %option = %{$self->{option}};
598    if ($new_field_type) {    $option{format} = $params{-format} if $params{-format};
599      $self->{option}->{field_type}->{$field_name} = $new_field_type;    $self->_init_by_format ($option{format}, \%option);
600      for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
601      my @ret;
602      my $_stringify = sub {
603        no strict 'refs';
604          my ($name, $body, $nsuri) = ($_[1]->{name}, $_[1]->{body}, $_[1]->{ns});
605          return unless length $name;
606          return if $option{output_mail_from} && $name eq 'mail-from';
607          return if !$option{output_bcc} && ($name eq 'bcc' || $name eq 'resent-bcc');
608          my $nspackage = &_NS_uri2phpackage ($nsuri);
609          my $oname;        ## Outputed field-name
610          my $prefix = ${$nspackage.'::OPTION'} {namespace_phname_goodcase}
611                    || $self->{ns}->{uri2phname}->{$nsuri};
612          $prefix = undef if $nsuri eq $self->{ns}->{default_phuri};
613          my $gc = ${$nspackage.'::OPTION'} {to_be_goodcase};
614          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          return unless length $fbody;
638          unless ($option{linebreak_strict}) {
639            ## bare \x0D and bare \x0A are unsafe
640            $fbody =~ s/\x0D(?=[^\x09\x0A\x20])/\x0D\x20/g;
641            $fbody =~ s/\x0A(?=[^\x09\x20])/\x0A\x20/g;
642          } else {
643            $fbody =~ s/\x0D\x0A(?=[^\x09\x20])/\x0D\x0A\x20/g;
644          }
645          if ($option{use_folding}) {
646            if (ref $option{output_folding}) {
647              $fbody = &{$option{output_folding}} ($self, $fbody,
648                -initial_length => length ($oname) +2);
649            } elsif ($option{output_folding}) {
650              $fbody = $self->_fold ($fbody, -initial_length => length ($oname) +2);
651            }
652          }
653          push @ret, sprintf $option{field_format_pattern}, $oname, $fbody;
654        };
655      if ($option{format} =~ /uri-url-mailto/) {
656        if ($option{format} =~ /uri-url-mailto-to/) {
657          my $to = $self->field ('to', -new_item_unless_exist => 0);
658          if ($to) {
659            unless ($to->have_group) {
660              my $fbody = $to->stringify (-format => $option{format}, -max => 1);
661              return &{$option{output_folding}} ($self, $fbody);
662            }
663          }
664          '';
665        } elsif ($option{format} =~ /uri-url-mailto-rfc1738/) {
666          my $to = $self->field ('to', -new_item_unless_exist => 0);
667          if ($to) {
668            my $fbody = $to->addr_spec (-format => $option{format});
669            return &{$option{output_folding}} ($self, $fbody);
670          }
671          '';
672        } else {
673          $self->scan ($_stringify);
674          my $ret = join ('&', @ret);
675          $ret;
676        }
677      } else {
678        if ($option{output_mail_from}) {
679          my $fromline = $self->field ('mail-from', -new_item_unless_exist => 0);
680          push @ret, 'From '.$fromline if $fromline;
681        }
682        $self->scan ($_stringify);
683        my $ret = join ("\x0D\x0A", @ret);
684        $ret? $ret."\x0D\x0A": '';
685    }    }
   $self->{option}->{field_type}->{$field_name}  
   || $self->{option}->{field_type}->{':DEFAULT'};  
686  }  }
687    *as_string = \&stringify;
688    
689    =head2 $self->option ($option_name, [$option_value])
690    
691    Set/gets new value of the option.
692    
693  sub _delete_empty_field ($) {  =cut
694    
695    sub option ($@) {
696    my $self = shift;    my $self = shift;
697    my @ret;    if (@_ == 1) {
698    for my $field (@{$self->{field}}) {      return $self->{option}->{ shift (@_) };
699      push @ret, $field if $field->{name};    }
700      while (my ($name, $value) = splice (@_, 0, 2)) {
701        $self->{option}->{$name} = $value;
702        if ($name eq 'format') {
703          for my $f (@{$self->{field}}) {
704            if (ref $f->{body}) {
705              $f->{body}->option (-format => $value);
706            }
707          }
708        }
709    }    }
   $self->{field} = \@ret;  
   $self;  
710  }  }
711    
712  sub fold ($$;$) {  sub field_type ($@) {shift->SUPER::value_type (@_)}
713    
714    ## $self->_fold ($string, %option = (-max, -initial_length(for field-name)) )
715    sub _fold ($$;%) {
716    my $self = shift;    my $self = shift;
717    my $string = shift;    my $string = shift;
718    my $len = shift || $self->{option}->{fold_length};    my %option = @_;
719    $len = 60 if $len < 60;    my $max = $self->{option}->{line_length_max};
720        $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;  
721        
722    if (length($string) > $ml) {    my $l = $option{-initial_length} || 0;
723       #Split the line up    $string =~ s{([\x09\x20][^\x09\x20]+)}{
724       # first bias towards splitting at a , or a ; >4/5 along the line      my $s = $1;
725       # next split a whitespace      if ($l + length $s > $max) {
726       # else we are looking at a single word and probably don't want to split        $s = "\x0D\x0A\x20" . $s;
727       my $x = "";        $l = length ($s) - 2;
728       $x .= "$1\n    "      } else { $l += length $s }
729         while($string =~ s/^$REG{WSP}*(      $s;
730                            [^"]{$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;  
   }  
731    $string;    $string;
732  }  }
733    
734    sub _ns_load_ph ($$) {
735      my $self = shift;
736      my $name = shift;     ## normalized prefix (without HYPHEN-MINUS)
737      return if $self->{ns}->{phname2uri}->{$name};
738      $self->{ns}->{phname2uri}->{$name} = $NS_phname2uri{$name};
739      return unless $self->{ns}->{phname2uri}->{$name};
740      $self->{ns}->{uri2phname}->{$self->{ns}->{phname2uri}->{$name}} = $name;
741    }
742    
743    sub _NS_uri2phpackage ($) {
744      $NS_uri2phpackage{$_[0]}
745      || $NS_uri2phpackage{$Message::Header::Default::OPTION{namespace_uri}};
746    }
747    
748    =head2 $self->clone ()
749    
750    Returns a copy of Message::Header object.
751    
752    =cut
753    
754    ## Inhreited
755    
756    =head1 NOTE
757    
758    =head2 C<field-name>
759    
760    The header field name is not case sensitive.  To make the life
761    easier for perl users who wants to avoid quoting before the => operator,
762    you can use '_' as a synonym for '-' in header field names
763    (this behaviour can be suppressed by setting
764    C<translate_underscore> option to C<0> value).
765    
766  =head1 EXAMPLE  =head1 EXAMPLE
767    
768    ## Print field list    ## Print field list
# Line 417  sub fold ($$;$) { Line 770  sub fold ($$;$) {
770    use Message::Header;    use Message::Header;
771    my $header = Message::Header->parse ($header);    my $header = Message::Header->parse ($header);
772        
   ## Next sample is better.  
   #for my $field (@$header) {  
   #  print $field->{name}, "\t=> ", $field->{body}, "\n";  
   #}  
     
773    for my $i (0..$#$header) {    for my $i (0..$#$header) {
774      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";
775    }    }
# Line 444  sub fold ($$;$) { Line 792  sub fold ($$;$) {
792    $header->add ('References' => '<hoge.msgid%foo@foo.example>');    $header->add ('References' => '<hoge.msgid%foo@foo.example>');
793    print $header;    print $header;
794    
795    =head1 ACKNOWLEDGEMENTS
796    
797    Some of codes are taken from other modules such as
798    HTTP::Header, Mail::Header.
799    
800  =head1 LICENSE  =head1 LICENSE
801    
802  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.8  
changed lines
  Added in v.1.25

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24