/[suikacvs]/test/cvs
Suika

Diff of /test/cvs

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

revision 1.3 by wakaba, Wed Mar 13 14:47:07 2002 UTC revision 1.31 by wakaba, Sat Jul 6 10:30:10 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    ## 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  use overload '@{}' => sub {shift->_delete_empty_field()->{field}},  ## taken from L<HTTP::Header>
58               '""' => sub {shift->stringify};  # "Good Practice" order of HTTP message headers:
59    #    - General-Headers
60    #    - Request-Headers
61    #    - 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  $REG{WSP}     = qr/[\x09\x20]/;    xref
84  $REG{FWS}     = qr/[\x09\x20]*/;  );
85  $REG{M_field} = qr/^([^\x3A]+):$REG{FWS}([\x00-\xFF]*)$/;  my %header_order;
86  $REG{M_fromline} = qr/^\x3E?From$REG{WSP}+([\x00-\xFF]*)$/;  
87  $REG{UNSAFE_field_name} = qr/[\x00-\x20\x3A\x7F-\xFF]/;  =head1 CONSTRUCTORS
88    
89  =head2 options  The following methods construct new C<Message::Header> objects:
90    
91  These options can be getten/set by C<get_option>/C<set_option>  =over 4
 method.  
92    
93  =head3 capitalize = 0/1  =cut
94    
95    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 ('x-rfc822');
103      $self->_ns_load_ph ('x-http');
104      $self->{option}->{ns_default_phuri} = $self->{ns}->{phname2uri}->{'x-rfc822'}
105        unless $self->{option}->{ns_default_phuri};
106      
107      ## For text/rfc822-headers
108      if (ref $options{entity_header}) {
109        $self->{entity_header} = $options{entity_header};
110        delete $options{entity_header};
111      }
112      my @new_fields = ();
113      for my $name (keys %options) {
114        unless (substr ($name, 0, 1) eq '-') {
115          push @new_fields, ($name => $options{$name});
116        }
117      }
118      $self->_init_by_format ($self->{option}->{format}, $self->{option});
119      # Make alternative representations of @header_order.  This is used
120      # for sorting.
121      my $i = 1;
122      for (@header_order) {
123          $header_order{$_} = $i++ unless $header_order{$_};
124      }
125      
126      $self->add (@new_fields, -parse => $self->{option}->{parse_all})
127        if $#new_fields > -1;
128    }
129    
130  (First character of) C<field-name> is capitalized  sub _init_by_format ($$\%) {
131  when C<stringify>.  (Default = 1)    my $self = shift;
132      my ($format, $option) = @_;
133      if ($format =~ /http/) {
134        $option->{ns_default_phuri} = $self->{ns}->{phname2uri}->{'x-http'};
135        if ($format =~ /cgi/) {
136          unshift @header_order, qw(content-type location);
137          $option->{field_sort} = 'good-practice';
138          $option->{use_folding} = 0;
139        } else {
140          $option->{field_sort} = 'good-practice';
141        }
142      } else {      ## RFC 822
143        $option->{ns_default_phuri} = $self->{ns}->{phname2uri}->{'x-rfc822'};
144      }
145      if ($format =~ /uri-url-mailto/) {
146        $option->{output_bcc} = 0;
147        $option->{field_format_pattern} = '%s=%s';
148        $option->{output_folding} = sub {
149          $_[1] =~ s/([^:@+\$A-Za-z0-9\-_.!~*])/sprintf('%%%02X', ord $1)/ge;
150          $_[1];
151        };  ## Yes, this is not folding!
152      }
153    }
154    
155  =head3 fold_length = numeric value  =item $msg = Message::Header->new ([%initial-fields/options])
156    
157  Length of line used to fold.  (Default = 70)  Constructs a new C<Message::Headers> object.  You might pass some initial
158    C<field-name>-C<field-body> pairs and/or options as parameters to the constructor.
159    
160  =head3 mail_from = 0/1  Example:
161    
162  Outputs "From " line (known as Un*x From, Mail-From, and so on)   $hdr = new Message::Headers
163  when C<stringify>.  (Default = 0)          Date         => 'Thu, 03 Feb 1994 00:00:00 +0000',
164            Content_Type => 'text/html',
165            Content_Location => 'http://www.foo.example/',
166            -format => 'mail-rfc2822'       ## not to be header field
167            ;
168    
169  =cut  =cut
170    
171  %DEFAULT = (  ## Inherited
   capitalize    => 1,  
   fold_length   => 70,  
   mail_from     => 0,  
 );  
