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   icalproperty *p = icalproperty_new_attach(attach);
00644 
00645   if ( !att->mimeType().isEmpty() ) {
00646     icalproperty_add_parameter( p,
00647         icalparameter_new_fmttype( att->mimeType().utf8().data() ) );
00648   }
00649 
00650   if ( att->isBinary() ) {
00651     icalproperty_add_parameter( p,
00652         icalparameter_new_value( ICAL_VALUE_BINARY ) );
00653     icalproperty_add_parameter( p,
00654         icalparameter_new_encoding( ICAL_ENCODING_BASE64 ) );
00655   }
00656 
00657   if ( att->showInline() ) {
00658     icalparameter* icalparameter_inline = icalparameter_new_x( "inline" );
00659     icalparameter_set_xname( icalparameter_inline, "X-CONTENT-DISPOSITION" );
00660     icalproperty_add_parameter( p, icalparameter_inline );
00661   }
00662 
00663   if ( !att->label().isEmpty() ) {
00664     icalparameter* icalparameter_label = icalparameter_new_x( att->label().utf8() );
00665     icalparameter_set_xname( icalparameter_label, "X-LABEL" );
00666     icalproperty_add_parameter( p, icalparameter_label );
00667   }
00668 
00669   return p;
00670 }
00671 
00672 icalrecurrencetype ICalFormatImpl::writeRecurrenceRule( RecurrenceRule *recur )
00673 {
00674 //  kdDebug(5800) << "ICalFormatImpl::writeRecurrenceRule()" << endl;
00675 
00676   icalrecurrencetype r;
00677   icalrecurrencetype_clear(&r);
00678 
00679   switch( recur->recurrenceType() ) {
00680     case RecurrenceRule::rSecondly:
00681       r.freq = ICAL_SECONDLY_RECURRENCE;
00682       break;
00683     case RecurrenceRule::rMinutely:
00684       r.freq = ICAL_MINUTELY_RECURRENCE;
00685       break;
00686     case RecurrenceRule::rHourly:
00687       r.freq = ICAL_HOURLY_RECURRENCE;
00688       break;
00689     case RecurrenceRule::rDaily:
00690       r.freq = ICAL_DAILY_RECURRENCE;
00691       break;
00692     case RecurrenceRule::rWeekly:
00693       r.freq = ICAL_WEEKLY_RECURRENCE;
00694       break;
00695     case RecurrenceRule::rMonthly:
00696       r.freq = ICAL_MONTHLY_RECURRENCE;
00697       break;
00698     case RecurrenceRule::rYearly:
00699       r.freq = ICAL_YEARLY_RECURRENCE;
00700       break;
00701     default:
00702       r.freq = ICAL_NO_RECURRENCE;
00703       kdDebug(5800) << "ICalFormatImpl::writeRecurrence(): no recurrence" << endl;
00704       break;
00705   }
00706 
00707   int index = 0;
00708   QValueList<int> bys;
00709   QValueList<int>::ConstIterator it;
00710 
00711   // Now write out the BY* parts:
00712   bys = recur->bySeconds();
00713   index = 0;
00714   for ( it = bys.begin(); it != bys.end(); ++it ) {
00715     r.by_second[index++] = *it;
00716   }
00717 
00718   bys = recur->byMinutes();
00719   index = 0;
00720   for ( it = bys.begin(); it != bys.end(); ++it ) {
00721     r.by_minute[index++] = *it;
00722   }
00723 
00724   bys = recur->byHours();
00725   index = 0;
00726   for ( it = bys.begin(); it != bys.end(); ++it ) {
00727     r.by_hour[index++] = *it;
00728   }
00729 
00730   bys = recur->byMonthDays();
00731   index = 0;
00732   for ( it = bys.begin(); it != bys.end(); ++it ) {
00733     r.by_month_day[index++] = icalrecurrencetype_day_position( (*it) * 8 );
00734   }
00735 
00736   bys = recur->byYearDays();
00737   index = 0;
00738   for ( it = bys.begin(); it != bys.end(); ++it ) {
00739     r.by_year_day[index++] = *it;
00740   }
00741 
00742   bys = recur->byWeekNumbers();
00743   index = 0;
00744   for ( it = bys.begin(); it != bys.end(); ++it ) {
00745      r.by_week_no[index++] = *it;
00746   }
00747 
00748   bys = recur->byMonths();
00749   index = 0;
00750   for ( it = bys.begin(); it != bys.end(); ++it ) {
00751     r.by_month[index++] = *it;
00752   }
00753 
00754   bys = recur->bySetPos();
00755   index = 0;
00756   for ( it = bys.begin(); it != bys.end(); ++it ) {
00757      r.by_set_pos[index++] = *it;
00758   }
00759 
00760 
00761   QValueList<RecurrenceRule::WDayPos> byd = recur->byDays();
00762   int day;
00763   index = 0;
00764   for ( QValueList<RecurrenceRule::WDayPos>::ConstIterator dit = byd.begin();
00765         dit != byd.end(); ++dit ) {
00766     day = (*dit).day() % 7 + 1;     // convert from Monday=1 to Sunday=1
00767     if ( (*dit).pos() < 0 ) {
00768       day += (-(*dit).pos())*8;
00769       day = -day;
00770     } else {
00771       day += (*dit).pos()*8;
00772     }
00773     r.by_day[index++] = day;
00774   }
00775 
00776   r.week_start = static_cast<icalrecurrencetype_weekday>(
00777                                              recur->weekStart()%7 + 1);
00778 
00779   if ( recur->frequency() > 1 ) {
00780     // Dont' write out INTERVAL=1, because that's the default anyway
00781     r.interval = recur->frequency();
00782   }
00783 
00784   if ( recur->duration() > 0 ) {
00785     r.count = recur->duration();
00786   } else if ( recur->duration() == -1 ) {
00787     r.count = 0;
00788   } else {
00789     if ( recur->doesFloat() )
00790       r.until = writeICalDate(recur->endDt().date());
00791     else
00792       r.until = writeICalDateTime(recur->endDt());
00793   }
00794 
00795 // Debug output
00796 #if 0
00797   const char *str = icalrecurrencetype_as_string(&r);
00798   if (str) {
00799     kdDebug(5800) << " String: " << str << endl;
00800   } else {
00801     kdDebug(5800) << " No String" << endl;
00802   }
00803 #endif
00804 
00805   return r;
00806 }
00807 
00808 
00809 icalcomponent *ICalFormatImpl::writeAlarm(Alarm *alarm)
00810 {
00811 // kdDebug(5800) << " ICalFormatImpl::writeAlarm" << endl;
00812   icalcomponent *a = icalcomponent_new(ICAL_VALARM_COMPONENT);
00813 
00814   icalproperty_action action;
00815   icalattach *attach = 0;
00816 
00817   switch (alarm->type()) {
00818     case Alarm::Procedure:
00819       action = ICAL_ACTION_PROCEDURE;
00820       attach = icalattach_new_from_url(QFile::encodeName(alarm->programFile()).data());
00821       icalcomponent_add_property(a,icalproperty_new_attach(attach));
00822       if (!alarm->programArguments().isEmpty()) {
00823         icalcomponent_add_property(a,icalproperty_new_description(alarm->programArguments().utf8()));
00824       }
00825       break;
00826     case Alarm::Audio:
00827       action = ICAL_ACTION_AUDIO;
00828 // kdDebug(5800) << " It's an audio action, file: " << alarm->audioFile() << endl;
00829       if (!alarm->audioFile().isEmpty()) {
00830         attach = icalattach_new_from_url(QFile::encodeName( alarm->audioFile() ).data());
00831         icalcomponent_add_property(a,icalproperty_new_attach(attach));
00832       }
00833       break;
00834     case Alarm::Email: {
00835       action = ICAL_ACTION_EMAIL;
00836       QValueList<Person> addresses = alarm->mailAddresses();
00837       for (QValueList<Person>::Iterator ad = addresses.begin();  ad != addresses.end();  ++ad) {
00838         icalproperty *p = icalproperty_new_attendee("MAILTO:" + (*ad).email().utf8());
00839         if (!(*ad).name().isEmpty()) {
00840           icalproperty_add_parameter(p,icalparameter_new_cn(quoteForParam((*ad).name()).utf8()));
00841         }
00842         icalcomponent_add_property(a,p);
00843       }
00844       icalcomponent_add_property(a,icalproperty_new_summary(alarm->mailSubject().utf8()));
00845       icalcomponent_add_property(a,icalproperty_new_description(alarm->mailText().utf8()));
00846       QStringList attachments = alarm->mailAttachments();
00847       if (attachments.count() > 0) {
00848         for (QStringList::Iterator at = attachments.begin();  at != attachments.end();  ++at) {
00849           attach = icalattach_new_from_url(QFile::encodeName( *at ).data());
00850           icalcomponent_add_property(a,icalproperty_new_attach(attach));
00851         }
00852       }
00853       break;
00854     }
00855     case Alarm::Display:
00856       action = ICAL_ACTION_DISPLAY;
00857       icalcomponent_add_property(a,icalproperty_new_description(alarm->text().utf8()));
00858       break;
00859     case Alarm::Invalid:
00860     default:
00861       kdDebug(5800) << "Unknown type of alarm" << endl;
00862       action = ICAL_ACTION_NONE;
00863       break;
00864   }
00865   icalcomponent_add_property(a,icalproperty_new_action(action));
00866 
00867   // Trigger time
00868   icaltriggertype trigger;
00869   if ( alarm->hasTime() ) {
00870     trigger.time = writeICalDateTime(alarm->time());
00871     trigger.duration = icaldurationtype_null_duration();
00872   } else {
00873     trigger.time = icaltime_null_time();
00874     Duration offset;
00875     if ( alarm->hasStartOffset() )
00876       offset = alarm->startOffset();
00877     else
00878       offset = alarm->endOffset();
00879     trigger.duration = writeICalDuration( offset.asSeconds() );
00880   }
00881   icalproperty *p = icalproperty_new_trigger(trigger);
00882   if ( alarm->hasEndOffset() )
00883     icalproperty_add_parameter(p,icalparameter_new_related(ICAL_RELATED_END));
00884   icalcomponent_add_property(a,p);
00885 
00886   // Repeat count and duration
00887   if (alarm->repeatCount()) {
00888     icalcomponent_add_property(a,icalproperty_new_repeat(alarm->repeatCount()));
00889     icalcomponent_add_property(a,icalproperty_new_duration(
00890                                  writeICalDuration(alarm->snoozeTime()*60)));
00891   }
00892 
00893   // Custom properties
00894   QMap<QCString, QString> custom = alarm->customProperties();
00895   for (QMap<QCString, QString>::Iterator c = custom.begin();  c != custom.end();  ++c) {
00896     icalproperty *p = icalproperty_new_x(c.data().utf8());
00897     icalproperty_set_x_name(p,c.key());
00898     icalcomponent_add_property(a,p);
00899   }
00900 
00901   return a;
00902 }
00903 
00904 Todo *ICalFormatImpl::readTodo(icalcomponent *vtodo)
00905 {
00906   Todo *todo = new Todo;
00907 
00908   readIncidence(vtodo, 0, todo); // FIXME timezone
00909 
00910   icalproperty *p = icalcomponent_get_first_property(vtodo,ICAL_ANY_PROPERTY);
00911 
00912 //  int intvalue;
00913   icaltimetype icaltime;
00914 
00915   QStringList categories;
00916 
00917   while (p) {
00918     icalproperty_kind kind = icalproperty_isa(p);
00919     switch (kind) {
00920 
00921       case ICAL_DUE_PROPERTY:  // due date
00922         icaltime = icalproperty_get_due(p);
00923         if (icaltime.is_date) {
00924           todo->setDtDue(QDateTime(readICalDate(icaltime),QTime(0,0,0)),true);
00925         } else {
00926           todo->setDtDue(readICalDateTime(icaltime),true);
00927           todo->setFloats(false);
00928         }
00929         todo->setHasDueDate(true);
00930         break;
00931 
00932       case ICAL_COMPLETED_PROPERTY:  // completion date
00933         icaltime = icalproperty_get_completed(p);
00934         todo->setCompleted(readICalDateTime(icaltime));
00935         break;
00936 
00937       case ICAL_PERCENTCOMPLETE_PROPERTY:  // Percent completed
00938         todo->setPercentComplete(icalproperty_get_percentcomplete(p));
00939         break;
00940 
00941       case ICAL_RELATEDTO_PROPERTY:  // related todo (parent)
00942         todo->setRelatedToUid(QString::fromUtf8(icalproperty_get_relatedto(p)));
00943         mTodosRelate.append(todo);
00944         break;
00945 
00946       case ICAL_DTSTART_PROPERTY: {
00947         // Flag that todo has start date. Value is read in by readIncidence().
00948         if ( todo->comments().grep("NoStartDate").count() )
00949           todo->setHasStartDate( false );
00950         else
00951           todo->setHasStartDate( true );
00952         break;
00953       }
00954 
00955       case ICAL_RECURRENCEID_PROPERTY:
00956         icaltime = icalproperty_get_recurrenceid(p);
00957         todo->setDtRecurrence( readICalDateTime(icaltime) );
00958         break;
00959 
00960       default:
00961 //        kdDebug(5800) << "ICALFormat::readTodo(): Unknown property: " << kind
00962 //                  << endl;
00963         break;
00964     }
00965 
00966     p = icalcomponent_get_next_property(vtodo,ICAL_ANY_PROPERTY);
00967   }
00968 
00969   if (mCompat) mCompat->fixEmptySummary( todo );
00970 
00971   return todo;
00972 }
00973 
00974 Event *ICalFormatImpl::readEvent( icalcomponent *vevent, icalcomponent *vtimezone )
00975 {
00976   Event *event = new Event;
00977 
00978   // FIXME where is this freed?
00979   icaltimezone *tz = icaltimezone_new();
00980   if ( !icaltimezone_set_component( tz, vtimezone ) ) {
00981     icaltimezone_free( tz, 1 );
00982     tz = 0;
00983   }
00984 
00985   readIncidence( vevent, tz, event);
00986 
00987   icalproperty *p = icalcomponent_get_first_property(vevent,ICAL_ANY_PROPERTY);
00988 
00989 //  int intvalue;
00990   icaltimetype icaltime;
00991 
00992   QStringList categories;
00993   icalproperty_transp transparency;
00994 
00995   bool dtEndProcessed = false;
00996 
00997   while (p) {
00998     icalproperty_kind kind = icalproperty_isa(p);
00999     switch (kind) {
01000 
01001       case ICAL_DTEND_PROPERTY:  // start date and time
01002         icaltime = icalproperty_get_dtend(p);
01003         if (icaltime.is_date) {
01004           // End date is non-inclusive
01005           QDate endDate = readICalDate( icaltime ).addDays( -1 );
01006           if ( mCompat ) mCompat->fixFloatingEnd( endDate );
01007           if ( endDate < event->dtStart().date() ) {
01008             endDate = event->dtStart().date();
01009           }
01010           event->setDtEnd( QDateTime( endDate, QTime( 0, 0, 0 ) ) );
01011         } else {
01012           event->setDtEnd(readICalDateTime(icaltime, tz));
01013           event->setFloats( false );
01014         }
01015         dtEndProcessed = true;
01016         break;
01017 
01018       case ICAL_RELATEDTO_PROPERTY:  // related event (parent)
01019         event->setRelatedToUid(QString::fromUtf8(icalproperty_get_relatedto(p)));
01020         mEventsRelate.append(event);
01021         break;
01022 
01023 
01024       case ICAL_TRANSP_PROPERTY:  // Transparency
01025         transparency = icalproperty_get_transp(p);
01026         if( transparency == ICAL_TRANSP_TRANSPARENT )
01027           event->setTransparency( Event::Transparent );
01028         else
01029           event->setTransparency( Event::Opaque );
01030         break;
01031 
01032       default:
01033 //        kdDebug(5800) << "ICALFormat::readEvent(): Unknown property: " << kind
01034 //                  << endl;
01035         break;
01036     }
01037 
01038     p = icalcomponent_get_next_property(vevent,ICAL_ANY_PROPERTY);
01039   }
01040 
01041   // according to rfc2445 the dtend shouldn't be written when it equals
01042   // start date. so assign one equal to start date.
01043   if ( !dtEndProcessed && !event->hasDuration() ) {
01044     event->setDtEnd( event->dtStart() );
01045   }
01046 
01047   QString msade = event->nonKDECustomProperty("X-MICROSOFT-CDO-ALLDAYEVENT");
01048   if (!msade.isEmpty()) {
01049     bool floats = (msade == QString::fromLatin1("TRUE"));
01050     event->setFloats(floats);
01051   }
01052 
01053   if ( mCompat ) mCompat->fixEmptySummary( event );
01054 
01055   return event;
01056 }
01057 
01058 FreeBusy *ICalFormatImpl::readFreeBusy(icalcomponent *vfreebusy)
01059 {
01060   FreeBusy *freebusy = new FreeBusy;
01061 
01062   readIncidenceBase(vfreebusy, freebusy);
01063 
01064   icalproperty *p = icalcomponent_get_first_property(vfreebusy,ICAL_ANY_PROPERTY);
01065 
01066   icaltimetype icaltime;
01067   PeriodList periods;
01068 
01069   while (p) {
01070     icalproperty_kind kind = icalproperty_isa(p);
01071     switch (kind) {
01072 
01073       case ICAL_DTSTART_PROPERTY:  // start date and time
01074         icaltime = icalproperty_get_dtstart(p);
01075         freebusy->setDtStart(readICalDateTime(icaltime));
01076         break;
01077 
01078       case ICAL_DTEND_PROPERTY:  // end Date and Time
01079         icaltime = icalproperty_get_dtend(p);
01080         freebusy->setDtEnd(readICalDateTime(icaltime));
01081         break;
01082 
01083       case ICAL_FREEBUSY_PROPERTY: { //Any FreeBusy Times
01084         icalperiodtype icalperiod = icalproperty_get_freebusy(p);
01085         QDateTime period_start = readICalDateTime(icalperiod.start);
01086         Period period;
01087         if ( !icaltime_is_null_time(icalperiod.end) ) {
01088           QDateTime period_end = readICalDateTime(icalperiod.end);
01089           period = Period(period_start, period_end);
01090         } else {
01091           Duration duration = readICalDuration( icalperiod.duration );
01092           period = Period(period_start, duration);
01093         }
01094         QCString param = icalproperty_get_parameter_as_string( p, "X-SUMMARY" );
01095         period.setSummary( QString::fromUtf8( KCodecs::base64Decode( param ) ) );
01096         param = icalproperty_get_parameter_as_string( p, "X-LOCATION" );
01097         period.setLocation( QString::fromUtf8( KCodecs::base64Decode( param ) ) );
01098         periods.append( period );
01099         break;}
01100 
01101       default:
01102 //        kdDebug(5800) << "ICalFormatImpl::readFreeBusy(): Unknown property: "
01103 //                      << kind << endl;
01104       break;
01105     }
01106     p = icalcomponent_get_next_property(vfreebusy,ICAL_ANY_PROPERTY);
01107   }
01108   freebusy->addPeriods( periods );
01109 
01110   return freebusy;
01111 }
01112 
01113 Journal *ICalFormatImpl::readJournal(icalcomponent *vjournal)
01114 {
01115   Journal *journal = new Journal;
01116 
01117   readIncidence(vjournal, 0, journal); // FIXME tz?
01118 
01119   return journal;
01120 }
01121 
01122 Attendee *ICalFormatImpl::readAttendee(icalproperty *attendee)
01123 {
01124   icalparameter *p = 0;
01125 
01126   QString email = QString::fromUtf8(icalproperty_get_attendee(attendee));
01127   if ( email.startsWith( "mailto:", false ) ) {
01128     email = email.mid( 7 );
01129   }
01130 
01131   QString name;
01132   QString uid = QString::null;
01133   p = icalproperty_get_first_parameter(attendee,ICAL_CN_PARAMETER);
01134   if (p) {
01135     name = QString::fromUtf8(icalparameter_get_cn(p));
01136   } else {
01137   }
01138 
01139   bool rsvp=false;
01140   p = icalproperty_get_first_parameter(attendee,ICAL_RSVP_PARAMETER);
01141   if (p) {
01142     icalparameter_rsvp rsvpParameter = icalparameter_get_rsvp(p);
01143     if (rsvpParameter == ICAL_RSVP_TRUE) rsvp = true;
01144   }
01145 
01146   Attendee::PartStat status = Attendee::NeedsAction;
01147   p = icalproperty_get_first_parameter(attendee,ICAL_PARTSTAT_PARAMETER);
01148   if (p) {
01149     icalparameter_partstat partStatParameter = icalparameter_get_partstat(p);
01150     switch(partStatParameter) {
01151       default:
01152       case ICAL_PARTSTAT_NEEDSACTION:
01153         status = Attendee::NeedsAction;
01154         break;
01155       case ICAL_PARTSTAT_ACCEPTED:
01156         status = Attendee::Accepted;
01157         break;
01158       case ICAL_PARTSTAT_DECLINED:
01159         status = Attendee::Declined;
01160         break;
01161       case ICAL_PARTSTAT_TENTATIVE:
01162         status = Attendee::Tentative;
01163         break;
01164       case ICAL_PARTSTAT_DELEGATED:
01165         status = Attendee::Delegated;
01166         break;
01167       case ICAL_PARTSTAT_COMPLETED:
01168         status = Attendee::Completed;
01169         break;
01170       case ICAL_PARTSTAT_INPROCESS:
01171         status = Attendee::InProcess;
01172         break;
01173     }
01174   }
01175 
01176   Attendee::Role role = Attendee::ReqParticipant;
01177   p = icalproperty_get_first_parameter(attendee,ICAL_ROLE_PARAMETER);
01178   if (p) {
01179     icalparameter_role roleParameter = icalparameter_get_role(p);
01180     switch(roleParameter) {
01181       case ICAL_ROLE_CHAIR:
01182         role = Attendee::Chair;
01183         break;
01184       default:
01185       case ICAL_ROLE_REQPARTICIPANT:
01186         role = Attendee::ReqParticipant;
01187         break;
01188       case ICAL_ROLE_OPTPARTICIPANT:
01189         role = Attendee::OptParticipant;
01190         break;
01191       case ICAL_ROLE_NONPARTICIPANT:
01192         role = Attendee::NonParticipant;
01193         break;
01194     }
01195   }
01196 
01197   p = icalproperty_get_first_parameter(attendee,ICAL_X_PARAMETER);
01198   uid = icalparameter_get_xvalue(p);
01199   // This should be added, but there seems to be a libical bug here.
01200   // TODO: does this work now in libical-0.24 or greater?
01201   /*while (p) {
01202    // if (icalparameter_get_xname(p) == "X-UID") {
01203     uid = icalparameter_get_xvalue(p);
01204     p = icalproperty_get_next_parameter(attendee,ICAL_X_PARAMETER);
01205   } */
01206 
01207   Attendee *a = new Attendee( name, email, rsvp, status, role, uid );
01208 
01209   p = icalproperty_get_first_parameter( attendee, ICAL_DELEGATEDTO_PARAMETER );
01210   if ( p )
01211     a->setDelegate( icalparameter_get_delegatedto( p ) );
01212 
01213   p = icalproperty_get_first_parameter( attendee, ICAL_DELEGATEDFROM_PARAMETER );
01214   if ( p )
01215     a->setDelegator( icalparameter_get_delegatedfrom( p ) );
01216 
01217   return a;
01218 }
01219 
01220 Person ICalFormatImpl::readOrganizer( icalproperty *organizer )
01221 {
01222   QString email = QString::fromUtf8(icalproperty_get_organizer(organizer));
01223   if ( email.startsWith( "mailto:", false ) ) {
01224     email = email.mid( 7 );
01225   }
01226   QString cn;
01227 
01228   icalparameter *p = icalproperty_get_first_parameter(
01229              organizer, ICAL_CN_PARAMETER );
01230 
01231   if ( p ) {
01232     cn = QString::fromUtf8( icalparameter_get_cn( p ) );
01233   }
01234   Person org( cn, email );
01235   // TODO: Treat sent-by, dir and language here, too
01236   return org;
01237 }
01238 
01239 Attachment *ICalFormatImpl::readAttachment(icalproperty *attach)
01240 {
01241   Attachment *attachment = 0;
01242 
01243   const char *p;
01244   icalvalue *value = icalproperty_get_value( attach );
01245 
01246   switch( icalvalue_isa( value ) ) {
01247   case ICAL_ATTACH_VALUE:
01248   {
01249     icalattach *a = icalproperty_get_attach( attach );
01250     if ( !icalattach_get_is_url( a ) ) {
01251       p = (const char *)icalattach_get_data( a );
01252       if ( p ) {
01253         attachment = new Attachment( p );
01254       }
01255     } else {
01256       p = icalattach_get_url( a );
01257       if ( p ) {
01258         attachment = new Attachment( QString::fromUtf8( p ) );
01259       }
01260     }
01261     break;
01262   }
01263   case ICAL_BINARY_VALUE:
01264   {
01265     icalattach *a = icalproperty_get_attach( attach );
01266     p = (const char *)icalattach_get_data( a );
01267     if ( p ) {
01268       attachment = new Attachment( p );
01269     }
01270     break;
01271   }
01272   case ICAL_URI_VALUE:
01273     p = icalvalue_get_uri( value );
01274     attachment = new Attachment( QString::fromUtf8( p ) );
01275     break;
01276   default:
01277     break;
01278   }
01279 
01280  if ( attachment ) {
01281     icalparameter *p =
01282       icalproperty_get_first_parameter( attach, ICAL_FMTTYPE_PARAMETER );
01283     if ( p ) {
01284       attachment->setMimeType( QString( icalparameter_get_fmttype( p ) ) );
01285     }
01286 
01287     p = icalproperty_get_first_parameter( attach, ICAL_X_PARAMETER );
01288     while ( p ) {
01289       QString xname = QString( icalparameter_get_xname( p ) ).upper();
01290       QString xvalue = QString::fromUtf8( icalparameter_get_xvalue( p ) );
01291       if ( xname == "X-CONTENT-DISPOSITION" ) {
01292         attachment->setShowInline( xvalue.lower() == "inline" );
01293       }
01294       if ( xname == "X-LABEL" ) {
01295         attachment->setLabel( xvalue );
01296       }
01297       p = icalproperty_get_next_parameter( attach, ICAL_X_PARAMETER );
01298     }
01299 
01300     p = icalproperty_get_first_parameter( attach, ICAL_X_PARAMETER );
01301     while ( p ) {
01302       if ( strncmp( icalparameter_get_xname( p ), "X-LABEL", 7 ) == 0 ) {
01303         attachment->setLabel( QString::fromUtf8( icalparameter_get_xvalue( p ) ) );
01304       }
01305       p = icalproperty_get_next_parameter( attach, ICAL_X_PARAMETER );
01306     }
01307   }
01308 
01309   return attachment;
01310 }
01311 
01312 void ICalFormatImpl::readIncidence(icalcomponent *parent, icaltimezone *tz, Incidence *incidence)
01313 {
01314   readIncidenceBase(parent,incidence);
01315 
01316   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_ANY_PROPERTY);
01317 
01318   const char *text;
01319   int intvalue, inttext;
01320   icaltimetype icaltime;
01321   icaldurationtype icalduration;
01322 
01323   QStringList categories;
01324 
01325   while (p) {
01326     icalproperty_kind kind = icalproperty_isa(p);
01327     switch (kind) {
01328 
01329       case ICAL_CREATED_PROPERTY:
01330         icaltime = icalproperty_get_created(p);
01331         incidence->setCreated(readICalDateTime(icaltime, tz));
01332         break;
01333 
01334       case ICAL_SEQUENCE_PROPERTY:  // sequence
01335         intvalue = icalproperty_get_sequence(p);
01336         incidence->setRevision(intvalue);
01337         break;
01338 
01339       case ICAL_LASTMODIFIED_PROPERTY:  // last modification date
01340         icaltime = icalproperty_get_lastmodified(p);
01341         incidence->setLastModified(readICalDateTime(icaltime, tz));
01342         break;
01343 
01344       case ICAL_DTSTART_PROPERTY:  // start date and time
01345         icaltime = icalproperty_get_dtstart(p);
01346         if (icaltime.is_date) {
01347           incidence->setDtStart(QDateTime(readICalDate(icaltime),QTime(0,0,0)));
01348           incidence->setFloats( true );
01349         } else {
01350           incidence->setDtStart(readICalDateTime(icaltime, tz));
01351           incidence->setFloats( false );
01352         }
01353         break;
01354 
01355       case ICAL_DURATION_PROPERTY:  // start date and time
01356         icalduration = icalproperty_get_duration(p);
01357         incidence->setDuration(readICalDuration(icalduration));
01358         break;
01359 
01360       case ICAL_DESCRIPTION_PROPERTY:  // description
01361         text = icalproperty_get_description(p);
01362         incidence->setDescription(QString::fromUtf8(text));
01363         break;
01364 
01365       case ICAL_SUMMARY_PROPERTY:  // summary
01366         text = icalproperty_get_summary(p);
01367         incidence->setSummary(QString::fromUtf8(text));
01368         break;
01369 
01370       case ICAL_LOCATION_PROPERTY:  // location
01371         text = icalproperty_get_location(p);
01372         incidence->setLocation(QString::fromUtf8(text));
01373         break;
01374 
01375       case ICAL_STATUS_PROPERTY: {  // status
01376         Incidence::Status stat;
01377         switch (icalproperty_get_status(p)) {
01378           case ICAL_STATUS_TENTATIVE:   stat = Incidence::StatusTentative; break;
01379           case ICAL_STATUS_CONFIRMED:   stat = Incidence::StatusConfirmed; break;
01380           case ICAL_STATUS_COMPLETED:   stat = Incidence::StatusCompleted; break;
01381           case ICAL_STATUS_NEEDSACTION: stat = Incidence::StatusNeedsAction; break;
01382           case ICAL_STATUS_CANCELLED:   stat = Incidence::StatusCanceled; break;
01383           case ICAL_STATUS_INPROCESS:   stat = Incidence::StatusInProcess; break;
01384           case ICAL_STATUS_DRAFT:       stat = Incidence::StatusDraft; break;
01385           case ICAL_STATUS_FINAL:       stat = Incidence::StatusFinal; break;
01386           case ICAL_STATUS_X:
01387             incidence->setCustomStatus(QString::fromUtf8(icalvalue_get_x(icalproperty_get_value(p))));
01388             stat = Incidence::StatusX;
01389             break;
01390           case ICAL_STATUS_NONE:
01391           default:                      stat = Incidence::StatusNone; break;
01392         }
01393         if (stat != Incidence::StatusX)
01394           incidence->setStatus(stat);
01395         break;
01396       }
01397 
01398       case ICAL_PRIORITY_PROPERTY:  // priority
01399         intvalue = icalproperty_get_priority( p );
01400         if ( mCompat )
01401           intvalue = mCompat->fixPriority( intvalue );
01402         incidence->setPriority( intvalue );
01403         break;
01404 
01405       case ICAL_CATEGORIES_PROPERTY:  // categories
01406         text = icalproperty_get_categories(p);
01407         categories.append(QString::fromUtf8(text));
01408         break;
01409 
01410       case ICAL_RRULE_PROPERTY:
01411         readRecurrenceRule( p, incidence );
01412         break;
01413 
01414       case ICAL_RDATE_PROPERTY: {
01415         icaldatetimeperiodtype rd = icalproperty_get_rdate( p );
01416         if ( icaltime_is_valid_time( rd.time ) ) {
01417           if ( icaltime_is_date( rd.time ) ) {
01418             incidence->recurrence()->addRDate( readICalDate( rd.time ) );
01419           } else {
01420             incidence->recurrence()->addRDateTime( readICalDateTime( rd.time, tz ) );
01421           }
01422         } else {
01423           // TODO: RDates as period are not yet implemented!
01424         }
01425         break; }
01426 
01427       case ICAL_EXRULE_PROPERTY:
01428         readExceptionRule( p, incidence );
01429         break;
01430 
01431       case ICAL_EXDATE_PROPERTY:
01432         icaltime = icalproperty_get_exdate(p);
01433         if ( icaltime_is_date(icaltime) ) {
01434           incidence->recurrence()->addExDate( readICalDate(icaltime) );
01435         } else {
01436           incidence->recurrence()->addExDateTime( readICalDateTime(icaltime, tz) );
01437         }
01438         break;
01439 
01440       case ICAL_CLASS_PROPERTY:
01441         inttext = icalproperty_get_class(p);
01442         if (inttext == ICAL_CLASS_PUBLIC ) {
01443           incidence->setSecrecy(Incidence::SecrecyPublic);
01444         } else if (inttext == ICAL_CLASS_CONFIDENTIAL ) {
01445           incidence->setSecrecy(Incidence::SecrecyConfidential);
01446         } else {
01447           incidence->setSecrecy(Incidence::SecrecyPrivate);
01448         }
01449         break;
01450 
01451       case ICAL_ATTACH_PROPERTY:  // attachments
01452         incidence->addAttachment(readAttachment(p));
01453         break;
01454 
01455       default:
01456 //        kdDebug(5800) << "ICALFormat::readIncidence(): Unknown property: " << kind
01457 //                  << endl;
01458         break;
01459     }
01460 
01461     p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY);
01462   }
01463 
01464   // Set the scheduling ID
01465   const QString uid = incidence->customProperty( "LIBKCAL", "ID" );
01466   if ( !uid.isNull() ) {
01467     // The UID stored in incidencebase is actually the scheduling ID
01468     // It has to be stored in the iCal UID component for compatibility
01469     // with other iCal applications
01470     incidence->setSchedulingID( incidence->uid() );
01471     incidence->setUid( uid );
01472   }
01473 
01474   // Now that recurrence and exception stuff is completely set up,
01475   // do any backwards compatibility adjustments.
01476   if ( incidence->doesRecur() && mCompat )
01477       mCompat->fixRecurrence( incidence );
01478 
01479   // add categories
01480   incidence->setCategories(categories);
01481 
01482   // iterate through all alarms
01483   for (icalcomponent *alarm = icalcomponent_get_first_component(parent,ICAL_VALARM_COMPONENT);
01484        alarm;
01485        alarm = icalcomponent_get_next_component(parent,ICAL_VALARM_COMPONENT)) {
01486     readAlarm(alarm,incidence);
01487   }
01488   // Fix incorrect alarm settings by other applications (like outloook 9)
01489   if ( mCompat ) mCompat->fixAlarms( incidence );
01490 
01491 }
01492 
01493 void ICalFormatImpl::readIncidenceBase(icalcomponent *parent,IncidenceBase *incidenceBase)
01494 {
01495   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_ANY_PROPERTY);
01496 
01497   while (p) {
01498     icalproperty_kind kind = icalproperty_isa(p);
01499     switch (kind) {
01500 
01501       case ICAL_UID_PROPERTY:  // unique id
01502         incidenceBase->setUid(QString::fromUtf8(icalproperty_get_uid(p)));
01503         break;
01504 
01505       case ICAL_ORGANIZER_PROPERTY:  // organizer
01506         incidenceBase->setOrganizer( readOrganizer(p));
01507         break;
01508 
01509       case ICAL_ATTENDEE_PROPERTY:  // attendee
01510         incidenceBase->addAttendee(readAttendee(p));
01511         break;
01512 
01513       case ICAL_COMMENT_PROPERTY:
01514         incidenceBase->addComment(
01515             QString::fromUtf8(icalproperty_get_comment(p)));
01516         break;
01517 
01518       default:
01519         break;
01520     }
01521 
01522     p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY);
01523   }
01524 
01525   // kpilot stuff
01526   // TODO: move this application-specific code to kpilot
01527   // need to get X-PILOT* attributes out, set correct properties, and get
01528   // rid of them...
01529   // Pointer fun, as per libical documentation
01530   // (documented in UsingLibical.txt)
01531   icalproperty *next =0;
01532 
01533   for ( p = icalcomponent_get_first_property(parent,ICAL_X_PROPERTY);
01534        p != 0;
01535        p = next )
01536   {
01537 
01538     next = icalcomponent_get_next_property(parent,ICAL_X_PROPERTY);
01539 
01540     QString value = QString::fromUtf8(icalproperty_get_x(p));
01541     QString name = icalproperty_get_x_name(p);
01542 
01543     if (name == "X-PILOTID" && !value.isEmpty()) {
01544       incidenceBase->setPilotId(value.toInt());
01545       icalcomponent_remove_property(parent,p);
01546     } else if (name == "X-PILOTSTAT" && !value.isEmpty()) {
01547       incidenceBase->setSyncStatus(value.toInt());
01548       icalcomponent_remove_property(parent,p);
01549     }
01550   }
01551 
01552   // custom properties
01553   readCustomProperties(parent, incidenceBase);
01554 }
01555 
01556 void ICalFormatImpl::readCustomProperties(icalcomponent *parent,CustomProperties *properties)
01557 {
01558   QMap<QCString, QString> customProperties;
01559   QString lastProperty;
01560 
01561   icalproperty *p = icalcomponent_get_first_property(parent,ICAL_X_PROPERTY);
01562 
01563   while (p) {
01564 
01565     QString value = QString::fromUtf8(icalproperty_get_x(p));
01566     const char *name = icalproperty_get_x_name(p);
01567     if ( lastProperty != name ) {
01568       customProperties[name] = value;
01569     } else {
01570       customProperties[name] = customProperties[name].append( "," ).append( value );
01571     }
01572     // kdDebug(5800) << "Set custom property [" << name << '=' << value << ']' << endl;
01573     p = icalcomponent_get_next_property(parent,ICAL_X_PROPERTY);
01574     lastProperty = name;
01575   }
01576 
01577   properties->setCustomProperties(customProperties);
01578 }
01579 
01580 
01581 
01582 void ICalFormatImpl::readRecurrenceRule(icalproperty *rrule,Incidence *incidence )
01583 {
01584 //  kdDebug(5800) << "Read recurrence for " << incidence->summary() << endl;
01585 
01586   Recurrence *recur = incidence->recurrence();
01587 
01588   struct icalrecurrencetype r = icalproperty_get_rrule(rrule);
01589 //   dumpIcalRecurrence(r);
01590 
01591   RecurrenceRule *recurrule = new RecurrenceRule( /*incidence*/ );
01592   recurrule->setStartDt( incidence->dtStart() );
01593   readRecurrence( r, recurrule );
01594   recur->addRRule( recurrule );
01595 }
01596 
01597 void ICalFormatImpl::readExceptionRule( icalproperty *rrule, Incidence *incidence )
01598 {
01599 //  kdDebug(5800) << "Read recurrence for " << incidence->summary() << endl;
01600 
01601   struct icalrecurrencetype r = icalproperty_get_exrule(rrule);
01602 //   dumpIcalRecurrence(r);
01603 
01604   RecurrenceRule *recurrule = new RecurrenceRule( /*incidence*/ );
01605   recurrule->setStartDt( incidence->dtStart() );
01606   readRecurrence( r, recurrule );
01607 
01608   Recurrence *recur = incidence->recurrence();
01609   recur->addExRule( recurrule );
01610 }
01611 
01612 void ICalFormatImpl::readRecurrence( const struct icalrecurrencetype &r, RecurrenceRule* recur )
01613 {
01614   // Generate the RRULE string
01615   recur->mRRule = QString( icalrecurrencetype_as_string( const_cast<struct icalrecurrencetype*>(&r) ) );
01616   // Period
01617   switch ( r.freq ) {
01618     case ICAL_SECONDLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rSecondly ); break;
01619     case ICAL_MINUTELY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rMinutely ); break;
01620     case ICAL_HOURLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rHourly ); break;
01621     case ICAL_DAILY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rDaily ); break;
01622     case ICAL_WEEKLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rWeekly ); break;
01623     case ICAL_MONTHLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rMonthly ); break;
01624     case ICAL_YEARLY_RECURRENCE: recur->setRecurrenceType( RecurrenceRule::rYearly ); break;
01625     case ICAL_NO_RECURRENCE:
01626     default:
01627         recur->setRecurrenceType( RecurrenceRule::rNone );
01628   }
01629   // Frequency
01630   recur->setFrequency( r.interval );
01631 
01632   // Duration & End Date
01633   if ( !icaltime_is_null_time( r.until ) ) {
01634     icaltimetype t;
01635     t = r.until;
01636     // Convert to the correct time zone! it's in UTC by specification.
01637     QDateTime endDate( readICalDateTime(t) );
01638     recur->setEndDt( endDate );
01639   } else {
01640     if (r.count == 0)
01641       recur->setDuration( -1 );
01642     else
01643       recur->setDuration( r.count );
01644   }
01645 
01646   // Week start setting
01647   int wkst = (r.week_start + 5)%7 + 1;
01648   recur->setWeekStart( wkst );
01649 
01650   // And now all BY*
01651   QValueList<int> lst;
01652   int i;
01653   int index = 0;
01654 
01655 #define readSetByList(rrulecomp,setfunc) \
01656   index = 0; \
01657   lst.clear(); \
01658   while ( (i = r.rrulecomp[index++] ) != ICAL_RECURRENCE_ARRAY_MAX ) \
01659     lst.append( i ); \
01660   if ( !lst.isEmpty() ) recur->setfunc( lst );
01661 
01662   // BYSECOND, MINUTE and HOUR, MONTHDAY, YEARDAY, WEEKNUMBER, MONTH
01663   // and SETPOS are standard int lists, so we can treat them with the
01664   // same macro
01665   readSetByList( by_second, setBySeconds );
01666   readSetByList( by_minute, setByMinutes );
01667   readSetByList( by_hour, setByHours );
01668   readSetByList( by_month_day, setByMonthDays );
01669   readSetByList( by_year_day, setByYearDays );
01670   readSetByList( by_week_no, setByWeekNumbers );
01671   readSetByList( by_month, setByMonths );
01672   readSetByList( by_set_pos, setBySetPos );
01673 #undef readSetByList
01674 
01675   // BYDAY is a special case, since it's not an int list
01676   QValueList<RecurrenceRule::WDayPos> wdlst;
01677   short day;
01678   index=0;
01679   while((day = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
01680     RecurrenceRule::WDayPos pos;
01681     pos.setDay( ( icalrecurrencetype_day_day_of_week( day ) + 5 )%7 + 1 );
01682     pos.setPos( icalrecurrencetype_day_position( day ) );
01683 //     kdDebug(5800)<< "    o) By day, index="<<index-1<<", pos="<<pos.Pos<<", day="<<pos.Day<<endl;
01684     wdlst.append( pos );
01685   }
01686   if ( !wdlst.isEmpty() ) recur->setByDays( wdlst );
01687 
01688 
01689   // TODO Store all X- fields of the RRULE inside the recurrence (so they are
01690   // preserved
01691 }
01692 
01693 
01694 void ICalFormatImpl::readAlarm(icalcomponent *alarm,Incidence *incidence)
01695 {
01696 //   kdDebug(5800) << "Read alarm for " << incidence->summary() << endl;
01697 
01698   Alarm* ialarm = incidence->newAlarm();
01699   ialarm->setRepeatCount(0);
01700   ialarm->setEnabled(true);
01701 
01702   // Determine the alarm's action type
01703   icalproperty *p = icalcomponent_get_first_property(alarm,ICAL_ACTION_PROPERTY);
01704   Alarm::Type type = Alarm::Display;
01705   icalproperty_action action = ICAL_ACTION_DISPLAY;
01706   if ( !p ) {
01707     kdDebug(5800) << "Unknown type of alarm, using default" << endl;
01708 //    return;
01709   } else {
01710 
01711     action = icalproperty_get_action(p);
01712     switch ( action ) {
01713       case ICAL_ACTION_DISPLAY:   type = Alarm::Display;  break;
01714       case ICAL_ACTION_AUDIO:     type = Alarm::Audio;  break;
01715       case ICAL_ACTION_PROCEDURE: type = Alarm::Procedure;  break;
01716       case ICAL_ACTION_EMAIL:     type = Alarm::Email;  break;
01717       default:
01718         kdDebug(5800) << "Unknown type of alarm: " << action << endl;
01719 //        type = Alarm::Invalid;
01720     }
01721   }
01722   ialarm->setType(type);
01723 // kdDebug(5800) << " alarm type =" << type << endl;
01724 
01725   p = icalcomponent_get_first_property(alarm,ICAL_ANY_PROPERTY);
01726   while (p) {
01727     icalproperty_kind kind = icalproperty_isa(p);
01728 
01729     switch (kind) {
01730 
01731       case ICAL_TRIGGER_PROPERTY: {
01732         icaltriggertype trigger = icalproperty_get_trigger(p);
01733         if (icaltime_is_null_time(trigger.time)) {
01734           if (icaldurationtype_is_null_duration(trigger.duration)) {
01735             kdDebug(5800) << "ICalFormatImpl::readAlarm(): Trigger has no time and no duration." << endl;
01736           } else {
01737             Duration duration = icaldurationtype_as_int( trigger.duration );
01738             icalparameter *param = icalproperty_get_first_parameter(p,ICAL_RELATED_PARAMETER);
01739             if (param && icalparameter_get_related(param) == ICAL_RELATED_END)
01740               ialarm->setEndOffset(duration);
01741             else
01742               ialarm->setStartOffset(duration);
01743           }
01744         } else {
01745           ialarm->setTime(readICalDateTime(trigger.time));
01746         }
01747         break;
01748       }
01749       case ICAL_DURATION_PROPERTY: {
01750         icaldurationtype duration = icalproperty_get_duration(p);
01751         ialarm->setSnoozeTime(icaldurationtype_as_int(duration)/60);
01752         break;
01753       }
01754       case ICAL_REPEAT_PROPERTY:
01755         ialarm->setRepeatCount(icalproperty_get_repeat(p));
01756         break;
01757 
01758       // Only in DISPLAY and EMAIL and PROCEDURE alarms
01759       case ICAL_DESCRIPTION_PROPERTY: {
01760         QString description = QString::fromUtf8(icalproperty_get_description(p));
01761         switch ( action ) {
01762           case ICAL_ACTION_DISPLAY:
01763             ialarm->setText( description );
01764             break;
01765           case ICAL_ACTION_PROCEDURE:
01766             ialarm->setProgramArguments( description );
01767             break;
01768           case ICAL_ACTION_EMAIL:
01769             ialarm->setMailText( description );
01770             break;
01771           default:
01772             break;
01773         }
01774         break;
01775       }
01776       // Only in EMAIL alarm
01777       case ICAL_SUMMARY_PROPERTY:
01778         ialarm->setMailSubject(QString::fromUtf8(icalproperty_get_summary(p)));
01779         break;
01780 
01781       // Only in EMAIL alarm
01782       case ICAL_ATTENDEE_PROPERTY: {
01783         QString email = QString::fromUtf8(icalproperty_get_attendee(p));
01784         if ( email.startsWith("mailto:", false ) ) {
01785           email = email.mid( 7 );
01786         }
01787         QString name;
01788         icalparameter *param = icalproperty_get_first_parameter(p,ICAL_CN_PARAMETER);
01789         if (param) {
01790           name = QString::fromUtf8(icalparameter_get_cn(param));
01791         }
01792         ialarm->addMailAddress(Person(name, email));
01793         break;
01794       }
01795       // Only in AUDIO and EMAIL and PROCEDURE alarms
01796       case ICAL_ATTACH_PROPERTY: {
01797         Attachment *attach = readAttachment( p );
01798         if ( attach && attach->isUri() ) {
01799           switch ( action ) {
01800             case ICAL_ACTION_AUDIO:
01801               ialarm->setAudioFile( attach->uri() );
01802               break;
01803             case ICAL_ACTION_PROCEDURE:
01804               ialarm->setProgramFile( attach->uri() );
01805               break;
01806             case ICAL_ACTION_EMAIL:
01807               ialarm->addMailAttachment( attach->uri() );
01808               break;
01809             default:
01810               break;
01811           }
01812         } else {
01813           kdDebug() << "Alarm attachments currently only support URIs, but "
01814                        "no binary data" << endl;
01815         }
01816         delete attach;
01817         break;
01818       }
01819       default:
01820         break;
01821     }
01822 
01823     p = icalcomponent_get_next_property(alarm,ICAL_ANY_PROPERTY);
01824   }
01825 
01826   // custom properties
01827   readCustomProperties(alarm, ialarm);
01828 
01829   // TODO: check for consistency of alarm properties
01830 }
01831 
01832 icaldatetimeperiodtype ICalFormatImpl::writeICalDatePeriod( const QDate &date )
01833 {
01834   icaldatetimeperiodtype t;
01835   t.time = writeICalDate( date );
01836   t.period = icalperiodtype_null_period();
01837   return t;
01838 }
01839 
01840 icaldatetimeperiodtype ICalFormatImpl::writeICalDateTimePeriod( const QDateTime &date )
01841 {
01842   icaldatetimeperiodtype t;
01843   t.time = writeICalDateTime( date );
01844   t.period = icalperiodtype_null_period();
01845   return t;
01846 }
01847 
01848 icaltimetype ICalFormatImpl::writeICalDate(const QDate &date)
01849 {
01850   icaltimetype t = icaltime_null_time();
01851 
01852   t.year = date.year();
01853   t.month = date.month();
01854   t.day = date.day();
01855 
01856   t.hour = 0;
01857   t.minute = 0;
01858   t.second = 0;
01859 
01860   t.is_date = 1;
01861 
01862   t.is_utc = 0;
01863 
01864   t.zone = 0;
01865 
01866   return t;
01867 }
01868 
01869 icaltimetype ICalFormatImpl::writeICalDateTime(const QDateTime &datetime)
01870 {
01871   icaltimetype t = icaltime_null_time();
01872 
01873   t.year = datetime.date().year();
01874   t.month = datetime.date().month();
01875   t.day = datetime.date().day();
01876 
01877   t.hour = datetime.time().hour();
01878   t.minute = datetime.time().minute();
01879   t.second = datetime.time().second();
01880 
01881   t.is_date = 0;
01882   t.zone = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01883   t.is_utc = 0;
01884 
01885  // _dumpIcaltime( t );
01886   /* The QDateTime we get passed in is to be considered in the timezone of
01887    * the current calendar (mParent's), or, if there is none, to be floating.
01888    * In the later case store a floating time, in the former normalize to utc. */
01889   if (mParent->timeZoneId().isEmpty())
01890     t = icaltime_convert_to_zone( t, 0 ); //make floating timezone
01891   else {
01892     icaltimezone* tz = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01893     icaltimezone* utc = icaltimezone_get_utc_timezone();
01894     if ( tz != utc ) {
01895       t.zone = tz;
01896       t = icaltime_convert_to_zone( t, utc );
01897     } else {
01898       t.is_utc = 1;
01899       t.zone = utc;
01900     }
01901   }
01902 //  _dumpIcaltime( t );
01903 
01904   return t;
01905 }
01906 
01907 QDateTime ICalFormatImpl::readICalDateTime( icaltimetype& t, icaltimezone* tz )
01908 {
01909 //   kdDebug(5800) << "ICalFormatImpl::readICalDateTime()" << endl;
01910   icaltimezone *zone = tz;
01911   if ( tz && t.is_utc == 0 ) { // Only use the TZ if time is not UTC.
01912     // FIXME: We'll need to make sure to apply the appropriate TZ, not just
01913     //        the first one found.
01914     t.zone = tz;
01915     t.is_utc = (tz == icaltimezone_get_utc_timezone())?1:0;
01916   } else {
01917     zone = icaltimezone_get_utc_timezone();
01918   }
01919   //_dumpIcaltime( t );
01920 
01921   // Convert to view time
01922   if ( !mParent->timeZoneId().isEmpty() && t.zone ) {
01923 //    kdDebug(5800) << "--- Converting time from: " << icaltimezone_get_tzid( const_cast<icaltimezone*>( t.zone ) ) << " (" << ICalDate2QDate(t) << ")." << endl;
01924     icaltimezone* viewTimeZone = icaltimezone_get_builtin_timezone ( mParent->timeZoneId().latin1() );
01925     icaltimezone_convert_time(  &t, zone, viewTimeZone );
01926 //    kdDebug(5800) << "--- Converted to zone " << mParent->timeZoneId() << " (" << ICalDate2QDate(t) << ")." << endl;
01927   }
01928 
01929   return ICalDate2QDate(t);
01930 }
01931 
01932 QDate ICalFormatImpl::readICalDate(icaltimetype t)
01933 {
01934   return ICalDate2QDate(t).date();
01935 }
01936 
01937 icaldurationtype ICalFormatImpl::writeICalDuration(int seconds)
01938 {
01939   // should be able to use icaldurationtype_from_int(), except we know
01940   // that some older tools do not properly support weeks. So we never
01941   // set a week duration, only days
01942 
01943   icaldurationtype d;
01944 
01945   d.is_neg  = (seconds<0)?1:0;
01946   if (seconds<0) seconds = -seconds;
01947 
01948   d.weeks    = 0;
01949   d.days     = seconds / gSecondsPerDay;
01950   seconds   %= gSecondsPerDay;
01951   d.hours    = seconds / gSecondsPerHour;
01952   seconds   %= gSecondsPerHour;
01953   d.minutes  = seconds / gSecondsPerMinute;
01954   seconds   %= gSecondsPerMinute;
01955   d.seconds  = seconds;
01956 
01957   return d;
01958 }
01959 
01960 int ICalFormatImpl::readICalDuration(icaldurationtype d)
01961 {
01962   int result = 0;
01963 
01964   result += d.weeks   * gSecondsPerWeek;
01965   result += d.days    * gSecondsPerDay;
01966   result += d.hours   * gSecondsPerHour;
01967   result += d.minutes * gSecondsPerMinute;
01968   result += d.seconds;
01969 
01970   if (d.is_neg) result *= -1;
01971 
01972   return result;
01973 }
01974 
01975 icalcomponent *ICalFormatImpl::createCalendarComponent(Calendar *cal)
01976 {
01977   icalcomponent *calendar;
01978 
01979   // Root component
01980   calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
01981 
01982   icalproperty *p;
01983 
01984   // Product Identifier
01985   p = icalproperty_new_prodid(CalFormat::productId().utf8());
01986   icalcomponent_add_property(calendar,p);
01987 
01988   // TODO: Add time zone
01989 
01990   // iCalendar version (2.0)
01991   p = icalproperty_new_version(const_cast<char *>(_ICAL_VERSION));
01992   icalcomponent_add_property(calendar,p);
01993 
01994   // Custom properties
01995   if( cal != 0 )
01996     writeCustomProperties(calendar, cal);
01997 
01998   return calendar;
01999 }
02000 
02001 
02002 
02003 // take a raw vcalendar (i.e. from a file on disk, clipboard, etc. etc.
02004 // and break it down from its tree-like format into the dictionary format
02005 // that is used internally in the ICalFormatImpl.
02006 bool ICalFormatImpl::populate( Calendar *cal, icalcomponent *calendar)
02007 {
02008   // this function will populate the caldict dictionary and other event
02009   // lists. It turns vevents into Events and then inserts them.
02010 
02011     if (!calendar) return false;
02012 
02013 // TODO: check for METHOD
02014 
02015   icalproperty *p;
02016 
02017   p = icalcomponent_get_first_property(calendar,ICAL_PRODID_PROPERTY);
02018   if (!p) {
02019     kdDebug(5800) << "No PRODID property found" << endl;
02020     mLoadedProductId = "";
02021   } else {
02022     mLoadedProductId = QString::fromUtf8(icalproperty_get_prodid(p));
02023 //    kdDebug(5800) << "VCALENDAR prodid: '" << mLoadedProductId << "'" << endl;
02024 
02025     delete mCompat;
02026     mCompat = CompatFactory::createCompat( mLoadedProductId );
02027   }
02028 
02029   p = icalcomponent_get_first_property(calendar,ICAL_VERSION_PROPERTY);
02030   if (!p) {
02031     kdDebug(5800) << "No VERSION property found" << endl;
02032     mParent->setException(new ErrorFormat(ErrorFormat::CalVersionUnknown));
02033     return false;
02034   } else {
02035     const char *version = icalproperty_get_version(p);
02036 //    kdDebug(5800) << "VCALENDAR version: '" << version << "'" << endl;
02037 
02038     if (strcmp(version,"1.0") == 0) {
02039       kdDebug(5800) << "Expected iCalendar, got vCalendar" << endl;
02040       mParent->setException(new ErrorFormat(ErrorFormat::CalVersion1,
02041                             i18n("Expected iCalendar format")));
02042       return false;
02043     } else if (strcmp(version,"2.0") != 0) {
02044       kdDebug(5800) << "Expected iCalendar, got unknown format" << endl;
02045       mParent->setException(new ErrorFormat(ErrorFormat::CalVersionUnknown));
02046       return false;
02047     }
02048   }
02049 
02050   // custom properties
02051   readCustomProperties(calendar, cal);
02052 
02053 // TODO: set time zone
02054 
02055   // read a VTIMEZONE if there is one
02056   icalcomponent *ctz =
02057     icalcomponent_get_first_component( calendar, ICAL_VTIMEZONE_COMPONENT );
02058 
02059   // Store all events with a relatedTo property in a list for post-processing
02060   mEventsRelate.clear();
02061   mTodosRelate.clear();
02062   // TODO: make sure that only actually added events go to this lists.
02063 
02064   icalcomponent *c;
02065 
02066   // Iterate through all todos
02067   c = icalcomponent_get_first_component(calendar,ICAL_VTODO_COMPONENT);
02068   while (c) {
02069 //    kdDebug(5800) << "----Todo found" << endl;
02070     Todo *todo = readTodo(c);
02071     if (todo) {
02072       if (!cal->todo(todo->uid())) {
02073         cal->addTodo(todo);
02074       } else {
02075         delete todo;
02076         mTodosRelate.remove( todo );
02077       }
02078     }
02079     c = icalcomponent_get_next_component(calendar,ICAL_VTODO_COMPONENT);
02080   }
02081 
02082   // Iterate through all events
02083   c = icalcomponent_get_first_component(calendar,ICAL_VEVENT_COMPONENT);
02084   while (c) {
02085 //    kdDebug(5800) << "----Event found" << endl;
02086     Event *event = readEvent(c, ctz);
02087     if (event) {
02088       if (!cal->event(event->uid())) {
02089         cal->addEvent(event);
02090       } else {
02091         delete event;
02092         mEventsRelate.remove( event );
02093       }
02094     }
02095     c = icalcomponent_get_next_component(calendar,ICAL_VEVENT_COMPONENT);
02096   }
02097 
02098   // Iterate through all journals
02099   c = icalcomponent_get_first_component(calendar,ICAL_VJOURNAL_COMPONENT);
02100   while (c) {
02101 //    kdDebug(5800) << "----Journal found" << endl;
02102     Journal *journal = readJournal(c);
02103     if (journal) {
02104       if (!cal->journal(journal->uid())) {
02105         cal->addJournal(journal);
02106       } else {
02107         delete journal;
02108       }
02109     }
02110     c = icalcomponent_get_next_component(calendar,ICAL_VJOURNAL_COMPONENT);
02111   }
02112 
02113   // Post-Process list of events with relations, put Event objects in relation
02114   Event::List::ConstIterator eIt;
02115   for ( eIt = mEventsRelate.begin(); eIt != mEventsRelate.end(); ++eIt ) {
02116     (*eIt)->setRelatedTo( cal->incidence( (*eIt)->relatedToUid() ) );
02117   }
02118   Todo::List::ConstIterator tIt;
02119   for ( tIt = mTodosRelate.begin(); tIt != mTodosRelate.end(); ++tIt ) {
02120     (*tIt)->setRelatedTo( cal->incidence( (*tIt)->relatedToUid() ) );
02121    }
02122 
02123   return true;
02124 }
02125 
02126 QString ICalFormatImpl::extractErrorProperty(icalcomponent *c)
02127 {
02128 //  kdDebug(5800) << "ICalFormatImpl:extractErrorProperty: "
02129 //            << icalcomponent_as_ical_string(c) << endl;
02130 
02131   QString errorMessage;
02132 
02133   icalproperty *error;
02134   error = icalcomponent_get_first_property(c,ICAL_XLICERROR_PROPERTY);
02135   while(error) {
02136     errorMessage += icalproperty_get_xlicerror(error);
02137     errorMessage += "\n";
02138     error = icalcomponent_get_next_property(c,ICAL_XLICERROR_PROPERTY);
02139   }
02140 
02141 //  kdDebug(5800) << "ICalFormatImpl:extractErrorProperty: " << errorMessage << endl;
02142 
02143   return errorMessage;
02144 }
02145 
02146 void ICalFormatImpl::dumpIcalRecurrence(icalrecurrencetype r)
02147 {
02148   int i;
02149 
02150   kdDebug(5800) << " Freq: " << r.freq << endl;
02151   kdDebug(5800) << " Until: " << icaltime_as_ical_string(r.until) << endl;
02152   kdDebug(5800) << " Count: " << r.count << endl;
02153   if (r.by_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02154     int index = 0;
02155     QString out = " By Day: ";
02156     while((i = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02157       out.append(QString::number(i) + " ");
02158     }
02159     kdDebug(5800) << out << endl;
02160   }
02161   if (r.by_month_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02162     int index = 0;
02163     QString out = " By Month Day: ";
02164     while((i = r.by_month_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02165       out.append(QString::number(i) + " ");
02166     }
02167     kdDebug(5800) << out << endl;
02168   }
02169   if (r.by_year_day[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02170     int index = 0;
02171     QString out = " By Year Day: ";
02172     while((i = r.by_year_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02173       out.append(QString::number(i) + " ");
02174     }
02175     kdDebug(5800) << out << endl;
02176   }
02177   if (r.by_month[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02178     int index = 0;
02179     QString out = " By Month: ";
02180     while((i = r.by_month[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02181       out.append(QString::number(i) + " ");
02182     }
02183     kdDebug(5800) << out << endl;
02184   }
02185   if (r.by_set_pos[0] != ICAL_RECURRENCE_ARRAY_MAX) {
02186     int index = 0;
02187     QString out = " By Set Pos: ";
02188     while((i = r.by_set_pos[index++]) != ICAL_RECURRENCE_ARRAY_MAX) {
02189       kdDebug(5800) << "========= " << i << endl;
02190       out.append(QString::number(i) + " ");
02191     }
02192     kdDebug(5800) << out << endl;
02193   }
02194 }
02195 
02196 icalcomponent *ICalFormatImpl::createScheduleComponent(IncidenceBase *incidence,
02197                                                    Scheduler::Method method)
02198 {
02199   icalcomponent *message = createCalendarComponent();
02200 
02201   icalproperty_method icalmethod = ICAL_METHOD_NONE;
02202 
02203   switch (method) {
02204     case Scheduler::Publish:
02205       icalmethod = ICAL_METHOD_PUBLISH;
02206       break;
02207     case Scheduler::Request:
02208       icalmethod = ICAL_METHOD_REQUEST;
02209       break;
02210     case Scheduler::Refresh:
02211       icalmethod = ICAL_METHOD_REFRESH;
02212       break;
02213     case Scheduler::Cancel:
02214       icalmethod = ICAL_METHOD_CANCEL;
02215       break;
02216     case Scheduler::Add:
02217       icalmethod = ICAL_METHOD_ADD;
02218       break;
02219     case Scheduler::Reply:
02220       icalmethod = ICAL_METHOD_REPLY;
02221       break;
02222     case Scheduler::Counter:
02223       icalmethod = ICAL_METHOD_COUNTER;
02224       break;
02225     case Scheduler::Declinecounter:
02226       icalmethod = ICAL_METHOD_DECLINECOUNTER;
02227       break;
02228     default:
02229       kdDebug(5800) << "ICalFormat::createScheduleMessage(): Unknow method" << endl;
02230       return message;
02231   }
02232 
02233   icalcomponent_add_property(message,icalproperty_new_method(icalmethod));
02234 
02235   icalcomponent *inc = writeIncidence( incidence, method );
02236   /*
02237    * RFC 2446 states in section 3.4.3 ( REPLY to a VTODO ), that
02238    * a REQUEST-STATUS property has to be present. For the other two, event and
02239    * free busy, it can be there, but is optional. Until we do more
02240    * fine grained handling, assume all is well. Note that this is the
02241    * status of the _request_, not the attendee. Just to avoid confusion.
02242    * - till
02243    */
02244   if ( icalmethod == ICAL_METHOD_REPLY ) {
02245     struct icalreqstattype rst;
02246     rst.code = ICAL_2_0_SUCCESS_STATUS;
02247     rst.desc = 0;
02248     rst.debug = 0;
02249     icalcomponent_add_property( inc, icalproperty_new_requeststatus( rst ) );
02250   }
02251   icalcomponent_add_component( message, inc );
02252 
02253   return message;
02254 }
KDE Home | KDE Accessibility Home | Description of Access Keys