ea210ee6549ff933ae9ef8e7a45a57a63aa024cb
[PerlMail.git] / PerlMail / Contacts.pm
1 #! /usr/bin/perl -w
2
3 #       $Id$
4 # Copyright (C) 2002-2003 Jan Kratochvil <short@ucw.cz>
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;
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
27
28 sub new
29 {
30 my($class)=@_;
31 my $self=bless {
32                 "data"=>[],
33                 },$class;
34
35         return $self;
36 }
37
38 sub _parse
39 {
40 my($self,$data,@headers)=@_;
41
42         my $re=join("(.*?)(\r\n)?",map("\Q[$_]\E\r\n",@headers));
43         $re=qr/^$re/s;
44         my @r=();
45         while (my @items=($data=~/$re/s)) {
46                 my %h=();
47                 for my $i (0..$#headers) {
48                         $h{$headers[$i]}=(!$items[2*$i+1] ? undef : $items[2*$i+0])
49                         }
50                 push @r,\%h;
51                 $data=substr($data,length $&);
52                 }
53         die "Unrecognized data (parsing ".join("/",@headers)."): $data" if $data;
54         return @r;
55 }
56
57 sub import
58 {
59 my($self,$data)=@_;
60
61         $self=$self->new() if !ref $self;
62         push @{$self->{"data"}},map({
63                         [ $self->_parse($_->{"RECORD"}."\r\n","FIELD","FIELD-NAME","FIELD-DATA","FIELD-END") ];
64                         } $self->_parse($data,"RECORD","RECORD-END"));
65         return (wantarray() ? @{$self->{"data"}} : $self->{"data"});
66 }
67
68 sub _join
69 {
70 my($self,$href,@headers)=@_;
71
72         my $trailer=pop @headers;
73         return join("",map(("[$_]\r\n".(!defined $href->{$_} ? "" : $href->{$_}."\r\n")),@headers))."[$trailer]\r\n";
74 }
75
76 sub export
77 {
78 my($self,$data)=@_;
79
80         $data=$self->{"data"} if !$data;
81         return join("",map({
82                         "[RECORD]\r\n".join("",map({
83                                         $self->_join($_,"FIELD","FIELD-NAME","FIELD-DATA","FIELD-END");
84                                         } @$_))."[RECORD-END]\r\n";
85                         } @$data));
86 }
87
88 1;