libkcal

icalformat.cpp

00001 /*
00002     This file is part of libkcal.
00003 
00004     Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
00005 
00006     This library is free software; you can redistribute it and/or
00007     modify it under the terms of the GNU Library General Public
00008     License as published by the Free Software Foundation; either
00009     version 2 of the License, or (at your option) any later version.
00010 
00011     This library is distributed in the hope that it will be useful,
00012     but WITHOUT ANY WARRANTY; without even the implied warranty of
00013     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014     Library General Public License for more details.
00015 
00016     You should have received a copy of the GNU Library General Public License
00017     along with this library; see the file COPYING.LIB.  If not, write to
00018     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00019     Boston, MA 02110-1301, USA.
00020 */
00021 
00022 #include <qdatetime.h>
00023 #include <qstring.h>
00024 #include <qptrlist.h>
00025 #include <qregexp.h>
00026 #include <qclipboard.h>
00027 #include <qfile.h>
00028 #include <qtextstream.h>
00029 
00030 #include <kdebug.h>
00031 #include <klocale.h>
00032 
00033 extern "C" {
00034   #include <ical.h>
00035   #include <icalss.h>
00036   #include <icalparser.h>
00037   #include <icalrestriction.h>
00038   #include <icalmemory.h>
00039 }
00040 
00041 #include "calendar.h"
00042 #include "calendarlocal.h"
00043 #include "journal.h"
00044 
00045 #include "icalformat.h"
00046 #include "icalformatimpl.h"
00047 #include <ksavefile.h>
00048 
00049 #include <stdio.h>
00050 
00051 #define _ICAL_VERSION "2.0"
00052 
00053 using namespace KCal;
00054 
00055 ICalFormat::ICalFormat() : mImpl(0)
00056 {
00057   setImplementation( new ICalFormatImpl( this ) );
00058 
00059   mTimeZoneId = "UTC";
00060   mUtc = true;
00061 }
00062 
00063 ICalFormat::~ICalFormat()
00064 {
00065   delete mImpl;
00066 }
00067 
00068 void ICalFormat::setImplementation( ICalFormatImpl *impl )
00069 {
00070   if ( mImpl ) delete mImpl;
00071   mImpl = impl;
00072 }
00073 
00074 #if defined(_AIX) && defined(open)
00075 #undef open
00076 #endif
00077 
00078 bool ICalFormat::load( Calendar *calendar, const QString &fileName)
00079 {
00080   kdDebug(5800) << "ICalFormat::load() " << fileName << endl;
00081 
00082   clearException();
00083 
00084   QFile file( fileName );
00085   if (!file.open( IO_ReadOnly ) ) {
00086     kdDebug(5800) << "ICalFormat::load() load error" << endl;
00087     setException(new ErrorFormat(ErrorFormat::LoadError));
00088     return false;
00089   }
00090   QTextStream ts( &file );
00091   ts.setEncoding( QTextStream::Latin1 );
00092   QString text = ts.read();
00093   file.close();
00094 
00095   if ( text.stripWhiteSpace().isEmpty() ) // empty files are valid
00096     return true;
00097   else
00098     return fromRawString( calendar, text.latin1() );
00099 }
00100 
00101 
00102 bool ICalFormat::save( Calendar *calendar, const QString &fileName )
00103 {
00104   kdDebug(5800) << "ICalFormat::save(): " << fileName << endl;
00105 
00106   clearException();
00107 
00108   QString text = toString( calendar );
00109 
00110   if ( text.isNull() ) return false;
00111 
00112   // Write backup file
00113   KSaveFile::backupFile( fileName );
00114 
00115   KSaveFile file( fileName );
00116   if ( file.status() != 0 ) {
00117     kdDebug(5800) << "ICalFormat::save() errno: " << strerror( file.status() )
00118               << endl;
00119     setException( new ErrorFormat( ErrorFormat::SaveError,
00120                   i18n( "Error saving to '%1'." ).arg( fileName ) ) );
00121     return false;
00122   }
00123 
00124   // Convert to UTF8 and save
00125   QCString textUtf8 = text.utf8();
00126   file.file()->writeBlock( textUtf8.data(), textUtf8.size() - 1 );
00127 
00128   if ( !file.close() ) {
00129     kdDebug(5800) << "KSaveFile: close: status was " << file.status() << ". See errno.h." << endl;
00130     setException(new ErrorFormat(ErrorFormat::SaveError,
00131                  i18n("Could not save '%1'").arg(fileName)));
00132     return false;
00133   }
00134 
00135   return true;
00136 }
00137 
00138 bool ICalFormat::fromString( Calendar *cal, const QString &text )
00139 {
00140   return fromRawString( cal, text.utf8() );
00141 }
00142 
00143 bool ICalFormat::fromRawString( Calendar *cal, const QCString &text )
00144 {
00145   setTimeZone( cal->timeZoneId(), !cal->isLocalTime() );
00146 
00147   // Get first VCALENDAR component.
00148   // TODO: Handle more than one VCALENDAR or non-VCALENDAR top components
00149   icalcomponent *calendar;
00150 
00151   // Let's defend const correctness until the very gates of hell^Wlibical
00152   calendar = icalcomponent_new_from_string( const_cast<char*>( (const char*)text ) );
00153   //  kdDebug(5800) << "Error: " << icalerror_perror() << endl;
00154   if (!calendar) {
00155     kdDebug(5800) << "ICalFormat::load() parse error" << endl;
00156     setException(new ErrorFormat(ErrorFormat::ParseErrorIcal));
00157     return false;
00158   }
00159 
00160   bool success = true;
00161 
00162   if (icalcomponent_isa(calendar) == ICAL_XROOT_COMPONENT) {
00163     icalcomponent *comp;
00164     for ( comp = icalcomponent_get_first_component(calendar, ICAL_VCALENDAR_COMPONENT);
00165           comp != 0; comp = icalcomponent_get_next_component(calendar, ICAL_VCALENDAR_COMPONENT) ) {
00166       // put all objects into their proper places
00167       if ( !mImpl->populate( cal, comp ) ) {
00168         kdDebug(5800) << "ICalFormat::load(): Could not populate calendar" << endl;
00169         if ( !exception() ) {
00170           setException(new ErrorFormat(ErrorFormat::ParseErrorKcal));
00171         }
00172         success = false;
00173       } else {
00174         mLoadedProductId = mImpl->loadedProductId();
00175       }
00176       icalcomponent_free( comp );
00177     }
00178   } else if (icalcomponent_isa(calendar) != ICAL_VCALENDAR_COMPONENT) {
00179     kdDebug(5800) << "ICalFormat::load(): No VCALENDAR component found" << endl;
00180     setException(new ErrorFormat(ErrorFormat::NoCalendar));
00181     success = false;
00182   } else {
00183     // put all objects into their proper places
00184     if ( !mImpl->populate( cal, calendar ) ) {
00185       kdDebug(5800) << "ICalFormat::load(): Could not populate calendar" << endl;
00186       if ( !exception() ) {
00187         setException(new ErrorFormat(ErrorFormat::ParseErrorKcal));
00188       }
00189       success = false;
00190     } else
00191       mLoadedProductId = mImpl->loadedProductId();
00192   }
00193 
00194   icalcomponent_free( calendar );
00195   icalmemory_free_ring();
00196 
00197   return success;
00198 }
00199 
00200 Incidence *ICalFormat::fromString( const QString &text )
00201 {
00202   CalendarLocal cal( mTimeZoneId );
00203   fromString(&cal, text);
00204 
00205   Incidence *ical = 0;
00206   Event::List elist = cal.events();
00207   if ( elist.count() > 0 ) {
00208     ical = elist.first();
00209   } else {
00210     Todo::List tlist = cal.todos();
00211     if ( tlist.count() > 0 ) {
00212       ical = tlist.first();
00213     } else {
00214       Journal::List jlist = cal.journals();
00215       if ( jlist.count() > 0 ) {
00216         ical = jlist.first();
00217       }
00218     }
00219   }
00220 
00221   return ical ? ical->clone() : 0;
00222 }
00223 
00224 QString ICalFormat::toString( Calendar *cal )
00225 {
00226   setTimeZone( cal->timeZoneId(), !cal->isLocalTime() );
00227 
00228   icalcomponent *calendar = mImpl->createCalendarComponent(cal);
00229 
00230   icalcomponent *component;
00231 
00232   // todos
00233   Todo::List todoList = cal->rawTodos();
00234   Todo::List::ConstIterator it;
00235   for( it = todoList.begin(); it != todoList.end(); ++it ) {
00236 //    kdDebug(5800) << "ICalFormat::toString() write todo "
00237 //                  << (*it)->uid() << endl;
00238     component = mImpl->writeTodo( *it );
00239     icalcomponent_add_component( calendar, component );
00240   }
00241 
00242   // events
00243   Event::List events = cal->rawEvents();
00244   Event::List::ConstIterator it2;
00245   for( it2 = events.begin(); it2 != events.end(); ++it2 ) {
00246 //    kdDebug(5800) << "ICalFormat::toString() write event "
00247 //                  << (*it2)->uid() << endl;
00248     component = mImpl->writeEvent( *it2 );
00249     icalcomponent_add_component( calendar, component );
00250   }
00251 
00252   // journals
00253   Journal::List journals = cal->journals();
00254   Journal::List::ConstIterator it3;
00255   for( it3 = journals.begin(); it3 != journals.end(); ++it3 ) {
00256     kdDebug(5800) << "ICalFormat::toString() write journal "
00257                   << (*it3)->uid() << endl;
00258     component = mImpl->writeJournal( *it3 );
00259     icalcomponent_add_component( calendar, component );
00260   }
00261 
00262   QString text = QString::fromUtf8( icalcomponent_as_ical_string( calendar ) );
00263 
00264   icalcomponent_free( calendar );
00265   icalmemory_free_ring();
00266 
00267   if (!text) {
00268     setException(new ErrorFormat(ErrorFormat::SaveError,
00269                  i18n("libical error")));
00270     return QString::null;
00271   }
00272 
00273   return text;
00274 }
00275 
00276 QString ICalFormat::toICalString( Incidence *incidence )
00277 {
00278   CalendarLocal cal( mTimeZoneId );
00279   cal.addIncidence( incidence->clone() );
00280   return toString( &cal );
00281 }
00282 
00283 QString ICalFormat::toString( Incidence *incidence )
00284 {
00285   icalcomponent *component;
00286 
00287   component = mImpl->writeIncidence( incidence );
00288 
00289   QString text = QString::fromUtf8( icalcomponent_as_ical_string( component ) );
00290 
00291   icalcomponent_free( component );
00292 
00293   return text;
00294 }
00295 
00296 QString ICalFormat::toString( RecurrenceRule *recurrence )
00297 {
00298   icalproperty *property;
00299   property = icalproperty_new_rrule( mImpl->writeRecurrenceRule( recurrence ) );
00300   QString text = QString::fromUtf8( icalproperty_as_ical_string( property ) );
00301   icalproperty_free( property );
00302   return text;
00303 }
00304 
00305 bool ICalFormat::fromString( RecurrenceRule * recurrence, const QString& rrule )
00306 {
00307   if ( !recurrence ) return false;
00308   bool success = true;
00309   icalerror_clear_errno();
00310   struct icalrecurrencetype recur = icalrecurrencetype_from_string( rrule.latin1() );
00311   if ( icalerrno != ICAL_NO_ERROR ) {
00312     kdDebug(5800) << "Recurrence parsing error: " << icalerror_strerror( icalerrno ) << endl;
00313     success = false;
00314   }
00315 
00316   if ( success ) {
00317     mImpl->readRecurrence( recur, recurrence );
00318   }
00319 
00320   return success;
00321 }
00322 
00323 
00324 QString ICalFormat::createScheduleMessage(IncidenceBase *incidence,
00325                                           Scheduler::Method method)
00326 {
00327   icalcomponent *message = 0;
00328 
00329   // Handle scheduling ID being present
00330   if ( incidence->type() == "Event" || incidence->type() == "Todo" ) {
00331     Incidence* i = static_cast<Incidence*>( incidence );
00332     Incidence* clone = i->clone();
00333 
00334     if ( i->schedulingID() != i->uid() ) {
00335       // We have a separation of scheduling ID and UID
00336       // DON'T change this order. setUid() emits incidenceUpdated().
00337       // setSchedulingID() doesn't. If you change the order, kolab resource will
00338       // catch the signal and think there isn't any schedulingId.
00339       // Possible kcal improvement: create a setUids( schedulingId, uid )
00340       // that changes both members and emits incidenceuIpdated() at the end.
00341       const QString tempId = clone->schedulingID();
00342       clone->setSchedulingID( QString::null );
00343       clone->setUid( tempId );
00344     }
00345 
00346     // If we send a schduling message this means that we have modified
00347     // the incidence. But as we save the incidence only after scheduling
00348     // the original incidence still has the old modified date.
00349     // So we set the last modified to NOW for the temporary scheduling
00350     // incidence.
00351     // To avoid regression risks we work on a clone and don't touch the
00352     // old incidence. kolab issue/4870
00353     clone->setLastModified( QDateTime::currentDateTime() );
00354 
00355     // Build the message with the cloned incidence
00356     message = mImpl->createScheduleComponent( clone, method );
00357 
00358     // And clean up
00359     delete clone;
00360   }
00361 
00362   if ( message == 0 )
00363     message = mImpl->createScheduleComponent(incidence,method);
00364 
00365   // FIXME TODO: Don't we have to free message? What about the ical_string? MEMLEAK
00366   QString messageText = QString::fromUtf8( icalcomponent_as_ical_string(message) );
00367 
00368 #if 0
00369   kdDebug(5800) << "ICalFormat::createScheduleMessage: message START\n"
00370             << messageText
00371             << "ICalFormat::createScheduleMessage: message END" << endl;
00372 #endif
00373 
00374   return messageText;
00375 }
00376 
00377 FreeBusy *ICalFormat::parseFreeBusy( const QString &str )
00378 {
00379   clearException();
00380 
00381   icalcomponent *message;
00382   message = icalparser_parse_string( str.utf8() );
00383 
00384   if ( !message ) return 0;
00385 
00386   FreeBusy *freeBusy = 0;
00387 
00388   icalcomponent *c;
00389   for ( c = icalcomponent_get_first_component( message, ICAL_VFREEBUSY_COMPONENT );
00390         c != 0; c = icalcomponent_get_next_component( message, ICAL_VFREEBUSY_COMPONENT ) ) {
00391     FreeBusy *fb = mImpl->readFreeBusy( c );
00392 
00393     if ( freeBusy ) {
00394       freeBusy->merge( fb );
00395       delete fb;
00396     } else {
00397       freeBusy = fb;
00398     }
00399   }
00400 
00401   if ( !freeBusy )
00402     kdDebug(5800) << "ICalFormat:parseFreeBusy: object is not a freebusy."
00403                   << endl;
00404   return freeBusy;
00405 }
00406 
00407 ScheduleMessage *ICalFormat::parseScheduleMessage( Calendar *cal,
00408                                                    const QString &messageText )
00409 {
00410   setTimeZone( cal->timeZoneId(), !cal->isLocalTime() );
00411   clearException();
00412 
00413   if (messageText.isEmpty())
00414   {
00415     setException( new ErrorFormat( ErrorFormat::ParseErrorKcal, QString::fromLatin1( "messageText was empty, unable to parse into a ScheduleMessage" ) ) );
00416     return 0;
00417   }
00418   // TODO FIXME: Don't we have to ical-free message??? MEMLEAK
00419   icalcomponent *message;
00420   message = icalparser_parse_string(messageText.utf8());
00421 
00422   if (!message)
00423   {
00424     setException( new ErrorFormat( ErrorFormat::ParseErrorKcal, QString::fromLatin1( "icalparser was unable to parse messageText into a ScheduleMessage" ) ) );
00425     return 0;
00426   }
00427 
00428   icalproperty *m = icalcomponent_get_first_property(message,
00429                                                      ICAL_METHOD_PROPERTY);
00430   if (!m)
00431   {
00432     setException( new ErrorFormat( ErrorFormat::ParseErrorKcal, QString::fromLatin1( "message didn't contain an ICAL_METHOD_PROPERTY" ) ) );
00433     return 0;
00434   }
00435 
00436   icalcomponent *c;
00437 
00438   IncidenceBase *incidence = 0;
00439   c = icalcomponent_get_first_component(message,ICAL_VEVENT_COMPONENT);
00440   if (c) {
00441     icalcomponent *ctz = icalcomponent_get_first_component(message,ICAL_VTIMEZONE_COMPONENT);
00442     incidence = mImpl->readEvent(c, ctz);
00443   }
00444 
00445   if (!incidence) {
00446     c = icalcomponent_get_first_component(message,ICAL_VTODO_COMPONENT);
00447     if (c) {
00448       incidence = mImpl->readTodo(c);
00449     }
00450   }
00451 
00452   if (!incidence) {
00453     c = icalcomponent_get_first_component(message,ICAL_VJOURNAL_COMPONENT);
00454     if (c) {
00455       incidence = mImpl->readJournal(c);
00456     }
00457   }
00458 
00459   if (!incidence) {
00460     c = icalcomponent_get_first_component(message,ICAL_VFREEBUSY_COMPONENT);
00461     if (c) {
00462       incidence = mImpl->readFreeBusy(c);
00463     }
00464   }
00465 
00466 
00467 
00468   if (!incidence) {
00469     kdDebug(5800) << "ICalFormat:parseScheduleMessage: object is not a freebusy, event, todo or journal" << endl;
00470     setException( new ErrorFormat( ErrorFormat::ParseErrorKcal, QString::fromLatin1( "object is not a freebusy, event, todo or journal" ) ) );
00471     return 0;
00472   }
00473 
00474   kdDebug(5800) << "ICalFormat::parseScheduleMessage() getting method..." << endl;
00475 
00476   icalproperty_method icalmethod = icalproperty_get_method(m);
00477   Scheduler::Method method;
00478 
00479   switch (icalmethod) {
00480     case ICAL_METHOD_PUBLISH:
00481       method = Scheduler::Publish;
00482       break;
00483     case ICAL_METHOD_REQUEST:
00484       method = Scheduler::Request;
00485       break;
00486     case ICAL_METHOD_REFRESH:
00487       method = Scheduler::Refresh;
00488       break;
00489     case ICAL_METHOD_CANCEL:
00490       method = Scheduler::Cancel;
00491       break;
00492     case ICAL_METHOD_ADD:
00493       method = Scheduler::Add;
00494       break;
00495     case ICAL_METHOD_REPLY:
00496       method = Scheduler::Reply;
00497       break;
00498     case ICAL_METHOD_COUNTER:
00499       method = Scheduler::Counter;
00500       break;
00501     case ICAL_METHOD_DECLINECOUNTER:
00502       method = Scheduler::Declinecounter;
00503       break;
00504     default:
00505       method = Scheduler::NoMethod;
00506       kdDebug(5800) << "ICalFormat::parseScheduleMessage(): Unknow method" << endl;
00507       break;
00508   }
00509 
00510   kdDebug(5800) << "ICalFormat::parseScheduleMessage() restriction..." << endl;
00511 
00512   if (!icalrestriction_check(message)) {
00513     kdWarning(5800) << k_funcinfo << endl << "libkcal reported a problem while parsing:" << endl;
00514     kdWarning(5800) << Scheduler::translatedMethodName(method) + ": " + mImpl->extractErrorProperty(c)<< endl;
00515     /*
00516     setException(new ErrorFormat(ErrorFormat::Restriction,
00517                                    Scheduler::translatedMethodName(method) + ": " +
00518                                    mImpl->extractErrorProperty(c)));
00519     delete incidence;
00520     return 0;
00521     */
00522   }
00523   icalcomponent *calendarComponent = mImpl->createCalendarComponent(cal);
00524 
00525   Incidence *existingIncidence = cal->incidenceFromSchedulingID(incidence->uid());
00526   if (existingIncidence) {
00527     Incidence *existingIncidenceCopy = existingIncidence->clone();
00528     // TODO: check, if cast is required, or if it can be done by virtual funcs.
00529     // TODO: Use a visitor for this!
00530     if (existingIncidenceCopy->type() == "Todo") {
00531       Todo *todo = static_cast<Todo *>(existingIncidenceCopy);
00532       icalcomponent_add_component(calendarComponent,
00533                                   mImpl->writeTodo(todo));
00534     }
00535     if (existingIncidenceCopy->type() == "Event") {
00536       Event *event = static_cast<Event *>(existingIncidenceCopy);
00537       icalcomponent_add_component(calendarComponent,
00538                                   mImpl->writeEvent(event));
00539     }
00540     delete existingIncidenceCopy;
00541   } else {
00542     calendarComponent = 0;
00543   }
00544 
00545   kdDebug(5800) << "ICalFormat::parseScheduleMessage() classify..." << endl;
00546 
00547   icalproperty_xlicclass result = icalclassify( message, calendarComponent,
00548                                                 (char *)"" );
00549 
00550   kdDebug(5800) << "ICalFormat::parseScheduleMessage() returning..." << endl;
00551   kdDebug(5800) << "ICalFormat::parseScheduleMessage(), result = " << result << endl;
00552 
00553   ScheduleMessage::Status status;
00554 
00555   switch (result) {
00556     case ICAL_XLICCLASS_PUBLISHNEW:
00557       status = ScheduleMessage::PublishNew;
00558       break;
00559     case ICAL_XLICCLASS_PUBLISHUPDATE:
00560       status = ScheduleMessage::PublishUpdate;
00561       break;
00562     case ICAL_XLICCLASS_OBSOLETE:
00563       status = ScheduleMessage::Obsolete;
00564       break;
00565     case ICAL_XLICCLASS_REQUESTNEW:
00566       status = ScheduleMessage::RequestNew;
00567       break;
00568     case ICAL_XLICCLASS_REQUESTUPDATE:
00569       status = ScheduleMessage::RequestUpdate;
00570       break;
00571     case ICAL_XLICCLASS_UNKNOWN:
00572     default:
00573       status = ScheduleMessage::Unknown;
00574       break;
00575   }
00576 
00577   kdDebug(5800) << "ICalFormat::parseScheduleMessage(), status = " << status << endl;
00578 // TODO FIXME: Don't we have to free calendarComponent??? MEMLEAK
00579 
00580   return new ScheduleMessage(incidence,method,status);
00581 }
00582 
00583 void ICalFormat::setTimeZone( const QString &id, bool utc )
00584 {
00585   mTimeZoneId = id;
00586   mUtc = utc;
00587 }
00588 
00589 QString ICalFormat::timeZoneId() const
00590 {
00591   return mTimeZoneId;
00592 }
00593 
00594 bool ICalFormat::utc() const
00595 {
00596   return mUtc;
00597 }
KDE Home | KDE Accessibility Home | Description of Access Keys