Aldo Valente <[EMAIL PROTECTED]>:
> Paul Franklin <[EMAIL PROTECTED]> writes:
> > If anyone has the original SyncAB with BBDB support, let me know. I
> > forgot to RCS the original before I started.
>
> I think i'll mail it to this list ASAP, so it will be available
> through the archive.
This is v1.4. It's plain ugly, but it works for me.
Aldo
package SyncAB;
# Address Book conduit for PilotManager
# 3/17/98,1/8/99 [EMAIL PROTECTED]
# http://www.moshpit.org/pilotmgr
# Some assistance with vCard testing and
# coding from [EMAIL PROTECTED]
#
# Aldo Valente, [EMAIL PROTECTED], Thu Oct 28 01:10:49 CEST 1999
#
# Wrote readBBDB, to parse a BBDB File and put it in the Pilot.
#
# $Id: SyncAB.pm,v 1.4 2000/01/13 12:04:22 aldo Exp $
#
# $Log: SyncAB.pm,v $
# Revision 1.4 2000/01/13 12:04:22 aldo
# $BBDFile instead of $BBDBFILE
#
# Revision 1.3 2000/01/13 12:01:49 aldo
# I found another User, it's Mark Moll, and he delivered me some fresh
# Bugs to squish:
#
# - Zip Codes can be `("String", "String")'. Fixed.
#
# - Empty Lines in Adresses weren't removed. Fixed.
#
# - It is not senseless to have a Record without Name but with Company.
# I also added Title for the Sanity Check. Fixed.
#
# - Thanks to Mark, i noticed that the Country Field is not existant at
# all in the BBDB. What are we going to do with this? Hmmm.
#
# Revision 1.2 1999/12/20 07:11:08 aldo
# *** empty log message ***
#
# Revision 1.1 1999/10/27 23:13:16 aldo
# Initial revision
#
use PilotSync;
use Tk;
use TkUtils;
use Data::Dumper;
use Carp;
use Lisp::Reader ;
my $VERSION = '0.96 BETAp1';
my ($RCFILE, $APPINFO_FILE, $CANCEL);
my ($gConfigDialog, $gFileLabel, $gFileEntry);
my %gEntryMap = ( 'lastname' => 0,
'firstname' => 1,
'company' => 2,
'phone1' => 3,
'phone2' => 4,
'phone3' => 5,
'phone4' => 6,
'phone5' => 7,
'address' => 8,
'city' => 9,
'state' => 10,
'zip' => 11,
'country' => 12,
'title' => 13,
'custom1' => 14,
'custom2' => 15,
'custom3' => 16,
'custom4' => 17,
'note' => 18,
'whichphone' => 'showPhone',
'phonetypes' => 'phoneLabel',
'category' => 'category',
'rolo_id' => 'rolo_id',
'updatetop' => 'updatetop',
'private' => 'secret',
'fullname' => 'fullname', # only for vcards
);
my @gCSVorder = ( 'rolo_id', 'lastname', 'firstname', 'company',
'phone1', 'phone2', 'phone3', 'phone4', 'phone5',
'address', 'city', 'state', 'zip', 'country', 'title',
'custom1', 'custom2', 'custom3', 'custom4', 'note',
'whichphone', 'phonetypes', 'category', 'private' );
my @gPhoneTypes = ( ['WORK', 0], # Work
['HOME', 1], # Home
['FAX', 2], # Fax
['PREF', 5], # Main
['PAGER', 6], # Page
['CELL', 7], # Mobile
['INTERNET', 4], # (Email)
);
sub conduitInit
{
$RCFILE = "SyncAB/SyncAB.prefs";
$APPINFO_FILE = "SyncAB/pilot.appinfo";
&loadPrefs;
$PREFS->{'syncType'} = 'CSV'
unless (defined $PREFS->{'syncType'});
$PREFS->{'CSVFile'} = "$ENV{HOME}/.csvAddr"
unless (defined $PREFS->{'CSVFile'});
$PREFS->{'vCardFile'} = "$ENV{HOME}/.vCards"
unless (defined $PREFS->{'vCardFile'});
$PREFS->{'vCardDir'} = "$ENV{HOME}/.dt/Addresses"
unless (defined $PREFS->{'vCardDir'});
$PREFS->{'RoloFile'} = "$ENV{HOME}/.rolo"
unless (defined $PREFS->{'RoloFile'});
$PREFS->{'BBDBFile'} = "$ENV{HOME}/.bbdb"
unless (defined $PREFS->{'BBDBFile'});
## Aldo
$PREFS->{'BBDB_DEFAULTCATEGORY'} = [ ('BBDB',1) ]
unless (defined $PREFS->{'BBDB_DEFAULTCATEGORY'});
$PREFS->{'BBDB_SAVE_SOME_PHONE'} = 'True'
unless (defined $PREFS->{'BBDB_SAVE_SOME_PHONE'});
$PREFS->{'BBDB_NO_NOPHONE'} = 'True'
unless (defined $PREFS->{'BBDB_NO_NOPHONE'});
$PREFS->{'BBDB_SAVE_SOME_ADDRESS'} = 'True'
unless (defined $PREFS->{'BBDB_SAVE_SOME_ADDRESS'});
$PREFS->{'BBDB_SAVE_SOME_MAIL'} = 'True'
unless (defined $PREFS->{'BBDB_SAVE_SOME_MAIL'});
$PREFS->{'BBDB_M_WORK'} = 'work|company|firma'
unless (defined $PREFS->{'BBDB_M_WORK'});
$PREFS->{'BBDB_M_HOME'} = 'home|heim|privat|bonn|vinxel'
unless (defined $PREFS->{'BBDB_M_HOME'});
$PREFS->{'BBDB_M_FAX'} = 'faksim|fax'
unless (defined $PREFS->{'BBDB_M_FAX'});
$PREFS->{'BBDB_M_MAIN'} = 'main'
unless (defined $PREFS->{'BBDB_M_MAIN'});
$PREFS->{'BBDB_M_PAGER'} = 'pager|skyper|scall'
unless (defined $PREFS->{'BBDB_M_PAGER'});
$PREFS->{'BBDB_M_MOBILE'} = 'mobil|handy|d1|d2|eplus|viag'
unless (defined $PREFS->{'BBDB_M_MOBILE'});
$PREFS->{'BBDB_SKIP_FIELDS'} = 'timestamp|creation-date'
unless (defined $PREFS->{'BBDB_SKIP_FIELDS'});
$PREFS->{'BBDB_PALM_FIELD'} = 'palm'
unless (defined $PREFS->{'BBDB_PALM_FIELD'});
$PREFS->{'BBDB_PALM_FIELD_IGNORE'} = 'ignore'
unless (defined $PREFS->{'BBDB_PALM_FIELD_IGNORE'});
}
sub conduitQuit
{
&savePrefs;
}
sub conduitInfo
{
return { 'database' =>
{
'name' => 'AddressDB',
'creator' => 'addr',
'type' => 'DATA',
'flags' => 0,
'version' => 0,
},
'version' => $VERSION,
'author' => 'Alan Harder',
'email' => '[EMAIL PROTECTED]' };
}
sub conduitConfigure
{
my ($this, $wm) = @_;
my ($frame, $obj, $subfr, @objs);
unless (defined $gConfigDialog and $gConfigDialog->Exists)
{
my $BBDB_INFO="WARNING! \n This BBDB Mode is ONEWAY!\n This means that all Your
Palm Data
get lost and will be overwritten from Your BBDB Data\n\n";
# my $bbdb_config = $wm->Toplevel(-title =>'Configuring BBDB')->
# Frame->Label(-textvariable =>\$BBDB_INFO);
$gConfigDialog = $wm->Toplevel(-title => "Configuring SyncAB");
$gConfigDialog->withdraw;
$gConfigDialog->transient($wm);
$frame = $gConfigDialog->Frame(-relief => 'ridge', -bd => 2);
$frame->Label(-text =>
"SyncAB v$VERSION\n" . &conduitInfo->{'email'})->pack;
$subfr = $frame->Frame;
@objs = TkUtils::Radiobuttons($subfr, \$PREFS->{'syncType'},
'CSV', 'vCard single file',
'vCard one per file', 'Rolo', 'BBDB');
$objs[0]->configure(-command => sub{
$gFileLabel = 'CSV file:';
$gFileEntry->configure(-textvariable =>
\$PREFS->{'CSVFile'});
});
$objs[1]->configure(-command => sub{
$gFileLabel = 'vCard file:';
$gFileEntry->configure(-textvariable =>
\$PREFS->{'vCardFile'});
});
$objs[2]->configure(-command => sub{
$gFileLabel = 'vCard dir:';
$gFileEntry->configure(-textvariable =>
\$PREFS->{'vCardDir'});
});
$objs[3]->configure(-command => sub{
$gFileLabel = 'Rolo file:';
$gFileEntry->configure(-textvariable =>
\$PREFS->{'RoloFile'});
});
$objs[4]->configure(-command => sub{
$gFileLabel = 'BBDB file:';
$gFileEntry->configure(-textvariable =>
\$PREFS->{'BBDBFile'});
unless ($bbdb_config) {
# Only one Window
$bbdb_config = $wm->Toplevel(-title =>'Configuring
BBDB');
$bbdb_config->Label(-textvariable =>
\$BBDB_INFO, -width => 80)->pack;
$bbdb_config->Label(-text =>
"In which default Address Category
inside
Palm do You want the BBDB Records?")->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_DEFAULTCATEGORY'}->[0], -width => 12)->pack;
$bbdb_config->Checkbutton(-variable =>
\$PREFS->{'BBDB_NO_NOPHONE'},
-text => 'Ignore Records
without Phone Number')->pack;
$bbdb_config->Label(-text =>
"\nIf you have more of the following
inside BBDB
than the Palm AddressDB can handle, do you want
them to save in AddressDB's Note Field?\n")->pack;
$bbdb_config->Checkbutton(-variable =>
\$PREFS->{'BBDB_SAVE_SOME_PHONE'},
-text => 'Save Some Phone
Numbers')->pack;
$bbdb_config->Checkbutton(-variable =>
\$PREFS->{'BBDB_SAVE_SOME_ADDRESS'},
-text => 'Save Some Postal
Addresses')->pack;
$bbdb_config->Checkbutton(-variable =>
\$PREFS->{'BBDB_SAVE_SOME_MAIL'},
-text => 'Save Some E-Mail
Addresses')->pack;
$bbdb_config->Label(-text =>
"\nRegexps for Your BBDB Phone
Locations to
match the following Palm AddressDB Fields\n")->pack;
$bbdb_config->Label(-text => 'Work Phone')->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_M_WORK'}, -width =>
30)->pack;
$bbdb_config->Label(-text => 'Home Phone')->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_M_HOME'}, -width =>
30)->pack;
$bbdb_config->Label(-text => 'Fax')->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_M_FAX'}, -width =>
30)->pack;
$bbdb_config->Label(-text => 'Main')->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_M_MAIN'}, -width =>
30)->pack;
$bbdb_config->Label(-text => 'Pager')->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_M_PAGER'}, -width =>
30)->pack;
$bbdb_config->Label(-text => 'Mobile')->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_M_MOBILE'}, -width
=> 30)->pack;
$bbdb_config->Label(-text => "\n\nRegexp for BBDB Fields
You don\'t want
to have inside the Palm\'s AddressDB")->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_SKIP_FIELDS'},
-width => 30)->pack;
$bbdb_config->Label(-text => "\nIf you want have more
Control over the Category
a BBDB Record gets filled into the Palm AddressDB
i recommend to insert a BBDB Custom Field, which values
should match existing AddressDB Categories\nWhat is the Name of this special
Field?")->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_PALM_FIELD'}, -width
=> 30)->pack;
$bbdb_config->Label(-text => "If You have such a BBDB
Custom Field, which value should
make SyncAB to ignore the BBDB Record?" )->pack;
$bbdb_config->Entry(-textvariable =>
\$PREFS->{'BBDB_PALM_FIELD_IGNORE'},
-width => 30)->pack;
$bbdb_config->Label(-text => "\nIf everythinks breaks,
the BBDB Mode
is my fault, not Alans. Send Bug reports to aldo\@rhein.de\n" )->pack;
TkUtils::Button($bbdb_config, 'Dismiss',
sub{ $bbdb_config->withdraw ; undef
$bbdb_config})->pack;
PilotMgr::setColors($bbdb_config);
}
});
######## End of BBBD Config Window
$subfr->pack(-fill => 'x', -expand => 1);
$subfr = $frame->Frame;
$obj = $subfr->Label(-textvariable => \$gFileLabel, -width => 10);
$obj->pack(-side => 'left', -anchor => 'e');
$gFileEntry = $subfr->Entry(-relief => 'sunken', -width => 40);
$gFileEntry->pack(-fill => 'x', -expand => 1);
$subfr->pack(-fill => 'x', -expand => 1);
$obj = TkUtils::Button($frame, 'Dismiss',
sub{ $gConfigDialog->withdraw });
$obj->pack;
$frame->pack(-fill => 'x', -expand => 1, -anchor => 'n');
PilotMgr::setColors($gConfigDialog);
}
if ($PREFS->{'syncType'} eq 'Rolo')
{
$gFileLabel = 'Rolo file:';
$gFileEntry->configure(-textvariable => \$PREFS->{'RoloFile'});
}
elsif ($PREFS->{'syncType'} eq 'CSV')
{
$gFileLabel = 'CSV file:';
$gFileEntry->configure(-textvariable => \$PREFS->{'CSVFile'});
}
elsif ($PREFS->{'syncType'} eq 'vCard single file')
{
$gFileLabel = 'vCard file:';
$gFileEntry->configure(-textvariable => \$PREFS->{'vCardFile'});
}
elsif ($PREFS->{'syncType'} eq 'vCard one per file')
{
$gFileLabel = 'vCard dir:';
$gFileEntry->configure(-textvariable => \$PREFS->{'vCardDir'});
}
elsif ($PREFS->{'syncType'} eq 'BBDB')
{
$gFileLabel = 'BBDB file:';
$gFileEntry->configure(-textvariable => \$PREFS->{'BBDBFile'});
}
$gConfigDialog->Popup(-popanchor => 'c', -overanchor => 'c',
-popover => $wm);
}
sub conduitSync
{
my ($this, $dlp, $info) = @_;
my ($idField, $file, $reader, $writer);
if (!exists $PREFS->{'lastSyncType'} or
$PREFS->{'syncType'} ne $PREFS->{'lastSyncType'})
{
# Full reset if changing sync type
rename "SyncAB/addr.db", "SyncAB/addr.db.bak";
}
$idField = 'rolo_id';
if ($PREFS->{'syncType'} eq 'Rolo')
{
$file = $PREFS->{'RoloFile'};
$reader = \&readRolo;
$writer = \&writeRolo;
}
elsif ($PREFS->{'syncType'} eq 'CSV')
{
$file = $PREFS->{'CSVFile'};
$reader = \&readCSV;
$writer = \&writeCSV;
}
elsif ($PREFS->{'syncType'} eq 'vCard one per file')
{
$file = $PREFS->{'vCardDir'};
$reader = \&readVCardsMultipleFiles;
$writer = \&writeVCardsMultipleFiles;
}
elsif ($PREFS->{'syncType'} eq 'vCard single file')
{
$file = $PREFS->{'vCardFile'};
$reader = \&readVCardsOneFile;
$writer = \&writeVCardsOneFile;
}
elsif ($PREFS->{'syncType'} eq 'BBDB')
{
$file = $PREFS->{'BBDBFile'};
$reader = \&readBBDB;
$writer = \&writeBBDB;
}
else
{
PilotMgr::msg(
"SyncAB does not yet support type $PREFS->{'syncType'}\n");
return;
}
$CANCEL = 0;
PilotSync::doSync( $dlp,
&conduitInfo->{'database'},
['entry', 'phoneLabel', 'showPhone',
'category', 'secret'],
['categoryName', 'phoneLabel', 'label'],
$idField,
"SyncAB/addr.db",
$file,
\&titleString,
$reader,
$writer,
\&newRoloId,
undef, undef, \$CANCEL);
$PREFS->{'lastSyncType'} = $PREFS->{'syncType'} unless ($CANCEL);
}
sub conduitCancel
{
$CANCEL = 'SyncAB Cancelled!';
}
sub loadPrefs
{
$PREFS = {}, return unless (-r "$RCFILE");
use vars qw($PREFS);
do "$RCFILE";
}
sub savePrefs
{
$Data::Dumper::Purity = 1;
$Data::Dumper::Deepcopy = 1;
$Data::Dumper::Indent = 0;
if (open(FD, ">$RCFILE"))
{
print FD Data::Dumper->Dumpxs([$PREFS], ['PREFS']), "1;\n";
close FD;
}
else
{
PilotMgr::msg("Unable to save preferences to $RCFILE!");
}
}
sub newRoloId
{
my ($db) = @_;
return $db->{'NEXT_ID'}++;
}
sub titleString
{
my ($rec) = @_;
my ($str, $str2) = ('');
$str2 = $rec->{'entry'}->[$gEntryMap{'firstname'}];
$str = $str2 if (&isgood($str2));
$str2 = $rec->{'entry'}->[$gEntryMap{'lastname'}];
if (&isgood($str2))
{
$str .= ' ' if (length $str);
$str .= $str2;
}
return $str if (length $str);
$str2 = $rec->{'entry'}->[$gEntryMap{'company'}];
return $str2 if (&isgood($str2));
return '-Unnamed-';
}
sub readAppInfoFile
{
# AppInfo file used by Rolo and CSV formats
#
my ($ai, $s) =
({ 'categoryName' => [], 'label' => [], 'phoneLabel' => [] });
open(FD, "<$APPINFO_FILE") or return $ai;
scalar(<FD>); # read off comment line
foreach (1..16)
{
chomp($s = <FD>);
push(@{$ai->{'categoryName'}}, $s);
}
foreach (1..22)
{
chomp($s = <FD>);
push(@{$ai->{'label'}}, $s);
}
foreach (1..8)
{
chomp($s = <FD>);
push(@{$ai->{'phoneLabel'}}, $s);
}
close(FD);
return $ai;
}
sub writeAppInfoFile
{
my ($ai) = @_;
open(FD, ">$APPINFO_FILE") or return;
print FD <<EOW;
WARNING- If you edit this file it will modify your pilot on the next sync!
EOW
foreach $_ (@{$ai->{'categoryName'}},
@{$ai->{'label'}},
@{$ai->{'phoneLabel'}})
{
print FD "$_\n";
}
close(FD);
}
sub writeBBDB {
my ($BBDBFILE, $db) = @_;
&writeAppInfoFile($db->{'__APPINFO'});
}
sub readBBDB
{
# Aldo Valente, [EMAIL PROTECTED], Mon Nov 8 13:17:32 CET 1999
# Trying to parse the BBDB and get it into my Palm Pilot.
# This looks more like the first Work of a BASIC Programmer than like
# a perl Program. At least, there are Comments. Alan? ;-)
my ($BBDBFile) = @_;
my ($max_id, $db) = (-1, { '__RECORDS' => [] , 'NEXT_ID' => 0 });
my ($rec);
my $BBDB_DEFAULTCATEGORY = $PREFS->{'BBDB_DEFAULTCATEGORY'};
my $BBDB_SAVE_SOME_PHONE = $PREFS->{'BBDB_SAVE_SOME_PHONE'};
my $BBDB_NO_NOPHONE = $PREFS->{'BBDB_NO_NOPHONE'};
my $BBDB_SAVE_SOME_ADDRESS = $PREFS->{'BBDB_SAVE_SOME_ADDRESS'};
my $BBDB_SAVE_SOME_MAIL = $PREFS->{'BBDB_SAVE_SOME_MAIL'};
my $BBDB_M_WORK = $PREFS->{'BBDB_M_WORK'};
my $BBDB_M_HOME = $PREFS->{'BBDB_M_HOME'};
my $BBDB_M_FAX = $PREFS->{'BBDB_M_FAX'};
my $BBDB_M_MAIN = $PREFS->{'BBDB_M_MAIN'};
my $BBDB_M_PAGER = $PREFS->{'BBDB_M_PAGER'};
my $BBDB_M_MOBILE = $PREFS->{'BBDB_M_MOBILE'};
my $BBDB_SKIP_FIELDS = $PREFS->{'BBDB_SKIP_FIELDS'};
my $BBDB_PALM_FIELD = $PREFS->{'BBDB_PALM_FIELD'};
my $BBDB_PALM_FIELD_IGNORE = $PREFS->{'BBDB_PALM_FIELD_IGNORE'};
my ($i, $j, $phone, $phones, $loc, $lastloc, $p,
$address, @address,
@mail, $val, $mymail,
$note, $notes, $notestype, @savenotes) = ();
$db->{'__APPINFO'} = &readAppInfoFile;
unless (open(FD, "<$BBDBFile"))
{
# Don't do a sync if master data file exists (then we'll end up
# deleting all records!)
if (-f "SyncAB/addr.db")
{
PilotMgr::msg(
"**ERROR: Unable to open $BBDBFile. Aborting SyncAB!");
croak("NODATA");
}
return $db;
}
# Search for User given Default Category
for ($j=0; $j < @{$db->{'__APPINFO'}{'categoryName'}}; $j++) {
if ( lc($BBDB_DEFAULTCATEGORY->[0]) eq
lc(${$db->{'__APPINFO'}{'categoryName'}}[$j])) {
$BBDB_DEFAULTCATEGORY->[1]=$j;
last;
}
}
RECORD: while (<FD>)
{
# Every Line in our BBBD is a single Record.
# Set some Vars right
$rec = { 'entry' => [],
'showPhone' => 0,
'phoneLabel' => [] };
undef @savenotes;
$rec->{'entry'}->[18] = undef; # ensure right array length
$_ = shift @{ &Lisp::Reader::lisp_read($_)}
or next RECORD;
# Now $_ is a rather complex Perl Data Structure. We shift
# field by Field. So be careful with shifting order.
$rec->{'entry'}->[1] = shift @{$_}; ### Name
$rec->{'entry'}->[0] = shift @{$_}; ### Last Name
### bbdb:AKA -> Palm:Title
$rec->{'entry'}->[13] = join ', ', @{ shift(@{$_}) };
### company
$rec->{'entry'}->[2] = shift @{$_};
# No No-Namers for Sanity. I think this can't happen more
# than once in the BBDB. Update: Mark Moll suggested to include
# Records with Company Entry, i also added Title.
next RECORD unless
$rec->{'entry'}->[1] . $rec->{'entry'}->[0] .
$rec->{'entry'}->[2] . $rec->{'entry'}->[13];
### Array of Array of Phones. This is the Main Reason why i
# wrote this. You can choose the Location Field of Your Phone
# Numbers in the BBDB, but NOT in Palms AddressDB.
# Furthermore, there are only 5 Fields in AddressDB for Phone
# AND Mail Adresses.
# We try to match the 5 first BBDB Phonelocations to Palm
# Fields. The Rest get perhaps in the AdressDB Notes Field.
$i=0; # This var is more than a simple Loopvar!
$phones = shift @{ $_};
next RECORD if $BBDB_NO_NOPHONE and not $phones ;
while ($phone = shift @{$phones}) {
$i++;
$loc = shift @{$phone};
$lastloc = $loc if $i == 5;
# $p = shift @{$phone};
# I don't know nothing about North American Style Phone
# Numbers, but this should work.
$p = join ' ', @{$phone};
if ($i > 5) {
# Palm doesn't have more than 5
# Fields for Phone AND Mail.
last unless $BBDB_SAVE_SOME_PHONE;
push @savenotes, $loc . ": " . $p . "\n" ;
next;
}
if ( $loc =~ /$BBDB_M_WORK/i ) {
# Work
push @{$rec->{'phoneLabel'}}, '0';
$rec->{'entry'}->[2+$i] = $p;
next;
}
if ( $loc =~ /$BBDB_M_HOME/i ) {
# Home
push @{$rec->{'phoneLabel'}}, '1';
$rec->{'entry'}->[2+$i] = $p;
next;
}
if ( $loc =~ /$BBDB_M_FAX/i ) {
# Fax
push @{$rec->{'phoneLabel'}}, '2';
$rec->{'entry'}->[2+$i] = $p;
next;
}
if ( $loc =~ /$BBDB_M_MAIN/i ) {
# what's a `main'?
push @{$rec->{'phoneLabel'}}, '5';
$rec->{'entry'}->[2+$i] = $p;
next;
}
if ( $loc =~ /$BBDB_M_PAGER/i ) {
# Pager
push @{$rec->{'phoneLabel'}}, '6';
$rec->{'entry'}->[2+$i] = $p;
next;
}
if ( $loc =~ /$BBDB_M_MOBILE/i ) {
# Mobile
push @{$rec->{'phoneLabel'}}, '7';
$rec->{'entry'}->[2+$i] = $p;
next;
} # `Other' is default
push @{$rec->{'phoneLabel'}}, '3';
$rec->{'entry'}->[2+$i] = $p;
};
### Array of Addresses.
# We push the first BBDB Adress into the AddressDB Fields
($address, @address) = @{shift @{$_}} ;
if ($address) {
$rec->{'entry'}->[8] = join ' ', @{$address}[1..3] ;
$rec->{'entry'}->[9] = ${$address}[4];
$rec->{'entry'}->[10] = ${$address}[5];
# Zip Code Problem
if (ref ${$address}[6]) {
${$address}[6] = "@{${$address}[6]}"
}
$rec->{'entry'}->[11] = ${$address}[6];
# Thanks to Mark, i noticed that the Country Field is
# not existant at all in the BBDB. What are we going
# to do with this?
$rec->{'entry'}->[12] = ${$address}[7];
}
if ($BBDB_SAVE_SOME_ADDRESS) {
# We push every other Address to palm Notesfield
foreach $address (@address) {
# filter out empty Lines
@{$address} = grep (! $_ eq "", @{$address});
# handle the zip code problem. Thanks to Mark Moll.
@{$address} = grep { if (ref $_) {
$_ = "@{$_}"
} else {1}
} @{$address};
# Thanks to Martin Sluka
#push @savenotes, grep defined, join "\n", @{$address} ;
push @savenotes, join "\n", @{$address} ;
push @savenotes, "\n";
}
}
### Array of Mailaddresses. We have to be careful. In the
# BBDB, we can have as much Mailaddresses as we want to. In
# AddressDB, we have the same Space for Mail and Phone. So, if
# the Palmspace is already full, we replace the last Phone
# Number with the First Mail Address, else we fill the AddressDB
# and perhaps save the Rest in AddressDB Notes.
if (@mail = @{ shift(@{$_}) }) {
if ( $i >= 5 ) {
# full with merde, we clear the last phonenumber for the
# first Mailaddress
pop @{$rec->{'phoneLabel'}};
if ($BBDB_SAVE_SOME_PHONE) {
# (@_=grep($_->[1] == $val, @gPhoneTypes))?$_[0]->[0]:'Other';
unshift @savenotes, $lastloc . ": " . $rec->{'entry'}->[7];
#unshift @savenotes, $lastloc;
}
$rec->{'entry'}->[7] = shift @mail;
push @{$rec->{'phoneLabel'}}, '4';
} elsif ( $i < 5) {
# There is some Space for Mailaddresses
for ($j=3+$i ; $j <= 7 and $mymail = shift @mail ; $j++) {
$rec->{'entry'}->[$j] = $mymail;
push @{$rec->{'phoneLabel'}}, '4';
}
}
}
# save rest of @mail in Palm Notes
if (@mail and $BBDB_SAVE_SOME_MAIL) {
push @savenotes, join "\n", @mail;
push @savenotes, "\n";
}
### Now we care about BBDBs Notes Field. This is the biggest
# Piece of Shit of all. BBDB has User customizable Fields and a
# Single Line `Notes' Field. AddressDB has four Custom Fields
# and a Multi Line `Notes' Field.
# First, we check if there is a BBDB Field called `$Palm'. If
# `Yes', the Value is used for the Category the Address record
# should be in (Work, Private, unfilled...). The Magic $Skip
# Value skips the BBDB Record in the AddressDB.
# After this, we try to match BBDB Custom Fields with the Names
# of the AddressDB Custom Fields and set the correspondending
# Values. I recommend setting an AddressDB Custom Field to
# `Notes', since the BBDB Notes are single Lines.
# Everything, which doesn't matched gets into the AddressDB
# Notes Field if not already filtered out. ToDo: Who needs the
# AddressDB 'secret' Field?
# Set a Default for the Category
$rec->{'category'}= $BBDB_DEFAULTCATEGORY->[1]
|| 1;
if ($notes = shift @{$_}) {
unless (ref $notes) {
# BBDB Note is just a single String, we treat it
# like ` (( notes . "foo"))'
@{$notes} = [ ({ 'name' => 'notes' }, ($notes)) ];
}
# $notes is now an array
NOTE:
while ( $note = shift @{$notes}) {
# The Format of the Notes Field is not my Fault!
$notestype = lc(${shift @{$note}}{'name'});
next NOTE if $notestype =~ /$BBDB_SKIP_FIELDS/i;
if (lc($notestype) =~ /$BBDB_PALM_FIELD/i) {
# We found the Magic $PALM BBDB Field.
next RECORD if lc( ${$note}[0]) =~
/$BBDB_PALM_FIELD_IGNORE/i;
FINDCATEGORY:
for ($j=0;
$j < @{$db->{'__APPINFO'}{'categoryName'}};
$j++) {
if ( lc(${$note}[0]) eq
lc(${$db->{'__APPINFO'}{'categoryName'}}[$j])) {
$rec->{'category'}= $j;
last FINDCATEGORY; # Found it.
} # if ${$note}[0] eq categoryName
} # for
} else {
# Some other BBDB Custom Field. We try to match with the
# AddressDB Custom Fields.
FINDMATCHINGFIELD:
for ($j=14; $j <= 17; $j++) {
if ($notestype =~
/${$db->{'__APPINFO'}{'label'}}[$j]/i) {
$rec->{'entry'}->[$j] = ${$note}[0];
undef $notestype;
last FINDMATCHINGFIELD; # Matched.
} # if
} # for
# Didn't found a match? Save it in @savenotes
if ($notestype) {
push @savenotes, $notestype . ": " . ${$note}[0] . "\n";
}
} # end-else
} # end-while $notes
} # end-if $notes
### Finally set the AddressDB Notes Field with all possible
# Nonsense: Phones, Addresses, Mail Addresses and BBBD Custom
# Fields. And perhaps even BBDB Notes.
$rec->{'entry'}->[18] = join "\n", @savenotes;
# I stole this from Alan, but it is not used.
# Value for "secret" field must be '' or '1'.
# Convert any perl "false" value to '' and any "true" value to 1:
#
$rec->{'secret'} =
(defined $rec->{'secret'} and $rec->{'secret'}) ? 1 : '';
# Push it, Baby.
push(@{$db->{'__RECORDS'}}, $rec);
# Alans Voodoo, not mine.
$db->{ $rec->{'rolo_id'} } = $#{$db->{'__RECORDS'}};
$max_id = $rec->{'rolo_id'} if ($rec->{'rolo_id'} > $max_id);
} # EOwhile (<FD>)
close(FD);
$db->{'NEXT_ID'} = $max_id+1;
foreach $i ($[..$#{$db->{'__RECORDS'}})
{
$rec = $db->{'__RECORDS'}->[$i];
unless (defined $rec->{'rolo_id'})
{
$rec->{'rolo_id'} = $db->{'NEXT_ID'}++;
$db->{ $rec->{'rolo_id'} } = $i;
}
}
return $db;
}
sub readRolo
{
my ($ROLOFILE) = @_;
my ($db, $rec) = ({ 'nonPilot' => [],
'isPilot' => [],
'__RECORDS' => [],
'NEXT_ID' => 0
});
$db->{'__APPINFO'} = &readAppInfoFile;
open(FD, "<$ROLOFILE") || return $db;
while (<FD>)
{
$rec = { 'topsect' => '' };
while ($_ !~ /^\*PILOT\*$/ && $_ !~ /^\014/)
{
$rec->{'topsect'} .= $_;
$_ = <FD>;
}
if ( /^\014/ )
{
push(@{$db->{'isPilot'}}, -1);
push(@{$db->{'nonPilot'}}, $rec);
next;
}
$rec->{'entry'} = [];
$rec->{'entry'}->[18] = undef; # ensure right array length
$rec->{'phoneLabel'} = [0,1,2,3,4];
$rec->{'showPhone'} = 0;
for ($_ = <FD>; $_ !~ /^\014/; $_ = <FD>)
{
if ($_ =~ /^([^:]*): ?(.*)$/)
{
$field = $1;
$value = $2;
$field =~ tr/A-Z/a-z/;
$value =~ s/\\n/\n/g; # translate newlines
unless (defined $gEntryMap{$field})
{
print "skipping bad field '$field' in rolo record.\n";
next;
}
$field = $gEntryMap{$field};
if ($field =~ /^\d+$/)
{
$rec->{'entry'}->[$field] = $value;
}
elsif ($field eq 'phoneLabel')
{
$rec->{$field} = [split(/ /, $value)];
}
else
{
$rec->{$field} = $value;
}
}
}
# 'secret' field value must be 1 or ''
$rec->{'secret'} = (exists $rec->{'secret'} and $rec->{'secret'})?1:'';
push(@{$db->{'isPilot'}}, $rec->{'rolo_id'});
push(@{$db->{'__RECORDS'}}, $rec);
$db->{ $rec->{'rolo_id'} } = $#{$db->{'__RECORDS'}};
$db->{'NEXT_ID'} = $rec->{'rolo_id'} + 1
if ($rec->{'rolo_id'} >= $db->{'NEXT_ID'});
}
close(FD);
return $db;
}
sub writeRolo
{
my ($ROLOFILE, $db) = @_;
my ($rec, $which);
&writeAppInfoFile($db->{'__APPINFO'});
unless (open(FD, ">$ROLOFILE"))
{
PilotMgr::msg("Unable to write to $ROLOFILE. Help!");
return;
}
foreach $which (@{$db->{'isPilot'}})
{
if ($which < 0)
{
# non-pilot rec
$rec = shift @{$db->{'nonPilot'}};
print FD $rec->{'topsect'}, "\014\n";
}
next unless (defined $db->{'__RECORDS'}->[0] &&
$which eq $db->{'__RECORDS'}->[0]->{'rolo_id'});
$rec->{'topsect'} = &makeTopSect($rec, $db->{'__APPINFO'})
unless exists $rec->{'topsect'};
&writeRec(FD, shift @{$db->{'__RECORDS'}});
}
while (defined ($rec = shift @{$db->{'__RECORDS'}}))
{
$rec->{'topsect'} = &makeTopSect($rec, $db->{'__APPINFO'})
unless exists $rec->{'topsect'};
&writeRec(FD, $rec);
}
close(FD);
}
sub writeRec
{
my ($fd, $rec) = @_;
my ($key, $val);
print $fd $rec->{'topsect'} if defined ($rec->{'topsect'});
print $fd "*PILOT*\n";
foreach $key (keys %gEntryMap)
{
$val = $gEntryMap{$key};
if ($val =~ /^\d+$/)
{
next unless (defined ($val = $rec->{'entry'}->[$val]));
$val =~ s/\n/\\n/g; # translate newlines
print $fd "$key: $val\n";
}
else
{
# shouldn't be any newlines to translate down here..
next unless (defined ($val = $rec->{$val}));
# for phoneLabel field:
$val = join(' ', @$val) if (ref($val) eq 'ARRAY');
print $fd "$key: $val\n";
}
}
print $fd "\014\n";
}
sub isgood
{
return (defined $_[0] and length($_[0]) > 0);
}
sub makeTopSect
{
my ($rec, $ai) = @_;
my ($topsect, $boo, $val, $val2, $i, @phonetypes) = ("", 0);
$val = $rec->{'entry'}->[ $gEntryMap{'lastname'} ];
$val2 = $rec->{'entry'}->[ $gEntryMap{'firstname'} ];
$i = $rec->{'entry'}->[ $gEntryMap{'company'} ];
if (&isgood($val))
{
$topsect .= "$val2 " if (&isgood($val2));
$topsect .= $val;
}
elsif (&isgood($val2))
{
$topsect .= $val2;
}
elsif (&isgood($i))
{
$topsect .= $i;
$boo = 1;
}
$topsect .= "\n";
$val = $rec->{'entry'}->[ $gEntryMap{'title'} ];
$topsect .= $val . "\n" if (&isgood($val));
$val = $rec->{'entry'}->[ $gEntryMap{'company'} ];
$topsect .= $val . "\n" if (!$boo and &isgood($val));
$topsect .= "\n";
$val = $rec->{ $gEntryMap{'phonetypes'} };
@phonetypes = @$val if (defined $val and ref($val) eq 'ARRAY');
foreach $i (1..5)
{
$val = $rec->{'entry'}->[ $gEntryMap{"phone$i"} ];
if (&isgood($val))
{
$topsect .= @phonetypes ? $ai->{'phoneLabel'}->[$phonetypes[$i-1]]
: "phone$i";
$topsect .= ": $val\n";
}
}
$topsect .= "\n";
$val = $rec->{'entry'}->[ $gEntryMap{'address'} ];
$topsect .= $val . "\n" if (&isgood($val));
$boo = 0;
$val = $rec->{'entry'}->[ $gEntryMap{'city'} ];
if (&isgood($val))
{
$topsect .= $val;
$boo = 1;
}
$val = $rec->{'entry'}->[ $gEntryMap{'state'} ];
if (&isgood($val))
{
$topsect .= ", " if ($boo);
$boo = 0;
$topsect .= "$val ";
}
$val = $rec->{'entry'}->[ $gEntryMap{'zip'} ];
if (&isgood($val))
{
$topsect .= ', ' if ($boo);
$topsect .= $val;
}
$topsect .= "\n";
$boo = 0;
foreach $i (1..4)
{
$val = $rec->{'entry'}->[ $gEntryMap{"custom$i"} ];
if (&isgood($val))
{
$topsect .= $ai->{'label'}->[$i+13] . ": $val\n";
$boo++;
}
}
$topsect .= "\n" if ($boo);
$val = $rec->{'entry'}->[ $gEntryMap{'note'} ];
$topsect .= $val . "\n" if (&isgood($val));
return $topsect;
}
sub readCSV
{
my ($CSVFILE) = @_;
my ($max_id, $db) = (-1, { '__RECORDS' => [] , 'NEXT_ID' => 0 });
my ($rec, $key, $fld, $val);
$db->{'__APPINFO'} = &readAppInfoFile;
unless (open(FD, "<$CSVFILE"))
{
# Don't do a sync if master data file exists (then we'll end up
# deleting all records!)
if (-f "SyncAB/addr.db")
{
PilotMgr::msg(
"**ERROR: Unable to open $CSVFILE. Aborting SyncAB!");
croak("NODATA");
}
return $db;
}
while (<FD>)
{
$rec = { 'entry' => [],
'showPhone' => 0,
'phoneLabel' => [0,1,2,3,4] };
$rec->{'entry'}->[18] = undef; # ensure right array length
foreach $key (@gCSVorder)
{
$fld = $gEntryMap{$key};
($val, $_) = &popCSV($_);
$val = &CSVToStr($val);
$val = undef if ($val eq '');
&setRecVal($rec, $fld, $val);
}
# Value for "secret" field must be '' or '1'.
# Convert any perl "false" value to '' and any "true" value to 1:
#
$rec->{'secret'} =
(defined $rec->{'secret'} and $rec->{'secret'}) ? 1 : '';
push(@{$db->{'__RECORDS'}}, $rec);
$db->{ $rec->{'rolo_id'} } = $#{$db->{'__RECORDS'}};
$max_id = $rec->{'rolo_id'} if ($rec->{'rolo_id'} > $max_id);
}
close(FD);
$db->{'NEXT_ID'} = $max_id+1;
return $db;
}
sub setRecVal
{
my ($rec, $fld, $val) = @_;
if ($fld =~ /^\d+$/)
{
$rec->{'entry'}->[$fld] = $val;
}
elsif ($fld eq 'phoneLabel')
{
$rec->{$fld} = [split(/ /, $val)];
}
else
{
$rec->{$fld} = $val;
}
}
sub writeCSV
{
my ($CSVFILE, $db) = @_;
my ($rec, $key, $val, @fields);
&writeAppInfoFile($db->{'__APPINFO'});
unless (open(FD, ">$CSVFILE"))
{
PilotMgr::msg("Unable to write to $CSVFILE. Help!");
return;
}
foreach $rec (@{$db->{'__RECORDS'}})
{
@fields = ();
foreach $key (@gCSVorder)
{
$val = $gEntryMap{$key};
if ($val =~ /^\d+$/)
{
if (defined ($val = $rec->{'entry'}->[$val]))
{
$val = &StrToCSV($val);
}
}
else
{
if (defined ($val = $rec->{$val}))
{
$val = join(' ', @$val) if (ref($val) eq 'ARRAY');
$val = &StrToCSV($val);
}
}
$val = '' unless (defined $val);
push(@fields, $val);
}
print FD join(',', @fields), "\n";
}
close(FD);
}
sub StrToCSV
{
my ($str) = @_;
$str =~ s/(\\*)(n|\n)/'\\' x (2*length($1)) . ($2 eq 'n' ? 'n' : '\\n')/ge;
if ($str =~ /[,"]/)
{
$str =~ s/"/""/g;
$str = '"' . $str . '"';
}
return $str;
}
sub popCSV
{
my ($str) = @_;
if ($str =~ s/^("([^"]|"")*")(,|$)//)
{
return($1, $str);
}
elsif ($str =~ s/^(.*?)(,|$)//)
{
return($1, $str);
}
return($str, '');
}
sub CSVToStr
{
my ($str) = @_;
if ($str =~ /^"(.*)"$/)
{
$str = $1;
$str =~ s/""/"/g;
}
$str =~ s/((\\\\)*)(\\)?n/'\\' x (length($1)\/2) . ($3 ? "\n" : 'n')/ge;
return $str;
}
sub writeVCardsOneFile
{
my ($VCARDFILE, $db) = @_;
my ($rec);
&writeAppInfoFile($db->{'__APPINFO'});
unless (open(FD, ">$VCARDFILE"))
{
PilotMgr::msg("Unable to write to $VCARDFILE. Help!");
return;
}
foreach $rec (@{$db->{'__RECORDS'}})
{
&writeVCard($rec, FD);
print FD "\n";
}
close(FD);
}
sub writeVCardsMultipleFiles
{
my ($VCARDDIR, $db) = @_;
my ($rec, $cat, $fn, @dirlist, $dir, @filelist, $file);
&writeAppInfoFile($db->{'__APPINFO'});
# yikes, scary! delete all old files!
# vCard files are stored in subdirectories named by category.
# Each SyncAB owned directory has a ".pilotmgr" file in it.
#
opendir DIR, "$VCARDDIR";
@dirlist = readdir DIR;
closedir DIR;
foreach $dir (@dirlist)
{
next if ($dir =~ /^\.\.?$/); # skip . and ..
if (-d "$VCARDDIR/$dir" and -f "$VCARDDIR/$dir/.pilotmgr")
{
opendir DEL, "$VCARDDIR/$dir";
@filelist = readdir DEL;
closedir DEL;
foreach $file (@filelist)
{
if ($file ne '.pilotmgr' and -f "$VCARDDIR/$dir/$file")
{
unlink "$VCARDDIR/$dir/$file";
}
}
}
}
foreach $rec (@{$db->{'__RECORDS'}})
{
($cat, $fn) = &vCardFileName($rec, $db->{'__APPINFO'});
unless (-d "$VCARDDIR/$cat")
{
mkdir "$VCARDDIR/$cat", 0755;
open(FD, ">$VCARDDIR/$cat/.pilotmgr") and close(FD);
}
if (-f "$VCARDDIR/$cat/$fn")
{
# file already exists
$_ = 1;
while (-f "$VCARDDIR/$cat/${fn}_$_") { $_++ }
$fn .= "_$_";
}
unless (open(FD, ">$VCARDDIR/$cat/$fn"))
{
PilotMgr::msg("** Error opening $VCARDDIR/$cat/$fn for write!");
next;
}
&writeVCard($rec, FD);
close(FD);
}
}
sub vCardFileName
{
my ($rec, $appinfo) = @_;
my $fn = $rec->{'fullname'};
$fn = &titleString($rec) unless (&isgood($str));
# remove newlines, and anything after them.
$fn =~ s/\n.*//g;
# remove spaces from beginning and end of line.
$fn =~ s/^\s*(.*?)\s*$/$1/;
# replace multiple spaces with a single space.
$fn =~ s/\s\s+/ /g;
# replace characters we don't want in filenames.
$fn =~ tr|'"<>[]/|_______|s;
my $cat = $appinfo->{'categoryName'}->[ $rec->{$gEntryMap{'category'}} ];
$cat = 'PilotDB' unless (&isgood($cat));
$cat =~ s/\n.*//g;
$cat =~ s/^\s*(.*?)\s*$/$1/;
$cat =~ s/\s\s+/ /g;
$cat =~ tr|'"<>[]/|_______|s;
return ($cat, $fn);
}
sub writeVCard
{
my ($rec, $FD) = @_;
my ($val, $val2, $i);
#XXX: need to handle newlines or semicolons in ADR and N fields!!
#sdtname requires a ADR type, HOME/WORK.. we'll default to HOME
my $defaultAddrPlace = 'HOME';
print $FD "BEGIN:VCARD\n";
# FN is just for looks, doesn't store actual data:
&printEncodedString('FN',
defined($rec->{'fullname'}) ? $rec->{'fullname'} : &titleString($rec),
$FD);
($val = $rec->{'entry'}->[$gEntryMap{'lastname'}]) =~ s/;/\\;/g;
($val2 = $rec->{'entry'}->[$gEntryMap{'firstname'}]) =~ s/;/\\;/g;
if (defined $val || defined $val2)
{
#XXX: use &printEncodedString here?
print $FD 'N:';
print $FD $val if (defined $val);
print $FD ';';
print $FD $val2 if (defined $val2);
print $FD "\n";
}
$val = $rec->{'entry'}->[$gEntryMap{'company'}];
&printEncodedString('ORG', $val, $FD) if (defined $val);
$val = $rec->{'entry'}->[$gEntryMap{'title'}];
&printEncodedString('TITLE', $val, $FD) if (defined $val);
print $FD 'ADR;';
$val = $rec->{'addrTypeInfo'}; # vCard info like HOME or WORK
$val = $defaultAddrPlace unless (defined $val);
print $FD "$val;X-pilot-field=addr:;;";
($val = $rec->{'entry'}->[$gEntryMap{'address'}]) =~ s/;/\\;/g;
$val =~ s/\n/\\n/g; #XXX- not right- what to do with newlines?
print $FD $val if (defined $val);
print $FD ';';
($val = $rec->{'entry'}->[$gEntryMap{'city'}]) =~ s/;/\\;/g;
print $FD $val if (defined $val);
print $FD ';';
($val = $rec->{'entry'}->[$gEntryMap{'state'}]) =~ s/;/\\;/g;
print $FD $val if (defined $val);
print $FD ';';
($val = $rec->{'entry'}->[$gEntryMap{'zip'}]) =~ s/;/\\;/g;
print $FD $val if (defined $val);
print $FD ';';
($val = $rec->{'entry'}->[$gEntryMap{'country'}]) =~ s/;/\\;/g;
print $FD $val if (defined $val);
print $FD "\n";
foreach $i (1..5)
{
$val = $rec->{'entry'}->[$gEntryMap{"phone$i"}];
$val2 = $rec->{'phoneLabel'}->[$i-1];
# Unless phonetype is equal to default, need to record even empty
# value, to get phonetype recorded..
next if (!defined $val and $val2 == ($i-1));
$val = '' unless (defined $val);
#XXX: might want to look at prefs and see what types these
# *really* are in case they've been changed..
if ($val2 == 4)
{
print $FD 'EMAIL;INTERNET';
}
else
{
print $FD 'TEL;',
(@_=grep($_->[1] == $val2, @gPhoneTypes))?$_[0]->[0]:'';
}
&printEncodedString(";X-pilot-field=phone$i", $val, $FD);
}
foreach $i (1..4)
{
$val = $rec->{'entry'}->[$gEntryMap{"custom$i"}];
next unless (defined $val);
&printEncodedString("NOTE;X-pilot-field=custom$i", $val, $FD);
}
$val = $rec->{'entry'}->[$gEntryMap{'note'}];
&printEncodedString('NOTE;X-pilot-field=note', $val, $FD)
if (defined $val);
print $FD "X-pilot-id:$rec->{rolo_id}\n",
"X-pilot-category:$rec->{category}\n",
"X-pilot-show-phone:$rec->{showPhone}\n";
print $FD "X-pilot-private:$rec->{secret}\n"
if (exists $rec->{'secret'} and length $rec->{'secret'});
print $FD "END:VCARD\n";
}
sub printEncodedString
{
# print string value to vcard. use Quoted-Printable if necessary
# XXX: this needs to be more complete to encode all control chars,etc too
#
my ($hdr, $val, $fd) = @_;
print $fd $hdr if ($hdr);
if ($val =~ /\n/)
{
$val =~ s/=/=3D/g;
$val =~ s/\n/=0A/g;
print $fd ";ENCODING=QUOTED-PRINTABLE";
}
print $fd ":$val\n";
}
sub readVCardsOneFile
{
my ($VCARDFILE) = @_;
my ($max_id, $db, $rec, $i) = (-1, { '__RECORDS' => [], 'NEXT_ID' => 0 });
$db->{'__APPINFO'} = &readAppInfoFile;
unless (open(FD, "<$VCARDFILE"))
{
# Don't do a sync if master data file exists (then we'll end up
# deleting all records!)
if (-f "SyncAB/addr.db")
{
PilotMgr::msg(
"**ERROR: Unable to open $VCARDFILE. Aborting SyncAB!");
croak("NODATA");
}
return $db;
}
while (<FD>)
{
if ( /^\s*BEGIN\s*:\s*VCARD\s*$/ )
{
$rec = &readVCard(FD);
push(@{$db->{'__RECORDS'}}, $rec);
if (defined $rec->{'rolo_id'})
{
$db->{ $rec->{'rolo_id'} } = $#{$db->{'__RECORDS'}};
$max_id = $rec->{'rolo_id'} if ($rec->{'rolo_id'} > $max_id);
}
}
}
close(FD);
$db->{'NEXT_ID'} = $max_id+1;
foreach $i ($[..$#{$db->{'__RECORDS'}})
{
$rec = $db->{'__RECORDS'}->[$i];
unless (defined $rec->{'rolo_id'})
{
$rec->{'rolo_id'} = $db->{'NEXT_ID'}++;
$db->{ $rec->{'rolo_id'} } = $i;
}
}
return $db;
}
sub readVCardsMultipleFiles
{
my ($VCARDDIR) = @_;
my ($max_id, $db, $rec, @dirlist, $dir, @filelist, $file, $cat) =
(-1, { '__RECORDS' => [], 'NEXT_ID' => 0 });
$db->{'__APPINFO'} = &readAppInfoFile;
# vCard files are stored in subdirectories named by category.
# Each SyncAB owned directory has a ".pilotmgr" file in it.
unless (opendir DIR, "$VCARDDIR")
{
PilotMgr::msg(
"**ERROR: Unable to open dir $VCARDDIR. Aborting SyncAB!");
croak("BADDIR");
}
@dirlist = readdir DIR;
closedir DIR;
foreach $dir (@dirlist)
{
next if ($dir =~ /^\.\.?$/); # skip . and ..
if (-d "$VCARDDIR/$dir" and -f "$VCARDDIR/$dir/.pilotmgr")
{
opendir DAT, "$VCARDDIR/$dir";
@filelist = readdir DAT;
closedir DAT;
foreach $file (@filelist)
{
if ($file ne '.pilotmgr' and -f "$VCARDDIR/$dir/$file")
{
unless (open(FD, "<$VCARDDIR/$dir/$file"))
{
PilotMgr::msg("** Unable to read $VCARDDIR/$dir/$file");
next;
}
do { $_ = <FD> }
until (/^\s*BEGIN\s*:\s*VCARD\s*$/i or eof(FD));
close(FD), next if (eof(FD));
$rec = &readVCard(FD);
close(FD);
push(@{$db->{'__RECORDS'}}, $rec);
if (defined $rec->{'rolo_id'})
{
$db->{ $rec->{'rolo_id'} } = $#{$db->{'__RECORDS'}};
$max_id = $rec->{'rolo_id'}
if ($rec->{'rolo_id'} > $max_id);
}
}
}
}
}
$db->{'NEXT_ID'} = $max_id+1;
foreach $i ($[..$#{$db->{'__RECORDS'}})
{
$rec = $db->{'__RECORDS'}->[$i];
unless (defined $rec->{'rolo_id'})
{
$rec->{'rolo_id'} = $db->{'NEXT_ID'}++;
$db->{ $rec->{'rolo_id'} } = $i;
}
}
return $db;
}
sub readVCard
{
my ($FD) = @_;
my $encodeMatch = '(^|;)\s*ENCODING\s*=\s*QUOTED-PRINTABLE\s*(;|$)';
my $pilotMatch = '(^|;)\s*X-pilot-field\s*=\s*(\S+?)\s*(;|$)';
my %fieldMap = ('FN' => 'fullname',
'ORG' => 'company',
'TITLE' => 'title',
'id' => 'rolo_id',
'category' => 'category',
'show-phone'=> 'whichphone',
'private' => 'private');
my ($rec, $field, $extra, $item);
$rec = { 'entry' => [],
'showPhone' => 0,
'phoneLabel' => [0,1,2,3,4],
'secret' => '' };
$rec->{'entry'}->[18] = undef; # ensure right array length
while (<$FD>)
{
s/\015?\n$//;
last if ( /^\s*END\s*:\s*VCARD\s*$/ );
if ( /^\s*(FN|ORG|TITLE)\s*(;[^:]*)?:(.*)$/i )
{
($field = $1) =~ tr/a-z/A-Z/;
$extra = $2;
$val = $3;
$val = &decodeQuotedPrintable($val, $FD)
if ($extra =~ /$encodeMatch/i);
&setRecVal($rec, $gEntryMap{$fieldMap{$field}}, $val);
}
elsif ( /^\s*N\s*(;[^:]*)?:(.*)$/i )
{
$extra = $1;
$val = $2;
&popFields($rec, $val, 'lastname', 'firstname');
#XXX: do anything with remaining fields? (ie suffix, etc)
}
elsif ( /^\s*ADR\s*(;[^:]*)?:(.*)$/i )
{
$extra = $1;
$val = $2;
unless ($extra =~ /$pilotMatch/i and ($field=$2) =~ /^addr$/i)
{
# Not the ADR entry for pilot
#XXX: save this somewhere so it won't be lost,
# or maybe select it for pilot data if there is none
next;
}
&popFields($rec, $val, 'SKIP', 'SKIP', #XXX use first values?
'address', 'city', 'state', 'zip', 'country');
}
elsif ( /^\s*(TEL|EMAIL|NOTE)\s*(;[^:]*)?:(.*)$/i )
{
$extra = $2;
$val = $3;
$val = &decodeQuotedPrintable($val, $FD)
if ($extra =~ /$encodeMatch/i);
unless ($extra =~ /$pilotMatch/i)
{
# Not a pilot entry
#XXX: save this somewhere so it won't be lost,
# or maybe assign to a pilot entry...
next;
}
($field = $2) =~ tr/A-Z/a-z/;
&setRecVal($rec, $gEntryMap{$field}, $val) if (length $val);
if ($field =~ /^phone(\d)$/)
{
$val = $1;
@_ = grep($extra =~ /(^|;)\s*$_->[0]\s*(;|$)/i, @gPhoneTypes);
$rec->{'phoneLabel'}->[$val-1] = @_ ? $_[0]->[1] : 3;
# default val == 3 == OTHER
}
}
elsif ( /^\s*X-pilot-(.*)\s*(;[^:]*)?:(.*)$/i )
{
$field = $fieldMap{$1};
next unless (defined $field);
$val = $3;
# Value for private must be 1 or ''
$val = $val ? 1 : '' if ($field eq 'private');
$rec->{$gEntryMap{$field}} = $val;
}
else
{
#XXX: save data somewhere so it won't be lost
}
}
return $rec;
}
sub popFields
{
my ($rec, $val, @fields) = @_;
my ($field, $item);
foreach $field (@fields)
{
($item = $1) =~ s/\\;/;/g if ($val =~ s/^(.*?(^|[^\\]))(;|$)//);
next if ($field eq 'SKIP');
$item = undef unless (length $item); #XXX I think I want this
&setRecVal($rec, $gEntryMap{$field}, $item);
}
}
sub decodeQuotedPrintable
{
my ($val, $FD) = @_;
while ($val =~ s/=$//)
{
$val .= <$FD>;
$val =~ s/\015?\n$//;
}
#XXX: should decode all =## things
$val =~ s/=0[Aa]/\n/g;
$val =~ s/=3[Dd]/=/g;
return $val;
}
#XXX test code XXX
#my $db = &readVCardsMultipleFiles("$ENV{HOME}/.dt/Addresses");
#foreach (@{$db->{'__RECORDS'}}) { print Dumper($_) }
1;
_______________________________________________
bbdb-info mailing list
[EMAIL PROTECTED]
http://lists.sourceforge.net/mailman/listinfo/bbdb-info