• Skip to content
  • Skip to link menu
KDE 4.1 API Reference
  • KDE API Reference
  • KDE-PIM Libraries
  • Sitemap
  • Contact Us
 

KCal Library

icaltimezones.cpp

00001 /*
00002   This file is part of the kcal library.
00003 
00004   Copyright (c) 2005-2007 David Jarvie <djarvie@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 "icaltimezones.h"
00023 #include "icalformat.h"
00024 #include "icalformat_p.h"
00025 
00026 extern "C" {
00027   #include <ical.h>
00028   #include <icaltimezone.h>
00029 }
00030 #include <ksystemtimezone.h>
00031 #include <kdatetime.h>
00032 #include <kdebug.h>
00033 
00034 #include <QtCore/QDateTime>
00035 #include <QtCore/QString>
00036 #include <QtCore/QList>
00037 #include <QtCore/QVector>
00038 #include <QtCore/QSet>
00039 #include <QtCore/QFile>
00040 #include <QtCore/QTextStream>
00041 
00042 using namespace KCal;
00043 
00044 // Minimum repetition counts for VTIMEZONE RRULEs
00045 static const int minRuleCount = 5;   // for any RRULE
00046 static const int minPhaseCount = 8;  // for separate STANDARD/DAYLIGHT component
00047 
00048 // Convert an ical time to QDateTime, preserving the UTC indicator
00049 static QDateTime toQDateTime( const icaltimetype &t )
00050 {
00051   return QDateTime( QDate( t.year, t.month, t.day ),
00052                     QTime( t.hour, t.minute, t.second ),
00053                     ( t.is_utc ? Qt::UTC : Qt::LocalTime ) );
00054 }
00055 
00056 // Maximum date for time zone data.
00057 // It's not sensible to try to predict them very far in advance, because
00058 // they can easily change. Plus, it limits the processing required.
00059 static QDateTime MAX_DATE()
00060 {
00061   static QDateTime dt;
00062   if ( !dt.isValid() ) {
00063     dt = QDateTime( QDate::currentDate().addYears( 20 ), QTime( 0, 0, 0 ) );
00064   }
00065   return dt;
00066 }
00067 
00068 static icaltimetype writeLocalICalDateTime( const QDateTime &utc, int offset )
00069 {
00070   QDateTime local = utc.addSecs( offset );
00071   icaltimetype t = icaltime_null_time();
00072   t.year = local.date().year();
00073   t.month = local.date().month();
00074   t.day = local.date().day();
00075   t.hour = local.time().hour();
00076   t.minute = local.time().minute();
00077   t.second = local.time().second();
00078   t.is_date = 0;
00079   t.zone = 0;
00080   t.is_utc = 0;
00081   return t;
00082 }
00083 
00084 namespace KCal {
00085 
00086 /******************************************************************************/
00087 
00088 //@cond PRIVATE
00089 class ICalTimeZonesPrivate
00090 {
00091   public:
00092     ICalTimeZonesPrivate() {}
00093     ICalTimeZones::ZoneMap zones;
00094 };
00095 //@endcond
00096 
00097 ICalTimeZones::ICalTimeZones()
00098   : d( new ICalTimeZonesPrivate )
00099 {
00100 }
00101 
00102 ICalTimeZones::~ICalTimeZones()
00103 {
00104   delete d;
00105 }
00106 
00107 const ICalTimeZones::ZoneMap ICalTimeZones::zones() const
00108 {
00109   return d->zones;
00110 }
00111 
00112 bool ICalTimeZones::add( const ICalTimeZone &zone )
00113 {
00114   if ( !zone.isValid() ) {
00115     return false;
00116   }
00117   if ( d->zones.find( zone.name() ) != d->zones.end() ) {
00118     return false;    // name already exists
00119   }
00120 
00121   d->zones.insert( zone.name(), zone );
00122   return true;
00123 }
00124 
00125 ICalTimeZone ICalTimeZones::remove( const ICalTimeZone &zone )
00126 {
00127   if ( zone.isValid() ) {
00128     for ( ZoneMap::Iterator it = d->zones.begin(), end = d->zones.end();  it != end;  ++it ) {
00129       if ( it.value() == zone ) {
00130         d->zones.erase( it );
00131         return ( zone == ICalTimeZone::utc() ) ? ICalTimeZone() : zone;
00132       }
00133     }
00134   }
00135   return ICalTimeZone();
00136 }
00137 
00138 ICalTimeZone ICalTimeZones::remove( const QString &name )
00139 {
00140   if ( !name.isEmpty() ) {
00141     ZoneMap::Iterator it = d->zones.find( name );
00142     if ( it != d->zones.end() ) {
00143       ICalTimeZone zone = it.value();
00144       d->zones.erase(it);
00145       return ( zone == ICalTimeZone::utc() ) ? ICalTimeZone() : zone;
00146     }
00147   }
00148   return ICalTimeZone();
00149 }
00150 
00151 void ICalTimeZones::clear()
00152 {
00153   d->zones.clear();
00154 }
00155 
00156 ICalTimeZone ICalTimeZones::zone( const QString &name ) const
00157 {
00158   if ( !name.isEmpty() ) {
00159     ZoneMap::ConstIterator it = d->zones.find( name );
00160     if ( it != d->zones.end() ) {
00161       return it.value();
00162     }
00163   }
00164   return ICalTimeZone();   // error
00165 }
00166 
00167 /******************************************************************************/
00168 
00169 ICalTimeZoneBackend::ICalTimeZoneBackend()
00170   : KTimeZoneBackend()
00171 {}
00172 
00173 ICalTimeZoneBackend::ICalTimeZoneBackend( ICalTimeZoneSource *source,
00174                                           const QString &name,
00175                                           const QString &countryCode,
00176                                           float latitude, float longitude,
00177                                           const QString &comment )
00178   : KTimeZoneBackend( source, name, countryCode, latitude, longitude, comment )
00179 {}
00180 
00181 ICalTimeZoneBackend::ICalTimeZoneBackend( const KTimeZone &tz, const QDate &earliest )
00182   : KTimeZoneBackend( 0, tz.name(), tz.countryCode(), tz.latitude(), tz.longitude(), tz.comment() )
00183 {
00184   Q_UNUSED( earliest );
00185 }
00186 
00187 ICalTimeZoneBackend::~ICalTimeZoneBackend()
00188 {}
00189 
00190 KTimeZoneBackend *ICalTimeZoneBackend::clone() const
00191 {
00192   return new ICalTimeZoneBackend( *this );
00193 }
00194 
00195 QByteArray ICalTimeZoneBackend::type() const
00196 {
00197   return "ICalTimeZone";
00198 }
00199 
00200 bool ICalTimeZoneBackend::hasTransitions( const KTimeZone *caller ) const
00201 {
00202   Q_UNUSED( caller );
00203   return true;
00204 }
00205 
00206 /******************************************************************************/
00207 
00208 ICalTimeZone::ICalTimeZone()
00209   : KTimeZone( new ICalTimeZoneBackend() )
00210 {}
00211 
00212 ICalTimeZone::ICalTimeZone( ICalTimeZoneSource *source, const QString &name,
00213                             ICalTimeZoneData *data )
00214   : KTimeZone( new ICalTimeZoneBackend( source, name ) )
00215 {
00216   setData( data );
00217 }
00218 
00219 ICalTimeZone::ICalTimeZone( const KTimeZone &tz, const QDate &earliest )
00220   : KTimeZone( new ICalTimeZoneBackend( 0, tz.name(), tz.countryCode(),
00221                                         tz.latitude(), tz.longitude(),
00222                                         tz.comment() ) )
00223 {
00224   const KTimeZoneData *data = tz.data( true );
00225   if ( data ) {
00226     const ICalTimeZoneData *icaldata = dynamic_cast<const ICalTimeZoneData*>( data );
00227     if ( icaldata ) {
00228       setData( new ICalTimeZoneData( *icaldata ) );
00229     } else {
00230       setData( new ICalTimeZoneData( *data, tz, earliest ) );
00231     }
00232   }
00233 }
00234 
00235 ICalTimeZone::~ICalTimeZone()
00236 {}
00237 
00238 QString ICalTimeZone::city() const
00239 {
00240   const ICalTimeZoneData *dat = static_cast<const ICalTimeZoneData*>( data() );
00241   return dat ? dat->city() : QString();
00242 }
00243 
00244 QByteArray ICalTimeZone::url() const
00245 {
00246   const ICalTimeZoneData *dat = static_cast<const ICalTimeZoneData*>( data() );
00247   return dat ? dat->url() : QByteArray();
00248 }
00249 
00250 QDateTime ICalTimeZone::lastModified() const
00251 {
00252   const ICalTimeZoneData *dat = static_cast<const ICalTimeZoneData*>( data() );
00253   return dat ? dat->lastModified() : QDateTime();
00254 }
00255 
00256 QByteArray ICalTimeZone::vtimezone() const
00257 {
00258   const ICalTimeZoneData *dat = static_cast<const ICalTimeZoneData*>( data() );
00259   return dat ? dat->vtimezone() : QByteArray();
00260 }
00261 
00262 icaltimezone *ICalTimeZone::icalTimezone() const
00263 {
00264   const ICalTimeZoneData *dat = static_cast<const ICalTimeZoneData*>( data() );
00265   return dat ? dat->icalTimezone() : 0;
00266 }
00267 
00268 bool ICalTimeZone::update( const ICalTimeZone &other )
00269 {
00270   if ( !updateBase( other ) ) {
00271     return false;
00272   }
00273 
00274   setData( other.data()->clone(), other.source() );
00275   return true;
00276 }
00277 
00278 ICalTimeZone ICalTimeZone::utc()
00279 {
00280   static ICalTimeZone utcZone;
00281   if ( !utcZone.isValid() ) {
00282     ICalTimeZoneSource tzs;
00283     utcZone = tzs.parse( icaltimezone_get_utc_timezone() );
00284   }
00285   return utcZone;
00286 }
00287 
00288 /******************************************************************************/
00289 
00290 //@cond PRIVATE
00291 class ICalTimeZoneDataPrivate
00292 {
00293   public:
00294     ICalTimeZoneDataPrivate() : icalComponent(0) {}
00295     ~ICalTimeZoneDataPrivate()
00296     {
00297       if ( icalComponent ) {
00298         icalcomponent_free( icalComponent );
00299       }
00300     }
00301     icalcomponent *component() const { return icalComponent; }
00302     void setComponent( icalcomponent *c )
00303     {
00304       if ( icalComponent ) {
00305         icalcomponent_free( icalComponent );
00306       }
00307       icalComponent = c;
00308     }
00309     QString       location;       // name of city for this time zone
00310     QByteArray    url;            // URL of published VTIMEZONE definition (optional)
00311     QDateTime     lastModified;   // time of last modification of the VTIMEZONE component (optional)
00312   private:
00313     icalcomponent *icalComponent; // ical component representing this time zone
00314 };
00315 //@endcond
00316 
00317 ICalTimeZoneData::ICalTimeZoneData()
00318   : d ( new ICalTimeZoneDataPrivate() )
00319 {
00320 }
00321 
00322 ICalTimeZoneData::ICalTimeZoneData( const ICalTimeZoneData &rhs )
00323   : KTimeZoneData( rhs ),
00324     d( new ICalTimeZoneDataPrivate() )
00325 {
00326   d->location = rhs.d->location;
00327   d->url = rhs.d->url;
00328   d->lastModified = rhs.d->lastModified;
00329   d->setComponent( icalcomponent_new_clone( rhs.d->component() ) );
00330 }
00331 
00332 ICalTimeZoneData::ICalTimeZoneData( const KTimeZoneData &rhs,
00333                                     const KTimeZone &tz, const QDate &earliest )
00334   : KTimeZoneData( rhs ),
00335     d( new ICalTimeZoneDataPrivate() )
00336 {
00337   // VTIMEZONE RRULE types
00338   enum {
00339     DAY_OF_MONTH          = 0x01,
00340     WEEKDAY_OF_MONTH      = 0x02,
00341     LAST_WEEKDAY_OF_MONTH = 0x04
00342   };
00343 
00344   if ( tz.type() == "KSystemTimeZone" ) {
00345     // Try to fetch a system time zone in preference, on the grounds
00346     // that system time zones are more likely to be up to date than
00347     // built-in libical ones.
00348     icalcomponent *c = 0;
00349     KTimeZone ktz = KSystemTimeZones::readZone( tz.name() );
00350     if ( ktz.isValid() ) {
00351       if ( ktz.data(true) ) {
00352         ICalTimeZone icaltz( ktz, earliest );
00353         icaltimezone *itz = icaltz.icalTimezone();
00354         c = icalcomponent_new_clone( icaltimezone_get_component( itz ) );
00355         icaltimezone_free( itz, 1 );
00356       }
00357     }
00358     if ( !c ) {
00359       // Try to fetch a built-in libical time zone.
00360       icaltimezone *itz = icaltimezone_get_builtin_timezone( tz.name().toUtf8() );
00361       c = icalcomponent_new_clone( icaltimezone_get_component( itz ) );
00362     }
00363     if ( c ) {
00364       // TZID in built-in libical time zones has a standard prefix.
00365       // To make the VTIMEZONE TZID match TZID references in incidences
00366       // (as required by RFC2445), strip off the prefix.
00367       icalproperty *prop = icalcomponent_get_first_property( c, ICAL_TZID_PROPERTY );
00368       if ( prop ) {
00369         icalvalue *value = icalproperty_get_value( prop );
00370         const char *tzid = icalvalue_get_text( value );
00371         QByteArray icalprefix = ICalTimeZoneSource::icalTzidPrefix();
00372         int len = icalprefix.size();
00373         if ( !strncmp( icalprefix, tzid, len ) ) {
00374           const char *s = strchr( tzid + len, '/' );    // find third '/'
00375           if ( s ) {
00376             QByteArray tzidShort( s + 1 ); // deep copy of string (needed by icalvalue_set_text())
00377             icalvalue_set_text( value, tzidShort );
00378 
00379             // Remove the X-LIC-LOCATION property, which is only used by libical
00380             prop = icalcomponent_get_first_property( c, ICAL_X_PROPERTY );
00381             const char *xname = icalproperty_get_x_name( prop );
00382             if ( xname && !strcmp( xname, "X-LIC-LOCATION" ) ) {
00383               icalcomponent_remove_property( c, prop );
00384             }
00385           }
00386         }
00387       }
00388     }
00389     d->setComponent( c );
00390   } else {
00391     // Write the time zone data into an iCal component
00392     icalcomponent *tzcomp = icalcomponent_new(ICAL_VTIMEZONE_COMPONENT);
00393     icalcomponent_add_property( tzcomp, icalproperty_new_tzid( tz.name().toUtf8() ) );
00394 //    icalcomponent_add_property(tzcomp, icalproperty_new_location( tz.name().toUtf8() ));
00395 
00396     // Compile an ordered list of transitions so that we can know the phases
00397     // which occur before and after each transition.
00398     QList<KTimeZone::Transition> transits = transitions();
00399     if ( earliest.isValid() ) {
00400       // Remove all transitions earlier than those we are interested in
00401       for ( int i = 0, end = transits.count();  i < end;  ++i ) {
00402         if ( transits[i].time().date() >= earliest ) {
00403           if ( i > 0 ) {
00404             transits.erase( transits.begin(), transits.begin() + i );
00405           }
00406           break;
00407         }
00408       }
00409     }
00410     int trcount = transits.count();
00411     QVector<bool> transitionsDone(trcount);
00412     transitionsDone.fill(false);
00413 
00414     // Go through the list of transitions and create an iCal component for each
00415     // distinct combination of phase after and UTC offset before the transition.
00416     icaldatetimeperiodtype dtperiod;
00417     dtperiod.period = icalperiodtype_null_period();
00418     for ( ; ; ) {
00419       int i = 0;
00420       for ( ;  i < trcount && transitionsDone[i];  ++i ) {
00421         ;
00422       }
00423       if ( i >= trcount ) {
00424         break;
00425       }
00426       // Found a phase combination which hasn't yet been processed
00427       int preOffset = ( i > 0 ) ? transits[i - 1].phase().utcOffset() : rhs.previousUtcOffset();
00428       KTimeZone::Phase phase = transits[i].phase();
00429       if ( phase.utcOffset() == preOffset ) {
00430         transitionsDone[i] = true;
00431         while ( ++i < trcount ) {
00432           if ( transitionsDone[i] ||
00433                transits[i].phase() != phase ||
00434                transits[i - 1].phase().utcOffset() != preOffset ) {
00435             continue;
00436           }
00437           transitionsDone[i] = true;
00438         }
00439         continue;
00440       }
00441       icalcomponent *phaseComp =
00442         icalcomponent_new( phase.isDst() ? ICAL_XDAYLIGHT_COMPONENT : ICAL_XSTANDARD_COMPONENT );
00443       QList<QByteArray> abbrevs = phase.abbreviations();
00444       for ( int a = 0, aend = abbrevs.count();  a < aend;  ++a ) {
00445         icalcomponent_add_property( phaseComp,
00446                                     icalproperty_new_tzname(
00447                                       static_cast<const char*>( abbrevs[a]) ) );
00448       }
00449       if ( !phase.comment().isEmpty() ) {
00450         icalcomponent_add_property( phaseComp,
00451                                     icalproperty_new_comment( phase.comment().toUtf8() ) );
00452       }
00453       icalcomponent_add_property( phaseComp,
00454                                   icalproperty_new_tzoffsetfrom( preOffset ) );
00455       icalcomponent_add_property( phaseComp,
00456                                   icalproperty_new_tzoffsetto( phase.utcOffset() ) );
00457       // Create a component to hold initial RRULE if any, plus all RDATEs
00458       icalcomponent *phaseComp1 = icalcomponent_new_clone( phaseComp );
00459       icalcomponent_add_property( phaseComp1,
00460                                   icalproperty_new_dtstart(
00461                                     writeLocalICalDateTime( transits[i].time(), preOffset ) ) );
00462       bool useNewRRULE = false;
00463 
00464       // Compile the list of UTC transition dates/times, and check
00465       // if the list can be reduced to an RRULE instead of multiple RDATEs.
00466       QTime time;
00467       QDate date;
00468       int year = 0, month = 0, daysInMonth = 0, dayOfMonth = 0; // avoid compiler warnings
00469       int dayOfWeek = 0;      // Monday = 1
00470       int nthFromStart = 0;   // nth (weekday) of month
00471       int nthFromEnd = 0;     // nth last (weekday) of month
00472       int newRule;
00473       int rule = 0;
00474       QList<QDateTime> rdates;// dates which (probably) need to be written as RDATEs
00475       QList<QDateTime> times;
00476       QDateTime qdt = transits[i].time();   // set 'qdt' for start of loop
00477       times += qdt;
00478       transitionsDone[i] = true;
00479       do {
00480         if ( !rule ) {
00481           // Initialise data for detecting a new rule
00482           rule = DAY_OF_MONTH | WEEKDAY_OF_MONTH | LAST_WEEKDAY_OF_MONTH;
00483           time = qdt.time();
00484           date = qdt.date();
00485           year = date.year();
00486           month = date.month();
00487           daysInMonth = date.daysInMonth();
00488           dayOfWeek = date.dayOfWeek();   // Monday = 1
00489           dayOfMonth = date.day();
00490           nthFromStart = ( dayOfMonth - 1 ) / 7 + 1;   // nth (weekday) of month
00491           nthFromEnd = ( daysInMonth - dayOfMonth ) / 7 + 1;   // nth last (weekday) of month
00492         }
00493         if ( ++i >= trcount ) {
00494           newRule = 0;
00495           times += QDateTime();   // append a dummy value since last value in list is ignored
00496         } else {
00497           if ( transitionsDone[i] ||
00498                transits[i].phase() != phase ||
00499                transits[i - 1].phase().utcOffset() != preOffset ) {
00500             continue;
00501           }
00502           transitionsDone[i] = true;
00503           qdt = transits[i].time();
00504           if ( !qdt.isValid() ) {
00505             continue;
00506           }
00507           newRule = rule;
00508           times += qdt;
00509           date = qdt.date();
00510           if ( qdt.time() != time ||
00511                date.month() != month ||
00512                date.year() != ++year ) {
00513             newRule = 0;
00514           } else {
00515             int day = date.day();
00516             if ( ( newRule & DAY_OF_MONTH ) && day != dayOfMonth ) {
00517               newRule &= ~DAY_OF_MONTH;
00518             }
00519             if ( newRule & ( WEEKDAY_OF_MONTH | LAST_WEEKDAY_OF_MONTH ) ) {
00520               if ( date.dayOfWeek() != dayOfWeek ) {
00521                 newRule &= ~( WEEKDAY_OF_MONTH | LAST_WEEKDAY_OF_MONTH );
00522               } else {
00523                 if ( ( newRule & WEEKDAY_OF_MONTH ) &&
00524                      ( day - 1 ) / 7 + 1 != nthFromStart ) {
00525                   newRule &= ~WEEKDAY_OF_MONTH;
00526                 }
00527                 if ( ( newRule & LAST_WEEKDAY_OF_MONTH ) &&
00528                      ( daysInMonth - day ) / 7 + 1 != nthFromEnd ) {
00529                   newRule &= ~LAST_WEEKDAY_OF_MONTH;
00530                 }
00531               }
00532             }
00533           }
00534         }
00535         if ( !newRule ) {
00536           // The previous rule (if any) no longer applies.
00537           // Write all the times up to but not including the current one.
00538           // First check whether any of the last RDATE values fit this rule.
00539           int yr = times[0].date().year();
00540           while ( !rdates.isEmpty() ) {
00541             qdt = rdates.last();
00542             date = qdt.date();
00543             if ( qdt.time() != time  ||
00544                  date.month() != month ||
00545                  date.year() != --yr ) {
00546               break;
00547             }
00548             int day  = date.day();
00549             if ( rule & DAY_OF_MONTH ) {
00550               if ( day != dayOfMonth ) {
00551                 break;
00552               }
00553             } else {
00554               if ( date.dayOfWeek() != dayOfWeek ||
00555                    ( ( rule & WEEKDAY_OF_MONTH ) &&
00556                      ( day - 1 ) / 7 + 1 != nthFromStart ) ||
00557                    ( ( rule & LAST_WEEKDAY_OF_MONTH ) &&
00558                      ( daysInMonth - day ) / 7 + 1 != nthFromEnd ) ) {
00559                 break;
00560               }
00561             }
00562             times.prepend( qdt );
00563             rdates.pop_back();
00564           }
00565           if ( times.count() > ( useNewRRULE ? minPhaseCount : minRuleCount ) ) {
00566             // There are enough dates to combine into an RRULE
00567             icalrecurrencetype r;
00568             icalrecurrencetype_clear( &r );
00569             r.freq = ICAL_YEARLY_RECURRENCE;
00570             r.count = ( year >= 2030 ) ? 0 : times.count() - 1;
00571             r.by_month[0] = month;
00572             if ( rule & DAY_OF_MONTH ) {
00573               r.by_month_day[0] = dayOfMonth;
00574             } else if ( rule & WEEKDAY_OF_MONTH ) {
00575               r.by_day[0] = ( dayOfWeek % 7 + 1 ) + ( nthFromStart * 8 );   // Sunday = 1
00576             } else if ( rule & LAST_WEEKDAY_OF_MONTH ) {
00577               r.by_day[0] = -( dayOfWeek % 7 + 1 ) - ( nthFromEnd * 8 );   // Sunday = 1
00578             }
00579             icalproperty *prop = icalproperty_new_rrule( r );
00580             if ( useNewRRULE ) {
00581               // This RRULE doesn't start from the phase start date, so set it into
00582               // a new STANDARD/DAYLIGHT component in the VTIMEZONE.
00583               icalcomponent *c = icalcomponent_new_clone( phaseComp );
00584               icalcomponent_add_property(
00585                 c, icalproperty_new_dtstart( writeLocalICalDateTime( times[0], preOffset ) ) );
00586               icalcomponent_add_property( c, prop );
00587               icalcomponent_add_component( tzcomp, c );
00588             } else {
00589               icalcomponent_add_property( phaseComp1, prop );
00590             }
00591           } else {
00592             // Save dates for writing as RDATEs
00593             for ( int t = 0, tend = times.count() - 1;  t < tend;  ++t ) {
00594               rdates += times[t];
00595             }
00596           }
00597           useNewRRULE = true;
00598           // All date/time values but the last have been added to the VTIMEZONE.
00599           // Remove them from the list.
00600           qdt = times.last();   // set 'qdt' for start of loop
00601           times.clear();
00602           times += qdt;
00603         }
00604         rule = newRule;
00605       } while ( i < trcount );
00606 
00607       // Write remaining dates as RDATEs
00608       for ( int rd = 0, rdend = rdates.count();  rd < rdend;  ++rd ) {
00609         dtperiod.time = writeLocalICalDateTime( rdates[rd], preOffset );
00610         icalcomponent_add_property( phaseComp1, icalproperty_new_rdate( dtperiod ) );
00611       }
00612       icalcomponent_add_component( tzcomp, phaseComp1 );
00613       icalcomponent_free( phaseComp );
00614     }
00615 
00616     d->setComponent( tzcomp );
00617   }
00618 }
00619 
00620 ICalTimeZoneData::~ICalTimeZoneData()
00621 {
00622   delete d;
00623 }
00624 
00625 ICalTimeZoneData &ICalTimeZoneData::operator=( const ICalTimeZoneData &rhs )
00626 {
00627   // check for self assignment
00628   if ( &rhs == this )
00629     return *this;
00630 
00631   KTimeZoneData::operator=( rhs );
00632   d->location = rhs.d->location;
00633   d->url = rhs.d->url;
00634   d->lastModified = rhs.d->lastModified;
00635   d->setComponent( icalcomponent_new_clone( rhs.d->component() ) );
00636   return *this;
00637 }
00638 
00639 KTimeZoneData *ICalTimeZoneData::clone() const
00640 {
00641   return new ICalTimeZoneData( *this );
00642 }
00643 
00644 QString ICalTimeZoneData::city() const
00645 {
00646   return d->location;
00647 }
00648 
00649 QByteArray ICalTimeZoneData::url() const
00650 {
00651   return d->url;
00652 }
00653 
00654 QDateTime ICalTimeZoneData::lastModified() const
00655 {
00656   return d->lastModified;
00657 }
00658 
00659 QByteArray ICalTimeZoneData::vtimezone() const
00660 {
00661   return icalcomponent_as_ical_string( d->component() );
00662 }
00663 
00664 icaltimezone *ICalTimeZoneData::icalTimezone() const
00665 {
00666   icaltimezone *icaltz = icaltimezone_new();
00667   if ( !icaltz ) {
00668     return 0;
00669   }
00670   icalcomponent *c = icalcomponent_new_clone( d->component() );
00671   if ( !icaltimezone_set_component( icaltz, c ) ) {
00672     icalcomponent_free( c );
00673     icaltimezone_free( icaltz, 1 );
00674     return 0;
00675   }
00676   return icaltz;
00677 }
00678 
00679 bool ICalTimeZoneData::hasTransitions() const
00680 {
00681     return true;
00682 }
00683 
00684 /******************************************************************************/
00685 
00686 //@cond PRIVATE
00687 class ICalTimeZoneSourcePrivate
00688 {
00689   public:
00690     static QList<QDateTime> parsePhase( icalcomponent *, bool daylight,
00691                                         int &prevOffset, KTimeZone::Phase & );
00692     static QByteArray icalTzidPrefix;
00693 };
00694 
00695 QByteArray ICalTimeZoneSourcePrivate::icalTzidPrefix;
00696 //@endcond
00697 
00698 ICalTimeZoneSource::ICalTimeZoneSource()
00699   : KTimeZoneSource( false ),
00700     d( 0 )
00701 {
00702 }
00703 
00704 ICalTimeZoneSource::~ICalTimeZoneSource()
00705 {
00706 }
00707 
00708 bool ICalTimeZoneSource::parse( const QString &fileName, ICalTimeZones &zones )
00709 {
00710   QFile file( fileName );
00711   if ( !file.open( QIODevice::ReadOnly ) ) {
00712     return false;
00713   }
00714   QTextStream ts( &file );
00715   ts.setCodec( "ISO 8859-1" );
00716   QByteArray text = ts.readAll().trimmed().toLatin1();
00717   file.close();
00718 
00719   bool result = false;
00720   icalcomponent *calendar = icalcomponent_new_from_string( text.data() );
00721   if ( calendar ) {
00722     if ( icalcomponent_isa( calendar ) == ICAL_VCALENDAR_COMPONENT ) {
00723       result = parse( calendar, zones );
00724     }
00725     icalcomponent_free( calendar );
00726   }
00727   return result;
00728 }
00729 
00730 bool ICalTimeZoneSource::parse( icalcomponent *calendar, ICalTimeZones &zones )
00731 {
00732   for ( icalcomponent *c = icalcomponent_get_first_component( calendar, ICAL_VTIMEZONE_COMPONENT );
00733         c;  c = icalcomponent_get_next_component( calendar, ICAL_VTIMEZONE_COMPONENT ) ) {
00734     ICalTimeZone zone = parse( c );
00735     if ( !zone.isValid() ) {
00736       return false;
00737     }
00738     ICalTimeZone oldzone = zones.zone( zone.name() );
00739     if ( oldzone.isValid() ) {
00740       // The zone already exists in the collection, so update the definition
00741       // of the zone rather than using a newly created one.
00742       oldzone.update( zone );
00743     } else if ( !zones.add( zone ) ) {
00744       return false;
00745     }
00746   }
00747   return true;
00748 }
00749 
00750 ICalTimeZone ICalTimeZoneSource::parse( icalcomponent *vtimezone )
00751 {
00752   QString name;
00753   QString xlocation;
00754   ICalTimeZoneData *data = new ICalTimeZoneData();
00755 
00756   // Read the fixed properties which can only appear once in VTIMEZONE
00757   icalproperty *p = icalcomponent_get_first_property( vtimezone, ICAL_ANY_PROPERTY );
00758   while ( p ) {
00759     icalproperty_kind kind = icalproperty_isa( p );
00760     switch ( kind ) {
00761 
00762     case ICAL_TZID_PROPERTY:
00763       name = QString::fromUtf8( icalproperty_get_tzid( p ) );
00764       break;
00765 
00766     case ICAL_TZURL_PROPERTY:
00767       data->d->url = icalproperty_get_tzurl( p );
00768       break;
00769 
00770     case ICAL_LOCATION_PROPERTY:
00771       // This isn't mentioned in RFC2445, but libical reads it ...
00772       data->d->location = QString::fromUtf8( icalproperty_get_location( p ) );
00773       break;
00774 
00775     case ICAL_X_PROPERTY:
00776     {   // use X-LIC-LOCATION if LOCATION is missing
00777       const char *xname = icalproperty_get_x_name( p );
00778       if ( xname && !strcmp( xname, "X-LIC-LOCATION" ) ) {
00779         xlocation = QString::fromUtf8( icalproperty_get_x( p ) );
00780       }
00781       break;
00782     }
00783     case ICAL_LASTMODIFIED_PROPERTY:
00784     {
00785       icaltimetype t = icalproperty_get_lastmodified(p);
00786       if ( t.is_utc ) {
00787         data->d->lastModified = toQDateTime( t );
00788       } else {
00789         kDebug() << "LAST-MODIFIED not UTC";
00790       }
00791       break;
00792     }
00793     default:
00794       break;
00795     }
00796     p = icalcomponent_get_next_property( vtimezone, ICAL_ANY_PROPERTY );
00797   }
00798 
00799   if ( name.isEmpty() ) {
00800     kDebug() << "TZID missing";
00801     delete data;
00802     return ICalTimeZone();
00803   }
00804   if ( data->d->location.isEmpty() && !xlocation.isEmpty() ) {
00805     data->d->location = xlocation;
00806   }
00807   QString prefix = QString::fromUtf8( icalTzidPrefix() );
00808   if ( name.startsWith( prefix ) ) {
00809     // Remove the prefix from libical built in time zone TZID
00810     int i = name.indexOf( '/', prefix.length() );
00811     if ( i > 0 ) {
00812       name = name.mid( i + 1 );
00813     }
00814   }
00815   //kDebug() << "---zoneId: \"" << name << '"';
00816 
00817   /*
00818    * Iterate through all time zone rules for this VTIMEZONE,
00819    * and create a Phase object containing details for each one.
00820    */
00821   int prevOffset = 0;
00822   QList<KTimeZone::Transition> transitions;
00823   QDateTime earliest;
00824   QList<KTimeZone::Phase> phases;
00825   for ( icalcomponent *c = icalcomponent_get_first_component( vtimezone, ICAL_ANY_COMPONENT );
00826         c;  c = icalcomponent_get_next_component( vtimezone, ICAL_ANY_COMPONENT ) )
00827   {
00828     int prevoff;
00829     KTimeZone::Phase phase;
00830     QList<QDateTime> times;
00831     icalcomponent_kind kind = icalcomponent_isa( c );
00832     switch ( kind ) {
00833 
00834     case ICAL_XSTANDARD_COMPONENT:
00835       //kDebug() << "---standard phase: found";
00836       times = ICalTimeZoneSourcePrivate::parsePhase( c, false, prevoff, phase );
00837       break;
00838 
00839     case ICAL_XDAYLIGHT_COMPONENT:
00840       //kDebug() << "---daylight phase: found";
00841       times = ICalTimeZoneSourcePrivate::parsePhase( c, true, prevoff, phase );
00842       break;
00843 
00844     default:
00845       kDebug() << "Unknown component:" << kind;
00846       break;
00847     }
00848     int tcount = times.count();
00849     if ( tcount ) {
00850       phases += phase;
00851       for ( int t = 0;  t < tcount;  ++t ) {
00852         transitions += KTimeZone::Transition( times[t], phase );
00853       }
00854       if ( !earliest.isValid() || times[0] < earliest ) {
00855         prevOffset = prevoff;
00856         earliest = times[0];
00857       }
00858     }
00859   }
00860   data->setPhases( phases, prevOffset );
00861   // Remove any "duplicate" transitions, i.e. those where two consecutive
00862   // transitions have the same phase.
00863   qSort( transitions );
00864   for ( int t = 1, tend = transitions.count();  t < tend; ) {
00865     if ( transitions[t].phase() == transitions[t - 1].phase() ) {
00866       transitions.removeAt( t );
00867       --tend;
00868     } else {
00869       ++t;
00870     }
00871   }
00872   data->setTransitions( transitions );
00873 
00874   data->d->setComponent( icalcomponent_new_clone( vtimezone ) );
00875   kDebug() << "VTIMEZONE" << name;
00876   return ICalTimeZone( this, name, data );
00877 }
00878 
00879 ICalTimeZone ICalTimeZoneSource::parse( icaltimezone *tz )
00880 {
00881   /* Parse the VTIMEZONE component stored in the icaltimezone structure.
00882    * This is both easier and provides more complete information than
00883    * extracting already parsed data from icaltimezone.
00884    */
00885   return parse( icaltimezone_get_component( tz ) );
00886 }
00887 
00888 //@cond PRIVATE
00889 QList<QDateTime> ICalTimeZoneSourcePrivate::parsePhase( icalcomponent *c,
00890                                                         bool daylight,
00891                                                         int &prevOffset,
00892                                                         KTimeZone::Phase &phase )
00893 {
00894   QList<QDateTime> transitions;
00895 
00896   // Read the observance data for this standard/daylight savings phase
00897   QList<QByteArray> abbrevs;
00898   QString comment;
00899   prevOffset = 0;
00900   int utcOffset = 0;
00901   bool recurs = false;
00902   bool found_dtstart = false;
00903   bool found_tzoffsetfrom = false;
00904   bool found_tzoffsetto = false;
00905   icaltimetype dtstart = icaltime_null_time();
00906 
00907   // Now do the ical reading.
00908   icalproperty *p = icalcomponent_get_first_property( c, ICAL_ANY_PROPERTY );
00909   while ( p ) {
00910     icalproperty_kind kind = icalproperty_isa( p );
00911     switch ( kind ) {
00912 
00913     case ICAL_TZNAME_PROPERTY:     // abbreviated name for this time offset
00914     {
00915       // TZNAME can appear multiple times in order to provide language
00916       // translations of the time zone offset name.
00917 #ifdef __GNUC__
00918 #warning Does this cope with multiple language specifications?
00919 #endif
00920       QByteArray tzname = icalproperty_get_tzname( p );
00921       // Outlook (2000) places "Standard Time" and "Daylight Time" in the TZNAME
00922       // strings, which is totally useless. So ignore those.
00923       if ( ( !daylight && tzname == "Standard Time" ) ||
00924            ( daylight && tzname == "Daylight Time" ) ) {
00925         break;
00926       }
00927       if ( !abbrevs.contains( tzname ) ) {
00928         abbrevs += tzname;
00929       }
00930       break;
00931     }
00932     case ICAL_DTSTART_PROPERTY:      // local time at which phase starts
00933       dtstart = icalproperty_get_dtstart( p );
00934       found_dtstart = true;
00935       break;
00936 
00937     case ICAL_TZOFFSETFROM_PROPERTY:    // UTC offset immediately before start of phase
00938       prevOffset = icalproperty_get_tzoffsetfrom( p );
00939       found_tzoffsetfrom = true;
00940       break;
00941 
00942     case ICAL_TZOFFSETTO_PROPERTY:
00943       utcOffset = icalproperty_get_tzoffsetto( p );
00944       found_tzoffsetto = true;
00945       break;
00946 
00947     case ICAL_COMMENT_PROPERTY:
00948       comment = QString::fromUtf8( icalproperty_get_comment( p ) );
00949       break;
00950 
00951     case ICAL_RDATE_PROPERTY:
00952     case ICAL_RRULE_PROPERTY:
00953       recurs = true;
00954       break;
00955 
00956     default:
00957       kDebug() << "Unknown property:" << kind;
00958       break;
00959     }
00960     p = icalcomponent_get_next_property( c, ICAL_ANY_PROPERTY );
00961   }
00962 
00963   // Validate the phase data
00964   if ( !found_dtstart || !found_tzoffsetfrom || !found_tzoffsetto ) {
00965     kDebug() << "DTSTART/TZOFFSETFROM/TZOFFSETTO missing";
00966     return transitions;
00967   }
00968 
00969   // Convert DTSTART to QDateTime, and from local time to UTC
00970   QDateTime localStart = toQDateTime( dtstart );   // local time
00971   dtstart.second -= prevOffset;
00972   dtstart.is_utc = 1;
00973   QDateTime utcStart = toQDateTime( icaltime_normalize( dtstart ) );   // UTC
00974 
00975   transitions += utcStart;
00976   if ( recurs ) {
00977     /* RDATE or RRULE is specified. There should only be one or the other, but
00978      * it doesn't really matter - the code can cope with both.
00979      * Note that we had to get DTSTART, TZOFFSETFROM, TZOFFSETTO before reading
00980      * recurrences.
00981      */
00982     KDateTime klocalStart( localStart, KDateTime::Spec::ClockTime() );
00983     KDateTime maxTime( MAX_DATE(), KDateTime::Spec::ClockTime() );
00984     Recurrence recur;
00985     icalproperty *p = icalcomponent_get_first_property( c, ICAL_ANY_PROPERTY );
00986     while ( p ) {
00987       icalproperty_kind kind = icalproperty_isa( p );
00988       switch ( kind ) {
00989 
00990       case ICAL_RDATE_PROPERTY:
00991       {
00992         icaltimetype t = icalproperty_get_rdate(p).time;
00993         if ( icaltime_is_date( t ) ) {
00994           // RDATE with a DATE value inherits the (local) time from DTSTART
00995           t.hour = dtstart.hour;
00996           t.minute = dtstart.minute;
00997           t.second = dtstart.second;
00998           t.is_date = 0;
00999           t.is_utc = 0;    // dtstart is in local time
01000         }
01001         // RFC2445 states that RDATE must be in local time,
01002         // but we support UTC as well to be safe.
01003         if ( !t.is_utc ) {
01004           t.second -= prevOffset;    // convert to UTC
01005           t.is_utc = 1;
01006           t = icaltime_normalize( t );
01007         }
01008         transitions += toQDateTime( t );
01009         break;
01010       }
01011       case ICAL_RRULE_PROPERTY:
01012       {
01013         RecurrenceRule r;
01014         ICalFormat icf;
01015         ICalFormatImpl impl( &icf );
01016         impl.readRecurrence( icalproperty_get_rrule( p ), &r );
01017         r.setStartDt( klocalStart );
01018         // The end date time specified in an RRULE should be in UTC.
01019         // Convert to local time to avoid timesInInterval() getting things wrong.
01020         if ( r.duration() == 0 ) {
01021           KDateTime end( r.endDt() );
01022           if ( end.timeSpec() == KDateTime::Spec::UTC() ) {
01023             end.setTimeSpec( KDateTime::Spec::ClockTime() );
01024             r.setEndDt( end.addSecs( prevOffset ) );
01025           }
01026         }
01027         DateTimeList dts = r.timesInInterval( klocalStart, maxTime );
01028         for ( int i = 0, end = dts.count();  i < end;  ++i ) {
01029           QDateTime utc = dts[i].dateTime();
01030           utc.setTimeSpec( Qt::UTC );
01031           transitions += utc.addSecs( -prevOffset );
01032         }
01033         break;
01034       }
01035       default:
01036         break;
01037       }
01038       p = icalcomponent_get_next_property( c, ICAL_ANY_PROPERTY );
01039     }
01040     qSortUnique( transitions );
01041   }
01042 
01043   phase = KTimeZone::Phase( utcOffset, abbrevs, daylight, comment );
01044   return transitions;
01045 }
01046 //@endcond
01047 
01048 ICalTimeZone ICalTimeZoneSource::standardZone( const QString &zone, bool icalBuiltIn )
01049 {
01050   if ( !icalBuiltIn ) {
01051     // Try to fetch a system time zone in preference, on the grounds
01052     // that system time zones are more likely to be up to date than
01053     // built-in libical ones.
01054     QString tzid = zone;
01055     QString prefix = QString::fromUtf8( icalTzidPrefix() );
01056     if ( zone.startsWith( prefix ) ) {
01057       int i = zone.indexOf( '/', prefix.length() );
01058       if ( i > 0 ) {
01059         tzid = zone.mid( i + 1 );   // strip off the libical prefix
01060       }
01061     }
01062     KTimeZone ktz = KSystemTimeZones::readZone( tzid );
01063     if ( ktz.isValid() ) {
01064       if ( ktz.data( true ) ) {
01065         ICalTimeZone icaltz( ktz );
01066         kDebug() << zone << " read from system database";
01067         return icaltz;
01068       }
01069     }
01070   }
01071   // Try to fetch a built-in libical time zone.
01072   // First try to look it up as a geographical location (e.g. Europe/London)
01073   QByteArray zoneName = zone.toUtf8();
01074   icaltimezone *icaltz = icaltimezone_get_builtin_timezone( zoneName );
01075   if ( !icaltz ) {
01076     // This will find it if it includes the libical prefix
01077     icaltz = icaltimezone_get_builtin_timezone_from_tzid( zoneName );
01078     if ( !icaltz ) {
01079       return ICalTimeZone();
01080     }
01081   }
01082   return parse( icaltz );
01083 }
01084 
01085 QByteArray ICalTimeZoneSource::icalTzidPrefix()
01086 {
01087   if ( ICalTimeZoneSourcePrivate::icalTzidPrefix.isEmpty() ) {
01088     icaltimezone *icaltz = icaltimezone_get_builtin_timezone( "Europe/London" );
01089     QByteArray tzid = icaltimezone_get_tzid( icaltz );
01090     if ( tzid.right( 13 ) == "Europe/London" ) {
01091       int i = tzid.indexOf( '/', 1 );
01092       if ( i > 0 ) {
01093         ICalTimeZoneSourcePrivate::icalTzidPrefix = tzid.left( i + 1 );
01094         return ICalTimeZoneSourcePrivate::icalTzidPrefix;
01095       }
01096     }
01097     kError() << "failed to get libical TZID prefix";
01098   }
01099   return ICalTimeZoneSourcePrivate::icalTzidPrefix;
01100 }
01101 
01102 }  // namespace KCal

KCal Library

Skip menu "KCal Library"
  • Main Page
  • Namespace List
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Namespace Members
  • Class Members
  • Related Pages

KDE-PIM Libraries

Skip menu "KDE-PIM Libraries"
  • akonadi
  • kabc
  • kblog
  • kcal
  • kimap
  • kioslave
  •   imap4
  •   mbox
  • kldap
  • kmime
  • kpimidentities
  • kpimutils
  • kresources
  • ktnef
  • kxmlrpcclient
  • mailtransport
  • qgpgme
  • syndication
  •   atom
  •   rdf
  •   rss2
Generated for KDE-PIM Libraries by doxygen 1.5.7.1
This website is maintained by Adriaan de Groot and Allen Winter.
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal