Main trunk update from the "lace" branch.
[PerlMail.git] / PerlMail / Contacts / 9000.pm
1 #! /usr/bin/perl
2
3 #       $Id$
4 # Copyright (C) 2002-2004 Jan Kratochvil <project-PerlMail@jankratochvil.net>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20
21 package PerlMail::Contacts::9000;
22 use vars qw($VERSION);
23 $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
24 use strict;
25 use warnings;
26 use vars qw(@ISA);
27 require PerlMail::Contacts;
28 @ISA=qw(PerlMail::Contacts);
29
30
31 sub _parse
32 {
33 my($self,$data,@headers)=@_;
34
35         my $re=join("(.*?)(\r\n)?",map("\Q[$_]\E\r\n",@headers));
36         $re=qr/^$re/s;
37         my @r=();
38         while (my @items=($data=~/$re/s)) {
39                 my %h=();
40                 for my $i (0..$#headers) {
41                         $h{$headers[$i]}=(!$items[2*$i+1] ? undef : $items[2*$i+0])
42                         }
43                 push @r,\%h;
44                 $data=substr($data,length $&);
45                 }
46         die "Unrecognized data (parsing ".join("/",@headers)."): $data" if $data;
47         return @r;
48 }
49
50 sub in
51 {
52 my($self,$data)=@_;
53
54         $self=$self->new() if !ref $self;
55         push @{$self->{"data"}},map({
56                         [ $self->_parse($_->{"RECORD"}."\r\n","FIELD","FIELD-NAME","FIELD-DATA","FIELD-END") ];
57                         } $self->_parse($data,"RECORD","RECORD-END"));
58         return (wantarray() ? @{$self->{"data"}} : $self->{"data"});
59 }
60
61 sub _join
62 {
63 my($self,$href,@headers)=@_;
64
65         my $trailer=pop @headers;
66         return join("",map(("[$_]\r\n".(!defined $href->{$_} ? "" : $href->{$_}."\r\n")),@headers))."[$trailer]\r\n";
67 }
68
69 sub out
70 {
71 my($self,$data)=@_;
72
73         $data=$self->{"data"} if !$data;
74         return join("",map({
75                         "[RECORD]\r\n".join("",map({
76                                         $self->_join($_,"FIELD","FIELD-NAME","FIELD-DATA","FIELD-END");
77                                         } @$_))."[RECORD-END]\r\n";
78                         } @$data));
79 }
80
81 1;