172    
173  =head2 Message::Header->new ([%option])  =item $msg = Message::Header->parse ($header, [%initial-fields/options])
174    
175  Returns new Message::Header instance.  Some options can be  Parses given C<header> and constructs a new C<Message::Headers>
176  specified as hash.  object.  You might pass some additional C<field-name>-C<field-body> pairs
177    or/and initial options as parameters to the constructor.
178    
179  =cut  =cut
180    
181  sub new ($;%) {  sub parse ($$;%) {
182    my $class = shift;    my $class = shift;
183    my $self = bless {option => {@_}}, $class;    my $header = shift;
184    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}    my $self = bless {}, $class;
185      $self->_init (@_);
186      if ($self->{option}->{linebreak_strict}) {
187        $header =~ s/\x0D\x0A$REG{WSP}/\x20/gos if $self->{option}->{use_folding};
188      } else {
189        $header =~ s/\x0D?\x0A$REG{WSP}/\x20/gos if $self->{option}->{use_folding};
190      }
191      for my $field (split /\x0D?\x0A/, $header) {
192        if ($field =~ /$REG{M_fromline}/) {
193          my ($s,undef,$value) = $self->_value_to_arrayitem
194            ('mail-from' => $1, $self->{option});
195          push @{$self->{value}}, $value if $s;
196        } elsif ($field =~ /$REG{M_field}/) {
197          my ($name, $body) = ($1, $2);
198          $body =~ s/$REG{WSP}+$//;
199          my ($s,undef,$value) = $self->_value_to_arrayitem
200            ($name => $body, $self->{option});
201          push @{$self->{value}}, $value if $s;
202        } elsif (length $field) {
203          my ($s,undef,$value) = $self->_value_to_arrayitem
204            ('x-unknown' => $field, $self->{option});
205          push @{$self->{value}}, $value if $s;
206        }
207      }
208      $self->_ns_associate_numerical_prefix;        ## RFC 2774 namespace
209    $self;    $self;
210  }  }
211    
212  =head2 Message::Header->parse ($header, [%option])  =item $msg = Message::Header->parse_array (\@header, [%initial-fields/options])
213    
214  Parses given C<header> and return a new Message::Header  Parses given C<header> and constructs a new C<Message::Headers>
215  object.  Some options can be specified as hash.  object.  Same as C<Message::Header-E<lt>parse> but this method
216    is given an array reference.  You might pass some additional
217    C<field-name>-C<field-body> pairs or/and initial options
218    as parameters to the constructor.
219    
220  =cut  =cut
221    
222  sub parse ($$;%) {  sub parse_array ($\@;%) {
223    my $class = shift;    my $class = shift;
224    my $header = shift;    my $header = shift;
225    my $self = bless {option => {@_}}, $class;    Carp::croak "parse_array: first argument is not an array reference"
226    for (keys %DEFAULT) {$self->{option}->{$_} ||= $DEFAULT{$_}}      unless ref $header eq 'ARRAY';
227    $header =~ s/\x0D?\x0A$REG{WSP}+/\x20/gos;    ## unfold    my $self = bless {}, $class;
228    for my $field (split /\x0D?\x0A/, $header) {    $self->_init (@_);
229      while (1) {
230        my $field = shift @$header;
231        if ($self->{option}->{use_folding}) {
232          while (1) {
233            if ($$header[0] =~ /^$REG{WSP}/) {
234              $field .= shift @$header;
235            } else {last}
236          }
237        }
238        if ($self->{option}->{linebreak_strict}) {
239          $field =~ s/\x0D\x0A//g;
240        } else {
241          $field =~ tr/\x0D\x0A//d;
242        }
243        local $self->{option}->{parse} = $self->{option}->{parse_all};
244      if ($field =~ /$REG{M_fromline}/) {      if ($field =~ /$REG{M_fromline}/) {
245        push @{$self->{field}}, {name => 'mail-from', body => $1};        my ($s,undef,$value) = $self->_value_to_arrayitem
246            ('mail-from' => $1, $self->{option});
247          push @{$self->{value}}, $value if $s;
248      } elsif ($field =~ /$REG{M_field}/) {      } elsif ($field =~ /$REG{M_field}/) {
249        my ($name, $body) = ($1, $2);        my ($name, $body) = ($self->_n11n_field_name ($1), $2);
       $name =~ s/$REG{WSP}+$//;  
250        $body =~ s/$REG{WSP}+$//;        $body =~ s/$REG{WSP}+$//;
251        push @{$self->{field}}, {name => lc $name, body => $body};        my ($s,undef,$value) = $self->_value_to_arrayitem
252            ($name => $body, $self->{option});
253          push @{$self->{value}}, $value if $s;
254        } elsif (length $field) {
255          my ($s,undef,$value) = $self->_value_to_arrayitem
256            ('x-unknown' => $field, $self->{option});
257          push @{$self->{value}}, $value if $s;
258      }      }
259        last if $#$header < 0;
260    }    }
261      $self->_ns_associate_numerical_prefix;        ## RFC 2774 namespace
262    $self;    $self;
263  }  }
264    
265    =back
266    
267    =head1 METHODS
268    
269  =head2 $self->field ($field_name)  =head2 $self->field ($field_name)
270    
271  Returns C<field-body> of given C<field-name>.  Returns C<field-body> of given C<field-name>.
# Line 99  context, only first one is returned.) Line 275  context, only first one is returned.)
275    
276  =cut  =cut
277    
278  sub field ($$) {  sub field ($@) {shift->SUPER::item (@_)}
279    sub field_exist ($@) {shift->SUPER::item_exist (@_)}
280    
281    ## item-by?, \$checked-item, {item-key => 1}, \%option
282    sub _item_match ($$\$\%\%) {
283    my $self = shift;    my $self = shift;
284    my $name = lc shift;    my ($by, $i, $list, $option) = @_;
285    my @ret;    return 0 unless ref $$i;  ## Already removed
286    for my $field (@{$self->{field}}) {    if ($by eq 'name') {
287      if ($field->{name} eq $name) {      my %o = %$option; #$o{parse} = 0;
288        unless (wantarray) {      my %l;
289          return $field->{body};      for (keys %$list) {
290          my ($s, undef, $v) = $self->_value_to_arrayitem ($_, '', %o);
291          if ($s) {
292            $l{$v->{name} . ':' . ( $option->{ns} || $v->{ns} ) } = 1;
293        } else {        } else {
294          push @ret, $field->{body};          $l{$v->{name} .':'. ( $option->{ns} || $self->{option}->{ns_default_phuri} ) } = 1;
295          }
296        }
297        return 1 if $l{$$i->{name} . ':' . $$i->{ns}};
298      } elsif ($by eq 'ns') {
299        return 1 if $list->{ $$i->{ns} };
300      } elsif ($by eq 'http-ns-define') {
301        if ($$i->{ns} eq $self->{ns}->{phname2uri}->{'x-http'}
302         || $$i->{ns} eq $self->{ns}->{phname2uri}->{'x-http-c'}) {
303          my $n = $$i->{name};
304          if ($n eq 'opt' || $n eq 'c-opt' || $n eq 'man' || $n eq 'c-man') {
305            $option->{parse} = 0;
306            $$i->{body} = $self->_parse_value ($$i->{name} => $$i->{body}, ns => $$i->{ns});
307            for my $j (0..$$i->{body}->count-1) {
308              return 1 if $list->{ ($$i->{body}->value ($j))[0]->value };
309            }
310        }        }
311      }      }
312    }    }
313    @ret;    0;
314  }  }
315    *_delete_match = \&_item_match;
316    
317  =head2 $self->field_name ($index)  ## Returns returned item value    \$item-value, \%option
318    sub _item_return_value ($\$\%) {
319  Returns C<field-name> of $index'th C<field>.    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      }
326    }
327    *_add_return_value = \&_item_return_value;
328    *_replace_return_value = \&_item_return_value;
329    
330  =head2 $self->field_body ($index)  ## Returns returned (new created) item value    $name, \%option
331    sub _item_new_value ($$\%) {
332      my $self = shift;
333      my ($name, $option) = @_;
334      if ($option->{by} eq 'http-ns-define') {
335        my $value = $self->_parse_value (opt => '', ns => $self->{ns}->{phname2uri}->{'x-http'});
336        ($value->value (0))[0]->value ($name);
337        {name => 'opt', body => $value, ns => $self->{ns}->{phname2uri}->{'x-http'}};
338      } else {
339        my ($s,undef,$value) = $self->_value_to_arrayitem
340            ($name => '', $option);
341        $s? $value: undef;
342      }
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    sub _parse_value ($$$;%) {
349    my $self = shift;    my $self = shift;
350    $self->{field}->[shift]->{name};    my $name = shift ;#|| $self->{option}->{_VALTYPE_DEFAULT};
351      my $value = shift;  return $value if ref $value;
352      my %option = @_;
353      my $vtype; { no strict 'refs';
354        my $vt = ${&_NS_uri2phpackage ($option{ns}).'::OPTION'}{value_type};
355        if (ref $vt) {
356          $vtype = $vt->{$name} || $vt->{$self->{option}->{_VALTYPE_DEFAULT}};
357        }
358        ## For compatiblity.
359        unless (ref $vtype) { $vtype = $self->{option}->{value_type}->{$name}
360          || $self->{option}->{value_type}->{$self->{option}->{_VALTYPE_DEFAULT}} }
361      }
362      my $vpackage = $vtype->[0];
363      my %vopt = %{$vtype->[1]} if ref $vtype->[1];
364      if ($vpackage eq ':none:') {
365        return $value;
366      } elsif (defined $value) {
367        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
368        return $vpackage->parse ($value,
369          -format   => $self->{option}->{format},
370          -field_ns => $option{ns},
371          -field_name       => $name,
372        -header_default_charset     => $self->{option}->{header_default_charset},
373        -header_default_charset_input       => $self->{option}->{header_default_charset_input},
374          -parse_all        => $self->{option}->{parse_all},
375        %vopt);
376      } else {
377        eval "require $vpackage" or Carp::croak qq{<parse>: $vpackage: Can't load package: $@};
378        return $vpackage->new (
379          -format   => $self->{option}->{format},
380          -field_ns => $option{ns},
381          -field_name       => $name,
382        -header_default_charset     => $self->{option}->{header_default_charset},
383        -header_default_charset_input       => $self->{option}->{header_default_charset_input},
384          -parse_all        => $self->{option}->{parse_all},
385        %vopt);
386      }
387  }  }
388  sub field_body ($$) {  
389    ## Defined for text/rfc822-headers
390    sub entity_header ($;$) {
391    my $self = shift;    my $self = shift;
392    $self->{field}->[shift]->{body};    my $new_header = shift;
393      if (ref $new_header) {
394        $self->{header} = $new_header;
395      }
396      $self->{header};
397  }  }
398    
399  =head2 $self->field_name_list ()  =head2 $self->field_name_list ()
# Line 144  returns ALL names.) Line 406  returns ALL names.)
406    
407  sub field_name_list ($) {  sub field_name_list ($) {
408    my $self = shift;    my $self = shift;
409    $self->_delete_empty_field ();    $self->_delete_empty ();
410    map {$_->{name}} @{$self->{field}};    map { $_->{name} . ':' . $_->{ns} } @{$self->{value}};
411  }  }
412    
413  =head2 $self->add ($field_name, $field_body)  sub namespace_ph_default ($;$) {
414      my $self = shift;
415      if (defined $_[0]) {
416        no strict 'refs';
417        $self->{option}->{ns_default_phuri} = $_[0];
418        $self->_ns_load_ph (${&_NS_uri2phpackage ($self->{option}->{ns_default_phuri}).'::OPTION'}{namespace_phname});
419      }
420      $self->{option}->{ns_default_phuri};
421    }
422    
423    =item $hdr->add ($field-name, $field-body, [$name, $body, ...])
424    
425    Adds some field name/body pairs.  Even if there are
426    one or more fields named given C<$field-name>,
427    given name/body pairs are ADDed.  Use C<replace>
428    to remove same-name-fields.
429    
430    Instead of field name-body pair, you might pass some options.
431    Four options are available for this method.
432    
433    C<-parse>: Parses and validates C<field-body>, and returns
434    C<field-body> object.  (When multiple C<field-body>s are
435    added, returns only last one.)  (Default: C<defined wantarray>)
436    
437  Adds an new C<field>.  It is not checked whether  C<-prepend>: New fields are not appended,
438  the field which named $field_body is already exist or not.  but prepended to current fields.  (Default: C<0>)
439  If you don't want duplicated C<field>s, use C<replace> method.  
440    C<-translate-underscore>: Do C<field-name> =~ tr/_/-/.  (Default: C<1>)
441    
442    C<-validate>: Checks whether C<field-name> is valid or not.
443    
444  =cut  =cut
445    
446  sub add ($$$) {  ## [Name: Value] pair -> internal array item
447    ## $self->_value_to_arrayitem ($name => $value, {%options})
448    ## or
449    ## $self->_value_to_arrayitem ($name => [$value, %value_options], {%options})
450    ##
451    ## Return: ((1 = success / 0 = failue), $full_name, $arrayitem)
452    sub _value_to_arrayitem ($$$\%) {
453    my $self = shift;    my $self = shift;
454    my ($name, $body) = (lc shift, shift);    my ($name, $value, $option) = @_;
455    return 0 if $name =~ /$REG{UNSAFE_field_name}/;    my $value_option = {};
456    push @{$self->{field}}, {name => $name, body => $body};    if (ref $value eq 'ARRAY') {
457    $self;      ($value, %$value_option) = @$value;
458      }
459      my $nsuri = $self->{option}->{ns_default_phuri};
460      $name =~ s/^$REG{WSP}+//;  $name =~ s/$REG{WSP}+$//;
461      
462      no strict 'refs';
463      if ($value_option->{ns}) {
464        $nsuri = $value_option->{ns};
465      } elsif ($option->{ns}) {
466        $nsuri = $option->{ns};
467      } elsif (($option->{ns_default_phuri} eq $self->{ns}->{uri2phname}->{'x-http'}
468           && $name =~ s/^([0-9]+)-//)
469        || ($name =~ s/^x-http-([0-9]+)-//i)) {     ## Numric namespace prefix, RFC 2774
470        my $prefix = 0+$1;
471        $nsuri = $self->{ns}->{number2uri}->{ $prefix };
472        unless ($nsuri) {
473          $self->{ns}->{number2uri}->{ $prefix } = 'urn:x-suika-fam-cx:msgpm:header:x-temp:'.$prefix;
474          $nsuri = $self->{ns}->{number2uri}->{ $prefix };
475        }
476      } elsif (($name =~ s/^([Xx]-[A-Za-z]+|[A-YZa-yz][A-Za-z]*)-
477                           ([Xx]-[A-Za-z]+|[A-YZa-yz][A-Za-z]*)-//x)
478        || $name =~ s/^([Xx]-[A-Za-z]+|[A-Za-z]+)-//) {
479        my ($prefix1, $prefix2) = ($1, $2);
480        my $original_prefix = $&;  my $one_prefix = 0;
481        unless ($prefix2) {
482          $prefix2 = $prefix1;
483          $prefix1 = $self->{ns}->{uri2phname}->{ $option->{ns_default_phuri} };
484          $one_prefix = 1;
485        }
486        my $prefix
487          = &{ ${ &_NS_uri2phpackage ($nsuri).'::OPTION' }{n11n_prefix} }
488            ($self, &_NS_uri2phpackage ($nsuri), $prefix1.'-'.$prefix2);
489        $self->_ns_load_ph ($prefix);
490        $nsuri = $self->{ns}->{phname2uri}->{ $prefix };
491        unless ($nsuri) {
492          $nsuri = $self->{option}->{ns_default_phuri};
493          $prefix
494            = &{ ${ &_NS_uri2phpackage ($nsuri).'::OPTION' }{n11n_prefix} }
495              ($self, &_NS_uri2phpackage ($nsuri), $one_prefix? $prefix2: $prefix1);
496          $self->_ns_load_ph ($prefix);
497          $nsuri = $self->{ns}->{phname2uri}->{ $prefix };
498          if ($nsuri) {
499            $name = $prefix2 . '-' . $name unless $one_prefix;
500          } else {
501            $name = $original_prefix . $name;
502            $nsuri = $self->{option}->{ns_default_phuri};
503          }
504        }
505      }
506      $name
507        = &{${&_NS_uri2phpackage ($nsuri).'::OPTION'}{n11n_name}}
508          ($self, &_NS_uri2phpackage ($nsuri), $name);
509      Carp::croak "$name: invalid field-name"
510        if $option->{field_name_validation}
511          && $name =~ /$REG{$option->{field_name_unsafe_rule}}/;
512      $value = $self->_parse_value ($name => $value, ns => $nsuri)
513        if $$option{parse} || $$option{parse_all};
514      $$option{parse} = 0;
515      (1, $name.':'.$nsuri => {name => $name, body => $value, ns => $nsuri});
516  }  }
517    *_add_hash_check = \&_value_to_arrayitem;
518    *_replace_hash_check = \&_value_to_arrayitem;
519    
520  =head2 $self->relace ($field_name, $field_body)  =head2 $self->relace ($field_name, $field_body)
521    
# Line 174  first one is used and the others are not Line 527  first one is used and the others are not
527    
528  =cut  =cut
529    
530  sub replace ($$$) {  sub _replace_hash_shift ($\%$\%) {
531    my $self = shift;    shift; my $r = shift;  my $n = $_[0]->{name} . ':' . $_[0]->{ns};
532    my ($name, $body) = (lc shift, shift);    if ($$r{$n}) {
533    return 0 if $name =~ /$REG{UNSAFE_field_name}/;      my $d = $$r{$n};
534    for my $field (@{$self->{field}}) {      delete $$r{$n};
535      if ($field->{name} eq $name) {      return $d;
       $field->{body} = $body;  
       return $self;  
     }  
536    }    }
537    push @{$self->{field}}, {name => $name, body => $body};    undef;
   $self;  
538  }  }
539    
540  =head2 $self->delete ($field_name, [$index])  =head2 $self->delete ($field-name, [$name, ...])
541    
542  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.  
543    
544  =cut  =cut
545    
 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;  
 }  
546    
547  =head2 $self->count ([$field_name])  =head2 $self->count ([$field_name])
548    
# Line 221  of fields.  (Same as $#$self+1) Line 552  of fields.  (Same as $#$self+1)
552    
553  =cut  =cut
554    
555  sub count ($;$) {  sub _count_by_name ($$\%) {
556    my $self = shift;    my $self = shift;
557    my ($name) = (lc shift);    my ($array, $option) = @_;
558    unless ($name) {    my $name = $self->_n11n_field_name ($$option{-name});
559      $self->_delete_empty_field ();    my @a = grep {$_->{name} eq $name} @{$self->{$array}};
560      return $#{$self->{field}}+1;    $#a + 1;
   }  
   my $count = 0;  
   for my $field (@{$self->{field}}) {  
     if ($field->{name} eq $name) {  
       $count++;  
     }  
   }  
   $count;  
561  }  }
562    
563  =head2 $self->stringify ([%option])  ## Delete empty items
564    sub _delete_empty ($) {
565      my $self = shift;
566      my $array = $self->{option}->{_HASH_NAME};
567      $self->{$array} = [grep {ref $_ && length $_->{name}} @{$self->{$array}}];
568    }
569    
570  Returns the C<header> as a string.  =head2 $self->rename ($field-name, $new-name, [$old, $new,...])
571    
572    Renames C<$field-name> as C<$new-name>.
573    
574  =cut  =cut
575    
576  sub stringify ($;%) {  sub rename ($%) {
577    my $self = shift;    my $self = shift;
578    my %OPT = @_;    my %params = @_;
579    my @ret;    my %option = %{$self->{option}};
580    $OPT{capitalize} ||= $self->{option}->{capitalize};    for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
581    $OPT{mail_from} ||= $self->{option}->{mail_from};    my %new_name;
582    push @ret, 'From '.$self->field ('mail-from') if $OPT{mail_from};    for (grep {/^[^-]/} keys %params) {
583    for my $field (@{$self->{field}}) {      my ($old => $new)
584      my $name = $field->{name};        = ($self->_n11n_field_name ($_) => $self->_n11n_field_name ($params{$_}));
585      next unless $field->{name};      $old =~ tr/_/-/ if $option{translate_underscore};
586      next if !$OPT{mail_from} && $name eq 'mail-from';      $new =~ tr/_/-/ if $option{translate_underscore};
587      $name =~ s/((?:^|-)[a-z])/uc($1)/ge if $OPT{capitalize};      Carp::croak "rename: $new: invalid field-name"
588      push @ret, $name.': '.$self->fold ($field->{body});        if $option{field_name_validation}
589            && $new =~ /$REG{$option{field_name_unsafe_rule}}/;
590        $new_name{$old} = $new;
591    }    }
592    my $ret = join ("\n", @ret);    for my $field (@{$self->{value}}) {
593    $ret? $ret."\n": "";      if (length $new_name{$field->{name}}) {
594          $field->{name} = $new_name{$field->{name}};
595        }
596      }
597      $self if defined wantarray;
598  }  }
599    
 =head2 $self->get_option ($option_name)  
   
 Returns value of the option.  
600    
601  =head2 $self->set_option ($option_name, $option_value)  =item $self->scan(\&doit)
602    
603  Set new value of the option.  Apply a subroutine to each header field in turn.  The callback routine is
604    called with two parameters; the name of the field and a single value.
605    If the header has more than one value, then the routine is called once
606    for each value.
607    
608  =cut  =cut
609    
610  sub get_option ($$) {  sub _scan_sort ($\@\%) {
611    my $self = shift;    my $self = shift;
612    my ($name) = @_;    my ($array, $option) = @_;
613    $self->{option}->{$name};    my $sort;
614      $sort = \&_header_cmp if $option->{field_sort} eq 'good-practice';
615      $sort = {$a cmp $b} if $option->{field_sort} eq 'alphabetic';
616      return ( sort $sort @$array ) if ref $sort;
617      @$array;
618  }  }
619  sub set_option ($$$) {  
620    sub _n11n_field_name ($$) {
621      no strict 'refs';
622    my $self = shift;    my $self = shift;
623    my ($name, $value) = @_;    my $s = shift;
624    $self->{option}->{$name} = $value;    $s =~ s/^$REG{WSP}+//; $s =~ s/$REG{WSP}+$//;
625    $self;    $s = lc $s unless ${&_NS_uri2phpackage ($self->{option}->{ns_default_phuri}).'::OPTION'}{case_sensible};
626      $s;
627  }  }
628    
629  sub _delete_empty_field ($) {  # Compare function which makes it easy to sort headers in the
630    # recommended "Good Practice" order.
631    ## taken from HTTP::Header
632    sub _header_cmp
633    {
634      my ($na, $nb) = ($a->{name}, $b->{name});
635        # Unknown headers are assign a large value so that they are
636        # sorted last.  This also helps avoiding a warning from -w
637        # about comparing undefined values.
638        $header_order{$na} = 999 unless defined $header_order{$na};
639        $header_order{$nb} = 999 unless defined $header_order{$nb};
640    
641        $header_order{$na} <=> $header_order{$nb} || $na cmp $nb;
642    }
643    
644    =head2 $self->stringify ([%option])
645    
646    Returns the C<header> as a string.
647    
648    =cut
649    
650    sub stringify ($;%) {
651    my $self = shift;    my $self = shift;
652      my %params = @_;
653      my %option = %{$self->{option}};
654      $option{format} = $params{-format} if $params{-format};
655      $self->_init_by_format ($option{format}, \%option);
656      for (grep {/^-/} keys %params) {$option{substr ($_, 1)} = $params{$_}}
657    my @ret;    my @ret;
658    for my $field (@{$self->{field}}) {    ## RFC 2774 numerical field name prefix
659      push @ret, $field if $field->{name};    my %nprefix;
660      {no strict 'refs';
661        %nprefix = reverse %{ $self->{ns}->{number2uri} };
662        my $i = (sort { $a <=> $b } keys %{ $self->{ns}->{number2uri} })[-1] + 1;
663        $i = 10 if $i < 10;
664        my $hprefix = ${ &_NS_uri2phpackage
665                           ($self->{ns}->{phname2uri}->{'x-http'})
666                           .'::OPTION' } {namespace_phname_goodcase};
667        for my $uri (keys %nprefix) {
668          if ($nprefix{ $uri } < 10) {
669            $nprefix{ $uri } = $i++;
670          }
671          my $nsfs = $self->item ($uri, -by => 'http-ns-define');
672          for my $i (0..$nsfs->count-1) {
673            my $nsf = ($nsfs->value ($i))[0];
674            if ($nsf->value eq $uri) {
675              $nsf->replace (ns => $nprefix{ $uri });
676              $nprefix{ $uri } = $hprefix . '-' . $nprefix{ $uri };
677              last;
678            }
679          }
680        }
681      }
682      my $_stringify = sub {
683        no strict 'refs';
684          my ($name, $body, $nsuri) = ($_[1]->{name}, $_[1]->{body}, $_[1]->{ns});
685          return unless length $name;
686          return if $option{output_mail_from} && $name eq 'mail-from';
687          $body = '' if !$option{output_bcc} && $name eq 'bcc';
688          my $nspackage = &_NS_uri2phpackage ($nsuri);
689          my $oname;        ## Outputed field-name
690          my $prefix = $nprefix{ $nsuri }
691                    || ${$nspackage.'::OPTION'} {namespace_phname_goodcase}
692                    || $self->{ns}->{uri2phname}->{ $nsuri };
693          my $default_prefix = ${ &_NS_uri2phpackage ($option{ns_default_phuri})
694                                  .'::OPTION'} {namespace_phname_goodcase};
695          $prefix = '' if $prefix eq $default_prefix;
696          $prefix =~ s/^\Q$default_prefix\E-//;
697          #$prefix = undef if $nsuri eq $option{ns_default_phuri};
698          #if ($prefix && $prefix eq $nprefix{ $nsuri }) {  ## RFC 2774 prefix
699          #  $prefix = ${ &_NS_uri2phpackage ($self->{ns}->{phname2uri}->{'x-http'})
700          #               .'::OPTION' } {namespace_phname_goodcase} . '-' . $prefix
701          #  unless $option{ns_default_phuri} eq $self->{ns}->{phname2uri}->{'x-http'};
702          #}
703          my $gc = ${$nspackage.'::OPTION'} {to_be_goodcase};
704          if (ref $gc) { $oname = &$gc ($self, $nspackage, $name, \%option) }
705          else { $oname = $name }
706          if ($prefix) { $oname = $prefix . '-' . $oname }
707          if ($option{format} =~ /uri-url-mailto/) {
708            return if (( ${$nspackage.'::OPTION'} {uri_mailto_safe}->{$name}
709                      || ${$nspackage.'::OPTION'} {uri_mailto_safe}->{':default'})
710                      < $option{uri_mailto_safe_level});
711            if ($name eq 'to') {
712              $body = $self->field ('to', -new_item_unless_exist => 0);
713              if (ref $body && $body->have_group) {
714                #
715              } elsif (ref $body && $body->count > 1) {
716                $body = $body->clone;
717                $body->delete ({-by => 'index'}, 0);
718              }
719            }
720          }
721          my $fbody;
722          if (ref $body) {
723            $fbody = $body->stringify (-format => $option{format});
724          } else {
725            $fbody = $body;
726          }
727          unless (${$nspackage.'::OPTION'} {field}->{$name}->{empty_body}) {
728            return unless length $fbody;
729          }
730          unless ($option{linebreak_strict}) {
731            ## bare \x0D and bare \x0A are unsafe
732            $fbody =~ s/\x0D(?=[^\x09\x0A\x20])/\x0D\x20/g;
733            $fbody =~ s/\x0A(?=[^\x09\x20])/\x0A\x20/g;
734          } else {
735            $fbody =~ s/\x0D\x0A(?=[^\x09\x20])/\x0D\x0A\x20/g;
736          }
737          if ($option{use_folding}) {
738            if (ref $option{output_folding}) {
739              $fbody = &{$option{output_folding}} ($self, $fbody,
740                -initial_length => length ($oname) +2);
741            } elsif ($option{output_folding}) {
742              $fbody = $self->_fold ($fbody, -initial_length => length ($oname) +2);
743            }
744          }
745          push @ret, sprintf $option{field_format_pattern}, $oname, $fbody;
746        };
747      if ($option{format} =~ /uri-url-mailto/) {
748        if ($option{format} =~ /uri-url-mailto-to/) {
749          my $to = $self->field ('to', -new_item_unless_exist => 0);
750          if ($to) {
751            unless ($to->have_group) {
752              my $fbody = $to->stringify (-format => $option{format}, -max => 1);
753              return &{$option{output_folding}} ($self, $fbody);
754            }
755          }
756          '';
757        } elsif ($option{format} =~ /uri-url-mailto-rfc1738/) {
758          my $to = $self->field ('to', -new_item_unless_exist => 0);
759          if ($to) {
760            my $fbody = $to->addr_spec (-format => $option{format});
761            return &{$option{output_folding}} ($self, $fbody);
762          }
763          '';
764        } else {
765          $self->scan ($_stringify);
766          my $ret = join ('&', @ret);
767          $ret;
768        }
769      } else {
770        if ($option{output_mail_from}) {
771          my $fromline = $self->field ('mail-from', -new_item_unless_exist => 0);
772          push @ret, 'From '.$fromline if $fromline;
773        }
774        $self->scan ($_stringify);
775        my $ret = join ("\x0D\x0A", @ret);
776        $ret? $ret."\x0D\x0A": '';
777      }
778    }
779    *as_string = \&stringify;
780    
781    =head2 $self->option ($option_name, [$option_value])
782    
783    Set/gets new value of the option.
784    
785    =cut
786    
787    sub option ($@) {
788      my $self = shift;
789      if (@_ == 1) {
790        return $self->{option}->{ shift (@_) };
791      }
792      while (my ($name, $value) = splice (@_, 0, 2)) {
793        $self->{option}->{$name} = $value;
794        if ($name eq 'format') {
795          for my $f (@{$self->{field}}) {
796            if (ref $f->{body}) {
797              $f->{body}->option (-format => $value);
798            }
799          }
800        }
801    }    }
   $self->{field} = \@ret;  
   $self;  
802  }  }
803    
804  sub fold ($$;$) {  sub field_type ($@) {shift->SUPER::value_type (@_)}
805    
806    ## $self->_fold ($string, %option = (-max, -initial_length(for field-name)) )
807    sub _fold ($$;%) {
808    my $self = shift;    my $self = shift;
809    my $string = shift;    my $string = shift;
810    my $len = shift || $self->{option}->{fold_length};    my %option = @_;
811    $len = 60 if $len < 60;    my $max = $self->{option}->{line_length_max};
812      $max = 20 if $max < 20;
813        
814    ## This code is taken from Mail::Header 1.43 in MailTools,    my $l = $option{-initial_length} || 0;
815    ## by Graham Barr (Maintained by Mark Overmeer <mailtools@overmeer.net>).    $l += length $1 if $string =~ /^([^\x09\x20]+)/;
816    my $max = int($len - 5);         # 4 for leading spcs + 1 for [\,\;]    $string =~ s{([\x09\x20][^\x09\x20]+)}{
817    my $min = int($len * 4 / 5) - 4;      my $s = $1;
818    my $ml = $len;      if (($l + length $s) > $max) {
819            $s = "\x0D\x0A\x20" . $s;
820    if (length($string) > $ml) {        $l = 1 + length $s;
821       #Split the line up      } else { $l += length $s }
822       # first bias towards splitting at a , or a ; >4/5 along the line      $s;
823       # next split a whitespace    }gex;
      # 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;  
   }  
824    $string;    $string;
825  }  }
826    
827    sub _ns_load_ph ($$) {
828      my $self = shift;
829      my $name = shift;     ## normalized prefix (without HYPHEN-MINUS)
830      return if $self->{ns}->{phname2uri}->{$name};
831      $self->{ns}->{phname2uri}->{$name} = $NS_phname2uri{$name};
832      return unless $self->{ns}->{phname2uri}->{$name};
833      $self->{ns}->{uri2phname}->{$self->{ns}->{phname2uri}->{$name}} = $name;
834    }
835    
836    sub _ns_associate_numerical_prefix ($) {
837      my $self = shift;
838      $self->scan (sub {shift;
839        my $f = shift;  return unless $f->{name};
840        if ($f->{ns} eq $self->{ns}->{phname2uri}->{'x-http'}
841         || $f->{ns} eq $self->{ns}->{phname2uri}->{'x-http-c'}) {
842          my $fn = $f->{name};
843          if ($fn eq 'opt' || $fn eq 'man') {
844            $f->{body} = $self->_parse_value ($fn => $f->{body}, ns => $f->{ns});
845            for ($f->{body}->value (0..$f->{body}->count-1)) {
846              my ($nsuri, $number) = ($_->value, $_->item ('ns'));
847              if ($number && $nsuri) {
848                $self->{ns}->{number2uri}->{ $number } = $nsuri;
849              }
850            }
851          }
852        }
853      });
854      $self->scan (sub {shift;
855        my $f = shift;
856        if ($f->{ns} =~ /urn:x-suika-fam-cx:msgpm:header:x-temp:([0-9]+)$/ && $self->{ns}->{number2uri}->{ $1 }) {
857          $f->{ns} = $self->{ns}->{number2uri}->{ $1 };
858        }
859      });
860    }
861    
862    ## $package_name = Message::Header::_NS_uri2phpackage ($nsuri)
863    ## (For internal use of Message::* modules)
864    sub _NS_uri2phpackage ($) {
865      $NS_uri2phpackage{$_[0]}
866      || $NS_uri2phpackage{$Message::Header::Default::OPTION{namespace_uri}};
867    }
868    
869    =head2 $self->clone ()
870    
871    Returns a copy of Message::Header object.
872    
873    =cut
874    
875    ## Inhreited
876    
877    =head1 NOTE
878    
879    =head2 C<field-name>
880    
881    The header field name is not case sensitive.  To make the life
882    easier for perl users who wants to avoid quoting before the => operator,
883    you can use '_' as a synonym for '-' in header field names
884    (this behaviour can be suppressed by setting
885    C<translate_underscore> option to C<0> value).
886    
887  =head1 EXAMPLE  =head1 EXAMPLE
888    
889    ## Print field list    ## Print field list
# Line 334  sub fold ($$;$) { Line 891  sub fold ($$;$) {
891    use Message::Header;    use Message::Header;
892    my $header = Message::Header->parse ($header);    my $header = Message::Header->parse ($header);
893        
   ## Next sample is better.  
   #for my $field (@$header) {  
   #  print $field->{name}, "\t=> ", $field->{body}, "\n";  
   #}  
     
894    for my $i (0..$#$header) {    for my $i (0..$#$header) {
895      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";      print $header->field_name ($i), "\t=> ", $header->field_body ($i), "\n";
896    }    }
# Line 361  sub fold ($$;$) { Line 913  sub fold ($$;$) {
913    $header->add ('References' => '<hoge.msgid%foo@foo.example>');    $header->add ('References' => '<hoge.msgid%foo@foo.example>');
914    print $header;    print $header;
915    
916    =head1 ACKNOWLEDGEMENTS
917    
918    Some of codes are taken from other modules such as
919    HTTP::Header, Mail::Header.
920    
921  =head1 LICENSE  =head1 LICENSE
922    
923  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.3  
changed lines
  Added in v.1.31

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24