lib: added NICKNAME support to vcard, and therefore to sync as well
[barry.git] / src / vcard.cc
blob33e7428e240a9d58f188babbe8ebd1b3bd6404a6
1 ///
2 /// \file vcard.cc
3 /// Conversion routines for vcards
4 ///
6 /*
7 Copyright (C) 2006-2012, Net Direct Inc. (http://www.netdirect.ca/)
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
22 #include "vcard.h"
23 #include <string.h>
24 #include <stdlib.h>
25 #include <ctype.h>
26 #include <sstream>
28 namespace Barry { namespace Sync {
30 //////////////////////////////////////////////////////////////////////////////
31 // Utility functions
33 namespace {
35 void ToLower(std::string &str)
37 size_t i = 0;
38 while( i < str.size() ) {
39 str[i] = tolower(str[i]);
40 i++;
46 //////////////////////////////////////////////////////////////////////////////
47 // vCard
49 vCard::vCard()
50 : m_gCardData(0)
54 vCard::~vCard()
56 if( m_gCardData ) {
57 g_free(m_gCardData);
61 void vCard::AddAddress(const char *rfc_type, const Barry::PostalAddress &address)
63 // add label first
64 vAttrPtr label = NewAttr("LABEL");
65 AddParam(label, "TYPE", rfc_type);
66 AddValue(label, address.GetLabel().c_str());
67 AddAttr(label);
69 // add breakout address form
70 vAttrPtr adr = NewAttr("ADR"); // RFC 2426, 3.2.1
71 AddParam(adr, "TYPE", rfc_type);
72 AddValue(adr, address.Address3.c_str()); // PO Box
73 AddValue(adr, address.Address2.c_str()); // Extended address
74 AddValue(adr, address.Address1.c_str()); // Street address
75 AddValue(adr, address.City.c_str()); // Locality (city)
76 AddValue(adr, address.Province.c_str()); // Region (province)
77 AddValue(adr, address.PostalCode.c_str()); // Postal code
78 AddValue(adr, address.Country.c_str()); // Country name
79 AddAttr(adr);
82 /// Add phone conditionally, only if phone has data in it. This version
83 /// does not add a TYPE parameter to the item.
84 void vCard::AddPhoneCond(const std::string &phone)
86 if( phone.size() ) {
87 vAttrPtr tel = NewAttr("TEL", phone.c_str());
88 AddAttr(tel);
92 /// Add phone conditionally, only if phone has data in it
93 void vCard::AddPhoneCond(const char *rfc_type, const std::string &phone)
95 if( phone.size() ) {
96 vAttrPtr tel = NewAttr("TEL", phone.c_str());
97 AddParam(tel, "TYPE", rfc_type);
98 AddAttr(tel);
102 void vCard::ParseAddress(vAttr &adr, Barry::PostalAddress &address)
104 // RFC 2426, 3.2.1
105 address.Address3 = adr.GetValue(0); // PO Box
106 address.Address2 = adr.GetValue(1); // Extended address
107 address.Address1 = adr.GetValue(2); // Street address
108 address.City = adr.GetValue(3); // Locality (city)
109 address.Province = adr.GetValue(4); // Region (province)
110 address.PostalCode = adr.GetValue(5); // Postal code
111 address.Country = adr.GetValue(6); // Country name
114 void vCard::ParseCategories(vAttr &cat, Barry::CategoryList &cats)
116 int i = 0;
117 std::string value = cat.GetValue(i);
118 while( value.size() ) {
119 cats.push_back(value);
120 i++;
121 value = cat.GetValue(i);
127 // Main conversion routine for converting from Barry::Contact to
128 // a vCard string of data.
129 const std::string& vCard::ToVCard(const Barry::Contact &con)
131 // Trace trace("vCard::ToVCard");
132 std::ostringstream oss;
133 con.Dump(oss);
134 // trace.logf("ToVCard, initial Barry record: %s", oss.str().c_str());
136 // start fresh
137 Clear();
138 SetFormat( b_vformat_new() );
139 if( !Format() )
140 throw ConvertError("resource error allocating vformat");
142 // store the Barry object we're working with
143 m_BarryContact = con;
146 // begin building vCard data
149 AddAttr(NewAttr("PRODID", "-//OpenSync//NONSGML Barry Contact Record//EN"));
151 std::string fullname = con.GetFullName();
152 if( fullname.size() ) {
153 AddAttr(NewAttr("FN", fullname.c_str()));
155 else {
157 // RFC 2426, 3.1.1 states that FN MUST be present in the
158 // vcard object. Unfortunately, the Blackberry doesn't
159 // require a name, only a name or company name.
161 // In this case we do nothing, and generate an invalid
162 // vcard, since if we try to fix our output here, we'll
163 // likely end up with duplicated company names in the
164 // Blackberry record after a few syncs.
168 if( con.FirstName.size() || con.LastName.size() ) {
169 vAttrPtr name = NewAttr("N"); // RFC 2426, 3.1.2
170 AddValue(name, con.LastName.c_str()); // Family Name
171 AddValue(name, con.FirstName.c_str()); // Given Name
172 AddValue(name, ""); // Additional Names
173 AddValue(name, con.Prefix.c_str()); // Honorific Prefixes
174 AddValue(name, ""); // Honorific Suffixes
175 AddAttr(name);
178 if( con.Nickname.size() )
179 AddAttr(NewAttr("NICKNAME", con.Nickname.c_str()));
181 if( con.WorkAddress.HasData() )
182 AddAddress("work", con.WorkAddress);
183 if( con.HomeAddress.HasData() )
184 AddAddress("home", con.HomeAddress);
186 // add all applicable phone numbers... there can be multiple
187 // TEL fields, even with the same TYPE value... therefore, the
188 // second TEL field with a TYPE=work, will be stored in WorkPhone2
189 AddPhoneCond("voice,pref", con.Phone);
190 AddPhoneCond("fax", con.Fax);
191 AddPhoneCond("voice,work", con.WorkPhone);
192 AddPhoneCond("voice,work", con.WorkPhone2);
193 AddPhoneCond("voice,home", con.HomePhone);
194 AddPhoneCond("voice,home", con.HomePhone2);
195 AddPhoneCond("msg,cell", con.MobilePhone);
196 AddPhoneCond("msg,pager", con.Pager);
197 AddPhoneCond("voice", con.OtherPhone);
199 // add all email addresses, marking first one as "pref"
200 Barry::Contact::EmailList::const_iterator eai = con.EmailAddresses.begin();
201 for( unsigned int i = 0; eai != con.EmailAddresses.end(); ++eai, ++i ) {
202 const std::string& e = con.GetEmail(i);
203 if( e.size() ) {
204 vAttrPtr email = NewAttr("EMAIL", e.c_str());
205 if( i == 0 ) {
206 AddParam(email, "TYPE", "internet,pref");
208 else {
209 AddParam(email, "TYPE", "internet");
211 AddAttr(email);
215 if( con.JobTitle.size() ) {
216 AddAttr(NewAttr("TITLE", con.JobTitle.c_str()));
217 AddAttr(NewAttr("ROLE", con.JobTitle.c_str()));
220 if( con.Company.size() ) {
221 // RFC 2426, 3.5.5
222 vAttrPtr org = NewAttr("ORG", con.Company.c_str()); // Organization name
223 AddValue(org, ""); // Division name
224 AddAttr(org);
227 if( con.Birthday.HasData() )
228 AddAttr(NewAttr("BDAY", con.Birthday.ToYYYYMMDD().c_str()));
230 if( con.Notes.size() )
231 AddAttr(NewAttr("NOTE", con.Notes.c_str()));
232 if( con.URL.size() )
233 AddAttr(NewAttr("URL", con.URL.c_str()));
234 if( con.Categories.size() )
235 AddCategories(con.Categories);
237 // Image / Photo
238 if (con.Image.size()) {
239 vAttrPtr photo = NewAttr("PHOTO");
240 AddEncodedValue(photo, VF_ENCODING_BASE64, con.Image.c_str(), con.Image.size());
241 AddParam(photo, "ENCODING", "BASE64");
242 AddAttr(photo);
245 // generate the raw VCARD data
246 m_gCardData = b_vformat_to_string(Format(), VFORMAT_CARD_30);
247 m_vCardData = m_gCardData;
249 // trace.logf("ToVCard, resulting vcard data: %s", m_vCardData.c_str());
250 return m_vCardData;
254 // NOTE:
255 // Treat the following pairs of variables like
256 // sliding buffers, where higher priority values
257 // can push existings values from 1 to 2, or from
258 // 2 to oblivion:
260 // HomePhone + HomePhone2
261 // WorkPhone + WorkPhone2
262 // Phone + OtherPhone
265 // class SlidingPair
267 // This class handles the sliding pair logic for a pair of std::strings.
269 class SlidingPair
271 std::string &m_first;
272 std::string &m_second;
273 int m_evolutionSlot1, m_evolutionSlot2;
274 public:
275 static const int DefaultSlot = 99;
276 SlidingPair(std::string &first, std::string &second)
277 : m_first(first)
278 , m_second(second)
279 , m_evolutionSlot1(DefaultSlot)
280 , m_evolutionSlot2(DefaultSlot)
284 bool assign(const std::string &value, const char *type_str, int evolutionSlot)
286 bool used = false;
288 if( strstr(type_str, "pref") || evolutionSlot < m_evolutionSlot1 ) {
289 m_second = m_first;
290 m_evolutionSlot2 = m_evolutionSlot1;
292 m_first = value;
293 m_evolutionSlot1 = evolutionSlot;
295 used = true;
297 else if( evolutionSlot < m_evolutionSlot2 ) {
298 m_second = value;
299 m_evolutionSlot2 = evolutionSlot;
300 used = true;
302 else if( m_first.size() == 0 ) {
303 m_first = value;
304 m_evolutionSlot1 = evolutionSlot;
305 used = true;
307 else if( m_second.size() == 0 ) {
308 m_second = value;
309 m_evolutionSlot2 = evolutionSlot;
310 used = true;
313 return used;
318 // Main conversion routine for converting from vCard data string
319 // to a Barry::Contact object.
320 const Barry::Contact& vCard::ToBarry(const char *vcard, uint32_t RecordId)
322 using namespace std;
324 // Trace trace("vCard::ToBarry");
325 // trace.logf("ToBarry, working on vcard data: %s", vcard);
327 // start fresh
328 Clear();
330 // store the vCard raw data
331 m_vCardData = vcard;
333 // create format parser structures
334 SetFormat( b_vformat_new_from_string(vcard) );
335 if( !Format() )
336 throw ConvertError("resource error allocating vformat");
340 // Parse the vcard data
343 Barry::Contact &con = m_BarryContact;
344 con.SetIds(Barry::Contact::GetDefaultRecType(), RecordId);
346 vAttr name = GetAttrObj("N");
347 if( name.Get() ) {
348 // RFC 2426, 3.1.2
349 con.LastName = name.GetValue(0); // Family Name
350 con.FirstName = name.GetValue(1); // Given Name
351 con.Prefix = name.GetValue(3); // Honorific Prefixes
354 con.Nickname = GetAttr("NICKNAME");
356 vAttr adr = GetAttrObj("ADR");
357 for( int i = 0; adr.Get(); adr = GetAttrObj("ADR", ++i) )
359 std::string type = adr.GetAllParams("TYPE");
360 ToLower(type);
362 // do not use "else" here, since TYPE can have multiple keys
363 if( strstr(type.c_str(), "work") )
364 ParseAddress(adr, con.WorkAddress);
365 if( strstr(type.c_str(), "home") )
366 ParseAddress(adr, con.HomeAddress);
371 // NOTE:
372 // Treat the following pairs of variables like
373 // sliding buffers, where higher priority values
374 // can push existings values from 1 to 2, or from
375 // 2 to oblivion:
377 // HomePhone + HomePhone2
378 // WorkPhone + WorkPhone2
379 // Phone + OtherPhone
381 SlidingPair HomePair(con.HomePhone, con.HomePhone2);
382 SlidingPair WorkPair(con.WorkPhone, con.WorkPhone2);
383 SlidingPair OtherPair(con.Phone, con.OtherPhone);
385 // add all applicable phone numbers... there can be multiple
386 // TEL fields, even with the same TYPE value... therefore, the
387 // second TEL field with a TYPE=work, will be stored in WorkPhone2
388 vAttr tel = GetAttrObj("TEL");
389 for( int i = 0; tel.Get(); tel = GetAttrObj("TEL", ++i) )
391 // grab all parameter values for this param name
392 std::string stype = tel.GetAllParams("TYPE");
394 // grab evolution-specific parameter... evolution is too
395 // lazy to sort its VCARD output, but instead it does
396 // its own non-standard tagging... so we try to
397 // accommodate it, so Work and Home phone numbers keep
398 // their order if possible
399 int evolutionSlot = atoi(tel.GetAllParams("X-EVOLUTION-UI-SLOT").c_str());
400 if( evolutionSlot == 0 )
401 evolutionSlot = SlidingPair::DefaultSlot;
403 // turn to lower case for comparison
404 // FIXME - is this i18n safe?
405 ToLower(stype);
407 // state
408 const char *type = stype.c_str();
409 bool used = false;
411 // Check for possible TYPE conflicts:
412 // pager can coexist with cell/pcs/car
413 // fax conflicts with cell/pcs/car
414 // fax conflicts with pager
415 bool mobile_type = strstr(type, "cell") ||
416 strstr(type, "pcs") ||
417 strstr(type, "car");
418 bool fax_type = strstr(type, "fax");
419 bool pager_type = strstr(type, "pager");
420 if( fax_type && (mobile_type || pager_type) ) {
421 // conflict found, log and skip
422 // trace.logf("ToBarry: skipping phone number due to TYPE conflict: fax cannot coexist with %s: %s",
423 // mobile_type ? "cell/pcs/car" : "pager",
424 // type);
425 continue;
428 // If phone number has the "pref" flag
429 if( strstr(type, "pref") ) {
430 // Always use cell phone if the "pref" flag is set
431 if( strstr(type, "cell") ) {
432 used = OtherPair.assign(tel.GetValue(), type, evolutionSlot);
434 // Otherwise, the phone has to be "voice" type
435 else if( strstr(type, "voice") && con.Phone.size() == 0 ) {
436 used = OtherPair.assign(tel.GetValue(), type, evolutionSlot);
440 // For each known phone type
441 // Fax :
442 if( strstr(type, "fax") && (strstr(type, "pref") || con.Fax.size() == 0) ) {
443 con.Fax = tel.GetValue();
444 used = true;
446 // Mobile phone :
447 else if( mobile_type && (strstr(type, "pref") || con.MobilePhone.size() == 0) ) {
448 con.MobilePhone = tel.GetValue();
449 used = true;
451 // Pager :
452 else if( strstr(type, "pager") && (strstr(type, "pref") || con.Pager.size() == 0) ) {
453 con.Pager = tel.GetValue();
454 used = true;
456 // Check for any TEL-ignore types, and use other phone field if possible
457 // bbs/video/modem entire TEL ignored by Barry
458 // isdn entire TEL ignored by Barry
459 else if( strstr(type, "bbs") || strstr(type, "video") || strstr(type, "modem") ) {
461 else if( strstr(type, "isdn") ) {
463 // Voice telephone :
464 else {
465 if( strstr(type, "work") ) {
466 used = WorkPair.assign(tel.GetValue(), type, evolutionSlot);
469 if( strstr(type, "home") ) {
470 used = HomePair.assign(tel.GetValue(), type, evolutionSlot);
474 // if this value has not been claimed by any of the
475 // cases above, claim it now as "OtherPhone"
476 if( !used && con.OtherPhone.size() == 0 ) {
477 OtherPair.assign(tel.GetValue(), type, evolutionSlot);
481 // scan for all email addresses... append addresses to the
482 // list by default, but prepend if its type is set to "pref"
483 // i.e. we want the preferred email address first
484 vAttr email = GetAttrObj("EMAIL");
485 for( int i = 0; email.Get(); email = GetAttrObj("EMAIL", ++i) )
487 std::string type = email.GetAllParams("TYPE");
488 ToLower(type);
490 bool of_interest = (i == 0 || strstr(type.c_str(), "pref"));
491 bool x400 = strstr(type.c_str(), "x400");
493 if( of_interest && !x400 ) {
494 con.EmailAddresses.insert(con.EmailAddresses.begin(), email.GetValue());
496 else {
497 con.EmailAddresses.push_back( email.GetValue() );
501 // figure out which company title we want to keep...
502 // favour the TITLE field, but if it's empty, use ROLE
503 con.JobTitle = GetAttr("TITLE");
504 if( !con.JobTitle.size() )
505 con.JobTitle = GetAttr("ROLE");
507 con.Company = GetAttr("ORG");
508 con.Notes = GetAttr("NOTE");
509 con.URL = GetAttr("URL");
510 if( GetAttr("BDAY").size() && !con.Birthday.FromYYYYMMDD( GetAttr("BDAY") ) )
511 throw ConvertError("Unable to parse BDAY field");
513 // Photo vCard ?
514 vAttr photo = GetAttrObj("PHOTO");
515 if (photo.Get()) {
516 std::string sencoding = photo.GetAllParams("ENCODING");
518 ToLower(sencoding);
520 const char *encoding = sencoding.c_str();
522 if (strstr(encoding, "quoted-printable")) {
523 photo.Get()->encoding = VF_ENCODING_QP;
525 con.Image = photo.GetDecodedValue();
527 else if (strstr(encoding, "b")) {
528 photo.Get()->encoding = VF_ENCODING_BASE64;
530 con.Image = photo.GetDecodedValue();
532 // Else
533 // We ignore the photo, I don't know decoded !
536 vAttr cat = GetAttrObj("CATEGORIES");
537 if( cat.Get() )
538 ParseCategories(cat, con.Categories);
540 // Last sanity check: Blackberry requires that at least
541 // name or Company has data.
542 if( !con.GetFullName().size() && !con.Company.size() )
543 throw ConvertError("FN and ORG fields both blank in VCARD data");
545 return m_BarryContact;
548 // Transfers ownership of m_gCardData to the caller.
549 char* vCard::ExtractVCard()
551 char *ret = m_gCardData;
552 m_gCardData = 0;
553 return ret;
556 void vCard::Clear()
558 vBase::Clear();
559 m_vCardData.clear();
560 m_BarryContact.Clear();
562 if( m_gCardData ) {
563 g_free(m_gCardData);
564 m_gCardData = 0;
568 }} // namespace Barry::Sync