예제 #1
0
void TestDistrList::testDuplicate()
{
    kDebug() ;
    // This is a special test for the case where we have a contact and a distr list with the same name
    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    KABC::Addressee addr;
    addr.setName( "foo" );
    addr.insertEmail( "*****@*****.**", true );
    ab->insertAddressee( addr );

#if 0 // we need a findByFormattedName
    KABC::Addressee::List addrList = ab->findByName( "foo" );
    assert( addrList.count() == 2 );

    bool a = DistributionList::isDistributionList( addrList.first() );
    bool b = DistributionList::isDistributionList( addrList.last() );
    // one is a distr list, but not both
    assert( a || b );
    //
    assert( ! ( a && b ) );
#endif

    DistributionList dl = DistributionList::findByName( ab, "foo" );
    assert( !dl.isEmpty() );
    assert( DistributionList::isDistributionList( dl ) );
    assert( dl.formattedName() == "foo" );
}
예제 #2
0
void RecentAddresses::add( const QString& entry )
{
  if ( !entry.isEmpty() && m_maxCount > 0 ) {
    QStringList list = KPIM::splitEmailAddrList( entry );
    for( QStringList::const_iterator e_it = list.begin(); e_it != list.end(); ++e_it ) {
      KPIM::EmailParseResult errorCode = KPIM::isValidEmailAddress( *e_it );
      if ( errorCode != KPIM::AddressOk ) 
        continue;
      QString email;
      QString fullName;
      KABC::Addressee addr;

      KABC::Addressee::parseEmailAddress( *e_it, fullName, email );

      for ( KABC::Addressee::List::Iterator it = m_addresseeList.begin();
          it != m_addresseeList.end(); ++it )
      {
        if ( email == (*it).preferredEmail() ) {
          //already inside, remove it here and add it later at pos==1
          m_addresseeList.remove( it );
          break;
        }
      }
      addr.setNameFromString( fullName );
      addr.insertEmail( email, true );
      m_addresseeList.prepend( addr );
      adjustSize();
    }
  }
}
void DistributionListDialog::setRecipients( const Recipient::List &recipients )
{
  Recipient::List::ConstIterator it;
  for( it = recipients.constBegin(); it != recipients.constEnd(); ++it ) {
    QStringList emails = KPIMUtils::splitAddressList( (*it).email() );
    QStringList::ConstIterator it2;
    for( it2 = emails.constBegin(); it2 != emails.constEnd(); ++it2 ) {
      QString name;
      QString email;
      KABC::Addressee::parseEmailAddress( *it2, name, email );
      if ( !email.isEmpty() ) {
        DistributionListItem *item = new DistributionListItem( mRecipientsList );
        KABC::Addressee::List addressees =
          KABC::StdAddressBook::self( true )->findByEmail( email );
        if ( addressees.isEmpty() ) {
          KABC::Addressee a;
          a.setNameFromString( name );
          a.insertEmail( email );
          item->setTransientAddressee( a, email );
          item->setCheckState( 0, Qt::Checked );
        } else {
          KABC::Addressee::List::ConstIterator it3;
          for( it3 = addressees.constBegin(); it3 != addressees.constEnd(); ++it3 ) {
            item->setAddressee( *it3, email );
            if ( it3 == addressees.constBegin() ) item->setCheckState( 0, Qt::Checked );
          }
        }
      }
    }
  }
}
예제 #4
0
void AddresseeEmailSelection::setSelectedItem( uint fieldIndex, const QStringList &emails )
{
  QStringList::ConstIterator it;
  for ( it = emails.begin(); it != emails.end(); ++it ) {
    KABC::Addressee addr;
    addr.insertEmail( *it, true );

    selector()->setItemSelected( fieldIndex, addr, 0, *it );
  }
}
void
AddressesDialog::setSelectedBCC( const QStringList& l )
{
  QString name, email;
  for ( QStringList::ConstIterator it = l.constBegin(); it != l.constEnd(); ++it ) {
    KABC::Addressee addr;
    KABC::Addressee::parseEmailAddress( *it, name, email );
    addr.setNameFromString( name );
    addr.insertEmail( email );
    addAddresseeToSelected( addr, selectedBccItem() );
  }
}
예제 #6
0
KABC::Addressee toKABC(const Kolab::Contact &contact)
{
  KABC::Addressee addressee;
  addressee.setUid(fromStdString(contact.uid()));
  addressee.setCategories(toStringList(contact.categories()));
  //addressee.setName(fromStdString(contact.name()));//This one is only for compatiblity (and results in a non-existing name property)
  addressee.setFormattedName(fromStdString(contact.name())); //This on corresponds to fn
  
  const Kolab::NameComponents &nc = contact.nameComponents();
  if (!nc.surnames().empty()) {
      addressee.setFamilyName(fromStdString(nc.surnames().front()));
  }
  if (!nc.given().empty()) {
      addressee.setGivenName(fromStdString(nc.given().front()));
  }
  if (!nc.additional().empty()) {
      addressee.setAdditionalName(fromStdString(nc.additional().front()));
  }
  if (!nc.prefixes().empty()) {
      addressee.setPrefix(fromStdString(nc.prefixes().front()));
  }
  if (!nc.suffixes().empty()) {
      addressee.setSuffix(fromStdString(nc.suffixes().front()));
  }
  
  addressee.setNote(fromStdString(contact.note()));
  
  addressee.setSecrecy(KABC::Secrecy::Public); //We don't have any privacy setting in xCard
  
  
  QString preferredEmail;
  
  if (!contact.emailAddresses().empty()) {
      QStringList emails;
      foreach( const Kolab::Email &email, contact.emailAddresses()) {
          emails << fromStdString(email.address());
          const QString types = emailTypesToStringList(email.types());
          if (!types.isEmpty()) {
              addressee.insertCustom(QLatin1String("KOLAB"), QString::fromLatin1("EmailTypes%1").arg(fromStdString(email.address())), types);
          }
      }
      addressee.setEmails(emails);
      if ((contact.emailAddressPreferredIndex() >= 0) && (contact.emailAddressPreferredIndex() < static_cast<int>(contact.emailAddresses().size()))) {
          preferredEmail = fromStdString(contact.emailAddresses().at(contact.emailAddressPreferredIndex()).address());
      } else {
          preferredEmail = fromStdString(contact.emailAddresses().at(0).address());
      }
      addressee.insertEmail(preferredEmail, true);
  }
예제 #7
0
void RecentAddresses::load( KConfig *config )
{
    QStringList addresses;
    QString name;
    QString email;

    m_addresseeList.clear();
    KConfigGroupSaver cs( config, "General" );
    m_maxCount = config->readNumEntry( "Maximum Recent Addresses", 40 );
    addresses = config->readListEntry( "Recent Addresses" );
    for ( QStringList::Iterator it = addresses.begin(); it != addresses.end(); ++it ) {
        KABC::Addressee::parseEmailAddress( *it, name, email );
        if ( !email.isEmpty() ) {
            KABC::Addressee addr;
            addr.setNameFromString( name );
            addr.insertEmail( email, true );
            m_addresseeList.append( addr );
        }
    }

    adjustSize();
}
예제 #8
0
//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail(const QString &addr, QWidget *parent)
{
    QString email;
    QString name;

    KABC::Addressee::parseEmailAddress(addr, name, email);

    KABC::AddressBook *ab = KABC::StdAddressBook::self(true);

    ab->setErrorHandler(new KABC::GuiErrorHandler(parent));

    // force a reload of the address book file so that changes that were made
    // by other programs are loaded
    ab->asyncLoad();

    // if we have to reload the address book then we should also wait until
    // it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
    // This ugly hack will be removed in 4.0
    while(!ab->loadingHasFinished())
    {
        QApplication::eventLoop()->processEvents(QEventLoop::ExcludeUserInput);

        // use sleep here to reduce cpu usage
        usleep(100);
    }
#endif

    KABC::Addressee::List addressees = ab->findByEmail(email);

    if(addressees.isEmpty())
    {
        KABC::Addressee a;
        a.setNameFromString(name);
        a.insertEmail(email, true);

        {
            KConfig config("kaddressbookrc");
            config.setGroup("General");
            int type = config.readNumEntry("FormattedNameType", 1);

            QString name;
            switch(type)
            {
                case 1:
                    name = a.givenName() + " " + a.familyName();
                    break;
                case 2:
                    name = a.assembledName();
                    break;
                case 3:
                    name = a.familyName() + ", " + a.givenName();
                    break;
                case 4:
                    name = a.familyName() + " " + a.givenName();
                    break;
                case 5:
                    name = a.organization();
                    break;
                default:
                    name = "";
                    break;
            }
            name.simplifyWhiteSpace();

            a.setFormattedName(name);
        }

        if(KAddrBookExternal::addAddressee(a))
        {
            QString text = i18n("<qt>The email address <b>%1</b> was added to your "
                                "addressbook; you can add more information to this "
                                "entry by opening the addressbook.</qt>").arg(addr);
            KMessageBox::information(parent, text, QString::null, "addedtokabc");
        }
    }
    else
    {
        QString text = i18n("<qt>The email address <b>%1</b> is already in your "
                            "addressbook.</qt>").arg(addr);
        KMessageBox::information(parent, text, QString::null,
                                 "alreadyInAddressBook");
    }
    ab->setErrorHandler(0);
}
예제 #9
0
bool KDEAccountsFormat::loadAll( KABC::AddressBook *book,
                              KABC::Resource *resource,
                              QFile *file )
{
    if ( !book || !file ) // eh?
        return false;

    QString uuid = "KDEAccountsEntry.";
    int id = 0;

    QByteArray array = file->readAll();
    file->close();

    QByteArray::ConstIterator it = array.begin();
    QByteArray::ConstIterator end = array.end();
    QByteArray::ConstIterator startLine;
    QString line;
    char eol = '\n';
    char delim = ' ';

    for ( ; it < end; it++ )
    {
        startLine = it;

        for ( ; it && it < end && *it != eol; it++ )
        { } // find eol

        uint length = it - startLine;
        line = QString::fromUtf8( startLine, length ).simplified();

        QString nickName;
        QString name;
        QString email;

        int firstSpace = line.indexOf( delim );
        if ( firstSpace > 0 )
        {
            nickName = line.left( firstSpace );

            int lastSpace = line.lastIndexOf( delim );
            if ( lastSpace > firstSpace )
            {
                email = line.mid( lastSpace +1 );

                int start = firstSpace + 1;
                int length = lastSpace - start;
                name = line.mid( start, length );

                if ( !email.isEmpty() )
                {
                    KABC::Addressee address;
                    address.setNickName( nickName  );
                    address.setNameFromString( name );
                    address.setOrganization("KDE Project");
                    address.insertCategory("KDE Developer");
                    address.insertEmail( email  );
                    address.setUid( uuid + QString::number( id++ ));

                    address.setResource( resource );
                    book->insertAddressee( address );
                }
            }
        }
    }

    return true;
}
예제 #10
0
KABC::Addressee VCard21Parser::readFromString(const QString &data)
{
    KABC::Addressee addressee;
    VCard21ParserImpl *vCard = VCard21ParserImpl::parseVCard(data);
    QString tmpStr;

    // Check if parsing failed
    if(vCard == 0)
    {
        kdDebug() << "Parsing failed" << endl;
        return addressee;
    }
    // set the addressees name and formated name
    QStringList tmpList = vCard->getValues(VCARD_N);
    QString formattedName = "";
    if(tmpList.count() > 0)
        addressee.setFamilyName(tmpList[0]);
    if(tmpList.count() > 1)
        addressee.setGivenName(tmpList[1]);
    if(tmpList.count() > 2)
        addressee.setAdditionalName(tmpList[2]);
    if(tmpList.count() > 3)
        addressee.setPrefix(tmpList[3]);
    if(tmpList.count() > 4)
        addressee.setSuffix(tmpList[4]);

    tmpStr = (vCard->getValue(VCARD_FN));
    if(!tmpStr.isEmpty())
        addressee.setFormattedName(tmpStr);

    // set the addressee's nick name
    tmpStr = vCard->getValue(VCARD_NICKNAME);
    addressee.setNickName(tmpStr);
    // set the addressee's organization
    tmpStr = vCard->getValue(VCARD_ORG);
    addressee.setOrganization(tmpStr);
    // set the addressee's title
    tmpStr = vCard->getValue(VCARD_TITLE);
    addressee.setTitle(tmpStr);
    // set the addressee's email - we can only deal with two.  The preferenced one and one other.
    tmpStr = vCard->getValue(VCARD_EMAIL, VCARD_EMAIL_INTERNET);
    addressee.insertEmail(tmpStr, false);
    tmpStr = vCard->getValue(VCARD_EMAIL, VCARD_EMAIL_PREF);
    addressee.insertEmail(tmpStr, true);
    // set the addressee's url
    tmpStr = vCard->getValue(VCARD_URL);
    if(tmpStr.isEmpty())
        tmpStr = vCard->getValue(VCARD_URL, VCARD_ADR_WORK);
    if(tmpStr.isEmpty())
        tmpStr = vCard->getValue(VCARD_URL, VCARD_ADR_HOME);
    if(!tmpStr.isEmpty())
    {
        addressee.setUrl(KURL(tmpStr));
    }

    // set the addressee's birthday
    tmpStr = vCard->getValue(VCARD_BDAY);
    addressee.setBirthday(VCardStringToDate(tmpStr));

    // set the addressee's phone numbers
    for(QValueListIterator< VCardLineX > i = vCard->_vcdata->begin(); i != vCard->_vcdata->end(); ++i)
    {
        if((*i).name == VCARD_TEL)
        {
            int type = 0;
            if((*i).qualified)
            {
                if((*i).qualifiers.contains(VCARD_TEL_HOME))
                    type |= PhoneNumber::Home;
                if((*i).qualifiers.contains(VCARD_TEL_WORK))
                    type |= PhoneNumber::Work;
                if((*i).qualifiers.contains(VCARD_TEL_PREF))
                    type |= PhoneNumber::Pref;
                // if ( (*i).qualifiers.contains( VCARD_TEL_VOICE ) )
                //  type |= PhoneNumber::Voice;
                if((*i).qualifiers.contains(VCARD_TEL_FAX))
                    type |= PhoneNumber::Fax;
                if((*i).qualifiers.contains(VCARD_TEL_MSG))
                    type |= PhoneNumber::Msg;
                if((*i).qualifiers.contains(VCARD_TEL_CELL))
                    type |= PhoneNumber::Cell;
                if((*i).qualifiers.contains(VCARD_TEL_PAGER))
                    type |= PhoneNumber::Pager;
                if((*i).qualifiers.contains(VCARD_TEL_BBS))
                    type |= PhoneNumber::Bbs;
                if((*i).qualifiers.contains(VCARD_TEL_MODEM))
                    type |= PhoneNumber::Modem;
                if((*i).qualifiers.contains(VCARD_TEL_CAR))
                    type |= PhoneNumber::Car;
                if((*i).qualifiers.contains(VCARD_TEL_ISDN))
                    type |= PhoneNumber::Isdn;
                if((*i).qualifiers.contains(VCARD_TEL_VIDEO))
                    type |= PhoneNumber::Video;
                if((*i).qualifiers.contains(VCARD_TEL_PCS))
                    type |= PhoneNumber::Pcs;
            }
            addressee.insertPhoneNumber(PhoneNumber((*i).parameters[0], type));
        }
    }

    // set the addressee's addresses
    for(QValueListIterator< VCardLineX > i = vCard->_vcdata->begin(); i != vCard->_vcdata->end(); ++i)
    {
        if((*i).name == VCARD_ADR)
        {
            int type = 0;
            if((*i).qualified)
            {
                if((*i).qualifiers.contains(VCARD_ADR_DOM))
                    type |= Address::Dom;
                if((*i).qualifiers.contains(VCARD_ADR_INTL))
                    type |= Address::Intl;
                if((*i).qualifiers.contains(VCARD_ADR_POSTAL))
                    type |= Address::Postal;
                if((*i).qualifiers.contains(VCARD_ADR_PARCEL))
                    type |= Address::Parcel;
                if((*i).qualifiers.contains(VCARD_ADR_HOME))
                    type |= Address::Home;
                if((*i).qualifiers.contains(VCARD_ADR_WORK))
                    type |= Address::Work;
                if((*i).qualifiers.contains(VCARD_ADR_PREF))
                    type |= Address::Pref;
            }
            addressee.insertAddress(readAddressFromQStringList((*i).parameters, type));
        }
    }

    // set the addressee's delivery label
    tmpStr = vCard->getValue(VCARD_LABEL);
    if(!tmpStr.isEmpty())
    {
        tmpStr.replace("\r\n", "\n");
        Address tmpAddress;
        tmpAddress.setLabel(tmpStr);
        addressee.insertAddress(tmpAddress);
    }

    // set the addressee's notes
    tmpStr = vCard->getValue(VCARD_NOTE);
    tmpStr.replace("\r\n", "\n");
    addressee.setNote(tmpStr);

    // set the addressee's timezone
    tmpStr = vCard->getValue(VCARD_TZ);
    TimeZone tmpZone(tmpStr.toInt());
    addressee.setTimeZone(tmpZone);

    // set the addressee's geographical position
    tmpList = vCard->getValues(VCARD_GEO);
    if(tmpList.count() == 2)
    {
        tmpStr = tmpList[0];
        float glat = tmpStr.toFloat();
        tmpStr = tmpList[1];
        float glong = tmpStr.toFloat();
        Geo tmpGeo(glat, glong);
        addressee.setGeo(tmpGeo);
    }

    // set the last revision date
    tmpStr = vCard->getValue(VCARD_REV);
    addressee.setRevision(VCardStringToDate(tmpStr));

    // set the role of the addressee
    tmpStr = vCard->getValue(VCARD_ROLE);
    addressee.setRole(tmpStr);

    delete vCard;

    return addressee;
}
예제 #11
0
KABC::AddresseeList GMXXXPort::importContacts( const QString& ) const
{
  KABC::AddresseeList addrList;

  QString fileName = KFileDialog::getOpenFileName( ":xxport_gmx", 
                      GMX_FILESELECTION_STRING, 0 );
  if ( fileName.isEmpty() )
    return addrList;

  QFile file( fileName );
  if ( !file.open( IO_ReadOnly ) ) {
    QString msg = i18n( "<qt>Unable to open <b>%1</b> for reading.</qt>" );
    KMessageBox::error( parentWidget(), msg.arg( fileName ) );
    return addrList;
  }

  QDateTime dt;
  QTextStream gmxStream( &file );
  gmxStream.setEncoding( QTextStream::Latin1 );
  QString line, line2;
  line  = gmxStream.readLine();
  line2 = gmxStream.readLine();
  if (!line.startsWith("AB_ADDRESSES:") || !line2.startsWith("Address_id")) {
	KMessageBox::error( parentWidget(), i18n("%1 is not a GMX address book file.").arg(fileName) );
	return addrList;
  }

  QStringList strList;
  typedef QMap<QString, KABC::Addressee *> AddressMap;
  AddressMap addrMap;

  // "Address_id,Nickname,Firstname,Lastname,Title,Birthday,Comments,Change_date,Status,Address_link_id,Categories"
  line = gmxStream.readLine();
  while (!line.startsWith("####") && !gmxStream.atEnd()) {
    while (1) {
       strList = QStringList::split('#', line, true);
       if (strList.count() >= 11) 
           break;
       line.append('\n');
       line.append(gmxStream.readLine());
    };

    KABC::Addressee *addr = new KABC::Addressee;
    addr->setNickName(strList[1]);
    addr->setGivenName(strList[2]);
    addr->setFamilyName(strList[3]);
    addr->setTitle(strList[4]);

    if (addr->formattedName().isEmpty())
	addr->setFormattedName(addr->realName());

    if (checkDateTime(strList[5],dt)) addr->setBirthday(dt);
    addr->setNote(strList[6]);
    if (checkDateTime(strList[7],dt)) addr->setRevision(dt);
    // addr->setStatus(strList[8]); Status
    // addr->xxx(strList[9]); Address_link_id 
    // addr->setCategory(strList[10]); Categories
    addrMap[strList[0]] = addr;

    line = gmxStream.readLine();
  }

  // now read the address records
  line  = gmxStream.readLine();
  if (!line.startsWith("AB_ADDRESS_RECORDS:")) {
	kdWarning() << "Could not find address records!\n";
	return addrList;
  }
  // Address_id,Record_id,Street,Country,Zipcode,City,Phone,Fax,Mobile,Mobile_type,Email,
  // Homepage,Position,Comments,Record_type_id,Record_type,Company,Department,Change_date,Preferred,Status
  line = gmxStream.readLine();
  line = gmxStream.readLine();

  while (!line.startsWith("####") && !gmxStream.atEnd()) {
    while (1) {
       strList = QStringList::split('#', line, true);
       if (strList.count() >= 21) 
           break;
       line.append('\n');
       line.append(gmxStream.readLine());
    };

    KABC::Addressee *addr = addrMap[strList[0]];
    if (addr) {
	for ( QStringList::Iterator it = strList.begin(); it != strList.end(); ++it )
		*it = (*it).simplifyWhiteSpace();
	// strList[1] = Record_id (numbered item, ignore here)
	int id = strList[14].toInt(); // Record_type_id (0=work,1=home,2=other)
	int type = (id==0) ? KABC::Address::Work : KABC::Address::Home;
	if (!strList[19].isEmpty() && strList[19].toInt()!=0)
		type |= KABC::Address::Pref; // Preferred address (seems to be bitfield for telephone Prefs)
        KABC::Address adr = addr->address(type);
	adr.setStreet(strList[2]);
	adr.setCountry(strList[3]);
	adr.setPostalCode(strList[4]);
	adr.setLocality(strList[5]);
	addr->insertPhoneNumber( KABC::PhoneNumber(strList[6], KABC::PhoneNumber::Home) );
	addr->insertPhoneNumber( KABC::PhoneNumber(strList[7], KABC::PhoneNumber::Fax) );
	int celltype = KABC::PhoneNumber::Cell;
	// strList[9]=Mobile_type // always 0 or -1(default phone).
	if (strList[9].toInt()) celltype |= KABC::PhoneNumber::Pref;
	addr->insertPhoneNumber( KABC::PhoneNumber(strList[8], celltype) );
	addr->insertEmail(strList[10]);
	if (!strList[11].isEmpty()) addr->setUrl(strList[11]);
	if (!strList[12].isEmpty()) addr->setRole(strList[12]);
	// strList[13]=Comments
	// strList[14]=Record_type_id (0,1,2) - see above
	// strList[15]=Record_type (name of this additional record entry)
	if (!strList[16].isEmpty()) addr->setOrganization(strList[16]); // Company
	if (!strList[17].isEmpty()) addr->insertCustom( 
			"KADDRESSBOOK", "X-Department", strList[17]); // Department
        if (checkDateTime(strList[18],dt)) addr->setRevision(dt); // Change_date
	// strList[19]=Preferred (see above)
	// strList[20]=Status (should always be "1")
	addr->insertAddress(adr);
    } else {
	kdWarning() << "unresolved line: " << line << endl;
    }

    line = gmxStream.readLine();
  }

  // now add the addresses to to addrList
  for ( AddressMap::Iterator it = addrMap.begin(); it != addrMap.end(); ++it ) {
     KABC::Addressee *addr = it.data();
     addrList.append(*addr);
     delete addr;
  }

  file.close();
  return addrList;
}
예제 #12
0
static void setEmail1(const QString &value, KABC::Addressee &addressee)
{
    addressee.insertEmail(value, true);
}
예제 #13
0
KABC::Addressee Contact::fromXml(const QString &xml)
{
    QDomDocument document;

    QString errorMsg;
    int errorLine, errorColumn;
    if(!document.setContent(xml, true, &errorMsg, &errorLine, &errorColumn))
    {
        qDebug("Error parsing XML in Scalix::Contact::fromXml: %s (%d,%d)", errorMsg.latin1(), errorLine, errorColumn);
        return KABC::Addressee();
    }

    QDomElement contactElement = document.documentElement();
    if(contactElement.tagName() != "contact")
    {
        if(contactElement.tagName() == "distlist")
        {
            const QDomNodeList names = contactElement.elementsByTagName("display_name");
            const QString listName = (names.count() == 1 ? names.item(0).toElement().text() : "Scalix Dummy List");

            /**
             * As we can't provide distribution list functionality we store the entry
             * here and return it on save.
             */
            KPIM::DistributionList list;
            list.setName(listName);

            if(!s_distListMap)
                sd.setObject(s_distListMap, new QMap<QString, QString>());

            s_distListMap->insert(list.uid(), xml);

            return list;
        }
        else
        {
            qDebug("Error interpreting XML in Scalix::Contact::fromXml: no 'contact' or 'distlist' tag found");
            return KABC::Addressee();
        }
    }

    QString emails[ 3 ];
    KABC::Address homeAddress(KABC::Address::Home);
    KABC::Address workAddress(KABC::Address::Work);
    KABC::Address otherAddress(KABC::Address::Dom);

    KABC::Addressee addr;
    setCustom("comes_from_scalix", "true", addr);

    QDomNode node = contactElement.firstChild();
    while(!node.isNull())
    {
        QDomElement element = node.toElement();
        if(!element.isNull())
        {
            if(element.tagName() == "direct_ref")
                addr.setUid(element.text());
            else if(element.tagName() == "sensitivity")
                setCustom("sensitivity", element.text(), addr);
            else if(element.tagName() == "is_recurring")
                setCustom("is_recurring", element.text(), addr);
            else if(element.tagName() == "reminder_set")
                setCustom("reminder_set", element.text(), addr);
            else if(element.tagName() == "send_rich_info")
                setCustom("send_rich_info", element.text(), addr);
            else if(element.tagName() == "last_modification_time")
                addr.setRevision(QDateTime::fromString(element.text(), Qt::ISODate));

            // name
            else if(element.tagName() == "display_name_prefix")
                addr.setPrefix(element.text());
            else if(element.tagName() == "first_name")
                addr.setGivenName(element.text());
            else if(element.tagName() == "middle_name")
                addr.setAdditionalName(element.text());
            else if(element.tagName() == "last_name")
                addr.setFamilyName(element.text());
            else if(element.tagName() == "suffix")
                addr.setSuffix(element.text());
            else if(element.tagName() == "file_as")
                addr.setFormattedName(element.text());
            else if(element.tagName() == "nickname")
                addr.setNickName(element.text());

            // job
            else if(element.tagName() == "web_page_address")
                addr.setUrl(element.text());
            else if(element.tagName() == "company_name")
                addr.setOrganization(element.text());
            else if(element.tagName() == "job_title")
                addr.setTitle(element.text());

            // emails
            else if(element.tagName().startsWith("email"))
            {
                if(element.tagName() == "email1_address")
                    emails[ 0 ] = element.text();
                else if(element.tagName() == "email2_address")
                    emails[ 1 ] = element.text();
                else if(element.tagName() == "email3_address")
                    emails[ 2 ] = element.text();
                else
                    setCustom(element.tagName(), element.text(), addr);
            }

            // phone numbers
            else if(element.tagName() == "home_phone_number")
                addr.insertPhoneNumber(KABC::PhoneNumber(element.text(), KABC::PhoneNumber::Home));
            else if(element.tagName() == "work_phone_number")
                addr.insertPhoneNumber(KABC::PhoneNumber(element.text(), KABC::PhoneNumber::Work));
            else if(element.tagName() == "work_fax_number")
                addr.insertPhoneNumber(KABC::PhoneNumber(element.text(), KABC::PhoneNumber::Work | KABC::PhoneNumber::Fax));
            else if(element.tagName() == "mobile_phone_number")
                addr.insertPhoneNumber(KABC::PhoneNumber(element.text(), KABC::PhoneNumber::Cell));

            // address (work)
            else if(element.tagName() == "work_address_street")
                workAddress.setStreet(element.text());
            else if(element.tagName() == "work_address_zip")
                workAddress.setPostalCode(element.text());
            else if(element.tagName() == "work_address_city")
                workAddress.setLocality(element.text());
            else if(element.tagName() == "work_address_state")
                workAddress.setRegion(element.text());
            else if(element.tagName() == "work_address_country")
                workAddress.setCountry(element.text());

            // address (home)
            else if(element.tagName() == "home_address_street")
                homeAddress.setStreet(element.text());
            else if(element.tagName() == "home_address_zip")
                homeAddress.setPostalCode(element.text());
            else if(element.tagName() == "home_address_city")
                homeAddress.setLocality(element.text());
            else if(element.tagName() == "home_address_state")
                homeAddress.setRegion(element.text());
            else if(element.tagName() == "home_address_country")
                homeAddress.setCountry(element.text());

            // address (other)
            else if(element.tagName() == "other_address_street")
                otherAddress.setStreet(element.text());
            else if(element.tagName() == "other_address_zip")
                otherAddress.setPostalCode(element.text());
            else if(element.tagName() == "other_address_city")
                otherAddress.setLocality(element.text());
            else if(element.tagName() == "other_address_state")
                otherAddress.setRegion(element.text());
            else if(element.tagName() == "other_address_country")
                otherAddress.setCountry(element.text());

            else if(element.tagName() == "selected_mailing_address")
                switch(element.text().toInt())
                {
                    case 1:
                        homeAddress.setType(homeAddress.type() | KABC::Address::Pref);
                        break;
                    case 2:
                        workAddress.setType(workAddress.type() | KABC::Address::Pref);
                        break;
                    case 3:
                        otherAddress.setType(otherAddress.type() | KABC::Address::Pref);
                        break;
                    default:
                        Q_ASSERT(!"Unknown selected_mailing_address enum");
                        break;
                }

            // misc
            else if(element.tagName() == "im_address")
                addr.insertCustom("KADDRESSBOOK", "X-IMAddress", element.text());
            else if(element.tagName() == "manager")
                addr.insertCustom("KADDRESSBOOK", "X-ManagersName", element.text());
            else if(element.tagName() == "department")
                addr.insertCustom("KADDRESSBOOK", "X-Department", element.text());
            else if(element.tagName() == "assistant")
                addr.insertCustom("KADDRESSBOOK", "X-AssistantsName", element.text());
            else if(element.tagName() == "profession")
                addr.insertCustom("KADDRESSBOOK", "X-Profession", element.text());
            else if(element.tagName() == "office_location")
                addr.insertCustom("KADDRESSBOOK", "X-Office", element.text());
            else if(element.tagName() == "spouse")
                addr.insertCustom("KADDRESSBOOK", "X-SpousesName", element.text());

            else if(element.tagName() == "bday")
                addr.setBirthday(QDateTime::fromString(element.text(), Qt::ISODate));
            else if(element.tagName() == "anniversary")
                addr.insertCustom("KADDRESSBOOK", "X-Anniversary", element.text());
            else
                setCustom(element.tagName(), element.text(), addr);
        }

        node = node.nextSibling();
    }

    for(int i = 0; i < 3; ++i)
        if(!emails[ i ].isEmpty())
            addr.insertEmail(emails[ i ]);

    if(!homeAddress.isEmpty())
        addr.insertAddress(homeAddress);
    if(!workAddress.isEmpty())
        addr.insertAddress(workAddress);
    if(!otherAddress.isEmpty())
        addr.insertAddress(otherAddress);

    return addr;
}
예제 #14
0
QString KTnef::msTNEFToVPart( const QByteArray &tnef )
{
  bool bOk = false;

  KTNEFParser parser;
  QByteArray b( tnef );
  QBuffer buf( &b );
  MemoryCalendar::Ptr cal( new MemoryCalendar( KDateTime::UTC ) );
  KABC::Addressee addressee;
  ICalFormat calFormat;
  Event::Ptr event( new Event() );

  if ( parser.openDevice( &buf ) ) {
    KTNEFMessage *tnefMsg = parser.message();
    //QMap<int,KTNEFProperty*> props = parser.message()->properties();

    // Everything depends from property PR_MESSAGE_CLASS
    // (this is added by KTNEFParser):
    QString msgClass = tnefMsg->findProp( 0x001A, QString(), true ).toUpper();
    if ( !msgClass.isEmpty() ) {
      // Match the old class names that might be used by Outlook for
      // compatibility with Microsoft Mail for Windows for Workgroups 3.1.
      bool bCompatClassAppointment = false;
      bool bCompatMethodRequest = false;
      bool bCompatMethodCancled = false;
      bool bCompatMethodAccepted = false;
      bool bCompatMethodAcceptedCond = false;
      bool bCompatMethodDeclined = false;
      if ( msgClass.startsWith( QLatin1String( "IPM.MICROSOFT SCHEDULE." ) ) ) {
        bCompatClassAppointment = true;
        if ( msgClass.endsWith( QLatin1String( ".MTGREQ" ) ) ) {
          bCompatMethodRequest = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGCNCL" ) ) ) {
          bCompatMethodCancled = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPP" ) ) ) {
          bCompatMethodAccepted = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPA" ) ) ) {
          bCompatMethodAcceptedCond = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPN" ) ) ) {
          bCompatMethodDeclined = true;
        }
      }
      bool bCompatClassNote = ( msgClass == "IPM.MICROSOFT MAIL.NOTE" );

      if ( bCompatClassAppointment || "IPM.APPOINTMENT" == msgClass ) {
        // Compose a vCal
        bool bIsReply = false;
        QString prodID = "-//Microsoft Corporation//Outlook ";
        prodID += tnefMsg->findNamedProp( "0x8554", "9.0" );
        prodID += "MIMEDIR/EN\n";
        prodID += "VERSION:2.0\n";
        calFormat.setApplication( "Outlook", prodID );

        iTIPMethod method;
        if ( bCompatMethodRequest ) {
          method = iTIPRequest;
        } else if ( bCompatMethodCancled ) {
          method = iTIPCancel;
        } else if ( bCompatMethodAccepted || bCompatMethodAcceptedCond ||
                 bCompatMethodDeclined ) {
          method = iTIPReply;
          bIsReply = true;
        } else {
          // pending(khz): verify whether "0x0c17" is the right tag ???
          //
          // at the moment we think there are REQUESTS and UPDATES
          //
          // but WHAT ABOUT REPLIES ???
          //
          //

          if ( tnefMsg->findProp(0x0c17) == "1" ) {
            bIsReply = true;
          }
          method = iTIPRequest;
        }

        /// ###  FIXME Need to get this attribute written
        ScheduleMessage schedMsg( event, method, ScheduleMessage::Unknown );

        QString sSenderSearchKeyEmail( tnefMsg->findProp( 0x0C1D ) );

        if ( !sSenderSearchKeyEmail.isEmpty() ) {
          int colon = sSenderSearchKeyEmail.indexOf( ':' );
          // May be e.g. "SMTP:[email protected]"
          if ( sSenderSearchKeyEmail.indexOf( ':' ) == -1 ) {
            sSenderSearchKeyEmail.remove( 0, colon+1 );
          }
        }

        QString s( tnefMsg->findProp( 0x8189 ) );
        const QStringList attendees = s.split( ';' );
        if ( attendees.count() ) {
          for ( QStringList::const_iterator it = attendees.begin();
               it != attendees.end(); ++it ) {
            // Skip all entries that have no '@' since these are
            // no mail addresses
            if ( (*it).indexOf( '@' ) == -1 ) {
              s = (*it).trimmed();

              Attendee::Ptr attendee( new Attendee( s, s, true ) );
              if ( bIsReply ) {
                if ( bCompatMethodAccepted ) {
                  attendee->setStatus( Attendee::Accepted );
                }
                if ( bCompatMethodDeclined ) {
                  attendee->setStatus( Attendee::Declined );
                }
                if ( bCompatMethodAcceptedCond ) {
                  attendee->setStatus( Attendee::Tentative );
                }
              } else {
                attendee->setStatus( Attendee::NeedsAction );
                attendee->setRole( Attendee::ReqParticipant );
              }
              event->addAttendee( attendee );
            }
          }
        } else {
          // Oops, no attendees?
          // This must be old style, let us use the PR_SENDER_SEARCH_KEY.
          s = sSenderSearchKeyEmail;
          if ( !s.isEmpty() ) {
            Attendee::Ptr attendee( new Attendee( QString(), QString(), true ) );
            if ( bIsReply ) {
              if ( bCompatMethodAccepted ) {
                attendee->setStatus( Attendee::Accepted );
              }
              if ( bCompatMethodAcceptedCond ) {
                attendee->setStatus( Attendee::Declined );
              }
              if ( bCompatMethodDeclined ) {
                attendee->setStatus( Attendee::Tentative );
              }
            } else {
              attendee->setStatus( Attendee::NeedsAction );
              attendee->setRole( Attendee::ReqParticipant );
            }
            event->addAttendee( attendee );
          }
        }
        s = tnefMsg->findProp( 0x3ff8 ); // look for organizer property
        if ( s.isEmpty() && !bIsReply ) {
          s = sSenderSearchKeyEmail;
        }
        // TODO: Use the common name?
        if ( !s.isEmpty() ) {
          event->setOrganizer( s );
        }

        s = tnefMsg->findProp( 0x819b ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        event->setDtStart( KDateTime::fromString( s ) ); // ## Format??

        s = tnefMsg->findProp( 0x819c ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        event->setDtEnd( KDateTime::fromString( s ) );

        s = tnefMsg->findProp( 0x810d );
        event->setLocation( s );
        // is it OK to set this to OPAQUE always ??
        //vPart += "TRANSP:OPAQUE\n"; ###FIXME, portme!
        //vPart += "SEQUENCE:0\n";

        // is "0x0023" OK  -  or should we look for "0x0003" ??
        s = tnefMsg->findProp( 0x0023 );
        event->setUid( s );

        // PENDING(khz): is this value in local timezone? Must it be
        // adjusted? Most likely this is a bug in the server or in
        // Outlook - we ignore it for now.
        s = tnefMsg->findProp( 0x8202 ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        // ### kcal always uses currentDateTime()
        // event->setDtStamp( QDateTime::fromString( s ) );

        s = tnefMsg->findNamedProp( "Keywords" );
        event->setCategories( s );

        s = tnefMsg->findProp( 0x1000 );
        event->setDescription( s );

        s = tnefMsg->findProp( 0x0070 );
        event->setSummary( s );

        s = tnefMsg->findProp( 0x0026 );
        event->setPriority( s.toInt() );
        // is reminder flag set ?
        if ( !tnefMsg->findProp( 0x8503 ).isEmpty() ) {
          Alarm::Ptr alarm( new Alarm( event.data() ) ); // TODO: fix when KCalCore::Alarm is fixed
          KDateTime highNoonTime =
            pureISOToLocalQDateTime( tnefMsg->findProp( 0x8502 ).
                                     remove( QChar( '-' ) ).remove( QChar( ':' ) ) );
          KDateTime wakeMeUpTime =
            pureISOToLocalQDateTime( tnefMsg->findProp( 0x8560, "" ).
                                     remove( QChar( '-' ) ).remove( QChar( ':' ) ) );
          alarm->setTime( wakeMeUpTime );

          if ( highNoonTime.isValid() && wakeMeUpTime.isValid() ) {
            alarm->setStartOffset( Duration( highNoonTime, wakeMeUpTime ) );
          } else {
            // default: wake them up 15 minutes before the appointment
            alarm->setStartOffset( Duration( 15 * 60 ) );
          }
          alarm->setDisplayAlarm( i18n( "Reminder" ) );

          // Sorry: the different action types are not known (yet)
          //        so we always set 'DISPLAY' (no sounds, no images...)
          event->addAlarm( alarm );
        }
        //ensure we have a uid for this event
        if ( event->uid().isEmpty() ) {
          event->setUid( CalFormat::createUniqueId() );
        }
        cal->addEvent( event );
        bOk = true;
        // we finished composing a vCal
      } else if ( bCompatClassNote || "IPM.CONTACT" == msgClass ) {
        addressee.setUid( stringProp( tnefMsg, attMSGID ) );
        addressee.setFormattedName( stringProp( tnefMsg, MAPI_TAG_PR_DISPLAY_NAME ) );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL1EMAILADDRESS ), true );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL2EMAILADDRESS ), false );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL3EMAILADDRESS ), false );
        addressee.insertCustom( "KADDRESSBOOK", "X-IMAddress",
                                sNamedProp( tnefMsg, MAPI_TAG_CONTACT_IMADDRESS ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-SpousesName",
                                stringProp( tnefMsg, MAPI_TAG_PR_SPOUSE_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-ManagersName",
                                stringProp( tnefMsg, MAPI_TAG_PR_MANAGER_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-AssistantsName",
                                stringProp( tnefMsg, MAPI_TAG_PR_ASSISTANT ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Department",
                                stringProp( tnefMsg, MAPI_TAG_PR_DEPARTMENT_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Office",
                                stringProp( tnefMsg, MAPI_TAG_PR_OFFICE_LOCATION ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Profession",
                                stringProp( tnefMsg, MAPI_TAG_PR_PROFESSION ) );

        QString s = tnefMsg->findProp( MAPI_TAG_PR_WEDDING_ANNIVERSARY ).
                    remove( QChar( '-' ) ).remove( QChar( ':' ) );
        if ( !s.isEmpty() ) {
          addressee.insertCustom( "KADDRESSBOOK", "X-Anniversary", s );
        }

        addressee.setUrl( KUrl( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_WEBPAGE ) ) );

        // collect parts of Name entry
        addressee.setFamilyName( stringProp( tnefMsg, MAPI_TAG_PR_SURNAME ) );
        addressee.setGivenName( stringProp( tnefMsg, MAPI_TAG_PR_GIVEN_NAME ) );
        addressee.setAdditionalName( stringProp( tnefMsg, MAPI_TAG_PR_MIDDLE_NAME ) );
        addressee.setPrefix( stringProp( tnefMsg, MAPI_TAG_PR_DISPLAY_NAME_PREFIX ) );
        addressee.setSuffix( stringProp( tnefMsg, MAPI_TAG_PR_GENERATION ) );

        addressee.setNickName( stringProp( tnefMsg, MAPI_TAG_PR_NICKNAME ) );
        addressee.setRole( stringProp( tnefMsg, MAPI_TAG_PR_TITLE ) );
        addressee.setOrganization( stringProp( tnefMsg, MAPI_TAG_PR_COMPANY_NAME ) );
        /*
        the MAPI property ID of this (multiline) )field is unknown:
        vPart += stringProp(tnefMsg, "\n","NOTE", ... , "" );
        */

        KABC::Address adr;
        adr.setPostOfficeBox( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_PO_BOX ) );
        adr.setStreet( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_STREET ) );
        adr.setLocality( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_CITY ) );
        adr.setRegion( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_STATE_OR_PROVINCE ) );
        adr.setPostalCode( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_POSTAL_CODE ) );
        adr.setCountry( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_COUNTRY ) );
        adr.setType( KABC::Address::Home );
        addressee.insertAddress( adr );

        adr.setPostOfficeBox( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSPOBOX ) );
        adr.setStreet( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSSTREET ) );
        adr.setLocality( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSCITY ) );
        adr.setRegion( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSSTATE ) );
        adr.setPostalCode( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSPOSTALCODE ) );
        adr.setCountry( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSCOUNTRY ) );
        adr.setType( KABC::Address::Work );
        addressee.insertAddress( adr );

        adr.setPostOfficeBox( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_PO_BOX ) );
        adr.setStreet( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_STREET ) );
        adr.setLocality( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_CITY ) );
        adr.setRegion( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_STATE_OR_PROVINCE ) );
        adr.setPostalCode( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_POSTAL_CODE ) );
        adr.setCountry( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_COUNTRY ) );
        adr.setType( KABC::Address::Dom );
        addressee.insertAddress( adr );

        // problem: the 'other' address was stored by KOrganizer in
        //          a line looking like the following one:
        // vPart += "\nADR;TYPE=dom;TYPE=intl;TYPE=parcel;TYPE=postal;TYPE=work;"
        //          "TYPE=home:other_pobox;;other_str1\nother_str2;other_loc;other_region;"
        //          "other_pocode;other_country"

        QString nr;
        nr = stringProp( tnefMsg, MAPI_TAG_PR_HOME_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Home ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_BUSINESS_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Work ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_MOBILE_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Cell ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_HOME_FAX_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Fax | KABC::PhoneNumber::Home ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_BUSINESS_FAX_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Fax | KABC::PhoneNumber::Work ) );

        s = tnefMsg->findProp( MAPI_TAG_PR_BIRTHDAY ).
            remove( QChar( '-' ) ).remove( QChar( ':' ) );
        if ( !s.isEmpty() ) {
          addressee.setBirthday( QDateTime::fromString( s ) );
        }

        bOk = ( !addressee.isEmpty() );
      } else if ( "IPM.NOTE" == msgClass ) {

      } // else if ... and so on ...
    }
  }

  // Compose return string
  // KDAB_TODO: Interesting, without the explicit QString the toString call is
  //            reported to be ambigious with toString( const Incidence::Ptr & ).
  const QString iCal = calFormat.toString( cal, QString() );
  if ( !iCal.isEmpty() ) {
    // This was an iCal
    return iCal;
  }

  // Not an iCal - try a vCard
  KABC::VCardConverter converter;
  return QString::fromUtf8( converter.createVCard( addressee ) );
}
예제 #15
0
KABC::AddresseeList OperaXXPort::importContacts(const QString &) const
{
    KABC::AddresseeList addrList;

    QString fileName = KFileDialog::getOpenFileName(QDir::homeDirPath() + QString::fromLatin1("/.opera/contacts.adr"));
    if(fileName.isEmpty())
        return addrList;

    QFile file(fileName);
    if(!file.open(IO_ReadOnly))
    {
        QString msg = i18n("<qt>Unable to open <b>%1</b> for reading.</qt>");
        KMessageBox::error(parentWidget(), msg.arg(fileName));
        return addrList;
    }

    QTextStream stream(&file);
    stream.setEncoding(QTextStream::UnicodeUTF8);
    QString line, key, value;
    bool parseContact = false;
    KABC::Addressee addr;

    QRegExp separator("\x02\x02");

    while(!stream.atEnd())
    {
        line = stream.readLine();
        line = line.stripWhiteSpace();
        if(line == QString::fromLatin1("#CONTACT"))
        {
            parseContact = true;
            addr = KABC::Addressee();
            continue;
        }
        else if(line.isEmpty())
        {
            parseContact = false;
            if(!addr.isEmpty())
            {
                addrList.append(addr);
                addr = KABC::Addressee();
            }
            continue;
        }

        if(parseContact == true)
        {
            int sep = line.find('=');
            key = line.left(sep).lower();
            value = line.mid(sep + 1);
            if(key == QString::fromLatin1("name"))
                addr.setNameFromString(value);
            else if(key == QString::fromLatin1("mail"))
            {
                QStringList emails = QStringList::split(separator, value);

                QStringList::Iterator it = emails.begin();
                bool preferred = true;
                for(; it != emails.end(); ++it)
                {
                    addr.insertEmail(*it, preferred);
                    preferred = false;
                }
            }
            else if(key == QString::fromLatin1("phone"))
                addr.insertPhoneNumber(KABC::PhoneNumber(value));
            else if(key == QString::fromLatin1("fax"))
                addr.insertPhoneNumber(KABC::PhoneNumber(value,
                                       KABC::PhoneNumber::Fax | KABC::PhoneNumber::Home));
            else if(key == QString::fromLatin1("postaladdress"))
            {
                KABC::Address address(KABC::Address::Home);
                address.setLabel(value.replace(separator, "\n"));
                addr.insertAddress(address);
            }
            else if(key == QString::fromLatin1("description"))
                addr.setNote(value.replace(separator, "\n"));
            else if(key == QString::fromLatin1("url"))
                addr.setUrl(KURL(value));
            else if(key == QString::fromLatin1("pictureurl"))
            {
                KABC::Picture pic(value);
                addr.setPhoto(pic);
            }
        }
    }

    file.close();

    return addrList;
}
예제 #16
0
void readKMailEntry(const QString &kmailEntry, KABC::AddressBook *ab)
{
    kdDebug() << "KMAILENTRY: " << kmailEntry << endl;

    QString entry = kmailEntry.simplifyWhiteSpace();
    if(entry.isEmpty())
        return;

    QString email;
    QString name;
    QString comment;

    if(entry.at(entry.length() - 1) == ')')
    {
        int br = entry.findRev('(');
        if(br >= 0)
        {
            comment = entry.mid(br + 1, entry.length() - br - 2);
            entry.truncate(br);
            if(entry.at(entry.length() - 1).isSpace())
            {
                entry.truncate(br - 1);
            }
        }
    }

    int posSpace = entry.findRev(' ');
    if(posSpace < 0)
    {
        email = entry;
        if(!comment.isEmpty())
        {
            name = comment;
            comment = "";
        }
    }
    else
    {
        email = entry.mid(posSpace + 1);
        name = entry.left(posSpace);
    }

    if(email.at(0) == '<' && email.at(email.length() - 1) == '>')
    {
        email = email.mid(1, email.length() - 2);
    }
    if(name.at(0) == '"' && name.at(name.length() - 1) == '"')
    {
        name = name.mid(1, name.length() - 2);
    }
    if(name.at(0) == '\'' && name.at(name.length() - 1) == '\'')
    {
        name = name.mid(1, name.length() - 2);
    }

    if(name.at(name.length() - 1) == ')')
    {
        int br = name.findRev('(');
        if(br >= 0)
        {
            comment = name.mid(br + 1, name.length() - br - 2) + " " + comment;
            name.truncate(br);
            if(name.at(name.length() - 1).isSpace())
            {
                name.truncate(br - 1);
            }
        }
    }

    kdDebug() << "  EMAIL   : " << email << endl;
    kdDebug() << "  NAME    : " << name << endl;
    kdDebug() << "  COMMENT : " << comment << endl;

    KABC::Addressee::List al = ab->findByEmail(email);
    if(al.isEmpty())
    {
        KABC::Addressee a;
        a.setNameFromString(name);
        a.insertEmail(email);
        a.setNote(comment);

        ab->insertAddressee(a);

        kdDebug() << "--INSERTED: " << a.realName() << endl;
    }
}
예제 #17
0
void CSVTemplate::setFieldText(int column, KABC::Addressee& addressee, const QString& text) const
{
    if (column < 0 || text.isEmpty()) return;
    if (m_columnToField.isEmpty()) return;

    QMap<int, int>::const_iterator it = m_columnToField.find(column);
    if (it == m_columnToField.end()) return;

    Address address;
    PhoneNumber phone;

    switch (it.value())
    {
        case  0: // "Formatted Name"
            addressee.setFormattedName(text);
            break;
        case  1: // "Family Name"
            addressee.setFamilyName(text);
            break;
        case  2: // "Given Name"
            addressee.setGivenName(text);
            break;
        case  3: // "Additional Names"
            addressee.setAdditionalName(text);
            break;
        case  4: // "Honorific Prefixes"
            addressee.setPrefix(text);
            break;
        case  5: // "Honorific Suffixes"
            addressee.setSuffix(text);
            break;
        case  6: // "Nick Name"
            addressee.setNickName(text);
            break;
        case  7: // "Birthday"
            addressee.setBirthday(parseDate(text));
            break;
        case  8: // "Home Address Street"
            address = addressee.address(Address::Home);
            address.setStreet(text);
            addressee.insertAddress(address);
            break;
        case  9: // "Home Address Locality"
            address = addressee.address(Address::Home);
            address.setLocality(text);
            addressee.insertAddress(address);
            break;
        case 10: // "Home Address Region"
            address = addressee.address(Address::Home);
            address.setRegion(text);
            addressee.insertAddress(address);
            break;
        case 11: // "Home Address Postal Code"
            address = addressee.address(Address::Home);
            address.setPostalCode(text);
            addressee.insertAddress(address);
            break;
        case 12: // "Home Address Country"
            address = addressee.address(Address::Home);
            address.setCountry(text);
            addressee.insertAddress(address);
            break;
        case 13: // "Home Address Label"
            address = addressee.address(Address::Home);
            address.setLabel(text);
            addressee.insertAddress(address);
            break;
        case 14: // "Business Address Street"
            address = addressee.address(Address::Work);
            address.setStreet(text);
            addressee.insertAddress(address);
            break;
        case 15: // "Business Address Locality"
            address = addressee.address(Address::Work);
            address.setLocality(text);
            addressee.insertAddress(address);
            break;
        case 16: // "Business Address Region"
            address = addressee.address(Address::Work);
            address.setRegion(text);
            addressee.insertAddress(address);
            break;
        case 17: // "Business Address Postal Code"
            address = addressee.address(Address::Work);
            address.setPostalCode(text);
            addressee.insertAddress(address);
            break;
        case 18: // "Business Address Country"
            address = addressee.address(Address::Work);
            address.setCountry(text);
            addressee.insertAddress(address);
            break;
        case 19: // "Business Address Label"
            address = addressee.address(Address::Work);
            address.setLabel(text);
            addressee.insertAddress(address);
            break;
        case 20: // "Home Phone"
            phone = PhoneNumber(text, PhoneNumber::Home);
            addressee.insertPhoneNumber(phone);
            break;
        case 21: // "Business Phone"
            phone = PhoneNumber(text, PhoneNumber::Work);
            addressee.insertPhoneNumber(phone);
            break;
        case 22: // "Mobile Phone"
            phone = PhoneNumber(text, PhoneNumber::Cell);
            addressee.insertPhoneNumber(phone);
            break;
        case 23: // "Home Fax"
            phone = PhoneNumber(text, PhoneNumber::Fax | PhoneNumber::Home);
            addressee.insertPhoneNumber(phone);
            break;
        case 24: // "Business Fax"
            phone = PhoneNumber(text, PhoneNumber::Fax | PhoneNumber::Work);
            addressee.insertPhoneNumber(phone);
            break;
        case 25: // "Car Phone"
            phone = PhoneNumber(text, PhoneNumber::Car);
            addressee.insertPhoneNumber(phone);
            break;
        case 26: // "Isdn"
            phone = PhoneNumber(text, PhoneNumber::Isdn);
            addressee.insertPhoneNumber(phone);
            break;
        case 27: // "Pager"
            phone = PhoneNumber(text, PhoneNumber::Pager);
            addressee.insertPhoneNumber(phone);
            break;
        case 28: // "Email Address"
            addressee.insertEmail(text);
            break;
        case 29: // "Mail Client"
            addressee.setMailer(text);
            break;
        case 30: // "Title"
            addressee.setTitle(text);
            break;
        case 31: // "Role"
            addressee.setRole(text);
            break;
        case 32: // "Organization"
            addressee.setOrganization(text);
            break;
        case 33: // "Note"
            addressee.setNote(text);
            break;
        case 34: // "URL"
            addressee.setUrl(text);
            break;
        case 35: // "Department"
            break;
        case 36: // "Profession"
            break;
        case 37: // "Assistant's Name"
            break;
        case 38: // "Manager's Name"
            break;
        case 39: // "Spouse's Name"
            break;
        case 40: // "Office"
            break;
        case 41: // "IM Address"
            break;
        case 42: // "Anniversary"
            break;

        default:
            break;
    }
}
static KABC::Addressee convertLdapAttributesToAddressee( const KLDAP::LdapAttrMap &attrs )
{
  KABC::Addressee addr;

  // name
  if ( !attrs.value( "cn" ).isEmpty() ) {
    addr.setNameFromString( asUtf8( attrs["cn"].first() ) );
  }

  // email
  KLDAP::LdapAttrValue lst = attrs["mail"];
  KLDAP::LdapAttrValue::ConstIterator it = lst.constBegin();
  bool pref = true;
  while ( it != lst.constEnd() ) {
    addr.insertEmail( asUtf8( *it ), pref );
    pref = false;
    ++it;
  }

  if ( !attrs.value( "o" ).isEmpty() ) {
    addr.setOrganization( asUtf8( attrs[ "o" ].first() ) );
  }
  if ( addr.organization().isEmpty() && !attrs.value( "Company" ).isEmpty() ) {
    addr.setOrganization( asUtf8( attrs[ "Company" ].first() ) );
  }

  // Address
  KABC::Address workAddr( KABC::Address::Work );

  if ( !attrs.value( "department" ).isEmpty() ) {
    addr.setDepartment( asUtf8( attrs[ "department" ].first() ) );
  }

  if ( !workAddr.isEmpty() ) {
    addr.insertAddress( workAddr );
  }

  // phone
  if ( !attrs.value( "homePhone" ).isEmpty() ) {
    KABC::PhoneNumber homeNr = asUtf8( attrs[  "homePhone" ].first() );
    homeNr.setType( KABC::PhoneNumber::Home );
    addr.insertPhoneNumber( homeNr );
  }

  if ( !attrs.value( "telephoneNumber" ).isEmpty() ) {
    KABC::PhoneNumber workNr = asUtf8( attrs[  "telephoneNumber" ].first() );
    workNr.setType( KABC::PhoneNumber::Work );
    addr.insertPhoneNumber( workNr );
  }

  if ( !attrs.value( "facsimileTelephoneNumber" ).isEmpty() ) {
    KABC::PhoneNumber faxNr = asUtf8( attrs[  "facsimileTelephoneNumber" ].first() );
    faxNr.setType( KABC::PhoneNumber::Fax );
    addr.insertPhoneNumber( faxNr );
  }

  if ( !attrs.value( "mobile" ).isEmpty() ) {
    KABC::PhoneNumber cellNr = asUtf8( attrs[  "mobile" ].first() );
    cellNr.setType( KABC::PhoneNumber::Cell );
    addr.insertPhoneNumber( cellNr );
  }

  if ( !attrs.value( "pager" ).isEmpty() ) {
    KABC::PhoneNumber pagerNr = asUtf8( attrs[  "pager" ].first() );
    pagerNr.setType( KABC::PhoneNumber::Pager );
    addr.insertPhoneNumber( pagerNr );
  }

  return addr;
}