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