libkcal

icalformatimpl.cpp

00001 /*
00002     This file is part of libkcal.
00003 
00004     Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
00005     Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
00006 
00007     This library is free software; you can redistribute it and/or
00008     modify it under the terms of the GNU Library General Public
00009     License as published by the Free Software Foundation; either
00010     version 2 of the License, or (at your option) any later version.
00011 
00012     This library is distributed in the hope that it will be useful,
00013     but WITHOUT ANY WARRANTY; without even the implied warranty of
00014     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015     Library General Public License for more details.
00016 
00017     You should have received a copy of the GNU Library General Public License
00018     along with this library; see the file COPYING.LIB.  If not, write to
00019     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00020     Boston, MA 02110-1301, USA.
00021 */
00022 
00023 #include <qdatetime.h>
00024 #include <qstring.h>
00025 #include <qptrlist.h>
00026 #include <qfile.h>
00027 #include <cstdlib>
00028 
00029 #include <kdebug.h>
00030 #include <klocale.h>
00031 #include <kmdcodec.h>
00032 
00033 extern "C" {
00034   #include <ical.h>
00035   #include <icalparser.h>
00036   #include <icalrestriction.h>
00037 }
00038 
00039 #include "calendar.h"
00040 #include "journal.h"
00041 #include "icalformat.h"
00042 #include "icalformatimpl.h"
00043 #include "compat.h"
00044 
00045 #define _ICAL_VERSION "2.0"
00046 
00047 using namespace KCal;
00048 
00049 /* Static helpers */
00050 static QDateTime ICalDate2QDate(const icaltimetype& t)
00051 {
00052   // Outlook sends dates starting from 1601-01-01, but QDate()
00053   // can only handle dates starting 1752-09-14.
00054   const int year = (t.year>=1754) ? t.year : 1754;
00055   return QDateTime(QDate(year,t.month,t.day), QTime(t.hour,t.minute,t.second));
00056 }
00057 
00058 static void _dumpIcaltime( const icaltimetype& t)
00059 {
00060   kdDebug(5800) << "--- Y: " << t.year << " M: " << t.month << " D: " << t.day
00061       << endl;
00062   kdDebug(5800) << "--- H: " << t.hour << " M: " << t.minute << " S: " << t.second
00063       << endl;
00064   kdDebug(5800) << "--- isUtc: " << icaltime_is_utc( t )<< endl;
00065   kdDebug(5800) << "--- zoneId: " << icaltimezone_get_tzid( const_cast<icaltimezone*>( t.zone ) )<< endl;
00066 }
00067 
00068 static QString quoteForParam( const QString &text )
00069 {
00070   QString tmp = text;
00071   tmp.remove( '"' );
00072   if ( tmp.contains( ';' ) || tmp.contains( ':' ) || tmp.contains( ',' ) )
00073     return tmp; // libical quotes in this case already, see icalparameter_as_ical_string()
00074   return QString::fromLatin1( "\"" ) + tmp + QString::fromLatin1( "\"" );
00075 }
00076 
00077 const int gSecondsPerMinute = 60;
00078 const int gSecondsPerHour   = gSecondsPerMinute * 60;
00079 const int gSecondsPerDay    = gSecondsPerHour   * 24;
00080 const int gSecondsPerWeek   = gSecondsPerDay    * 7;
00081 
00082 ICalFormatImpl::ICalFormatImpl( ICalFormat *parent ) :
00083   mParent( parent ), mCompat( new Compat )
00084 {
00085 }
00086 
00087 ICalFormatImpl::~ICalFormatImpl()
00088 {
00089   delete mCompat;
00090 }
00091 
00092 class ICalFormatImpl::ToComponentVisitor : public IncidenceBase::Visitor
00093 {
00094   public:
00095     ToComponentVisitor( ICalFormatImpl *impl, Scheduler::Method m ) : mImpl( impl ), mComponent( 0 ), mMethod( m ) {}
00096 
00097     bool visit( Event *e ) { mComponent = mImpl->writeEvent( e ); return true; }
00098     bool visit( Todo *e ) { mComponent = mImpl->writeTodo( e ); return true; }
00099     bool visit( Journal *e ) { mComponent = mImpl->writeJournal( e ); return true; }
00100     bool visit( FreeBusy *fb ) { mComponent = mImpl->writeFreeBusy( fb, mMethod ); return true; }
00101 
00102     icalcomponent *component() { return mComponent; }
00103 
00104   private:
00105     ICalFormatImpl *mImpl;
00106     icalcomponent *mComponent;
00107     Scheduler::Method mMethod;
00108 };
00109 
00110 icalcomponent *ICalFormatImpl::writeIncidence( IncidenceBase *incidence, Scheduler::Method method )
00111 {
00112   ToComponentVisitor v( this, method );
00113   if ( incidence->accept(v) )
00114     return v.component();
00115   else return 0;
00116 }
00117 
00118 icalcomponent *ICalFormatImpl::writeTodo(Todo *todo)
00119 {
00120   QString tmpStr;
00121   QStringList tmpStrList;
00122 
00123   icalcomponent *vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT);
00124 
00125   writeIncidence(vtodo,todo);
00126 
00127   // due date
00128   if (todo->hasDueDate()) {
00129     icaltimetype due;
00130     if (todo->doesFloat()) {
00131       due = writeICalDate(todo->dtDue(true).date());
00132     } else {
00133       due = writeICalDateTime(todo->dtDue(true));
00134     }
00135     icalcomponent_add_property(vtodo,icalproperty_new_due(due));
00136   }
00137 
00138   // start time
00139   if ( todo->hasStartDate() || todo->doesRecur() ) {
00140     icaltimetype start;
00141     if (todo->doesFloat()) {
00142 //      kdDebug(5800) << " Incidence " << todo->summary() << " floats." << endl;
00143       start = writeICalDate(todo->dtStart(true).date());
00144     } else {
00145 //      kdDebug(5800) << " incidence " << todo->summary() << " has time." << endl;
00146       start = writeICalDateTime(todo->dtStart(true));
00147     }
00148     icalcomponent_add_property(vtodo,icalproperty_new_dtstart(start));
00149   }
00150 
00151   // completion date
00152   if (todo->isCompleted()) {
00153     if (!todo->hasCompletedDate()) {
00154       // If todo was created by KOrganizer <2.2 it has no correct completion
00155       // date. Set it to now.
00156       todo->setCompleted(QDateTime::currentDateTime());
00157     }
00158     icaltimetype completed = writeICalDateTime(todo->completed());
00159     icalcomponent_add_property(vtodo,icalproperty_new_completed(completed));
00160   }
00161 
00162   icalcomponent_add_property(vtodo,
00163       icalproperty_new_percentcomplete(todo->percentComplete()));
00164 
00165   if( todo->doesRecur() ) {
00166     icalcomponent_add_property(vtodo,
00167         icalproperty_new_recurrenceid( writeICalDateTime( todo->dtDue())));
00168   }
00169 
00170   return vtodo;
00171 }
00172 
00173 icalcomponent *ICalFormatImpl::writeEvent(Event *event)
00174 {
00175 #if 0
00176   kdDebug(5800) << "Write Event '" << event->summary() << "' (" << event->uid()
00177                 << ")" << endl;
00178 #endif
00179 
00180   QString tmpStr;
00181   QStringList tmpStrList;
00182 
00183   icalcomponent *vevent = icalcomponent_new(ICAL_VEVENT_COMPONENT);
00184 
00185   writeIncidence(vevent,event);
00186 
00187   // start time
00188   icaltimetype start;
00189   if (event->doesFloat()) {
00190 //    kdDebug(5800) << " Incidence " << event->summary() << " floats." << endl;
00191     start = writeICalDate(event->dtStart().date());
00192   } else {
00193 //    kdDebug(5800) << " incidence " << event->summary() << " has time." << endl;
00194     start = writeICalDateTime(event->dtStart());
00195   }
00196   icalcomponent_add_property(vevent,icalproperty_new_dtstart(start));
00197 
00198   if (event->hasEndDate()) {
00199     // End time.
00200     // RFC2445 says that if DTEND is present, it has to be greater than DTSTART.
00201     icaltimetype end;
00202     if (event->doesFloat()) {
00203 //      kdDebug(5800) << " Event " << event->summary() << " floats." << endl;
00204       // +1 day because end date is non-inclusive.
00205       end = writeICalDate( event->dtEnd().date().addDays( 1 ) );
00206       icalcomponent_add_property(vevent,icalproperty_new_dtend(end));
00207     } else {
00208 //      kdDebug(5800) << " Event " << event->summary() << " has time." << endl;
00209       if (event->dtEnd() != event->dtStart()) {
00210         end = writeICalDateTime(event->dtEnd());
00211         icalcomponent_add_property(vevent,icalproperty_new_dtend(end));
00212       }
00213     }
00214   }
00215 
00216 // TODO: resources
00217 #if 0
00218   // resources
00219   tmpStrList = anEvent->resources();
00220   tmpStr = tmpStrList.join(";");
00221   if (!tmpStr.isEmpty())
00222     addPropValue(vevent, VCResourcesProp, tmpStr.utf8());
00223 
00224 #endif
00225 
00226   // Transparency
00227   switch( event->transparency() ) {
00228   case Event::Transparent:
00229     icalcomponent_add_property(
00230       vevent,
00231       icalproperty_new_transp( ICAL_TRANSP_TRANSPARENT ) );
00232     break;
00233   case Event::Opaque:
00234     icalcomponent_add_property(
00235       vevent,
00236       icalproperty_new_transp( ICAL_TRANSP_OPAQUE ) );
00237     break;
00238   }
00239 
00240   return vevent;
00241 }
00242 
00243 icalcomponent *ICalFormatImpl::writeFreeBusy(FreeBusy *freebusy,
00244                                              Scheduler::Method method)
00245 {
00246 #if QT_VERSION >= 300
00247   kdDebug(5800) << "icalformatimpl: writeFreeBusy: startDate: "
00248     << freebusy->dtStart().toString("ddd MMMM d yyyy: h:m:s ap") << " End Date: "
00249     << freebusy->dtEnd().toString("ddd MMMM d yyyy: h:m:s ap") << endl;
00250 #endif
00251 
00252   icalcomponent *vfreebusy = icalcomponent_new(ICAL_VFREEBUSY_COMPONENT);
00253 
00254   writeIncidenceBase(vfreebusy,freebusy);
00255 
00256   icalcomponent_add_property(vfreebusy, icalproperty_new_dtstart(
00257       writeICalDateTime(freebusy->dtStart())));
00258 
00259   icalcomponent_add_property(vfreebusy, icalproperty_new_dtend(
00260       writeICalDateTime(freebusy->dtEnd())));
00261 
00262   if (method == Scheduler::Request) {
00263     icalcomponent_add_property(vfreebusy,icalproperty_new_uid(
00264        freebusy->uid().utf8()));
00265   }
00266 
00267   //Loops through all the periods in the freebusy object
00268   QValueList<Period> list = freebusy->busyPeriods();
00269   QValueList<Period>::Iterator it;
00270   icalperiodtype period = icalperiodtype_null_period();
00271   for (it = list.begin(); it!= list.end(); ++it) {
00272     period.start = writeICalDateTime((*it).start());
00273     if ( (*it).hasDuration() ) {
00274       period.duration = writeICalDuration( (*it).duration().asSeconds() );
00275     } else {
00276       period.end = writeICalDateTime((*it).end());
00277     }
00278     icalcomponent_add_property(vfreebusy, icalproperty_new_freebusy(period) );
00279   }
00280 
00281   return vfreebusy;
00282 }
00283 
00284 icalcomponent *ICalFormatImpl::writeJournal(Journal *journal)
00285 {
00286   icalcomponent *vjournal = icalcomponent_new(ICAL_VJOURNAL_COMPONENT);
00287 
00288   writeIncidence(vjournal,journal);
00289 
00290   // start time
00291   if (journal->dtStart().isValid()) {
00292     icaltimetype start;
00293     if (journal->doesFloat()) {
00294 //      kdDebug(5800) << " Incidence " << event->summary() << " floats." << endl;
00295       start = writeICalDate(journal->dtStart().date());
00296     } else {
00297 //      kdDebug(5800) << " incidence " << event->summary() << " has time." << endl;
00298       start = writeICalDateTime(journal->dtStart());
00299     }
00300     icalcomponent_add_property(vjournal,icalproperty_new_dtstart(start));
00301   }
00302 
00303   return vjournal;
00304 }
00305 
00306 void ICalFormatImpl::writeIncidence(icalcomponent *parent,Incidence *incidence)
00307 {
00308   // pilot sync stuff
00309 // TODO: move this application-specific code to kpilot
00310   if (incidence->pilotId()) {
00311     // NOTE: we can't do setNonKDECustomProperty here because this changes
00312     // data and triggers an updated() event...
00313     // incidence->setNonKDECustomProperty("X-PILOTSTAT", QString::number(incidence->syncStatus()));
00314     // incidence->setNonKDECustomProperty("X-PILOTID", QString::number(incidence->pilotId()));
00315 
00316     icalproperty *p = 0;
00317     p = icalproperty_new_x(QString::number(incidence->syncStatus()).utf8());
00318     icalproperty_set_x_name(p,"X-PILOTSTAT");
00319     icalcomponent_add_property(parent,p);
00320 
00321     p = icalproperty_new_x(QString::number(incidence->pilotId()).utf8());
00322     icalproperty_set_x_name(p,"X-PILOTID");
00323     icalcomponent_add_property(parent,p);
00324   }
00325 
00326   if ( incidence->schedulingID() != incidence->uid() )
00327     // We need to store the UID in here. The rawSchedulingID will
00328     // go into the iCal UID component
00329     incidence->setCustomProperty( "LIBKCAL", "ID", incidence->uid() );
00330   else
00331     incidence->removeCustomProperty( "LIBKCAL", "ID" );
00332 
00333   writeIncidenceBase(parent,incidence);
00334 
00335   // creation date
00336   icalcomponent_add_property(parent,icalproperty_new_created(
00337       writeICalDateTime(incidence->created())));
00338 
00339   // unique id
00340   // If the scheduling ID is different from the real UID, the real
00341   // one is stored on X-REALID above
00342   if ( !incidence->schedulingID().isEmpty() ) {
00343     icalcomponent_add_property(parent,icalproperty_new_uid(
00344         incidence->schedulingID().utf8()));
00345   }
00346 
00347   // revision
00348   if ( incidence->revision() > 0 ) { // 0 is default, so don't write that out
00349     icalcomponent_add_property(parent,icalproperty_new_sequence(
00350         incidence->revision()));
00351   }
00352 
00353   // last modification date
00354   if ( incidence->lastModified().isValid() ) {
00355    icalcomponent_add_property(parent,icalproperty_new_lastmodified(
00356        writeICalDateTime(incidence->lastModified())));
00357   }
00358 
00359   // description
00360   if (!incidence->description().isEmpty()) {
00361     icalcomponent_add_property(parent,icalproperty_new_description(
00362         incidence->description().utf8()));
00363   }
00364 
00365   // summary
00366   if (!incidence->summary().isEmpty()) {
00367     icalcomponent_add_property(parent,icalproperty_new_summary(
00368         incidence->summary().utf8()));
00369   }
00370 
00371   // location
00372   if (!incidence->location().isEmpty()) {
00373     icalcomponent_add_property(parent,icalproperty_new_location(
00374         incidence->location().utf8()));
00375   }
00376 
00377   // status
00378   icalproperty_status status = ICAL_STATUS_NONE;
00379   switch (incidence->status()) {
00380     case Incidence::StatusTentative:    status = ICAL_STATUS_TENTATIVE;  break;
00381     case Incidence::StatusConfirmed:    status = ICAL_STATUS_CONFIRMED;  break;
00382     case Incidence::StatusCompleted:    status = ICAL_STATUS_COMPLETED;  break;
00383     case Incidence::StatusNeedsAction:  status = ICAL_STATUS_NEEDSACTION;  break;
00384     case Incidence::StatusCanceled:     status = ICAL_STATUS_CANCELLED;  break;
00385     case Incidence::StatusInProcess:    status = ICAL_STATUS_INPROCESS;  break;
00386     case Incidence::StatusDraft:        status = ICAL_STATUS_DRAFT;  break;
00387     case Incidence::StatusFinal:        status = ICAL_STATUS_FINAL;  break;
00388     case Incidence::StatusX: {
00389       icalproperty* p = icalproperty_new_status(ICAL_STATUS_X);
00390       icalvalue_set_x(icalproperty_get_value(p), incidence->statusStr().utf8());
00391       icalcomponent_add_property(parent, p);
00392       break;
00393     }
00394     case Incidence::StatusNone:
00395     default:
00396       break;
00397   }
00398   if (status != ICAL_STATUS_NONE)
00399     icalcomponent_add_property(parent, icalproperty_new_status(status));
00400 
00401   // secrecy
00402   icalproperty_class secClass;
00403   switch (incidence->secrecy()) {
00404     case Incidence::SecrecyPublic:
00405       secClass = ICAL_CLASS_PUBLIC;
00406       break;
00407     case Incidence::SecrecyConfidential:
00408       secClass = ICAL_CLASS_CONFIDENTIAL;
00409       break;
00410     case Incidence::SecrecyPrivate:
00411     default:
00412       secClass = ICAL_CLASS_PRIVATE;
00413       break;
00414   }
00415   if ( secClass != ICAL_CLASS_PUBLIC ) {
00416     icalcomponent_add_property(parent,icalproperty_new_class(secClass));
00417   }
00418 
00419   // priority
00420   if ( incidence->priority() > 0 ) { // 0 is undefined priority
00421     icalcomponent_add_property(parent,icalproperty_new_priority(
00422         incidence->priority()));
00423   }
00424 
00425   // categories
00426   QStringList categories = incidence->categories();
00427   QStringList::Iterator it;
00428   for(it = categories.begin(); it != categories.end(); ++it ) {
00429     icalcomponent_add_property(parent,icalproperty_new_categories((*it).utf8()));
00430   }
00431 
00432   // related event
00433   if ( !incidence->relatedToUid().isEmpty() ) {
00434     icalcomponent_add_property(parent,icalproperty_new_relatedto(
00435         incidence->relatedToUid().utf8()));
00436   }
00437 
00438 //   kdDebug(5800) << "Write recurrence for '" << incidence->summary() << "' (" << incidence->uid()
00439 //             << ")" << endl;
00440 
00441   RecurrenceRule::List rrules( incidence->recurrence()->rRules() );
00442   RecurrenceRule::List::ConstIterator rit;
00443   for ( rit = rrules.begin(); rit != rrules.end(); ++rit ) {
00444     icalcomponent_add_property( parent, icalproperty_new_rrule(
00445                                 writeRecurrenceRule( (*rit) ) ) );
00446   }
00447 
00448   RecurrenceRule::List exrules( incidence->recurrence()->exRules() );
00449   RecurrenceRule::List::ConstIterator exit;
00450   for ( exit = exrules.begin(); exit != exrules.end(); ++exit ) {
00451     icalcomponent_add_property( parent, icalproperty_new_rrule(
00452                                 writeRecurrenceRule( (*exit) ) ) );
00453   }
00454 
00455   DateList dateList = incidence->recurrence()->exDates();
00456   DateList::ConstIterator exIt;
00457   for(exIt = dateList.begin(); exIt != dateList.end(); ++exIt) {
00458     icalcomponent_add_property(parent,icalproperty_new_exdate(
00459         writeICalDate(*exIt)));
00460   }
00461   DateTimeList dateTimeList = incidence->recurrence()->exDateTimes();
00462   DateTimeList::ConstIterator extIt;
00463   for(extIt = dateTimeList.begin(); extIt != dateTimeList.end(); ++extIt) {
00464     icalcomponent_add_property(parent,icalproperty_new_exdate(
00465         writeICalDateTime(*extIt)));
00466   }
00467 
00468 
00469   dateList = incidence->recurrence()->rDates();
00470   DateList::ConstIterator rdIt;
00471   for( rdIt = dateList.begin(); rdIt != dateList.end(); ++rdIt) {
00472      icalcomponent_add_property( parent, icalproperty_new_rdate(
00473          writeICalDatePeriod(*rdIt) ) );
00474   }
00475   dateTimeList = incidence->recurrence()->rDateTimes();
00476   DateTimeList::ConstIterator rdtIt;
00477   for( rdtIt = dateTimeList.begin(); rdtIt != dateTimeList.end(); ++rdtIt) {
00478      icalcomponent_add_property( parent, icalproperty_new_rdate(
00479          writeICalDateTimePeriod(*rdtIt) ) );
00480   }
00481 
00482   // attachments
00483   Attachment::List attachments = incidence->attachments();
00484   Attachment::List::ConstIterator atIt;
00485   for ( atIt = attachments.begin(); atIt != attachments.end(); ++atIt ) {
00486     icalcomponent_add_property( parent, writeAttachment( *atIt ) );
00487   }
00488 
00489   // alarms
00490   Alarm::List::ConstIterator alarmIt;
00491   for ( alarmIt = incidence->alarms().begin();
00492         alarmIt != incidence->alarms().end(); ++alarmIt ) {
00493     if ( (*alarmIt)->enabled() ) {
00494 //      kdDebug(5800) << "Write alarm for " << incidence->summary() << endl;
00495       icalcomponent_add_component( parent, writeAlarm( *alarmIt ) );
00496     }
00497   }
00498 
00499   // duration
00500   if (incidence->hasDuration()) {
00501     icaldurationtype duration;
00502     duration = writeICalDuration( incidence->duration() );
00503     icalcomponent_add_property(parent,icalproperty_new_duration(duration));
00504   }
00505 }
00506 
00507 void ICalFormatImpl::writeIncidenceBase( icalcomponent *parent,
00508                                          IncidenceBase * incidenceBase )
00509 {
00510   icalcomponent_add_property( parent, icalproperty_new_dtstamp(
00511       writeICalDateTime( QDateTime::currentDateTime() ) ) );
00512 
00513   // organizer stuff
00514   if ( !incidenceBase->organizer().isEmpty() ) {
00515     icalcomponent_add_property( parent, writeOrganizer( incidenceBase->organizer() ) );
00516   }
00517 
00518   // attendees
00519   if ( incidenceBase->attendeeCount() > 0 ) {
00520     Attendee::List::ConstIterator it;
00521     for( it = incidenceBase->attendees().begin();
00522          it != incidenceBase->attendees().end(); ++it ) {
00523       icalcomponent_add_property( parent, writeAttendee( *it ) );
00524     }
00525   }
00526 
00527   // comments
00528   QStringList comments = incidenceBase->comments();
00529   for (QStringList::Iterator it=comments.begin(); it!=comments.end(); ++it) {
00530     icalcomponent_add_property(parent, icalproperty_new_comment((*it).utf8()));
00531   }
00532 
00533   // custom properties
00534   writeCustomProperties( parent, incidenceBase );
00535 }
00536 
00537 void ICalFormatImpl::writeCustomProperties(icalcomponent *parent,CustomProperties *properties)
00538 {
00539   QMap<QCString, QString> custom = properties->customProperties();
00540   for (QMap<QCString, QString>::Iterator c = custom.begin();  c != custom.end();  ++c) {
00541     icalproperty *p = icalproperty_new_x(c.data().utf8());
00542     icalproperty_set_x_name(p,c.key());
00543     icalcomponent_add_property(parent,p);
00544   }
00545 }
00546 
00547 icalproperty *ICalFormatImpl::writeOrganizer( const Person &organizer )
00548 {
00549   icalproperty *p = icalproperty_new_organizer("MAILTO:" + organizer.email().utf8());
00550 
00551   if (!organizer.name().isEmpty()) {
00552     icalproperty_add_parameter( p, icalparameter_new_cn(quoteForParam(organizer.name()).utf8()) );
00553   }
00554   // TODO: Write dir, sent-by and language
00555 
00556   return p;
00557 }
00558 
00559 
00560 icalproperty *ICalFormatImpl::writeAttendee(Attendee *attendee)
00561 {
00562   icalproperty *p = icalproperty_new_attendee("mailto:" + attendee->email().utf8());
00563 
00564   if (!attendee->name().isEmpty()) {
00565     icalproperty_add_parameter(p,icalparameter_new_cn(quoteForParam(attendee->name()).utf8()));
00566   }
00567 
00568 
00569   icalproperty_add_parameter(p,icalparameter_new_rsvp(
00570           attendee->RSVP() ? ICAL_RSVP_TRUE : ICAL_RSVP_FALSE ));
00571 
00572   icalparameter_partstat status = ICAL_PARTSTAT_NEEDSACTION;
00573   switch (attendee->status()) {
00574     default:
00575     case Attendee::NeedsAction:
00576       status = ICAL_PARTSTAT_NEEDSACTION;
00577       break;
00578     case Attendee::Accepted:
00579       status = ICAL_PARTSTAT_ACCEPTED;
00580       break;
00581     case Attendee::Declined:
00582       status = ICAL_PARTSTAT_DECLINED;
00583       break;
00584     case Attendee::Tentative:
00585       status = ICAL_PARTSTAT_TENTATIVE;
00586       break;
00587     case Attendee::Delegated:
00588       status = ICAL_PARTSTAT_DELEGATED;
00589       break;
00590     case Attendee::Completed:
00591       status = ICAL_PARTSTAT_COMPLETED;
00592       break;
00593     case Attendee::InProcess:
00594       status = ICAL_PARTSTAT_INPROCESS;
00595       break;
00596   }
00597   icalproperty_add_parameter(p,icalparameter_new_partstat(status));
00598 
00599   icalparameter_role role = ICAL_ROLE_REQPARTICIPANT;
00600   switch (attendee->role()) {
00601     case Attendee::Chair:
00602       role = ICAL_ROLE_CHAIR;
00603       break;
00604     default:
00605     case Attendee::ReqParticipant:
00606       role = ICAL_ROLE_REQPARTICIPANT;
00607       break;
00608     case Attendee::OptParticipant:
00609       role = ICAL_ROLE_OPTPARTICIPANT;
00610       break;
00611     case Attendee::NonParticipant:
00612       role = ICAL_ROLE_NONPARTICIPANT;
00613       break;
00614   }
00615   icalproperty_add_parameter(p,icalparameter_new_role(role));
00616 
00617   if (!attendee->uid().isEmpty()) {
00618     icalparameter* icalparameter_uid = icalparameter_new_x(attendee->uid().utf8());
00619     icalparameter_set_xname(icalparameter_uid,"X-UID");
00620     icalproperty_add_parameter(p,icalparameter_uid);
00621   }
00622 
00623   if ( !attendee->delegate().isEmpty() ) {
00624     icalparameter* icalparameter_delegate = icalparameter_new_delegatedto( attendee->delegate().utf8() );
00625     icalproperty_add_parameter( p, icalparameter_delegate );
00626   }
00627 
00628   if ( !attendee->delegator().isEmpty() ) {
00629     icalparameter* icalparameter_delegator = icalparameter_new_delegatedfrom( attendee->delegator().utf8() );
00630     icalproperty_add_parameter( p, icalparameter_delegator );
00631   }
00632 
00633   return p;
00634 }
00635 
00636 icalproperty *ICalFormatImpl::writeAttachment( Attachment *att )
00637 {
00638   icalattach *attach;
00639   if ( att->isUri() ) {
00640     attach = icalattach_new_from_url( att->uri().utf8().data() );
00641   } else {
00642     attach = icalattach_new_from_data ( (unsigned char *)att->data(), 0, 0 );
00643   }
00644   icalproperty *p = icalproperty_new_attach( attach );
00645 
00646   if ( !att->mimeType().isEmpty() ) {
00647     icalproperty_add_parameter( p,
00648         icalparameter_new_fmttype( att->mimeType().utf8().data() ) );
00649   }
00650 
00651   if ( att->isBinary() ) {
00652     icalproperty_add_parameter( p,
00653         icalparameter_new_value( ICAL_VALUE_BINARY ) );
00654     icalproperty_add_parameter( p,
00655         icalparameter_new_encoding( ICAL_ENCODING_BASE64 ) );
00656   }
00657 
00658   if ( att->showInline() ) {
00659     icalparameter* icalparameter_inline = icalparameter_new_x( "inline" );
00660     icalparameter_set_xname( icalparameter_inline, "X-CONTENT-DISPOSITION" );
00661     icalproperty_add_parameter( p, icalparameter_inline );
00662   }
00663 
00664   if ( !att->label().isEmpty() ) {
00665     icalparameter* icalparameter_label = icalparameter_new_x( att->label().utf8() );
00666     icalparameter_set_xname( icalparameter_label, "X-LABEL" );
00667     icalproperty_add_parameter( p, icalparameter_label );
00668   }
00669 
00670   return p;
00671 }
00672 
00673 icalrecurrencetype ICalFormatImpl::writeRecurrenceRule( RecurrenceRule *recur )
00674 {
00675 //  kdDebug(5800) << "ICalFormatImpl::writeRecurrenceRule()" << endl;
00676 
00677   icalrecurrencetype r;
00678   icalrecurrencetype_clear(&r);
00679 
00680   switch( recur->recurrenceType() ) {
00681     case RecurrenceRule::rSecondly:
00682       r.freq = ICAL_SECONDLY_RECURRENCE;
00683       break;
00684     case RecurrenceRule::rMinutely:
00685       r.freq = ICAL_MINUTELY_RECURRENCE;
00686       break;
00687     case RecurrenceRule::rHourly:
00688       r.freq = ICAL_HOURLY_RECURRENCE;
00689       break;
00690     case RecurrenceRule::rDaily:
00691       r.freq = ICAL_DAILY_RECURRENCE;
00692       break;
00693     case RecurrenceRule::rWeekly:
00694       r.freq = ICAL_WEEKLY_RECURRENCE;
00695       break;
00696     case RecurrenceRule::rMonthly:
00697       r.freq = ICAL_MONTHLY_RECURRENCE;
00698       break;
00699     case RecurrenceRule::rYearly:
00700       r.freq = ICAL_YEARLY_RECURRENCE;
00701       break;
00702     default:
00703       r.freq = ICAL_NO_RECURRENCE;
00704       kdDebug(5800) << "ICalFormatImpl::writeRecurrence(): no recurrence" << endl;
00705       break;
00706   }
00707 
00708   int index = 0;
00709   QValueList<int> bys;
00710   QValueList<int>::ConstIterator it;
00711 
00712   // Now write out the BY* parts:
00713   bys = recur->bySeconds();
00714   index = 0;
00715   for ( it = bys.begin(); it != bys.end(); ++it ) {
00716     r.by_second[index++] = *it;
00717   }
00718 
00719   bys = recur->byMinutes();
00720   index = 0;
00721   for ( it = bys.begin(); it != bys.end(); ++it ) {
00722     r.by_minute[index++] = *it;
00723   }
00724 
00725   bys = recur->byHours();
00726   index = 0;
00727   for ( it = bys.begin(); it != bys.end(); ++it ) {
00728     r.by_hour[index++] = *it;
00729   }
00730 
00731   bys = recur->byMonthDays();
00732   index = 0;
00733   for ( it = bys.begin(); it != bys.end(); ++it ) {
00734     r.by_month_day[index++] = icalrecurrencetype_day_position( (*it) * 8 );
00735   }
00736 
00737   bys = recur->byYearDays();
00738   index = 0;
00739   for ( it = bys.begin(); it != bys.end(); ++it ) {
00740     r.by_year_day[index++] = *it;
00741   }
00742 
00743   bys = recur->byWeekNumbers();
00744   index = 0;
00745   for ( it = bys.begin(); it != bys.end(); ++it ) {
00746      r.by_week_no[index++] = *it;
00747   }
00748 
00749   bys = recur->byMonths();
00750   index = 0;
00751   for ( it = bys.begin(); it != bys.end(); ++it ) {
00752     r.by_month[index++] = *it;
00753   }
00754 
00755   bys = recur->bySetPos();
00756   index = 0;
00757   for ( it = bys.begin(); it != bys.end(); ++it ) {
00758      r.by_set_pos[index++] = *it;
00759   }
00760 
00761 
00762   QValueList<RecurrenceRule::WDayPos> byd = recur->byDays();
00763   int day;
00764   index = 0;
00765   for ( QValueList<RecurrenceRule::WDayPos>::ConstIterator dit = byd.begin();
00766         dit != byd.end(); ++dit ) {
00767     day = (*dit).day() % 7 + 1;     // convert from Monday=1 to Sunday=1
00768     if ( (*dit).pos() < 0 ) {
00769       day += (-(*dit).pos())*8;
00770       day = -day;
00771     } else {
00772       day += (*dit).pos()*8;
00773     }
00774     r.by_day[index++] = day;
00775   }
00776 
00777   r.week_start = static_cast<icalrecurrencetype_weekday>(
00778                                              recur->weekStart()%7 + 1);
00779 
00780   if ( recur->frequency() > 1 ) {
00781     // Dont' write out INTERVAL=1, because that's the default anyway
00782     r.interval = recur->frequency();
00783   }
00784 
00785   if ( recur->duration() > 0 ) {
00786     r.count = recur->duration();
00787   } else if ( recur->duration() == -1 ) {
00788     r.count = 0;
00789   } else {
00790     if ( recur->doesFloat() )
00791       r.until = writeICalDate(recur->endDt().date());
00792     else
00793       r.until = writeICalDateTime(recur->endDt());
00794   }
00795 
00796 // Debug output
00797 #if 0
00798   const char *str = icalrecurrencetype_as_string(&r);
00799   if (str) {
00800     kdDebug(5800) << " String: " << str << endl;
00801   } else {
00802     kdDebug(5800) << " No String" << endl;
00803   }
00804 #endif
00805 
00806   return r;
00807 }
00808 
00809 
00810 icalcomponent *ICalFormatImpl::writeAlarm(Alarm *alarm)
00811 {
00812 // kdDebug(5800) << " ICalFormatImpl::writeAlarm" << endl;
00813   icalcomponent *a = icalcomponent_new(ICAL_VALARM_COMPONENT);
00814 
00815   icalproperty_action action;
00816   icalattach *attach = 0;
00817 
00818   switch (alarm->type()) {
00819     case Alarm::Procedure:
00820       action = ICAL_ACTION_PROCEDURE;
00821       attach = icalattach_new_from_url(QFile::encodeName(alarm->programFile()).data());
00822       icalcomponent_add_property(a,icalproperty_new_attach(attach));
00823       if (!alarm->programArguments().isEmpty()) {
00824         icalcomponent_add_property(a,icalproperty_new_description(alarm->programArguments().utf8()));
00825       }
00826       break;
00827     case Alarm::Audio:
00828       action = ICAL_ACTION_AUDIO;
00829 // kdDebug(5800) << " It's an audio action, file: " << alarm->audioFile() << endl;
00830       if (!alarm->audioFile().isEmpty()) {
00831         attach = icalattach_new_from_url(QFile::encodeName( alarm->audioFile() ).data());
00832         icalcomponent_add_property(a,icalproperty_new_attach(attach));
00833       }
00834       break;
00835     case Alarm::Email: {
00836       action = ICAL_ACTION_EMAIL;
00837       QValueList<Person> addresses = alarm->mailAddresses();
00838       for (QValueList<Person>::Iterator ad = addresses.begin();  ad != addresses.end();  ++ad) {
00839         icalproperty *p = icalproperty_new_attendee("MAILTO:" + (*ad).email().utf8());
00840         if (!(*ad).name().isEmpty()) {
00841           icalproperty_add_parameter(p,icalparameter_new_cn(quoteForParam((*ad).name()).utf8()));
00842         }
00843         icalcomponent_add_property(a,p);
00844       }
00845       icalcomponent_add_property(a,icalproperty_new_summary(alarm->mailSubject().utf8()));
00846       icalcomponent_add_property(a,icalproperty_new_description(alarm->mailText().utf8()));
00847       QStringList attachments = alarm->mailAttachments();
00848       if (attachments.count() > 0) {
00849         for (QStringList::Iterator at = attachments.begin();  at != attachments.end();  ++at) {
00850           attach = icalattach_new_from_url(QFile::encodeName( *at ).data());
00851           icalcomponent_add_property(a,icalproperty_new_attach(attach));
00852         }
00853       }
00854       break;
00855     }
00856     case Alarm::Display:
00857       action = ICAL_ACTION_DISPLAY;
00858       icalcomponent_add_property(a,icalproperty_new_description(alarm->text().utf8()));
00859       break;
00860     case Alarm::Invalid:
00861     default:
00862       kdDebug(5800) << "Unknown type of alarm" << endl;
00863       action = ICAL_ACTION_NONE;
00864       break;
00865   }
00866   icalcomponent_add_property(a,icalproperty_new_action(action));
00867 
00868   // Trigger time
00869   icaltriggertype trigger;
00870   if ( alarm->hasTime() ) {
00871     trigger.time = writeICalDateTime(alarm->time());
00872     trigger.duration = icaldurationtype_null_duration();
00873   } else {
00874     trigger.time = icaltime_null_time();
00875     Duration offset;
00876     if ( alarm->hasStartOffset() )
00877       offset = alarm->startOffset();
00878     else
00879       offset = alarm->endOffset();
00880     trigger.duration = writeICalDuration( offset.asSeconds() );
00881   }
00882   icalproperty *p = icalproperty_new_trigger(trigger);
00883   if ( alarm->hasEndOffset() )
00884     icalproperty_add_parameter(p,icalparameter_new_related(ICAL_RELATED_END));
00885   icalcomponent_add_property(a,p);
00886 
00887   // Repeat count and duration
00888   if (alarm->repeatCount()) {
00889     icalcomponent_add_property(a,icalproperty_new_repeat(alarm->repeatCount()));
00890     icalcomponent_add_property(a,icalproperty_new_duration(
00891                                  writeICalDuration(alarm->snoozeTime().value())));
00892   }
00893 
00894   // Custom properties
00895   QMap<QCString, QString> custom = alarm->customProperties();
00896   for (QMap<QCString, QString>::Iterator c = custom.begin();  c != custom.end();  ++c) {
00897     icalproperty *p = icalproperty_new_x(c.data().utf8());
00898     icalproperty_set_x_name(p,c.key());
00899     icalcomponent_add_property(a,p);
00900   }
00901 
00902   return a;
00903 }
00904 
00905 Todo *ICalFormatImpl::readTodo(icalcomponent *vtodo)
00906 {
00907   Todo *todo = new Todo;
00908 
00909   readIncidence(vtodo, 0, todo); // FIXME timezone
00910 
00911   icalproperty *p = icalcomponent_get_first_property(vtodo,ICAL_ANY_PROPERTY);
00912 
00913 //  int intvalue;
00914   icaltimetype icaltime;
00915 
00916   QStringList categories;
00917 
00918   while (p) {
00919     icalproperty_kind kind = icalproperty_isa(p);
00920     switch (kind) {
00921 
00922       case ICAL_DUE_PROPERTY:  // due date
00923         icaltime = icalproperty_get_due(p);
00924         if (icaltime.is_date) {
00925           todo->setDtDue(QDateTime(readICalDate(icaltime),QTime(0,0,0)),true);
00926         } else {
00927           todo->setDtDue(readICalDateTime(icaltime),true);
00928           todo->setFloats(false);
00929         }
00930         todo->setHasDueDate(true);
00931         break;
00932 
00933       case ICAL_COMPLETED_PROPERTY:  // completion date
00934         icaltime = icalproperty_get_completed(p);
00935         todo->setCompleted(readICalDateTime(icaltime));
00936         break;
00937 
00938       case ICAL_PERCENTCOMPLETE_PROPERTY:  // Percent completed
00939         todo->setPercentComplete(icalproperty_get_percentcomplete(p));
00940         break;
00941 
00942       case ICAL_RELATEDTO_PROPERTY:  // related todo (parent)
00943         todo->setRelatedToUid(QString::fromUtf8(icalproperty_get_relatedto(p)));
00944         mTodosRelate.append(todo);
00945         break;
00946 
00947       case ICAL_DTSTART_PROPERTY: {
00948         // Flag that todo has start date. Value is read in by readIncidence().
00949         if ( todo->comments().grep("NoStartDate").count() )
00950           todo->setHasStartDate( false );
00951         else
00952           todo->setHasStartDate( true );
00953         break;
00954       }
00955 
00956       case ICAL_RECURRENCEID_PROPERTY:
00957         icaltime = icalproperty_get_recurrenceid(p);
00958         todo->setDtRecurrence( readICalDateTime(icaltime) );
00959         break;
00960 
00961       default:
00962 //        kdDebug(5800) << "ICALFormat::readTodo(): Unknown property: " << kind
00963 //                  << endl;
00964         break;
00965     }
00966 
00967     p = icalcomponent_get_next_property(vtodo,ICAL_ANY_PROPERTY);
00968   }
00969 
00970   if (mCompat) mCompat->fixEmptySummary( todo );
00971 
00972   return todo;
00973 }
00974 
00975 Event *ICalFormatImpl::readEvent( icalcomponent *vevent, icalcomponent *vtimezone )
00976 {
00977   Event *event = new Event;
00978 
00979   // FIXME where is this freed?
00980   icaltimezone *tz = icaltimezone_new();
00981   if ( !icaltimezone_set_component( tz, vtimezone ) ) {
00982     icaltimezone_free( tz, 1 );
00983     tz = 0;
00984   }
00985 
00986   readIncidence( vevent, tz, event);
00987 
00988   icalproperty *p = icalcomponent_get_first_property(vevent,ICAL_ANY_PROPERTY);
00989 
00990 //  int intvalue;
00991   icaltimetype icaltime;
00992 
00993   QStringList categories;
00994   icalproperty_transp transparency;
00995 
00996   bool dtEndProcessed = false;
00997 
00998   while (p) {
00999     icalproperty_kind kind = icalproperty_isa(p);
01000     switch (kind) {
01001 
01002       case ICAL_DTEND_PROPERTY:  // start date and time
01003         icaltime = icalproperty_get_dtend(p);
01004         if (icaltime.is_date) {
01005           // End date is non-inclusive
01006           QDate endDate = readICalDate( icaltime ).addDays( -1 );
01007           if ( mCompat ) mCompat->fixFloatingEnd( endDate );
01008           if ( endDate < event->dtStart().date() ) {
01009             endDate = event->dtStart().date();
01010           }
01011           event->setDtEnd( QDateTime( endDate, QTime( 0, 0, 0 ) ) );
01012         } else {
01013           event->setDtEnd(readICalDateTime(icaltime, tz));
01014           event->setFloats( false );
01015         }
01016         dtEndProcessed = true;
01017         break;
01018 
01019       case ICAL_RELATEDTO_PROPERTY:  // related event (parent)
01020         event->setRelatedToUid(QString::fromUtf8(icalproperty_get_relatedto(p)));
01021         mEventsRelate.append(event);
01022         break;
01023 
01024 
01025       case ICAL_TRANSP_PROPERTY:  // Transparency
01026         transparency = icalproperty_get_transp(p);
01027         if( transparency == ICAL_TRANSP_TRANSPARENT )
01028           event->setTransparency( Event::Transparent );
01029         else
01030           event->setTransparency( Event::Opaque );
01031         break;
01032 
01033       default:
01034 //        kdDebug(5800) << "ICALFormat::readEvent(): Unknown property: " << kind
01035 //                  << endl;
01036         break;
01037     }
01038 
01039     p = icalcomponent_get_next_property(vevent,ICAL_ANY_PROPERTY);
01040   }
01041 
01042   // according to rfc2445 the dtend shouldn't be written when it equals
01043   // start date. so assign one equal to start date.
01044   if ( !dtEndProcessed && !event->hasDuration() ) {
01045     event->setDtEnd( event->dtStart() );
01046   }
01047 
01048   QString msade = event->nonKDECustomProperty("X-MICROSOFT-CDO-ALLDAYEVENT");
01049   if (!msade.isEmpty()) {
01050     bool floats = (msade == QString::fromLatin1("TRUE"));
01051     event->setFloats(floats);
01052   }
01053 
01054   if ( mCompat ) mCompat->fixEmptySummary( event );
01055 
01056   return event;
01057 }
01058 
01059 FreeBusy *ICalFormatImpl::readFreeBusy(icalcomponent *vfreebusy)
01060 {
01061   FreeBusy *freebusy = new FreeBusy;
01062 
01063   readIncidenceBase(vfreebusy, freebusy);
01064 
01065   icalproperty *p = icalcomponent_get_first_property(vfreebusy,ICAL_ANY_PROPERTY);
01066 
01067   icaltimetype icaltime;
01068   PeriodList periods;
01069 
01070   while (p) {
01071     icalproperty_kind kind = icalproperty_isa(p);
01072     switch (kind) {
01073 
01074       case ICAL_DTSTART_PROPERTY:  // start date and time
01075         icaltime = icalproperty_get_dtstart(p);
01076         freebusy->setDtStart(readICalDateTime(icaltime));
01077         break;
01078 
01079       case ICAL_DTEND_PROPERTY:  // end Date and Time
01080         icaltime = icalproperty_get_dtend(p);
01081         freebusy->setDtEnd(readICalDateTime(icaltime));
01082         break;
01083 
01084       case ICAL_FREEBUSY_PROPERTY:  //Any FreeBusy Times
01085       {
01086         icalperiodtype icalperiod = icalproperty_get_freebusy(p);
01087         QDateTime period_start = readICalDateTime(icalperiod.start);
01088         Period period;
01089         if ( !icaltime_is_null_time(icalperiod.end) ) {
01090           QDateTime period_end = readICalDateTime(icalperiod.end);
01091           period = Period(period_start, period_end);
01092         } else {
01093           Duration duration = readICalDuration( icalperiod.duration );
01094           period = Period(period_start, duration);
01095         }
01096         icalparameter *param = icalproperty_get_first_parameter( p, ICAL_X_PARAMETER );
01097         while ( param ) {
01098           if ( strncmp( icalparameter_get_xname( param ), "X-SUMMARY", 9 ) == 0 ) {
01099             period.setSummary( QString::fromUtf8(
01100                                  KCodecs::base64Decode( icalparameter_get_xvalue( param ) ) ) );
01101           }
01102           if ( strncmp( icalparameter_get_xname( param ), "X-LOCATION", 10 ) == 0 ) {
01103             period.setLocation( QString::fromUtf8(
01104                                   KCodecs::base64Decode( icalparameter_get_xvalue( param ) ) ) );
01105           }
01106           param = icalproperty_get_next_parameter( p, ICAL_X_PARAMETER );
01107         }
01108         periods.append( period );
01109         break;
01110       }
01111 
01112       default:
01113 //        kdDebug(5800) << "ICalFormatImpl::readFreeBusy(): Unknown property: "
01114 //                      << kind << endl;
01115       break;
01116     }
01117     p = icalcomponent_get_next_property(vfreebusy,ICAL_ANY_PROPERTY);
01118   }
01119   freebusy->addPeriods( periods );
01120 
01121   return freebusy;
01122 }
01123 
01124 Journal *ICalFormatImpl::readJournal(icalcomponent *vjournal)
01125 {
01126   Journal *journal = new Journal;
01127 
01128   readIncidence(vjournal, 0, journal); // FIXME tz?
01129 
01130   return journal;
01131 }
01132 
01133 Attendee *ICalFormatImpl::readAttendee(icalproperty *attendee)
01134 {
01135   icalparameter *p = 0;
01136 
01137   QString email = QString::fromUtf8(icalproperty_get_attendee(attendee));
01138   if ( email.startsWith( "mailto:", false ) ) {
01139     email = email.mid( 7 );
01140   }
01141 
01142   QString name;
01143   QString uid = QString::null;
01144   p = icalproperty_get_first_parameter(attendee,ICAL_CN_PARAMETER);
01145   if (p) {
01146     name = QString::fromUtf8(icalparameter_get_cn(p));
01147   } else {
01148   }
01149 
01150   bool rsvp=false;
01151   p = icalproperty_get_first_parameter(attendee,ICAL_RSVP_PARAMETER);
01152   if (p) {
01153     icalparameter_rsvp rsvpParameter = icalparameter_get_rsvp(p);
01154     if (rsvpParameter == ICAL_RSVP_TRUE) rsvp = true;
01155   }
01156 
01157   Attendee::PartStat status = Attendee::NeedsAction;
01158   p = icalproperty_get_first_parameter(attendee,ICAL_PARTSTAT_PARAMETER);
01159   if (p) {
01160     icalparameter_partstat partStatParameter = icalparameter_get_partstat(p);
01161     switch(partStatParameter) {
01162       default:
01163       case ICAL_PARTSTAT_NEEDSACTION:
01164         status = Attendee::NeedsAction;
01165         break;
01166       case ICAL_PARTSTAT_ACCEPTED:
01167         status = Attendee::Accepted;
01168         break;
01169       case ICAL_PARTSTAT_DECLINED:
01170         status = Attendee::Declined;
01171         break;
01172       case ICAL_PARTSTAT_TENTATIVE:
01173         status = Attendee::Tentative;
01174         break;
01175       case ICAL_PARTSTAT_DELEGATED:
01176         status = Attendee::Delegated;
01177         break;
01178       case ICAL_PARTSTAT_COMPLETED:
01179         status = Attendee::Completed;
01180         break;
01181       case ICAL_PARTSTAT_INPROCESS:
01182         status = Attendee::InProcess;
01183         break;
01184     }
01185   }
01186 
01187   Attendee::Role role = Attendee::ReqParticipant;
01188   p = icalproperty_get_first_parameter(attendee,ICAL_ROLE_PARAMETER);
01189   if (p) {
01190     icalparameter_role roleParameter = icalparameter_get_role(p);
01191     switch(roleParameter) {
01192       case ICAL_ROLE_CHAIR:
01193         role = Attendee::Chair;
01194         break;
01195       default:
01196       case ICAL_ROLE_REQPARTICIPANT:
01197         role = Attendee::ReqParticipant;
01198         break;
01199       case ICAL_ROLE_OPTPARTICIPANT:
01200         role = Attendee::OptParticipant;
01201         break;
01202       case ICAL_ROLE_NONPARTICIPANT:
01203         role = Attendee::NonParticipant;
01204         break;
01205     }
01206   }
01207 
01208   p = icalproperty_get_first_parameter(attendee,ICAL_X_PARAMETER);
01209   uid = icalparameter_get_xvalue(p);
01210   // This should be added, but there seems to be a libical bug here.
01211   // TODO: does this work now in libical-0.24 or greater?
01212   /*while (p) {
01213    // if (icalparameter_get_xname(p) == "X-UID") {
01214     uid = icalparameter_get_xvalue(p);
01215     p = icalproperty_get_next_parameter(attendee,ICAL_X_PARAMETER);
01216   } */
01217 
01218   Attendee *a = new Attendee( name, email, rsvp, status, role, uid );
01219 
01220   p = icalproperty_get_first_parameter( attendee, ICAL_DELEGATEDTO_PARAMETER );
01221   if ( p )
01222     a->setDelegate( icalparameter_get_delegatedto( p ) );
01223 
01224   p = icalproperty_get_first_parameter( attendee, ICAL_DELEGATEDFROM_PARAMETER );
01225   if ( p )
01226     a->setDelegator( icalparameter_get_delegatedfrom( p ) );
01227 
01228   return a;
01229 }
01230 
01231 Person ICalFormatImpl::readOrganizer( icalproperty *organizer )
01232 {
01233   QString email = QString::fromUtf8(icalproperty_get_organizer(organizer));
01234   if ( email.startsWith( "mailto:", false ) ) {
01235     email = email.mid( 7 );
01236   }
01237   QString cn;
01238 
01239   icalparameter *p = icalproperty_get_first_parameter(
01240              organizer, ICAL_CN_PARAMETER );
01241 
01242   if ( p ) {
01243     cn = QString::fromUtf8( icalparameter_get_cn( p ) );
01244   }
01245   Person org( cn, email );
01246   // TODO: Treat sent-by, dir and language here, too
01247   return org;
01248 }
01249 
01250 Attachment *ICalFormatImpl::readAttachment(icalproperty *attach)
01251 {
01252   Attachment *attachment = 0;
01253 
01254   const char *p;
01255   icalvalue *value = icalproperty_get_value( attach );
01256 
01257   switch( icalvalue_isa( value ) ) {
01258   case ICAL_ATTACH_VALUE:
01259   {
01260     icalattach *a = icalproperty_get_attach( attach );
01261     if ( !icalattach_get_is_url( a ) ) {
01262       p = (const char *)icalattach_get_data( a );
01263       if ( p ) {
01264         attachment = new Attachment( p );
01265       }
01266     } else {
01267       p = icalattach_get_url( a );
01268       if ( p ) {
01269         attachment = new Attachment( QString::fromUtf8( p ) );
01270       }
01271     }
01272     break;
01273   }
01274   case ICAL_BINARY_VALUE:
01275   {
01276     icalattach *a = icalproperty_get_attach( attach );
01277     p = (const char *)icalattach_get_data( a );
01278     if ( p ) {
01279       attachment = new Attachment( p );
01280     }
01281     break;
01282   }
01283   case ICAL_URI_VALUE:
01284     p = icalvalue_get_uri( value );
01285     attachment = new Attachment( QString::fromUtf8( p ) );
01286     break;
01287   default:
01288     break;
01289   }
01290 
01291  if ( attachment ) {
01292     icalparameter *p =
01293       icalproperty_get_first_parameter( attach, ICAL_FMTTYPE_PARAMETER );
01294     if ( p ) {
01295       attachment->setMimeType( QString( icalparameter_get_fmttype( p ) ) );
01296     }
01297 
01298     p = icalproperty_get_first_parameter( attach, ICAL_X_PARAMETER );
01299     while ( p ) {
01300       QString xname = QString( icalparameter_get_xname( p ) ).upper();
01301       QString xvalue = QString::fromUtf8( icalparameter_get_xvalue( p ) );
01302       if ( xname == "X-CONTENT-DISPOSITION" ) {
01303         attachment->setShowInline( xvalue.lower() == "inline" );
01304       }
01305       if ( xname == "X-LABEL" ) {
01306         attachment->setLabel( xvalue );
01307       }
01308       p = icalproperty_get_next_parameter( attach, ICAL_X_PARAMETER );
01309     }
01310 
01311     p = icalproperty_get_first_parameter( attach, ICAL_X_PARAMETER );
01312     while ( p ) {
01313       if ( strncmp( icalparameter_get_xname( p ), "X-LABEL", 7 ) == 0 ) {
01314         attachment->setLabel( QString::fromUtf8( icalparameter_get_xvalue( p ) ) );
01315       }
01316       p = icalproperty_get_next_parameter( attach, ICAL_X_PARAMETER );
01317     }
01318   }
01319 
01320   return attachment;
01321 }
01322 
01323 void ICalFormatImpl::readIncidence(icalcomponent *parent, icaltimezone *tz, Incidence *incidence)
01324 {
01325   readIncidenceBase(parent,incidence);
01326 
01327   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_ANY_PROPERTY);
01328 
01329   const char *text;
01330   int intvalue, inttext;
01331   icaltimetype icaltime;
01332   icaldurationtype icalduration;
01333 
01334   QStringList categories;
01335 
01336   while (p) {
01337     icalproperty_kind kind = icalproperty_isa(p);
01338     switch (kind) {
01339 
01340       case ICAL_CREATED_PROPERTY:
01341         icaltime = icalproperty_get_created(p);
01342         incidence->setCreated(readICalDateTime(icaltime, tz));
01343         break;
01344 
01345       case ICAL_SEQUENCE_PROPERTY:  // sequence
01346         intvalue = icalproperty_get_sequence(p);
01347         incidence->setRevision(intvalue);
01348         break;
01349 
01350       case ICAL_LASTMODIFIED_PROPERTY:  // last modification date
01351         icaltime = icalproperty_get_lastmodified(p);
01352         incidence->setLastModified(readICalDateTime(icaltime, tz));
01353         break;
01354 
01355       case ICAL_DTSTART_PROPERTY:  // start date and time
01356         icaltime = icalproperty_get_dtstart(p);
01357         if (icaltime.is_date) {
01358           incidence->setDtStart(QDateTime(readICalDate(icaltime),QTime(0,0,0)));
01359           incidence->setFloats( true );
01360         } else {
01361           incidence->setDtStart(readICalDateTime(icaltime, tz));
01362           incidence->setFloats( false );
01363         }
01364         break;
01365 
01366       case ICAL_DURATION_PROPERTY:  // start date and time
01367         icalduration = icalproperty_get_duration(p);
01368         incidence->setDuration(readICalDuration(icalduration));
01369         break;
01370 
01371       case ICAL_DESCRIPTION_PROPERTY:  // description
01372         text = icalproperty_get_description(p);
01373         incidence->setDescription(QString::fromUtf8(text));
01374         break;
01375 
01376       case ICAL_SUMMARY_PROPERTY:  // summary
01377         text = icalproperty_get_summary(p);
01378         incidence->setSummary(QString::fromUtf8(text));
01379         break;
01380 
01381       case ICAL_LOCATION_PROPERTY:  // location
01382         text = icalproperty_get_location(p);
01383         incidence->setLocation(QString::fromUtf8(text));
01384         break;
01385 
01386       case ICAL_STATUS_PROPERTY: {  // status
01387         Incidence::Status stat;
01388         switch (icalproperty_get_status(p)) {
01389           case ICAL_STATUS_TENTATIVE:   stat = Incidence::StatusTentative; break;
01390           case ICAL_STATUS_CONFIRMED:   stat = Incidence::StatusConfirmed; break;
01391           case ICAL_STATUS_COMPLETED:   stat = Incidence::StatusCompleted; break;
01392           case ICAL_STATUS_NEEDSACTION: stat = Incidence::StatusNeedsAction; break;
01393           case ICAL_STATUS_CANCELLED:   stat = Incidence::StatusCanceled; break;
01394           case ICAL_STATUS_INPROCESS:   stat = Incidence::StatusInProcess; break;
01395           case ICAL_STATUS_DRAFT:       stat = Incidence::StatusDraft; break;
01396           case ICAL_STATUS_FINAL:       stat = Incidence::StatusFinal; break;
01397           case ICAL_STATUS_X:
01398             incidence->setCustomStatus(QString::fromUtf8(icalvalue_get_x(icalproperty_get_value(p))));
01399             stat = Incidence::StatusX;
01400             break;
01401           case ICAL_STATUS_NONE:
01402           default:                      stat = Incidence::StatusNone; break;
01403         }
01404         if (stat != Incidence::StatusX)
01405           incidence->setStatus(stat);
01406         break;
01407       }
01408 
01409       case ICAL_PRIORITY_PROPERTY:  // priority
01410         intvalue = icalproperty_get_priority( p );
01411         if ( mCompat )
01412           intvalue = mCompat->fixPriority( intvalue );
01413         incidence->setPriority( intvalue );
01414         break;
01415 
01416       case ICAL_CATEGORIES_PROPERTY:  // categories
01417         text = icalproperty_get_categories(p);
01418         categories.append(QString::fromUtf8(text));
01419         break;
01420 
01421       case ICAL_RRULE_PROPERTY:
01422         readRecurrenceRule( p, incidence );
01423         break;
01424 
01425       case ICAL_RDATE_PROPERTY: {
01426         icaldatetimeperiodtype rd = icalproperty_get_rdate( p );
01427         if ( icaltime_is_valid_time( rd.time ) ) {
01428           if ( icaltime_is_date( rd.time ) ) {
01429             incidence->recurrence()->addRDate( readICalDate( rd.time ) );
01430           } else {
01431             incidence->recurrence()->addRDateTime( readICalDateTime( rd.time, tz ) );
01432           }
01433         } else {
01434           // TODO: RDates as period are not yet implemented!
01435         }
01436         break; }
01437 
01438       case ICAL_EXRULE_PROPERTY:
01439         readExceptionRule( p, incidence );
01440         break;
01441 
01442       case ICAL_EXDATE_PROPERTY:
01443         icaltime = icalproperty_get_exdate(p);
01444         if ( icaltime_is_date(icaltime) ) {
01445           incidence->recurrence()->addExDate( readICalDate(icaltime) );
01446         } else {
01447           incidence->recurrence()->addExDateTime( readICalDateTime(icaltime, tz) );
01448         }
01449         break;
01450 
01451       case ICAL_CLASS_PROPERTY:
01452         inttext = icalproperty_get_class(p);
01453         if (inttext == ICAL_CLASS_PUBLIC ) {
01454           incidence->setSecrecy(Incidence::SecrecyPublic);
01455         } else if (inttext == ICAL_CLASS_CONFIDENTIAL ) {
01456           incidence->setSecrecy(Incidence::SecrecyConfidential);
01457         } else {
01458           incidence->setSecrecy(Incidence::SecrecyPrivate);
01459         }
01460         break;
01461 
01462       case ICAL_ATTACH_PROPERTY:  // attachments
01463         incidence->addAttachment(readAttachment(p));
01464         break;
01465 
01466       default:
01467 //        kdDebug(5800) << "ICALFormat::readIncidence(): Unknown property: " << kind
01468 //                  << endl;
01469         break;
01470     }
01471 
01472     p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY);
01473   }
01474 
01475   // Set the scheduling ID
01476   const QString uid = incidence->customProperty( "LIBKCAL", "ID" );
01477   if ( !uid.isNull() ) {
01478     // The UID stored in incidencebase is actually the scheduling ID
01479     // It has to be stored in the iCal UID component for compatibility
01480     // with other iCal applications
01481     incidence->setSchedulingID( incidence->uid() );
01482     incidence->setUid( uid );
01483   }
01484 
01485   // Now that recurrence and exception stuff is completely set up,
01486   // do any backwards compatibility adjustments.
01487   if ( incidence->doesRecur() && mCompat )
01488       mCompat->fixRecurrence( incidence );
01489 
01490   // add categories
01491   incidence->setCategories(categories);
01492 
01493   // iterate through all alarms
01494   for (icalcomponent *alarm = icalcomponent_get_first_component(parent,ICAL_VALARM_COMPONENT);
01495        alarm;
01496        alarm = icalcomponent_get_next_component(parent,ICAL_VALARM_COMPONENT)) {
01497     readAlarm(alarm,incidence);
01498   }
01499   // Fix incorrect alarm settings by other applications (like outloook 9)
01500   if ( mCompat ) mCompat->fixAlarms( incidence );
01501 
01502 }
01503 
01504 void ICalFormatImpl::readIncidenceBase(icalcomponent *parent,IncidenceBase *incidenceBase)
01505 {
01506   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_ANY_PROPERTY);
01507 
01508   while (p) {
01509     icalproperty_kind kind = icalproperty_isa(p);
01510     switch (kind) {
01511 
01512       case ICAL_UID_PROPERTY:  // unique id
01513         incidenceBase->setUid(QString::fromUtf8(icalproperty_get_uid(p)));
01514         break;
01515 
01516       case ICAL_ORGANIZER_PROPERTY:  // organizer
01517         incidenceBase->setOrganizer( readOrganizer(p));
01518         break;
01519 
01520       case ICAL_ATTENDEE_PROPERTY:  // attendee
01521         incidenceBase->addAttendee(readAttendee(p));
01522         break;
01523 
01524       case ICAL_COMMENT_PROPERTY:
01525         incidenceBase->addComment(
01526             QString::fromUtf8(icalproperty_get_comment(p)));
01527         break;
01528 
01529       default:
01530         break;
01531     }
01532 
01533     p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY);
01534   }
01535 
01536   // kpilot stuff
01537   // TODO: move this application-specific code to kpilot
01538   // need to get X-PILOT* attributes out, set correct properties, and get
01539   // rid of them...
01540   // Pointer fun, as per libical documentation
01541   // (documented in UsingLibical.txt)
01542   icalproperty *next =0;
01543 
01544   for ( p = icalcomponent_get_first_property(parent,ICAL_X_PROPERTY);
01545        p != 0;
01546        p = next )
01547   {
01548 
01549     next = icalcomponent_get_next_property(parent,ICAL_X_PROPERTY);
01550 
01551     QString value = QString::fromUtf8(icalproperty_get_x(p));
01552     QString name = icalproperty_get_x_name(p);
01553 
01554     if (name == "X-PILOTID" && !value.isEmpty()) {
01555       incidenceBase->setPilotId(value.toInt());
01556       icalcomponent_remove_property(parent,p);
01557     } else if (name == "X-PILOTSTAT" && !value.isEmpty()) {
01558       incidenceBase->setSyncStatus(value.toInt());
01559       icalcomponent_remove_property(parent,p);
01560     }
01561   }
01562 
01563   // custom properties
01564   readCustomProperties(parent, incidenceBase);
01565 }
01566 
01567 void ICalFormatImpl::readCustomProperties(icalcomponent *parent,CustomProperties *properties)
01568 {
01569   QMap<QCString, QString> customProperties;
01570   QString lastProperty;
01571 
01572   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_X_PROPERTY);
01573 
01574   while (p) {
01575 
01576     QString value = QString::fromUtf8(icalproperty_get_x(p));
01577     const char *name = icalproperty_get_x_name(p);
01578     if ( lastProperty != name ) {
01579       customProperties[name] = value;
01580     } else {
01581       customProperties[name] = customProperties[name].append( "," ).append( value );
01582     }
01583     // kdDebug(5800) << "Set custom property [" << name << '=' << value << ']' << endl;
01584     p = icalcomponent_get_next_property(parent,ICAL_X_PROPERTY);
01585     lastProperty = name;
01586   }
01587 
01588   properties->setCustomProperties(customProperties);
01589 }
01590 
01591 
01592 
01593 void ICalFormatImpl::readRecurrenceRule(icalproperty *rrule,Incidence *incidence )
01594 {
01595 //  kdDebug(5800) << "Read recurrence for " << incidence->summary() << endl;
01596 
01597   Recurrence *recur = incidence->recurrence();
01598 
01599   struct icalrecurrencetype r = icalproperty_get_rrule(rrule);
01600 //   dumpIcalRecurrence(r);
01601 
01602   RecurrenceRule *recurrule = new RecurrenceRule( /*incidence*/ );
01603   recurrule->setStartDt( incidence->dtStart() );
01604   readRecurrence( r, recurrule );
01605   recur->addRRule( recurrule );
01606 }
01607 
01608 void ICalFormatImpl::readExceptionRule( icalproperty *rrule, Incidence *incidence )
01609 {
01610 //  kdDebug(5800) << "Read recurrence for " << incidence->summary() << endl;
01611 
01612   struct icalrecurrencetype r = icalproperty_get_exrule(rrule);
01613 //   dumpIcalRecurrence(r);
01614 
01615   RecurrenceRule *recurrule = new RecurrenceRule( /*incidence*/ );
01616   recurrule->setStartDt( incidence->dtStart() );
01617   readRecurrence( r, recurrule );
01618 
01619   Recurrence *recur = incidence->recurrence();
01620   recur->addExRule( recurrule );
01621 }
01622 
01623 void ICalFormatImpl::readRecurrence( const struct icalrecurrencetype &r, RecurrenceRule* recur )
01624 {
01625   // Generate the RRULE string
01626   recur->mRRule = QString( icalrecurrencetype_as_string( const_cast<struct icalrecurrencetype*>(&r) ) );
01627   // Period
01628   switch ( r.freq ) {
01629     case ICAL_SECONDLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rSecondly ); break;
01630     case ICAL_MINUTELY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rMinutely ); break;
01631     case ICAL_HOURLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rHourly ); break;
01632     case ICAL_DAILY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rDaily ); break;
01633     case ICAL_WEEKLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rWeekly ); break;
01634     case ICAL_MONTHLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rMonthly ); break;
01635     case ICAL_YEARLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rYearly ); break;
01636     case ICAL_NO_RECURRENCE:
01637     default:
01638         recur->setRecurrenceType( RecurrenceRule::rNone );
01639   }
01640   // Frequency
01641   recur->setFrequency( r.interval );
01642 
01643   // Duration & End Date
01644   if ( !icaltime_is_null_time( r.until ) ) {
01645     icaltimetype t;
01646     t = r.until;
01647     // Convert to the correct time zone! it's in UTC by specification.
01648     QDateTime endDate( readICalDateTime(t) );
01649     recur->setEndDt( endDate );
01650   } else {
01651     if (r.count == 0)
01652       recur->setDuration( -1 );
01653     else
01654       recur->setDuration( r.count );
01655   }
01656 
01657   // Week start setting
01658   int wkst = (r.week_start + 5)%7 + 1;
01659   recur->setWeekStart( wkst );
01660 
01661   // And now all BY*
01662   QValueList<int> lst;
01663   int i;
01664   int index = 0;
01665 
01666 #define readSetByList(rrulecomp,setfunc) \
01667   index = 0; \
01668   lst.clear(); \
01669   while ( (i = r.rrulecomp[index++] ) != ICAL_RECURRENCE_ARRAY_MAX ) \
01670     lst.append( i ); \
01671   if ( !lst.isEmpty() ) recur->setfunc( lst );
01672 
01673   // BYSECOND, MINUTE and HOUR, MONTHDAY, YEARDAY, WEEKNUMBER, MONTH
01674   // and SETPOS are standard int lists, so we can treat them with the
01675   // same macro
01676   readSetByList( by_second, setBySeconds );
01677   readSetByList( by_minute, setByMinutes );
01678   readSetByList( by_hour, setByHours );
01679   readSetByList( by_month_day, setByMonthDays );
01680   readSetByList( by_year_day, setByYearDays );
01681   readSetByList( by_week_no, setByWeekNumbers );
01682   readSetByList( by_month, setByMonths );
01683   readSetByList( by_set_pos, setBySetPos );
01684 #undef readSetByList
01685 
01686   // BYDAY is a special case, since it's not an int list
01687   QValueList<RecurrenceRule::WDayPos> wdlst;
01688   short day;
01689   index=0;
01690   while((day = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
01691     RecurrenceRule::WDayPos pos;
01692     pos.setDay( ( icalrecurrencetype_day_day_of_week( day ) + 5 )%7 + 1 );
01693     pos.setPos( icalrecurrencetype_day_position( day ) );
01694 //     kdDebug(5800)<< "    o) By day, index="<<index-1<<", pos="<<pos.Pos<<", day="<<pos.Day<<endl;
01695     wdlst.append( pos );
01696   }
01697   if ( !wdlst.isEmpty() ) recur->setByDays( wdlst );
01698 
01699 
01700   // TODO Store all X- fields of the RRULE inside the recurrence (so they are
01701   // preserved
01702 }
01703 
01704 
01705 void ICalFormatImpl::readAlarm(icalcomponent *alarm,Incidence *incidence)
01706 {
01707 //   kdDebug(5800) << "Read alarm for " << incidence->summary() << endl;
01708 
01709   Alarm* ialarm = incidence->newAlarm();
01710   ialarm->setRepeatCount(0);
01711   ialarm->setEnabled(true);
01712 
01713   // Determine the alarm's action type
01714   icalproperty *p = icalcomponent_get_first_property(alarm,ICAL_ACTION_PROPERTY);
01715   Alarm::Type type = Alarm::Display;
01716   icalproperty_action action = ICAL_ACTION_DISPLAY;
01717   if ( !p ) {
01718     kdDebug(5800) << "Unknown type of alarm, using default" << endl;
01719 //    return;
01720   } else {
01721 
01722     action = icalproperty_get_action(p);
01723     switch ( action ) {
01724       case ICAL_ACTION_DISPLAY:   type = Alarm::Display;  break;
01725       case ICAL_ACTION_AUDIO:     type = Alarm::Audio;  break;
01726       case ICAL_ACTION_PROCEDURE: type = Alarm::Procedure;  break;
01727       case ICAL_ACTION_EMAIL:     type = Alarm::Email;  break;
01728       default:
01729         kdDebug(5800) << "Unknown type of alarm: " << action << endl;
01730 //        type = Alarm::Invalid;
01731     }
01732   }
01733   ialarm->setType(type);
01734 // kdDebug(5800) << " alarm type =" << type << endl;
01735 
01736   p = icalcomponent_get_first_property(alarm,ICAL_ANY_PROPERTY);
01737   while (p) {
01738     icalproperty_kind kind = icalproperty_isa(p);
01739 
01740     switch (kind) {
01741 
01742       case ICAL_TRIGGER_PROPERTY: {
01743         icaltriggertype trigger = icalproperty_get_trigger(p);
01744         if (icaltime_is_null_time(trigger.time)) {
01745           if (icaldurationtype_is_null_duration(trigger.duration)) {
01746             kdDebug(5800) << "ICalFormatImpl::readAlarm(): Trigger has no time and no duration." << endl;
01747           } else {
01748             Duration duration = icaldurationtype_as_int( trigger.duration );
01749             icalparameter *param = icalproperty_get_first_parameter(p,ICAL_RELATED_PARAMETER);
01750             if (param && icalparameter_get_related(param) == ICAL_RELATED_END)
01751               ialarm->setEndOffset(duration);
01752             else
01753               ialarm->setStartOffset(duration);
01754           }
01755         } else {
01756           ialarm->setTime(readICalDateTime(trigger.time));
01757         }
01758         break;
01759       }
01760       case ICAL_DURATION_PROPERTY: {
01761         icaldurationtype duration = icalproperty_get_duration(p);
01762         ialarm->setSnoozeTime( readICalDuration( duration ) );
01763         break;
01764       }
01765       case ICAL_REPEAT_PROPERTY:
01766         ialarm->setRepeatCount(icalproperty_get_repeat(p));
01767         break;
01768 
01769       // Only in DISPLAY and EMAIL and PROCEDURE alarms
01770       case ICAL_DESCRIPTION_PROPERTY: {
01771         QString description = QString::fromUtf8(icalproperty_get_description(p));
01772         switch ( action ) {
01773           case ICAL_ACTION_DISPLAY:
01774             ialarm->setText( description );
01775             break;
01776           case ICAL_ACTION_PROCEDURE:
01777             ialarm->setProgramArguments( description );
01778             break;
01779           case ICAL_ACTION_EMAIL:
01780             ialarm->setMailText( description );
01781             break;
01782           default:
01783             break;
01784         }
01785         break;
01786       }
01787       // Only in EMAIL alarm
01788       case ICAL_SUMMARY_PROPERTY:
01789         ialarm->setMailSubject(QString::fromUtf8(icalproperty_get_summary(p)));
01790         break;
01791 
01792       // Only in EMAIL alarm
01793       case ICAL_ATTENDEE_PROPERTY: {
01794         QString email = QString::fromUtf8(icalproperty_get_attendee(p));
01795         if ( email.startsWith("mailto:", false ) ) {
01796           email = email.mid( 7 );
01797         }
01798         QString name;
01799         icalparameter *param = icalproperty_get_first_parameter(p,ICAL_CN_PARAMETER);
01800         if (param) {
01801           name = QString::fromUtf8(icalparameter_get_cn(param));
01802         }
01803         ialarm->addMailAddress(Person(name, email));
01804         break;
01805       }
01806       // Only in AUDIO and EMAIL and PROCEDURE alarms
01807       case ICAL_ATTACH_PROPERTY: {
01808         Attachment *attach = readAttachment( p );
01809         if ( attach && attach->isUri() ) {
01810           switch ( action ) {
01811             case ICAL_ACTION_AUDIO:
01812               ialarm->setAudioFile( attach->uri() );
01813               break;
01814             case ICAL_ACTION_PROCEDURE:
01815               ialarm->setProgramFile( attach->uri() );
01816               break;
01817             case ICAL_ACTION_EMAIL:
01818               ialarm->addMailAttachment( attach->uri() );
01819               break;
01820             default:
01821               break;
01822           }
01823         } else {
01824           kdDebug() << "Alarm attachments currently only support URIs, but "
01825                        "no binary data" << endl;
01826         }
01827         delete attach;
01828         break;
01829       }
01830       default:
01831         break;
01832     }
01833 
01834     p = icalcomponent_get_next_property(alarm,ICAL_ANY_PROPERTY);
01835   }
01836 
01837   // custom properties
01838   readCustomProperties(alarm, ialarm);
01839 
01840   // TODO: check for consistency of alarm properties
01841 }
01842 
01843 icaldatetimeperiodtype ICalFormatImpl::writeICalDatePeriod( const QDate &date )
01844 {
01845   icaldatetimeperiodtype t;
01846   t.time = writeICalDate( date );
01847   t.period = icalperiodtype_null_period();
01848   return t;
01849 }
01850 
01851 icaldatetimeperiodtype ICalFormatImpl::writeICalDateTimePeriod( const QDateTime &date )
01852 {
01853   icaldatetimeperiodtype t;
01854   t.time = writeICalDateTime( date );
01855   t.period = icalperiodtype_null_period();
01856   return t;
01857 }
01858 
01859 icaltimetype ICalFormatImpl::writeICalDate(const QDate &date)
01860 {
01861   icaltimetype t = icaltime_null_time();
01862 
01863   t.year = date.year();
01864   t.month = date.month();
01865   t.day = date.day();
01866 
01867   t.hour = 0;
01868   t.minute = 0;
01869   t.second = 0;
01870 
01871   t.is_date = 1;
01872 
01873   t.is_utc = 0;
01874 
01875   t.zone = 0;
01876 
01877   return t;
01878 }
01879 
01880 icaltimetype ICalFormatImpl::writeICalDateTime(const QDateTime &datetime)
01881 {
01882   icaltimetype t = icaltime_null_time();
01883 
01884   t.year = datetime.date().year();
01885   t.month = datetime.date().month();
01886   t.day = datetime.date().day();
01887 
01888   t.hour = datetime.time().hour();
01889   t.minute = datetime.time().minute();
01890   t.second = datetime.time().second();
01891 
01892   t.is_date = 0;
01893   t.zone = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01894   t.is_utc = 0;
01895 
01896  // _dumpIcaltime( t );
01897   /* The QDateTime we get passed in is to be considered in the timezone of
01898    * the current calendar (mParent's), or, if there is none, to be floating.
01899    * In the later case store a floating time, in the former normalize to utc. */
01900   if (mParent->timeZoneId().isEmpty())
01901     t = icaltime_convert_to_zone( t, 0 ); //make floating timezone
01902   else {
01903     icaltimezone* tz = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01904     icaltimezone* utc = icaltimezone_get_utc_timezone();
01905     if ( tz != utc ) {
01906       t.zone = tz;
01907       t = icaltime_convert_to_zone( t, utc );
01908     } else {
01909       t.is_utc = 1;
01910       t.zone = utc;
01911     }
01912   }
01913 //  _dumpIcaltime( t );
01914 
01915   return t;
01916 }
01917 
01918 QDateTime ICalFormatImpl::readICalDateTime( icaltimetype& t, icaltimezone* tz )
01919 {
01920 //   kdDebug(5800) << "ICalFormatImpl::readICalDateTime()" << endl;
01921   icaltimezone *zone = tz;
01922   if ( tz && t.is_utc == 0 ) { // Only use the TZ if time is not UTC.
01923     // FIXME: We'll need to make sure to apply the appropriate TZ, not just
01924     //        the first one found.
01925     t.zone = tz;
01926     t.is_utc = (tz == icaltimezone_get_utc_timezone())?1:0;
01927   } else {
01928     zone = icaltimezone_get_utc_timezone();
01929   }
01930   //_dumpIcaltime( t );
01931 
01932   // Convert to view time
01933   if ( !mParent->timeZoneId().isEmpty() && t.zone ) {
01934 //    kdDebug(5800) << "--- Converting time from: " << icaltimezone_get_tzid( const_cast<icaltimezone*>( t.zone ) ) << " (" << ICalDate2QDate(t) << ")." << endl;
01935     icaltimezone* viewTimeZone = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01936     icaltimezone_convert_time(  &t, zone, viewTimeZone );
01937 //    kdDebug(5800) << "--- Converted to zone " << mParent->timeZoneId() << " (" << ICalDate2QDate(t) << ")." << endl;
01938   }
01939 
01940   return ICalDate2QDate(t);
01941 }
01942 
01943 QDate ICalFormatImpl::readICalDate(icaltimetype t)
01944 {
01945   return ICalDate2QDate(t).date();
01946 }
01947 
01948 icaldurationtype ICalFormatImpl::writeICalDuration(int seconds)
01949 {
01950   // should be able to use icaldurationtype_from_int(), except we know
01951   // that some older tools do not properly support weeks. So we never
01952   // set a week duration, only days
01953 
01954   icaldurationtype d;
01955 
01956   d.is_neg  = (seconds<0)?1:0;
01957   if (seconds<0) seconds = -seconds;
01958 
01959   d.weeks    = 0;
01960   d.days     = seconds / gSecondsPerDay;
01961   seconds   %= gSecondsPerDay;
01962   d.hours    = seconds / gSecondsPerHour;
01963   seconds   %= gSecondsPerHour;
01964   d.minutes  = seconds / gSecondsPerMinute;
01965   seconds   %= gSecondsPerMinute;
01966   d.seconds  = seconds;
01967 
01968   return d;
01969 }
01970 
01971 int ICalFormatImpl::readICalDuration(icaldurationtype d)
01972 {
01973   int result = 0;
01974 
01975   result += d.weeks   * gSecondsPerWeek;
01976   result += d.days    * gSecondsPerDay;
01977   result += d.hours   * gSecondsPerHour;
01978   result += d.minutes * gSecondsPerMinute;
01979   result += d.seconds;
01980 
01981   if (d.is_neg) result *= -1;
01982 
01983   return result;
01984 }
01985 
01986 icalcomponent *ICalFormatImpl::createCalendarComponent(Calendar *cal)
01987 {
01988   icalcomponent *calendar;
01989 
01990   // Root component
01991   calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
01992 
01993   icalproperty *p;
01994 
01995   // Product Identifier
01996   p = icalproperty_new_prodid(CalFormat::productId().utf8());
01997   icalcomponent_add_property(calendar,p);
01998 
01999   // TODO: Add time zone
02000 
02001   // iCalendar version (2.0)
02002   p = icalproperty_new_version(const_cast<char *>(_ICAL_VERSION));
02003   icalcomponent_add_property(calendar,p);
02004 
02005   // Custom properties
02006   if( cal != 0 )
02007     writeCustomProperties(calendar, cal);
02008 
02009   return calendar;
02010 }
02011 
02012 
02013 
02014 // take a raw vcalendar (i.e. from a file on disk, clipboard, etc. etc.
02015 // and break it down from its tree-like format into the dictionary format
02016 // that is used internally in the ICalFormatImpl.
02017 bool ICalFormatImpl::populate( Calendar *cal, icalcomponent *calendar)
02018 {
02019   // this function will populate the caldict dictionary and other event
02020   // lists. It turns vevents into Events and then inserts them.
02021 
02022     if (!calendar) return false;
02023 
02024 // TODO: check for METHOD
02025 
02026   icalproperty *p;
02027 
02028   p = icalcomponent_get_first_property(calendar,ICAL_PRODID_PROPERTY);
02029   if (!p) {
02030     kdDebug(5800) << "No PRODID property found" << endl;
02031     mLoadedProductId = "";
02032   } else {
02033     mLoadedProductId = QString::fromUtf8(icalproperty_get_prodid(p));
02034 //    kdDebug(5800) << "VCALENDAR prodid: '" << mLoadedProductId << "'" << endl;
02035 
02036     delete mCompat;
02037     mCompat = CompatFactory::createCompat( mLoadedProductId );
02038   }
02039 
02040   p = icalcomponent_get_first_property(calendar,ICAL_VERSION_PROPERTY);
02041   if (!p) {
02042     kdDebug(5800) << "No VERSION property found" << endl;
02043     mParent->setException(new ErrorFormat(ErrorFormat::CalVersionUnknown));
02044     return false;
02045   } else {
02046     const char *version = icalproperty_get_version(p);
02047     if ( !version ) {
02048       kdDebug(5800) << "No VERSION property found" << endl;
02049       mParent->setException( new ErrorFormat(
02050                                ErrorFormat::CalVersionUnknown,
02051                                i18n( "No VERSION property found" ) ) );
02052       return false;
02053     }
02054 
02055 //    kdDebug(5800) << "VCALENDAR version: '" << version << "'" << endl;
02056 
02057     if (strcmp(version,"1.0") == 0) {
02058       kdDebug(5800) << "Expected iCalendar, got vCalendar" << endl;
02059       mParent->setException(new ErrorFormat(ErrorFormat::CalVersion1,
02060                             i18n("Expected iCalendar format")));
02061       return false;
02062     } else if (strcmp(version,"2.0") != 0) {
02063       kdDebug(5800) << "Expected iCalendar, got unknown format" << endl;
02064       mParent->setException(new ErrorFormat(ErrorFormat::CalVersionUnknown));
02065       return false;
02066     }
02067   }
02068 
02069   // custom properties
02070   readCustomProperties(calendar, cal);
02071 
02072 // TODO: set time zone
02073 
02074   // read a VTIMEZONE if there is one
02075   icalcomponent *ctz =
02076     icalcomponent_get_first_component( calendar, ICAL_VTIMEZONE_COMPONENT );
02077 
02078   // Store all events with a relatedTo property in a list for post-processing
02079   mEventsRelate.clear();
02080   mTodosRelate.clear();
02081   // TODO: make sure that only actually added events go to this lists.
02082 
02083   icalcomponent *c;
02084 
02085   // Iterate through all todos
02086   c = icalcomponent_get_first_component(calendar,ICAL_VTODO_COMPONENT);
02087   cal->beginBatchAdding();
02088   while (c) {
02089 //    kdDebug(5800) << "----Todo found" << endl;
02090     Todo *todo = readTodo(c);
02091     if (todo) {
02092       if (!cal->todo(todo->uid())) {
02093         cal->addTodo(todo);
02094       } else {
02095         delete todo;
02096         mTodosRelate.remove( todo );
02097       }
02098     }
02099     c = icalcomponent_get_next_component(calendar,ICAL_VTODO_COMPONENT);
02100   }
02101 
02102   // Iterate through all events
02103   c = icalcomponent_get_first_component(calendar,ICAL_VEVENT_COMPONENT);
02104   while (c) {
02105 //    kdDebug(5800) << "----Event found" << endl;
02106     Event *event = readEvent(c, ctz);
02107     if (event) {
02108       if (!cal->event(event->uid())) {
02109         cal->addEvent(event);
02110       } else {
02111         delete event;
02112         mEventsRelate.remove( event );
02113       }
02114     }
02115     c = icalcomponent_get_next_component(calendar,ICAL_VEVENT_COMPONENT);
02116   }
02117 
02118   // Iterate through all journals
02119   c = icalcomponent_get_first_component(calendar,ICAL_VJOURNAL_COMPONENT);
02120   while (c) {
02121 //    kdDebug(5800) << "----Journal found" << endl;
02122     Journal *journal = readJournal(c);
02123     if (journal) {
02124       if (!cal->journal(journal->uid())) {
02125         cal->addJournal(journal);
02126       } else {
02127         delete journal;
02128       }
02129     }
02130     c = icalcomponent_get_next_component(calendar,ICAL_VJOURNAL_COMPONENT);
02131   }
02132 
02133   cal->endBatchAdding();
02134 
02135   // Post-Process list of events with relations, put Event objects in relation
02136   Event::List::ConstIterator eIt;
02137   for ( eIt = mEventsRelate.begin(); eIt != mEventsRelate.end(); ++eIt ) {
02138     (*eIt)->setRelatedTo( cal->incidence( (*eIt)->relatedToUid() ) );
02139   }
02140   Todo::List::ConstIterator tIt;
02141   for ( tIt = mTodosRelate.begin(); tIt != mTodosRelate.end(); ++tIt ) {
02142     (*tIt)->setRelatedTo( cal->incidence( (*tIt)->relatedToUid() ) );
02143    }
02144 
02145   return true;
02146 }
02147 
02148 QString ICalFormatImpl::extractErrorProperty(icalcomponent *c)
02149 {
02150 //  kdDebug(5800) << "ICalFormatImpl:extractErrorProperty: "
02151 //            << icalcomponent_as_ical_string(c) << endl;
02152 
02153   QString errorMessage;
02154 
02155   icalproperty *error;
02156   error = icalcomponent_get_first_property(c,ICAL_XLICERROR_PROPERTY);
02157   while(error) {
02158     errorMessage += icalproperty_get_xlicerror(error);
02159     errorMessage += "\n";
02160     error = icalcomponent_get_next_property(c,ICAL_XLICERROR_PROPERTY);
02161   }
02162 
02163 //  kdDebug(5800) << "ICalFormatImpl:extractErrorProperty: " << errorMessage << endl;
02164 
02165   return errorMessage;
02166 }
02167 
02168 void ICalFormatImpl::dumpIcalRecurrence(icalrecurrencetype r)
02169 {
02170   int i;
02171 
02172   kdDebug(5800) << " Freq: " << r.freq << endl;
02173   kdDebug(5800) << " Until: " << icaltime_as_ical_string(r.until) << endl;
02174   kdDebug(5800) << " Count: " << r.count << endl;
02175   if (r.by_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02176     int index = 0;
02177     QString out = " By Day: ";
02178     while((i = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02179       out.append(QString::number(i) + " ");
02180     }
02181     kdDebug(5800) << out << endl;
02182   }
02183   if (r.by_month_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02184     int index = 0;
02185     QString out = " By Month Day: ";
02186     while((i = r.by_month_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02187       out.append(QString::number(i) + " ");
02188     }
02189     kdDebug(5800) << out << endl;
02190   }
02191   if (r.by_year_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02192     int index = 0;
02193     QString out = " By Year Day: ";
02194     while((i = r.by_year_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02195       out.append(QString::number(i) + " ");
02196     }
02197     kdDebug(5800) << out << endl;
02198   }
02199   if (r.by_month[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02200     int index = 0;
02201     QString out = " By Month: ";
02202     while((i = r.by_month[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02203       out.append(QString::number(i) + " ");
02204     }
02205     kdDebug(5800) << out << endl;
02206   }
02207   if (r.by_set_pos[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02208     int index = 0;
02209     QString out = " By Set Pos: ";
02210     while((i = r.by_set_pos[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02211       kdDebug(5800) << "========= " << i << endl;
02212       out.append(QString::number(i) + " ");
02213     }
02214     kdDebug(5800) << out << endl;
02215   }
02216 }
02217 
02218 icalcomponent *ICalFormatImpl::createScheduleComponent(IncidenceBase *incidence,
02219                                                    Scheduler::Method method)
02220 {
02221   icalcomponent *message = createCalendarComponent();
02222 
02223   icalproperty_method icalmethod = ICAL_METHOD_NONE;
02224 
02225   switch (method) {
02226     case Scheduler::Publish:
02227       icalmethod = ICAL_METHOD_PUBLISH;
02228       break;
02229     case Scheduler::Request:
02230       icalmethod = ICAL_METHOD_REQUEST;
02231       break;
02232     case Scheduler::Refresh:
02233       icalmethod = ICAL_METHOD_REFRESH;
02234       break;
02235     case Scheduler::Cancel:
02236       icalmethod = ICAL_METHOD_CANCEL;
02237       break;
02238     case Scheduler::Add:
02239       icalmethod = ICAL_METHOD_ADD;
02240       break;
02241     case Scheduler::Reply:
02242       icalmethod = ICAL_METHOD_REPLY;
02243       break;
02244     case Scheduler::Counter:
02245       icalmethod = ICAL_METHOD_COUNTER;
02246       break;
02247     case Scheduler::Declinecounter:
02248       icalmethod = ICAL_METHOD_DECLINECOUNTER;
02249       break;
02250     default:
02251       kdDebug(5800) << "ICalFormat::createScheduleMessage(): Unknow method" << endl;
02252       return message;
02253   }
02254 
02255   icalcomponent_add_property(message,icalproperty_new_method(icalmethod));
02256 
02257   icalcomponent *inc = writeIncidence( incidence, method );
02258   /*
02259    * RFC 2446 states in section 3.4.3 ( REPLY to a VTODO ), that
02260    * a REQUEST-STATUS property has to be present. For the other two, event and
02261    * free busy, it can be there, but is optional. Until we do more
02262    * fine grained handling, assume all is well. Note that this is the
02263    * status of the _request_, not the attendee. Just to avoid confusion.
02264    * - till
02265    */
02266   if ( icalmethod == ICAL_METHOD_REPLY ) {
02267     struct icalreqstattype rst;
02268     rst.code = ICAL_2_0_SUCCESS_STATUS;
02269     rst.desc = 0;
02270     rst.debug = 0;
02271     icalcomponent_add_property( inc, icalproperty_new_requeststatus( rst ) );
02272   }
02273   icalcomponent_add_component( message, inc );
02274 
02275   return message;
02276 }
KDE Home | KDE Accessibility Home | Description of Access Keys