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()*60)));
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         icalperiodtype icalperiod = icalproperty_get_freebusy(p);
01086         QDateTime period_start = readICalDateTime(icalperiod.start);
01087         Period period;
01088         if ( !icaltime_is_null_time(icalperiod.end) ) {
01089           QDateTime period_end = readICalDateTime(icalperiod.end);
01090           period = Period(period_start, period_end);
01091         } else {
01092           Duration duration = readICalDuration( icalperiod.duration );
01093           period = Period(period_start, duration);
01094         }
01095         QCString param = icalproperty_get_parameter_as_string( p, "X-SUMMARY" );
01096         period.setSummary( QString::fromUtf8( KCodecs::base64Decode( param ) ) );
01097         param = icalproperty_get_parameter_as_string( p, "X-LOCATION" );
01098         period.setLocation( QString::fromUtf8( KCodecs::base64Decode( param ) ) );
01099         periods.append( period );
01100         break;}
01101 
01102       default:
01103 //        kdDebug(5800) << "ICalFormatImpl::readFreeBusy(): Unknown property: "
01104 //                      << kind << endl;
01105       break;
01106     }
01107     p = icalcomponent_get_next_property(vfreebusy,ICAL_ANY_PROPERTY);
01108   }
01109   freebusy->addPeriods( periods );
01110 
01111   return freebusy;
01112 }
01113 
01114 Journal *ICalFormatImpl::readJournal(icalcomponent *vjournal)
01115 {
01116   Journal *journal = new Journal;
01117 
01118   readIncidence(vjournal, 0, journal); // FIXME tz?
01119 
01120   return journal;
01121 }
01122 
01123 Attendee *ICalFormatImpl::readAttendee(icalproperty *attendee)
01124 {
01125   icalparameter *p = 0;
01126 
01127   QString email = QString::fromUtf8(icalproperty_get_attendee(attendee));
01128   if ( email.startsWith( "mailto:", false ) ) {
01129     email = email.mid( 7 );
01130   }
01131 
01132   QString name;
01133   QString uid = QString::null;
01134   p = icalproperty_get_first_parameter(attendee,ICAL_CN_PARAMETER);
01135   if (p) {
01136     name = QString::fromUtf8(icalparameter_get_cn(p));
01137   } else {
01138   }
01139 
01140   bool rsvp=false;
01141   p = icalproperty_get_first_parameter(attendee,ICAL_RSVP_PARAMETER);
01142   if (p) {
01143     icalparameter_rsvp rsvpParameter = icalparameter_get_rsvp(p);
01144     if (rsvpParameter == ICAL_RSVP_TRUE) rsvp = true;
01145   }
01146 
01147   Attendee::PartStat status = Attendee::NeedsAction;
01148   p = icalproperty_get_first_parameter(attendee,ICAL_PARTSTAT_PARAMETER);
01149   if (p) {
01150     icalparameter_partstat partStatParameter = icalparameter_get_partstat(p);
01151     switch(partStatParameter) {
01152       default:
01153       case ICAL_PARTSTAT_NEEDSACTION:
01154         status = Attendee::NeedsAction;
01155         break;
01156       case ICAL_PARTSTAT_ACCEPTED:
01157         status = Attendee::Accepted;
01158         break;
01159       case ICAL_PARTSTAT_DECLINED:
01160         status = Attendee::Declined;
01161         break;
01162       case ICAL_PARTSTAT_TENTATIVE:
01163         status = Attendee::Tentative;
01164         break;
01165       case ICAL_PARTSTAT_DELEGATED:
01166         status = Attendee::Delegated;
01167         break;
01168       case ICAL_PARTSTAT_COMPLETED:
01169         status = Attendee::Completed;
01170         break;
01171       case ICAL_PARTSTAT_INPROCESS:
01172         status = Attendee::InProcess;
01173         break;
01174     }
01175   }
01176 
01177   Attendee::Role role = Attendee::ReqParticipant;
01178   p = icalproperty_get_first_parameter(attendee,ICAL_ROLE_PARAMETER);
01179   if (p) {
01180     icalparameter_role roleParameter = icalparameter_get_role(p);
01181     switch(roleParameter) {
01182       case ICAL_ROLE_CHAIR:
01183         role = Attendee::Chair;
01184         break;
01185       default:
01186       case ICAL_ROLE_REQPARTICIPANT:
01187         role = Attendee::ReqParticipant;
01188         break;
01189       case ICAL_ROLE_OPTPARTICIPANT:
01190         role = Attendee::OptParticipant;
01191         break;
01192       case ICAL_ROLE_NONPARTICIPANT:
01193         role = Attendee::NonParticipant;
01194         break;
01195     }
01196   }
01197 
01198   p = icalproperty_get_first_parameter(attendee,ICAL_X_PARAMETER);
01199   uid = icalparameter_get_xvalue(p);
01200   // This should be added, but there seems to be a libical bug here.
01201   // TODO: does this work now in libical-0.24 or greater?
01202   /*while (p) {
01203    // if (icalparameter_get_xname(p) == "X-UID") {
01204     uid = icalparameter_get_xvalue(p);
01205     p = icalproperty_get_next_parameter(attendee,ICAL_X_PARAMETER);
01206   } */
01207 
01208   Attendee *a = new Attendee( name, email, rsvp, status, role, uid );
01209 
01210   p = icalproperty_get_first_parameter( attendee, ICAL_DELEGATEDTO_PARAMETER );
01211   if ( p )
01212     a->setDelegate( icalparameter_get_delegatedto( p ) );
01213 
01214   p = icalproperty_get_first_parameter( attendee, ICAL_DELEGATEDFROM_PARAMETER );
01215   if ( p )
01216     a->setDelegator( icalparameter_get_delegatedfrom( p ) );
01217 
01218   return a;
01219 }
01220 
01221 Person ICalFormatImpl::readOrganizer( icalproperty *organizer )
01222 {
01223   QString email = QString::fromUtf8(icalproperty_get_organizer(organizer));
01224   if ( email.startsWith( "mailto:", false ) ) {
01225     email = email.mid( 7 );
01226   }
01227   QString cn;
01228 
01229   icalparameter *p = icalproperty_get_first_parameter(
01230              organizer, ICAL_CN_PARAMETER );
01231 
01232   if ( p ) {
01233     cn = QString::fromUtf8( icalparameter_get_cn( p ) );
01234   }
01235   Person org( cn, email );
01236   // TODO: Treat sent-by, dir and language here, too
01237   return org;
01238 }
01239 
01240 Attachment *ICalFormatImpl::readAttachment(icalproperty *attach)
01241 {
01242   Attachment *attachment = 0;
01243 
01244   const char *p;
01245   icalvalue *value = icalproperty_get_value( attach );
01246 
01247   switch( icalvalue_isa( value ) ) {
01248   case ICAL_ATTACH_VALUE:
01249   {
01250     icalattach *a = icalproperty_get_attach( attach );
01251     if ( !icalattach_get_is_url( a ) ) {
01252       p = (const char *)icalattach_get_data( a );
01253       if ( p ) {
01254         attachment = new Attachment( p );
01255       }
01256     } else {
01257       p = icalattach_get_url( a );
01258       if ( p ) {
01259         attachment = new Attachment( QString::fromUtf8( p ) );
01260       }
01261     }
01262     break;
01263   }
01264   case ICAL_BINARY_VALUE:
01265   {
01266     icalattach *a = icalproperty_get_attach( attach );
01267     p = (const char *)icalattach_get_data( a );
01268     if ( p ) {
01269       attachment = new Attachment( p );
01270     }
01271     break;
01272   }
01273   case ICAL_URI_VALUE:
01274     p = icalvalue_get_uri( value );
01275     attachment = new Attachment( QString::fromUtf8( p ) );
01276     break;
01277   default:
01278     break;
01279   }
01280 
01281  if ( attachment ) {
01282     icalparameter *p =
01283       icalproperty_get_first_parameter( attach, ICAL_FMTTYPE_PARAMETER );
01284     if ( p ) {
01285       attachment->setMimeType( QString( icalparameter_get_fmttype( p ) ) );
01286     }
01287 
01288     p = icalproperty_get_first_parameter( attach, ICAL_X_PARAMETER );
01289     while ( p ) {
01290       QString xname = QString( icalparameter_get_xname( p ) ).upper();
01291       QString xvalue = QString::fromUtf8( icalparameter_get_xvalue( p ) );
01292       if ( xname == "X-CONTENT-DISPOSITION" ) {
01293         attachment->setShowInline( xvalue.lower() == "inline" );
01294       }
01295       if ( xname == "X-LABEL" ) {
01296         attachment->setLabel( xvalue );
01297       }
01298       p = icalproperty_get_next_parameter( attach, ICAL_X_PARAMETER );
01299     }
01300 
01301     p = icalproperty_get_first_parameter( attach, ICAL_X_PARAMETER );
01302     while ( p ) {
01303       if ( strncmp( icalparameter_get_xname( p ), "X-LABEL", 7 ) == 0 ) {
01304         attachment->setLabel( QString::fromUtf8( icalparameter_get_xvalue( p ) ) );
01305       }
01306       p = icalproperty_get_next_parameter( attach, ICAL_X_PARAMETER );
01307     }
01308   }
01309 
01310   return attachment;
01311 }
01312 
01313 void ICalFormatImpl::readIncidence(icalcomponent *parent, icaltimezone *tz, Incidence *incidence)
01314 {
01315   readIncidenceBase(parent,incidence);
01316 
01317   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_ANY_PROPERTY);
01318 
01319   const char *text;
01320   int intvalue, inttext;
01321   icaltimetype icaltime;
01322   icaldurationtype icalduration;
01323 
01324   QStringList categories;
01325 
01326   while (p) {
01327     icalproperty_kind kind = icalproperty_isa(p);
01328     switch (kind) {
01329 
01330       case ICAL_CREATED_PROPERTY:
01331         icaltime = icalproperty_get_created(p);
01332         incidence->setCreated(readICalDateTime(icaltime, tz));
01333         break;
01334 
01335       case ICAL_SEQUENCE_PROPERTY:  // sequence
01336         intvalue = icalproperty_get_sequence(p);
01337         incidence->setRevision(intvalue);
01338         break;
01339 
01340       case ICAL_LASTMODIFIED_PROPERTY:  // last modification date
01341         icaltime = icalproperty_get_lastmodified(p);
01342         incidence->setLastModified(readICalDateTime(icaltime, tz));
01343         break;
01344 
01345       case ICAL_DTSTART_PROPERTY:  // start date and time
01346         icaltime = icalproperty_get_dtstart(p);
01347         if (icaltime.is_date) {
01348           incidence->setDtStart(QDateTime(readICalDate(icaltime),QTime(0,0,0)));
01349           incidence->setFloats( true );
01350         } else {
01351           incidence->setDtStart(readICalDateTime(icaltime, tz));
01352           incidence->setFloats( false );
01353         }
01354         break;
01355 
01356       case ICAL_DURATION_PROPERTY:  // start date and time
01357         icalduration = icalproperty_get_duration(p);
01358         incidence->setDuration(readICalDuration(icalduration));
01359         break;
01360 
01361       case ICAL_DESCRIPTION_PROPERTY:  // description
01362         text = icalproperty_get_description(p);
01363         incidence->setDescription(QString::fromUtf8(text));
01364         break;
01365 
01366       case ICAL_SUMMARY_PROPERTY:  // summary
01367         text = icalproperty_get_summary(p);
01368         incidence->setSummary(QString::fromUtf8(text));
01369         break;
01370 
01371       case ICAL_LOCATION_PROPERTY:  // location
01372         text = icalproperty_get_location(p);
01373         incidence->setLocation(QString::fromUtf8(text));
01374         break;
01375 
01376       case ICAL_STATUS_PROPERTY: {  // status
01377         Incidence::Status stat;
01378         switch (icalproperty_get_status(p)) {
01379           case ICAL_STATUS_TENTATIVE:   stat = Incidence::StatusTentative; break;
01380           case ICAL_STATUS_CONFIRMED:   stat = Incidence::StatusConfirmed; break;
01381           case ICAL_STATUS_COMPLETED:   stat = Incidence::StatusCompleted; break;
01382           case ICAL_STATUS_NEEDSACTION: stat = Incidence::StatusNeedsAction; break;
01383           case ICAL_STATUS_CANCELLED:   stat = Incidence::StatusCanceled; break;
01384           case ICAL_STATUS_INPROCESS:   stat = Incidence::StatusInProcess; break;
01385           case ICAL_STATUS_DRAFT:       stat = Incidence::StatusDraft; break;
01386           case ICAL_STATUS_FINAL:       stat = Incidence::StatusFinal; break;
01387           case ICAL_STATUS_X:
01388             incidence->setCustomStatus(QString::fromUtf8(icalvalue_get_x(icalproperty_get_value(p))));
01389             stat = Incidence::StatusX;
01390             break;
01391           case ICAL_STATUS_NONE:
01392           default:                      stat = Incidence::StatusNone; break;
01393         }
01394         if (stat != Incidence::StatusX)
01395           incidence->setStatus(stat);
01396         break;
01397       }
01398 
01399       case ICAL_PRIORITY_PROPERTY:  // priority
01400         intvalue = icalproperty_get_priority( p );
01401         if ( mCompat )
01402           intvalue = mCompat->fixPriority( intvalue );
01403         incidence->setPriority( intvalue );
01404         break;
01405 
01406       case ICAL_CATEGORIES_PROPERTY:  // categories
01407         text = icalproperty_get_categories(p);
01408         categories.append(QString::fromUtf8(text));
01409         break;
01410 
01411       case ICAL_RRULE_PROPERTY:
01412         readRecurrenceRule( p, incidence );
01413         break;
01414 
01415       case ICAL_RDATE_PROPERTY: {
01416         icaldatetimeperiodtype rd = icalproperty_get_rdate( p );
01417         if ( icaltime_is_valid_time( rd.time ) ) {
01418           if ( icaltime_is_date( rd.time ) ) {
01419             incidence->recurrence()->addRDate( readICalDate( rd.time ) );
01420           } else {
01421             incidence->recurrence()->addRDateTime( readICalDateTime( rd.time, tz ) );
01422           }
01423         } else {
01424           // TODO: RDates as period are not yet implemented!
01425         }
01426         break; }
01427 
01428       case ICAL_EXRULE_PROPERTY:
01429         readExceptionRule( p, incidence );
01430         break;
01431 
01432       case ICAL_EXDATE_PROPERTY:
01433         icaltime = icalproperty_get_exdate(p);
01434         if ( icaltime_is_date(icaltime) ) {
01435           incidence->recurrence()->addExDate( readICalDate(icaltime) );
01436         } else {
01437           incidence->recurrence()->addExDateTime( readICalDateTime(icaltime, tz) );
01438         }
01439         break;
01440 
01441       case ICAL_CLASS_PROPERTY:
01442         inttext = icalproperty_get_class(p);
01443         if (inttext == ICAL_CLASS_PUBLIC ) {
01444           incidence->setSecrecy(Incidence::SecrecyPublic);
01445         } else if (inttext == ICAL_CLASS_CONFIDENTIAL ) {
01446           incidence->setSecrecy(Incidence::SecrecyConfidential);
01447         } else {
01448           incidence->setSecrecy(Incidence::SecrecyPrivate);
01449         }
01450         break;
01451 
01452       case ICAL_ATTACH_PROPERTY:  // attachments
01453         incidence->addAttachment(readAttachment(p));
01454         break;
01455 
01456       default:
01457 //        kdDebug(5800) << "ICALFormat::readIncidence(): Unknown property: " << kind
01458 //                  << endl;
01459         break;
01460     }
01461 
01462     p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY);
01463   }
01464 
01465   // Set the scheduling ID
01466   const QString uid = incidence->customProperty( "LIBKCAL", "ID" );
01467   if ( !uid.isNull() ) {
01468     // The UID stored in incidencebase is actually the scheduling ID
01469     // It has to be stored in the iCal UID component for compatibility
01470     // with other iCal applications
01471     incidence->setSchedulingID( incidence->uid() );
01472     incidence->setUid( uid );
01473   }
01474 
01475   // Now that recurrence and exception stuff is completely set up,
01476   // do any backwards compatibility adjustments.
01477   if ( incidence->doesRecur() && mCompat )
01478       mCompat->fixRecurrence( incidence );
01479 
01480   // add categories
01481   incidence->setCategories(categories);
01482 
01483   // iterate through all alarms
01484   for (icalcomponent *alarm = icalcomponent_get_first_component(parent,ICAL_VALARM_COMPONENT);
01485        alarm;
01486        alarm = icalcomponent_get_next_component(parent,ICAL_VALARM_COMPONENT)) {
01487     readAlarm(alarm,incidence);
01488   }
01489   // Fix incorrect alarm settings by other applications (like outloook 9)
01490   if ( mCompat ) mCompat->fixAlarms( incidence );
01491 
01492 }
01493 
01494 void ICalFormatImpl::readIncidenceBase(icalcomponent *parent,IncidenceBase *incidenceBase)
01495 {
01496   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_ANY_PROPERTY);
01497 
01498   while (p) {
01499     icalproperty_kind kind = icalproperty_isa(p);
01500     switch (kind) {
01501 
01502       case ICAL_UID_PROPERTY:  // unique id
01503         incidenceBase->setUid(QString::fromUtf8(icalproperty_get_uid(p)));
01504         break;
01505 
01506       case ICAL_ORGANIZER_PROPERTY:  // organizer
01507         incidenceBase->setOrganizer( readOrganizer(p));
01508         break;
01509 
01510       case ICAL_ATTENDEE_PROPERTY:  // attendee
01511         incidenceBase->addAttendee(readAttendee(p));
01512         break;
01513 
01514       case ICAL_COMMENT_PROPERTY:
01515         incidenceBase->addComment(
01516             QString::fromUtf8(icalproperty_get_comment(p)));
01517         break;
01518 
01519       default:
01520         break;
01521     }
01522 
01523     p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY);
01524   }
01525 
01526   // kpilot stuff
01527   // TODO: move this application-specific code to kpilot
01528   // need to get X-PILOT* attributes out, set correct properties, and get
01529   // rid of them...
01530   // Pointer fun, as per libical documentation
01531   // (documented in UsingLibical.txt)
01532   icalproperty *next =0;
01533 
01534   for ( p = icalcomponent_get_first_property(parent,ICAL_X_PROPERTY);
01535        p != 0;
01536        p = next )
01537   {
01538 
01539     next = icalcomponent_get_next_property(parent,ICAL_X_PROPERTY);
01540 
01541     QString value = QString::fromUtf8(icalproperty_get_x(p));
01542     QString name = icalproperty_get_x_name(p);
01543 
01544     if (name == "X-PILOTID" && !value.isEmpty()) {
01545       incidenceBase->setPilotId(value.toInt());
01546       icalcomponent_remove_property(parent,p);
01547     } else if (name == "X-PILOTSTAT" && !value.isEmpty()) {
01548       incidenceBase->setSyncStatus(value.toInt());
01549       icalcomponent_remove_property(parent,p);
01550     }
01551   }
01552 
01553   // custom properties
01554   readCustomProperties(parent, incidenceBase);
01555 }
01556 
01557 void ICalFormatImpl::readCustomProperties(icalcomponent *parent,CustomProperties *properties)
01558 {
01559   QMap<QCString, QString> customProperties;
01560   QString lastProperty;
01561 
01562   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_X_PROPERTY);
01563 
01564   while (p) {
01565 
01566     QString value = QString::fromUtf8(icalproperty_get_x(p));
01567     const char *name = icalproperty_get_x_name(p);
01568     if ( lastProperty != name ) {
01569       customProperties[name] = value;
01570     } else {
01571       customProperties[name] = customProperties[name].append( "," ).append( value );
01572     }
01573     // kdDebug(5800) << "Set custom property [" << name << '=' << value << ']' << endl;
01574     p = icalcomponent_get_next_property(parent,ICAL_X_PROPERTY);
01575     lastProperty = name;
01576   }
01577 
01578   properties->setCustomProperties(customProperties);
01579 }
01580 
01581 
01582 
01583 void ICalFormatImpl::readRecurrenceRule(icalproperty *rrule,Incidence *incidence )
01584 {
01585 //  kdDebug(5800) << "Read recurrence for " << incidence->summary() << endl;
01586 
01587   Recurrence *recur = incidence->recurrence();
01588 
01589   struct icalrecurrencetype r = icalproperty_get_rrule(rrule);
01590 //   dumpIcalRecurrence(r);
01591 
01592   RecurrenceRule *recurrule = new RecurrenceRule( /*incidence*/ );
01593   recurrule->setStartDt( incidence->dtStart() );
01594   readRecurrence( r, recurrule );
01595   recur->addRRule( recurrule );
01596 }
01597 
01598 void ICalFormatImpl::readExceptionRule( icalproperty *rrule, Incidence *incidence )
01599 {
01600 //  kdDebug(5800) << "Read recurrence for " << incidence->summary() << endl;
01601 
01602   struct icalrecurrencetype r = icalproperty_get_exrule(rrule);
01603 //   dumpIcalRecurrence(r);
01604 
01605   RecurrenceRule *recurrule = new RecurrenceRule( /*incidence*/ );
01606   recurrule->setStartDt( incidence->dtStart() );
01607   readRecurrence( r, recurrule );
01608 
01609   Recurrence *recur = incidence->recurrence();
01610   recur->addExRule( recurrule );
01611 }
01612 
01613 void ICalFormatImpl::readRecurrence( const struct icalrecurrencetype &r, RecurrenceRule* recur )
01614 {
01615   // Generate the RRULE string
01616   recur->mRRule = QString( icalrecurrencetype_as_string( const_cast<struct icalrecurrencetype*>(&r) ) );
01617   // Period
01618   switch ( r.freq ) {
01619     case ICAL_SECONDLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rSecondly ); break;
01620     case ICAL_MINUTELY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rMinutely ); break;
01621     case ICAL_HOURLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rHourly ); break;
01622     case ICAL_DAILY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rDaily ); break;
01623     case ICAL_WEEKLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rWeekly ); break;
01624     case ICAL_MONTHLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rMonthly ); break;
01625     case ICAL_YEARLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rYearly ); break;
01626     case ICAL_NO_RECURRENCE:
01627     default:
01628         recur->setRecurrenceType( RecurrenceRule::rNone );
01629   }
01630   // Frequency
01631   recur->setFrequency( r.interval );
01632 
01633   // Duration & End Date
01634   if ( !icaltime_is_null_time( r.until ) ) {
01635     icaltimetype t;
01636     t = r.until;
01637     // Convert to the correct time zone! it's in UTC by specification.
01638     QDateTime endDate( readICalDateTime(t) );
01639     recur->setEndDt( endDate );
01640   } else {
01641     if (r.count == 0)
01642       recur->setDuration( -1 );
01643     else
01644       recur->setDuration( r.count );
01645   }
01646 
01647   // Week start setting
01648   int wkst = (r.week_start + 5)%7 + 1;
01649   recur->setWeekStart( wkst );
01650 
01651   // And now all BY*
01652   QValueList<int> lst;
01653   int i;
01654   int index = 0;
01655 
01656 #define readSetByList(rrulecomp,setfunc) \
01657   index = 0; \
01658   lst.clear(); \
01659   while ( (i = r.rrulecomp[index++] ) != ICAL_RECURRENCE_ARRAY_MAX ) \
01660     lst.append( i ); \
01661   if ( !lst.isEmpty() ) recur->setfunc( lst );
01662 
01663   // BYSECOND, MINUTE and HOUR, MONTHDAY, YEARDAY, WEEKNUMBER, MONTH
01664   // and SETPOS are standard int lists, so we can treat them with the
01665   // same macro
01666   readSetByList( by_second, setBySeconds );
01667   readSetByList( by_minute, setByMinutes );
01668   readSetByList( by_hour, setByHours );
01669   readSetByList( by_month_day, setByMonthDays );
01670   readSetByList( by_year_day, setByYearDays );
01671   readSetByList( by_week_no, setByWeekNumbers );
01672   readSetByList( by_month, setByMonths );
01673   readSetByList( by_set_pos, setBySetPos );
01674 #undef readSetByList
01675 
01676   // BYDAY is a special case, since it's not an int list
01677   QValueList<RecurrenceRule::WDayPos> wdlst;
01678   short day;
01679   index=0;
01680   while((day = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
01681     RecurrenceRule::WDayPos pos;
01682     pos.setDay( ( icalrecurrencetype_day_day_of_week( day ) + 5 )%7 + 1 );
01683     pos.setPos( icalrecurrencetype_day_position( day ) );
01684 //     kdDebug(5800)<< "    o) By day, index="<<index-1<<", pos="<<pos.Pos<<", day="<<pos.Day<<endl;
01685     wdlst.append( pos );
01686   }
01687   if ( !wdlst.isEmpty() ) recur->setByDays( wdlst );
01688 
01689 
01690   // TODO Store all X- fields of the RRULE inside the recurrence (so they are
01691   // preserved
01692 }
01693 
01694 
01695 void ICalFormatImpl::readAlarm(icalcomponent *alarm,Incidence *incidence)
01696 {
01697 //   kdDebug(5800) << "Read alarm for " << incidence->summary() << endl;
01698 
01699   Alarm* ialarm = incidence->newAlarm();
01700   ialarm->setRepeatCount(0);
01701   ialarm->setEnabled(true);
01702 
01703   // Determine the alarm's action type
01704   icalproperty *p = icalcomponent_get_first_property(alarm,ICAL_ACTION_PROPERTY);
01705   Alarm::Type type = Alarm::Display;
01706   icalproperty_action action = ICAL_ACTION_DISPLAY;
01707   if ( !p ) {
01708     kdDebug(5800) << "Unknown type of alarm, using default" << endl;
01709 //    return;
01710   } else {
01711 
01712     action = icalproperty_get_action(p);
01713     switch ( action ) {
01714       case ICAL_ACTION_DISPLAY:   type = Alarm::Display;  break;
01715       case ICAL_ACTION_AUDIO:     type = Alarm::Audio;  break;
01716       case ICAL_ACTION_PROCEDURE: type = Alarm::Procedure;  break;
01717       case ICAL_ACTION_EMAIL:     type = Alarm::Email;  break;
01718       default:
01719         kdDebug(5800) << "Unknown type of alarm: " << action << endl;
01720 //        type = Alarm::Invalid;
01721     }
01722   }
01723   ialarm->setType(type);
01724 // kdDebug(5800) << " alarm type =" << type << endl;
01725 
01726   p = icalcomponent_get_first_property(alarm,ICAL_ANY_PROPERTY);
01727   while (p) {
01728     icalproperty_kind kind = icalproperty_isa(p);
01729 
01730     switch (kind) {
01731 
01732       case ICAL_TRIGGER_PROPERTY: {
01733         icaltriggertype trigger = icalproperty_get_trigger(p);
01734         if (icaltime_is_null_time(trigger.time)) {
01735           if (icaldurationtype_is_null_duration(trigger.duration)) {
01736             kdDebug(5800) << "ICalFormatImpl::readAlarm(): Trigger has no time and no duration." << endl;
01737           } else {
01738             Duration duration = icaldurationtype_as_int( trigger.duration );
01739             icalparameter *param = icalproperty_get_first_parameter(p,ICAL_RELATED_PARAMETER);
01740             if (param && icalparameter_get_related(param) == ICAL_RELATED_END)
01741               ialarm->setEndOffset(duration);
01742             else
01743               ialarm->setStartOffset(duration);
01744           }
01745         } else {
01746           ialarm->setTime(readICalDateTime(trigger.time));
01747         }
01748         break;
01749       }
01750       case ICAL_DURATION_PROPERTY: {
01751         icaldurationtype duration = icalproperty_get_duration(p);
01752         ialarm->setSnoozeTime(icaldurationtype_as_int(duration)/60);
01753         break;
01754       }
01755       case ICAL_REPEAT_PROPERTY:
01756         ialarm->setRepeatCount(icalproperty_get_repeat(p));
01757         break;
01758 
01759       // Only in DISPLAY and EMAIL and PROCEDURE alarms
01760       case ICAL_DESCRIPTION_PROPERTY: {
01761         QString description = QString::fromUtf8(icalproperty_get_description(p));
01762         switch ( action ) {
01763           case ICAL_ACTION_DISPLAY:
01764             ialarm->setText( description );
01765             break;
01766           case ICAL_ACTION_PROCEDURE:
01767             ialarm->setProgramArguments( description );
01768             break;
01769           case ICAL_ACTION_EMAIL:
01770             ialarm->setMailText( description );
01771             break;
01772           default:
01773             break;
01774         }
01775         break;
01776       }
01777       // Only in EMAIL alarm
01778       case ICAL_SUMMARY_PROPERTY:
01779         ialarm->setMailSubject(QString::fromUtf8(icalproperty_get_summary(p)));
01780         break;
01781 
01782       // Only in EMAIL alarm
01783       case ICAL_ATTENDEE_PROPERTY: {
01784         QString email = QString::fromUtf8(icalproperty_get_attendee(p));
01785         if ( email.startsWith("mailto:", false ) ) {
01786           email = email.mid( 7 );
01787         }
01788         QString name;
01789         icalparameter *param = icalproperty_get_first_parameter(p,ICAL_CN_PARAMETER);
01790         if (param) {
01791           name = QString::fromUtf8(icalparameter_get_cn(param));
01792         }
01793         ialarm->addMailAddress(Person(name, email));
01794         break;
01795       }
01796       // Only in AUDIO and EMAIL and PROCEDURE alarms
01797       case ICAL_ATTACH_PROPERTY: {
01798         Attachment *attach = readAttachment( p );
01799         if ( attach && attach->isUri() ) {
01800           switch ( action ) {
01801             case ICAL_ACTION_AUDIO:
01802               ialarm->setAudioFile( attach->uri() );
01803               break;
01804             case ICAL_ACTION_PROCEDURE:
01805               ialarm->setProgramFile( attach->uri() );
01806               break;
01807             case ICAL_ACTION_EMAIL:
01808               ialarm->addMailAttachment( attach->uri() );
01809               break;
01810             default:
01811               break;
01812           }
01813         } else {
01814           kdDebug() << "Alarm attachments currently only support URIs, but "
01815                        "no binary data" << endl;
01816         }
01817         delete attach;
01818         break;
01819       }
01820       default:
01821         break;
01822     }
01823 
01824     p = icalcomponent_get_next_property(alarm,ICAL_ANY_PROPERTY);
01825   }
01826 
01827   // custom properties
01828   readCustomProperties(alarm, ialarm);
01829 
01830   // TODO: check for consistency of alarm properties
01831 }
01832 
01833 icaldatetimeperiodtype ICalFormatImpl::writeICalDatePeriod( const QDate &date )
01834 {
01835   icaldatetimeperiodtype t;
01836   t.time = writeICalDate( date );
01837   t.period = icalperiodtype_null_period();
01838   return t;
01839 }
01840 
01841 icaldatetimeperiodtype ICalFormatImpl::writeICalDateTimePeriod( const QDateTime &date )
01842 {
01843   icaldatetimeperiodtype t;
01844   t.time = writeICalDateTime( date );
01845   t.period = icalperiodtype_null_period();
01846   return t;
01847 }
01848 
01849 icaltimetype ICalFormatImpl::writeICalDate(const QDate &date)
01850 {
01851   icaltimetype t = icaltime_null_time();
01852 
01853   t.year = date.year();
01854   t.month = date.month();
01855   t.day = date.day();
01856 
01857   t.hour = 0;
01858   t.minute = 0;
01859   t.second = 0;
01860 
01861   t.is_date = 1;
01862 
01863   t.is_utc = 0;
01864 
01865   t.zone = 0;
01866 
01867   return t;
01868 }
01869 
01870 icaltimetype ICalFormatImpl::writeICalDateTime(const QDateTime &datetime)
01871 {
01872   icaltimetype t = icaltime_null_time();
01873 
01874   t.year = datetime.date().year();
01875   t.month = datetime.date().month();
01876   t.day = datetime.date().day();
01877 
01878   t.hour = datetime.time().hour();
01879   t.minute = datetime.time().minute();
01880   t.second = datetime.time().second();
01881 
01882   t.is_date = 0;
01883   t.zone = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01884   t.is_utc = 0;
01885 
01886  // _dumpIcaltime( t );
01887   /* The QDateTime we get passed in is to be considered in the timezone of
01888    * the current calendar (mParent's), or, if there is none, to be floating.
01889    * In the later case store a floating time, in the former normalize to utc. */
01890   if (mParent->timeZoneId().isEmpty())
01891     t = icaltime_convert_to_zone( t, 0 ); //make floating timezone
01892   else {
01893     icaltimezone* tz = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01894     icaltimezone* utc = icaltimezone_get_utc_timezone();
01895     if ( tz != utc ) {
01896       t.zone = tz;
01897       t = icaltime_convert_to_zone( t, utc );
01898     } else {
01899       t.is_utc = 1;
01900       t.zone = utc;
01901     }
01902   }
01903 //  _dumpIcaltime( t );
01904 
01905   return t;
01906 }
01907 
01908 QDateTime ICalFormatImpl::readICalDateTime( icaltimetype& t, icaltimezone* tz )
01909 {
01910 //   kdDebug(5800) << "ICalFormatImpl::readICalDateTime()" << endl;
01911   icaltimezone *zone = tz;
01912   if ( tz && t.is_utc == 0 ) { // Only use the TZ if time is not UTC.
01913     // FIXME: We'll need to make sure to apply the appropriate TZ, not just
01914     //        the first one found.
01915     t.zone = tz;
01916     t.is_utc = (tz == icaltimezone_get_utc_timezone())?1:0;
01917   } else {
01918     zone = icaltimezone_get_utc_timezone();
01919   }
01920   //_dumpIcaltime( t );
01921 
01922   // Convert to view time
01923   if ( !mParent->timeZoneId().isEmpty() && t.zone ) {
01924 //    kdDebug(5800) << "--- Converting time from: " << icaltimezone_get_tzid( const_cast<icaltimezone*>( t.zone ) ) << " (" << ICalDate2QDate(t) << ")." << endl;
01925     icaltimezone* viewTimeZone = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01926     icaltimezone_convert_time(  &t, zone, viewTimeZone );
01927 //    kdDebug(5800) << "--- Converted to zone " << mParent->timeZoneId() << " (" << ICalDate2QDate(t) << ")." << endl;
01928   }
01929 
01930   return ICalDate2QDate(t);
01931 }
01932 
01933 QDate ICalFormatImpl::readICalDate(icaltimetype t)
01934 {
01935   return ICalDate2QDate(t).date();
01936 }
01937 
01938 icaldurationtype ICalFormatImpl::writeICalDuration(int seconds)
01939 {
01940   // should be able to use icaldurationtype_from_int(), except we know
01941   // that some older tools do not properly support weeks. So we never
01942   // set a week duration, only days
01943 
01944   icaldurationtype d;
01945 
01946   d.is_neg  = (seconds<0)?1:0;
01947   if (seconds<0) seconds = -seconds;
01948 
01949   d.weeks    = 0;
01950   d.days     = seconds / gSecondsPerDay;
01951   seconds   %= gSecondsPerDay;
01952   d.hours    = seconds / gSecondsPerHour;
01953   seconds   %= gSecondsPerHour;
01954   d.minutes  = seconds / gSecondsPerMinute;
01955   seconds   %= gSecondsPerMinute;
01956   d.seconds  = seconds;
01957 
01958   return d;
01959 }
01960 
01961 int ICalFormatImpl::readICalDuration(icaldurationtype d)
01962 {
01963   int result = 0;
01964 
01965   result += d.weeks   * gSecondsPerWeek;
01966   result += d.days    * gSecondsPerDay;
01967   result += d.hours   * gSecondsPerHour;
01968   result += d.minutes * gSecondsPerMinute;
01969   result += d.seconds;
01970 
01971   if (d.is_neg) result *= -1;
01972 
01973   return result;
01974 }
01975 
01976 icalcomponent *ICalFormatImpl::createCalendarComponent(Calendar *cal)
01977 {
01978   icalcomponent *calendar;
01979 
01980   // Root component
01981   calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
01982 
01983   icalproperty *p;
01984 
01985   // Product Identifier
01986   p = icalproperty_new_prodid(CalFormat::productId().utf8());
01987   icalcomponent_add_property(calendar,p);
01988 
01989   // TODO: Add time zone
01990 
01991   // iCalendar version (2.0)
01992   p = icalproperty_new_version(const_cast<char *>(_ICAL_VERSION));
01993   icalcomponent_add_property(calendar,p);
01994 
01995   // Custom properties
01996   if( cal != 0 )
01997     writeCustomProperties(calendar, cal);
01998 
01999   return calendar;
02000 }
02001 
02002 
02003 
02004 // take a raw vcalendar (i.e. from a file on disk, clipboard, etc. etc.
02005 // and break it down from its tree-like format into the dictionary format
02006 // that is used internally in the ICalFormatImpl.
02007 bool ICalFormatImpl::populate( Calendar *cal, icalcomponent *calendar)
02008 {
02009   // this function will populate the caldict dictionary and other event
02010   // lists. It turns vevents into Events and then inserts them.
02011 
02012     if (!calendar) return false;
02013 
02014 // TODO: check for METHOD
02015 
02016   icalproperty *p;
02017 
02018   p = icalcomponent_get_first_property(calendar,ICAL_PRODID_PROPERTY);
02019   if (!p) {
02020     kdDebug(5800) << "No PRODID property found" << endl;
02021     mLoadedProductId = "";
02022   } else {
02023     mLoadedProductId = QString::fromUtf8(icalproperty_get_prodid(p));
02024 //    kdDebug(5800) << "VCALENDAR prodid: '" << mLoadedProductId << "'" << endl;
02025 
02026     delete mCompat;
02027     mCompat = CompatFactory::createCompat( mLoadedProductId );
02028   }
02029 
02030   p = icalcomponent_get_first_property(calendar,ICAL_VERSION_PROPERTY);
02031   if (!p) {
02032     kdDebug(5800) << "No VERSION property found" << endl;
02033     mParent->setException(new ErrorFormat(ErrorFormat::CalVersionUnknown));
02034     return false;
02035   } else {
02036     const char *version = icalproperty_get_version(p);
02037 //    kdDebug(5800) << "VCALENDAR version: '" << version << "'" << endl;
02038 
02039     if (strcmp(version,"1.0") == 0) {
02040       kdDebug(5800) << "Expected iCalendar, got vCalendar" << endl;
02041       mParent->setException(new ErrorFormat(ErrorFormat::CalVersion1,
02042                             i18n("Expected iCalendar format")));
02043       return false;
02044     } else if (strcmp(version,"2.0") != 0) {
02045       kdDebug(5800) << "Expected iCalendar, got unknown format" << endl;
02046       mParent->setException(new ErrorFormat(ErrorFormat::CalVersionUnknown));
02047       return false;
02048     }
02049   }
02050 
02051   // custom properties
02052   readCustomProperties(calendar, cal);
02053 
02054 // TODO: set time zone
02055 
02056   // read a VTIMEZONE if there is one
02057   icalcomponent *ctz =
02058     icalcomponent_get_first_component( calendar, ICAL_VTIMEZONE_COMPONENT );
02059 
02060   // Store all events with a relatedTo property in a list for post-processing
02061   mEventsRelate.clear();
02062   mTodosRelate.clear();
02063   // TODO: make sure that only actually added events go to this lists.
02064 
02065   icalcomponent *c;
02066 
02067   // Iterate through all todos
02068   c = icalcomponent_get_first_component(calendar,ICAL_VTODO_COMPONENT);
02069   while (c) {
02070 //    kdDebug(5800) << "----Todo found" << endl;
02071     Todo *todo = readTodo(c);
02072     if (todo) {
02073       if (!cal->todo(todo->uid())) {
02074         cal->addTodo(todo);
02075       } else {
02076         delete todo;
02077         mTodosRelate.remove( todo );
02078       }
02079     }
02080     c = icalcomponent_get_next_component(calendar,ICAL_VTODO_COMPONENT);
02081   }
02082 
02083   // Iterate through all events
02084   c = icalcomponent_get_first_component(calendar,ICAL_VEVENT_COMPONENT);
02085   while (c) {
02086 //    kdDebug(5800) << "----Event found" << endl;
02087     Event *event = readEvent(c, ctz);
02088     if (event) {
02089       if (!cal->event(event->uid())) {
02090         cal->addEvent(event);
02091       } else {
02092         delete event;
02093         mEventsRelate.remove( event );
02094       }
02095     }
02096     c = icalcomponent_get_next_component(calendar,ICAL_VEVENT_COMPONENT);
02097   }
02098 
02099   // Iterate through all journals
02100   c = icalcomponent_get_first_component(calendar,ICAL_VJOURNAL_COMPONENT);
02101   while (c) {
02102 //    kdDebug(5800) << "----Journal found" << endl;
02103     Journal *journal = readJournal(c);
02104     if (journal) {
02105       if (!cal->journal(journal->uid())) {
02106         cal->addJournal(journal);
02107       } else {
02108         delete journal;
02109       }
02110     }
02111     c = icalcomponent_get_next_component(calendar,ICAL_VJOURNAL_COMPONENT);
02112   }
02113 
02114   // Post-Process list of events with relations, put Event objects in relation
02115   Event::List::ConstIterator eIt;
02116   for ( eIt = mEventsRelate.begin(); eIt != mEventsRelate.end(); ++eIt ) {
02117     (*eIt)->setRelatedTo( cal->incidence( (*eIt)->relatedToUid() ) );
02118   }
02119   Todo::List::ConstIterator tIt;
02120   for ( tIt = mTodosRelate.begin(); tIt != mTodosRelate.end(); ++tIt ) {
02121     (*tIt)->setRelatedTo( cal->incidence( (*tIt)->relatedToUid() ) );
02122    }
02123 
02124   return true;
02125 }
02126 
02127 QString ICalFormatImpl::extractErrorProperty(icalcomponent *c)
02128 {
02129 //  kdDebug(5800) << "ICalFormatImpl:extractErrorProperty: "
02130 //            << icalcomponent_as_ical_string(c) << endl;
02131 
02132   QString errorMessage;
02133 
02134   icalproperty *error;
02135   error = icalcomponent_get_first_property(c,ICAL_XLICERROR_PROPERTY);
02136   while(error) {
02137     errorMessage += icalproperty_get_xlicerror(error);
02138     errorMessage += "\n";
02139     error = icalcomponent_get_next_property(c,ICAL_XLICERROR_PROPERTY);
02140   }
02141 
02142 //  kdDebug(5800) << "ICalFormatImpl:extractErrorProperty: " << errorMessage << endl;
02143 
02144   return errorMessage;
02145 }
02146 
02147 void ICalFormatImpl::dumpIcalRecurrence(icalrecurrencetype r)
02148 {
02149   int i;
02150 
02151   kdDebug(5800) << " Freq: " << r.freq << endl;
02152   kdDebug(5800) << " Until: " << icaltime_as_ical_string(r.until) << endl;
02153   kdDebug(5800) << " Count: " << r.count << endl;
02154   if (r.by_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02155     int index = 0;
02156     QString out = " By Day: ";
02157     while((i = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02158       out.append(QString::number(i) + " ");
02159     }
02160     kdDebug(5800) << out << endl;
02161   }
02162   if (r.by_month_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02163     int index = 0;
02164     QString out = " By Month Day: ";
02165     while((i = r.by_month_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02166       out.append(QString::number(i) + " ");
02167     }
02168     kdDebug(5800) << out << endl;
02169   }
02170   if (r.by_year_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02171     int index = 0;
02172     QString out = " By Year Day: ";
02173     while((i = r.by_year_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02174       out.append(QString::number(i) + " ");
02175     }
02176     kdDebug(5800) << out << endl;
02177   }
02178   if (r.by_month[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02179     int index = 0;
02180     QString out = " By Month: ";
02181     while((i = r.by_month[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02182       out.append(QString::number(i) + " ");
02183     }
02184     kdDebug(5800) << out << endl;
02185   }
02186   if (r.by_set_pos[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02187     int index = 0;
02188     QString out = " By Set Pos: ";
02189     while((i = r.by_set_pos[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02190       kdDebug(5800) << "========= " << i << endl;
02191       out.append(QString::number(i) + " ");
02192     }
02193     kdDebug(5800) << out << endl;
02194   }
02195 }
02196 
02197 icalcomponent *ICalFormatImpl::createScheduleComponent(IncidenceBase *incidence,
02198                                                    Scheduler::Method method)
02199 {
02200   icalcomponent *message = createCalendarComponent();
02201 
02202   icalproperty_method icalmethod = ICAL_METHOD_NONE;
02203 
02204   switch (method) {
02205     case Scheduler::Publish:
02206       icalmethod = ICAL_METHOD_PUBLISH;
02207       break;
02208     case Scheduler::Request:
02209       icalmethod = ICAL_METHOD_REQUEST;
02210       break;
02211     case Scheduler::Refresh:
02212       icalmethod = ICAL_METHOD_REFRESH;
02213       break;
02214     case Scheduler::Cancel:
02215       icalmethod = ICAL_METHOD_CANCEL;
02216       break;
02217     case Scheduler::Add:
02218       icalmethod = ICAL_METHOD_ADD;
02219       break;
02220     case Scheduler::Reply:
02221       icalmethod = ICAL_METHOD_REPLY;
02222       break;
02223     case Scheduler::Counter:
02224       icalmethod = ICAL_METHOD_COUNTER;
02225       break;
02226     case Scheduler::Declinecounter:
02227       icalmethod = ICAL_METHOD_DECLINECOUNTER;
02228       break;
02229     default:
02230       kdDebug(5800) << "ICalFormat::createScheduleMessage(): Unknow method" << endl;
02231       return message;
02232   }
02233 
02234   icalcomponent_add_property(message,icalproperty_new_method(icalmethod));
02235 
02236   icalcomponent *inc = writeIncidence( incidence, method );
02237   /*
02238    * RFC 2446 states in section 3.4.3 ( REPLY to a VTODO ), that
02239    * a REQUEST-STATUS property has to be present. For the other two, event and
02240    * free busy, it can be there, but is optional. Until we do more
02241    * fine grained handling, assume all is well. Note that this is the
02242    * status of the _request_, not the attendee. Just to avoid confusion.
02243    * - till
02244    */
02245   if ( icalmethod == ICAL_METHOD_REPLY ) {
02246     struct icalreqstattype rst;
02247     rst.code = ICAL_2_0_SUCCESS_STATUS;
02248     rst.desc = 0;
02249     rst.debug = 0;
02250     icalcomponent_add_property( inc, icalproperty_new_requeststatus( rst ) );
02251   }
02252   icalcomponent_add_component( message, inc );
02253 
02254   return message;
02255 }
KDE Home | KDE Accessibility Home | Description of Access Keys