desktop: fixed Evolution config writing, setting enabled only if URL is present
[barry.git] / src / vcard.cc
blob65a6c283c6552993140c3ac5f5a0d163270b18cd
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.WorkAddress.HasData() )
179 AddAddress("work", con.WorkAddress);
180 if( con.HomeAddress.HasData() )
181 AddAddress("home", con.HomeAddress);
183 // add all applicable phone numbers... there can be multiple
184 // TEL fields, even with the same TYPE value... therefore, the
185 // second TEL field with a TYPE=work, will be stored in WorkPhone2
186 AddPhoneCond("voice,pref", con.Phone);
187 AddPhoneCond("fax", con.Fax);
188 AddPhoneCond("voice,work", con.WorkPhone);
189 AddPhoneCond("voice,work", con.WorkPhone2);
190 AddPhoneCond("voice,home", con.HomePhone);
191 AddPhoneCond("voice,home", con.HomePhone2);
192 AddPhoneCond("msg,cell", con.MobilePhone);
193 AddPhoneCond("msg,pager", con.Pager);
194 AddPhoneCond("voice", con.OtherPhone);
196 // add all email addresses, marking first one as "pref"
197 Barry::Contact::EmailList::const_iterator eai = con.EmailAddresses.begin();
198 for( unsigned int i = 0; eai != con.EmailAddresses.end(); ++eai, ++i ) {
199 const std::string& e = con.GetEmail(i);
200 if( e.size() ) {
201 vAttrPtr email = NewAttr("EMAIL", e.c_str());
202 if( i == 0 ) {
203 AddParam(email, "TYPE", "internet,pref");
205 else {
206 AddParam(email, "TYPE", "internet");
208 AddAttr(email);
212 if( con.JobTitle.size() ) {
213 AddAttr(NewAttr("TITLE", con.JobTitle.c_str()));
214 AddAttr(NewAttr("ROLE", con.JobTitle.c_str()));
217 if( con.Company.size() ) {
218 // RFC 2426, 3.5.5
219 vAttrPtr org = NewAttr("ORG", con.Company.c_str()); // Organization name
220 AddValue(org, ""); // Division name
221 AddAttr(org);
224 if( con.Birthday.HasData() )
225 AddAttr(NewAttr("BDAY", con.Birthday.ToYYYYMMDD().c_str()));
227 if( con.Notes.size() )
228 AddAttr(NewAttr("NOTE", con.Notes.c_str()));
229 if( con.URL.size() )
230 AddAttr(NewAttr("URL", con.URL.c_str()));
231 if( con.Categories.size() )
232 AddCategories(con.Categories);
234 // Image / Photo
235 if (con.Image.size()) {
236 vAttrPtr photo = NewAttr("PHOTO");
237 AddEncodedValue(photo, VF_ENCODING_BASE64, con.Image.c_str(), con.Image.size());
238 AddParam(photo, "ENCODING", "BASE64");
239 AddAttr(photo);
242 // generate the raw VCARD data
243 m_gCardData = b_vformat_to_string(Format(), VFORMAT_CARD_30);
244 m_vCardData = m_gCardData;
246 // trace.logf("ToVCard, resulting vcard data: %s", m_vCardData.c_str());
247 return m_vCardData;
251 // NOTE:
252 // Treat the following pairs of variables like
253 // sliding buffers, where higher priority values
254 // can push existings values from 1 to 2, or from
255 // 2 to oblivion:
257 // HomePhone + HomePhone2
258 // WorkPhone + WorkPhone2
259 // Phone + OtherPhone
262 // class SlidingPair
264 // This class handles the sliding pair logic for a pair of std::strings.
266 class SlidingPair
268 std::string &m_first;
269 std::string &m_second;
270 int m_evolutionSlot1, m_evolutionSlot2;
271 public:
272 static const int DefaultSlot = 99;
273 SlidingPair(std::string &first, std::string &second)
274 : m_first(first)
275 , m_second(second)
276 , m_evolutionSlot1(DefaultSlot)
277 , m_evolutionSlot2(DefaultSlot)
281 bool assign(const std::string &value, const char *type_str, int evolutionSlot)
283 bool used = false;
285 if( strstr(type_str, "pref") || evolutionSlot < m_evolutionSlot1 ) {
286 m_second = m_first;
287 m_evolutionSlot2 = m_evolutionSlot1;
289 m_first = value;
290 m_evolutionSlot1 = evolutionSlot;
292 used = true;
294 else if( evolutionSlot < m_evolutionSlot2 ) {
295 m_second = value;
296 m_evolutionSlot2 = evolutionSlot;
297 used = true;
299 else if( m_first.size() == 0 ) {
300 m_first = value;
301 m_evolutionSlot1 = evolutionSlot;
302 used = true;
304 else if( m_second.size() == 0 ) {
305 m_second = value;
306 m_evolutionSlot2 = evolutionSlot;
307 used = true;
310 return used;
315 // Main conversion routine for converting from vCard data string
316 // to a Barry::Contact object.
317 const Barry::Contact& vCard::ToBarry(const char *vcard, uint32_t RecordId)
319 using namespace std;
321 // Trace trace("vCard::ToBarry");
322 // trace.logf("ToBarry, working on vcard data: %s", vcard);
324 // start fresh
325 Clear();
327 // store the vCard raw data
328 m_vCardData = vcard;
330 // create format parser structures
331 SetFormat( b_vformat_new_from_string(vcard) );
332 if( !Format() )
333 throw ConvertError("resource error allocating vformat");
337 // Parse the vcard data
340 Barry::Contact &con = m_BarryContact;
341 con.SetIds(Barry::Contact::GetDefaultRecType(), RecordId);
343 vAttr name = GetAttrObj("N");
344 if( name.Get() ) {
345 // RFC 2426, 3.1.2
346 con.LastName = name.GetValue(0); // Family Name
347 con.FirstName = name.GetValue(1); // Given Name
348 con.Prefix = name.GetValue(3); // Honorific Prefixes
351 vAttr adr = GetAttrObj("ADR");
352 for( int i = 0; adr.Get(); adr = GetAttrObj("ADR", ++i) )
354 std::string type = adr.GetAllParams("TYPE");
355 ToLower(type);
357 // do not use "else" here, since TYPE can have multiple keys
358 if( strstr(type.c_str(), "work") )
359 ParseAddress(adr, con.WorkAddress);
360 if( strstr(type.c_str(), "home") )
361 ParseAddress(adr, con.HomeAddress);
366 // NOTE:
367 // Treat the following pairs of variables like
368 // sliding buffers, where higher priority values
369 // can push existings values from 1 to 2, or from
370 // 2 to oblivion:
372 // HomePhone + HomePhone2
373 // WorkPhone + WorkPhone2
374 // Phone + OtherPhone
376 SlidingPair HomePair(con.HomePhone, con.HomePhone2);
377 SlidingPair WorkPair(con.WorkPhone, con.WorkPhone2);
378 SlidingPair OtherPair(con.Phone, con.OtherPhone);
380 // add all applicable phone numbers... there can be multiple
381 // TEL fields, even with the same TYPE value... therefore, the
382 // second TEL field with a TYPE=work, will be stored in WorkPhone2
383 vAttr tel = GetAttrObj("TEL");
384 for( int i = 0; tel.Get(); tel = GetAttrObj("TEL", ++i) )
386 // grab all parameter values for this param name
387 std::string stype = tel.GetAllParams("TYPE");
389 // grab evolution-specific parameter... evolution is too
390 // lazy to sort its VCARD output, but instead it does
391 // its own non-standard tagging... so we try to
392 // accommodate it, so Work and Home phone numbers keep
393 // their order if possible
394 int evolutionSlot = atoi(tel.GetAllParams("X-EVOLUTION-UI-SLOT").c_str());
395 if( evolutionSlot == 0 )
396 evolutionSlot = SlidingPair::DefaultSlot;
398 // turn to lower case for comparison
399 // FIXME - is this i18n safe?
400 ToLower(stype);
402 // state
403 const char *type = stype.c_str();
404 bool used = false;
406 // Check for possible TYPE conflicts:
407 // pager can coexist with cell/pcs/car
408 // fax conflicts with cell/pcs/car
409 // fax conflicts with pager
410 bool mobile_type = strstr(type, "cell") ||
411 strstr(type, "pcs") ||
412 strstr(type, "car");
413 bool fax_type = strstr(type, "fax");
414 bool pager_type = strstr(type, "pager");
415 if( fax_type && (mobile_type || pager_type) ) {
416 // conflict found, log and skip
417 // trace.logf("ToBarry: skipping phone number due to TYPE conflict: fax cannot coexist with %s: %s",
418 // mobile_type ? "cell/pcs/car" : "pager",
419 // type);
420 continue;
423 // If phone number has the "pref" flag
424 if( strstr(type, "pref") ) {
425 // Always use cell phone if the "pref" flag is set
426 if( strstr(type, "cell") ) {
427 used = OtherPair.assign(tel.GetValue(), type, evolutionSlot);
429 // Otherwise, the phone has to be "voice" type
430 else if( strstr(type, "voice") && con.Phone.size() == 0 ) {
431 used = OtherPair.assign(tel.GetValue(), type, evolutionSlot);
435 // For each known phone type
436 // Fax :
437 if( strstr(type, "fax") && (strstr(type, "pref") || con.Fax.size() == 0) ) {
438 con.Fax = tel.GetValue();
439 used = true;
441 // Mobile phone :
442 else if( mobile_type && (strstr(type, "pref") || con.MobilePhone.size() == 0) ) {
443 con.MobilePhone = tel.GetValue();
444 used = true;
446 // Pager :
447 else if( strstr(type, "pager") && (strstr(type, "pref") || con.Pager.size() == 0) ) {
448 con.Pager = tel.GetValue();
449 used = true;
451 // Check for any TEL-ignore types, and use other phone field if possible
452 // bbs/video/modem entire TEL ignored by Barry
453 // isdn entire TEL ignored by Barry
454 else if( strstr(type, "bbs") || strstr(type, "video") || strstr(type, "modem") ) {
456 else if( strstr(type, "isdn") ) {
458 // Voice telephone :
459 else {
460 if( strstr(type, "work") ) {
461 used = WorkPair.assign(tel.GetValue(), type, evolutionSlot);
464 if( strstr(type, "home") ) {
465 used = HomePair.assign(tel.GetValue(), type, evolutionSlot);
469 // if this value has not been claimed by any of the
470 // cases above, claim it now as "OtherPhone"
471 if( !used && con.OtherPhone.size() == 0 ) {
472 OtherPair.assign(tel.GetValue(), type, evolutionSlot);
476 // scan for all email addresses... append addresses to the
477 // list by default, but prepend if its type is set to "pref"
478 // i.e. we want the preferred email address first
479 vAttr email = GetAttrObj("EMAIL");
480 for( int i = 0; email.Get(); email = GetAttrObj("EMAIL", ++i) )
482 std::string type = email.GetAllParams("TYPE");
483 ToLower(type);
485 bool of_interest = (i == 0 || strstr(type.c_str(), "pref"));
486 bool x400 = strstr(type.c_str(), "x400");
488 if( of_interest && !x400 ) {
489 con.EmailAddresses.insert(con.EmailAddresses.begin(), email.GetValue());
491 else {
492 con.EmailAddresses.push_back( email.GetValue() );
496 // figure out which company title we want to keep...
497 // favour the TITLE field, but if it's empty, use ROLE
498 con.JobTitle = GetAttr("TITLE");
499 if( !con.JobTitle.size() )
500 con.JobTitle = GetAttr("ROLE");
502 con.Company = GetAttr("ORG");
503 con.Notes = GetAttr("NOTE");
504 con.URL = GetAttr("URL");
505 if( GetAttr("BDAY").size() && !con.Birthday.FromYYYYMMDD( GetAttr("BDAY") ) )
506 throw ConvertError("Unable to parse BDAY field");
508 // Photo vCard ?
509 vAttr photo = GetAttrObj("PHOTO");
510 if (photo.Get()) {
511 std::string sencoding = photo.GetAllParams("ENCODING");
513 ToLower(sencoding);
515 const char *encoding = sencoding.c_str();
517 if (strstr(encoding, "quoted-printable")) {
518 photo.Get()->encoding = VF_ENCODING_QP;
520 con.Image = photo.GetDecodedValue();
522 else if (strstr(encoding, "b")) {
523 photo.Get()->encoding = VF_ENCODING_BASE64;
525 con.Image = photo.GetDecodedValue();
527 // Else
528 // We ignore the photo, I don't know decoded !
531 vAttr cat = GetAttrObj("CATEGORIES");
532 if( cat.Get() )
533 ParseCategories(cat, con.Categories);
535 // Last sanity check: Blackberry requires that at least
536 // name or Company has data.
537 if( !con.GetFullName().size() && !con.Company.size() )
538 throw ConvertError("FN and ORG fields both blank in VCARD data");
540 return m_BarryContact;
543 // Transfers ownership of m_gCardData to the caller.
544 char* vCard::ExtractVCard()
546 char *ret = m_gCardData;
547 m_gCardData = 0;
548 return ret;
551 void vCard::Clear()
553 vBase::Clear();
554 m_vCardData.clear();
555 m_BarryContact.Clear();
557 if( m_gCardData ) {
558 g_free(m_gCardData);
559 m_gCardData = 0;
563 }} // namespace Barry::Sync