<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package DateTime::Format::ICal;

use strict;

use vars qw ($VERSION);

$VERSION = '0.09';

use DateTime;
use DateTime::Span;
use DateTime::Event::ICal;

use Params::Validate qw( validate_with SCALAR );

sub new
{
    my $class = shift;

    return bless {}, $class;
}

# key is string length
my %valid_formats =
    ( 15 =&gt;
      { params =&gt; [ qw( year month day hour minute second ) ],
        regex  =&gt; qr/^(\d\d\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)$/,
      },
      13 =&gt;
      { params =&gt; [ qw( year month day hour minute ) ],
        regex  =&gt; qr/^(\d\d\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)$/,
      },
      11 =&gt;
      { params =&gt; [ qw( year month day hour ) ],
        regex  =&gt; qr/^(\d\d\d\d)(\d\d)(\d\d)T(\d\d)$/,
      },
      8 =&gt;
      { params =&gt; [ qw( year month day ) ],
        regex  =&gt; qr/^(\d\d\d\d)(\d\d)(\d\d)$/,
      },
    );

sub parse_datetime
{
    my ( $self, $date ) = @_;

    # save for error messages
    my $original = $date;

    my %p;
    if ( $date =~ s/^TZID=([^:]+):// )
    {
        $p{time_zone} = $1;
    }
    # Z at end means UTC
    elsif ( $date =~ s/Z$// )
    {
        $p{time_zone} = 'UTC';
    }
    else
    {
        $p{time_zone} = 'floating';
    }

    my $format = $valid_formats{ length $date }
        or die "Invalid iCal datetime string ($original)\n";

    @p{ @{ $format-&gt;{params} } } = $date =~ /$format-&gt;{regex}/;

    return DateTime-&gt;new(%p);
}

sub parse_duration
{
    my ( $self, $dur ) = @_;

    my @units = qw( weeks days hours minutes seconds );

    $dur =~ m{ ([\+\-])?         # Sign
               P                 # 'P' for period? This is our magic character)
               (?:
                   (?:(\d+)W)?   # Weeks
                   (?:(\d+)D)?   # Days
               )?
               (?: T             # Time prefix
                   (?:(\d+)H)?   # Hours
                   (?:(\d+)M)?   # Minutes
                   (?:(\d+)S)?   # Seconds
               )?
             }x;

    my $sign = $1;

    my %units;
    $units{weeks}   = $2 if defined $2;
    $units{days}    = $3 if defined $3;
    $units{hours}   = $4 if defined $4;
    $units{minutes} = $5 if defined $5;
    $units{seconds} = $6 if defined $6;

    die "Invalid ICal duration string ($dur)\n"
        unless %units;

    if ( defined $sign &amp;&amp; $sign eq '-' )
    {
        # $_ *= -1 foreach values %units;  - does not work in 5.00503
        $units{$_} *= -1 foreach keys %units;
    }

    return DateTime::Duration-&gt;new(%units);
}

sub parse_period
{
    my ( $self, $period ) = @_;

    my ( $start, $end ) = $period =~ /^((?:TZID=[^:]+:)?.*?)\/(.*)/;

    die "Invalid ICal period string ($period)\n"
        unless $start &amp;&amp; $end;

    $start = $self-&gt;parse_datetime( $start );

    if ( $end =~ /[\+\-]P/i ) {
        $end = $start + $self-&gt;parse_duration( $end );
    }
    else
    {
        $end = $self-&gt;parse_datetime( $end );
    }

    die "Invalid ICal period: end before start ($period)\n"
        if $start &gt; $end;

    return DateTime::Span-&gt;new( start =&gt; $start, end =&gt; $end );
}

sub parse_recurrence
{
    my $self = shift;
    my %p = validate_with( params =&gt; \@_,
                           spec   =&gt; { recurrence =&gt; { type =&gt; SCALAR } },
                           allow_extra =&gt; 1,
                         );

    my $recurrence = delete $p{recurrence};

    # recurrence may start with RRULE:
    $recurrence =~ s/^(?:RRULE|EXRULE)://i;

    # parser: adapted from code written for Date::Set by jesse
    # RRULEs look like 'FREQ=foo;INTERVAL=bar;' etc.
    foreach ( split /;/, $recurrence )
    {
        my ( $name, $value ) = split /=/;

        $name  = lc $name;

        # BY&lt;FOO&gt; parameters should be arrays. everything else should be strings
        if ( $name eq 'until' )
        {
            $p{$name} = __PACKAGE__-&gt;parse_datetime( $value );
        }
        elsif ( $name =~ /^by/i )
        {
            $p{$name} = [ split /,/, lc( $value ) ];
        }
        else
        {
            $p{$name} = lc( $value );
        }
    }

    return DateTime::Event::ICal-&gt;recur(%p);
}

sub format_datetime
{
    my ( $self, $dt ) = @_;

    my $tz = $dt-&gt;time_zone;

    unless ( $tz-&gt;is_floating ||
             $tz-&gt;is_utc ||
             $tz-&gt;is_olson )
    {
        $dt = $dt-&gt;clone-&gt;set_time_zone('UTC');
        $tz = $dt-&gt;time_zone;
    }

    my $base =
        sprintf( '%04d%02d%02dT%02d%02d%02d',
                 $dt-&gt;year, $dt-&gt;month, $dt-&gt;day,
                 $dt-&gt;hour, $dt-&gt;minute, $dt-&gt;second );

    return $base if $tz-&gt;is_floating;

    return $base . 'Z' if $tz-&gt;is_utc;

    return 'TZID=' . $tz-&gt;name . ':' . $base;
}

sub format_duration
{
    my ( $self, $duration ) = @_;

    die "Cannot represent years or months in an iCal duration\n"
        if $duration-&gt;delta_months;

    # simple string for 0-length durations
    return '+PT0S'
        unless $duration-&gt;delta_days ||
               $duration-&gt;delta_minutes ||
               $duration-&gt;delta_seconds;

    my $ical = $duration-&gt;is_positive ? '+' : '-';
    $ical .= 'P';

    if ( $duration-&gt;delta_days )
    {
        $ical .= $duration-&gt;weeks . 'W' if $duration-&gt;weeks;
        $ical .= $duration-&gt;days  . 'D' if $duration-&gt;days;
    }

    if ( $duration-&gt;delta_minutes || $duration-&gt;delta_seconds )
    {
        $ical .= 'T';

        $ical .= $duration-&gt;hours   . 'H' if $duration-&gt;hours;
        $ical .= $duration-&gt;minutes . 'M' if $duration-&gt;minutes;
        $ical .= $duration-&gt;seconds . 'S' if $duration-&gt;seconds;
    }

    return $ical;
}


sub format_period
{
    my ( $self, $span ) = @_;

    return $self-&gt;format_datetime( $span-&gt;start ) . '/' .
           $self-&gt;format_datetime( $span-&gt;end ) ;
}

sub format_period_with_duration
{
    my ( $self, $span ) = @_;

    return $self-&gt;format_datetime( $span-&gt;start ) . '/' .
           $self-&gt;format_duration( $span-&gt;duration ) ;
}


sub _split_datetime_tz 
{
    my ( $self, $dt ) = @_;

    my $tz = $dt-&gt;time_zone;

    unless ( $tz-&gt;is_floating ||
             $tz-&gt;is_utc ||
             $tz-&gt;is_olson )
    {
        $dt = $dt-&gt;clone-&gt;set_time_zone('UTC');
        $tz = $dt-&gt;time_zone;
    }

    my $base =
        ( $dt-&gt;hour || $dt-&gt;min || $dt-&gt;sec ?
          sprintf( '%04d%02d%02dT%02d%02d%02d',
                   $dt-&gt;year, $dt-&gt;month, $dt-&gt;day,
                   $dt-&gt;hour, $dt-&gt;minute, $dt-&gt;second ) :
          sprintf( '%04d%02d%02d', $dt-&gt;year, $dt-&gt;month, $dt-&gt;day )
        );

    return ($base, '')    if $tz-&gt;is_floating;
    return ($base, 'UTC') if $tz-&gt;is_utc;
    return ($base, $tz-&gt;name);
}

sub format_recurrence
{
    my ( $self, $set, @more ) = @_;
    my @result;

    # normalize param to either DT::Set or DT::SpanSet
    # DT list =&gt;       convert to DT::Set
    # DT::Span list =&gt; convert to DT::SpanSet

    if ( $set-&gt;isa('DateTime') )
    {
        $set = DateTime::Set-&gt;from_datetimes( dates =&gt; [ $set, @more ] );
    }
    elsif ( $set-&gt;isa('DateTime::Span') )
    {
        $set = DateTime::SpanSet-&gt;from_spans( spans =&gt; [ $set, @more ] );
    }

    # is it a recurrence?
    if ( $set-&gt;{set}-&gt;is_too_complex )
    {
        # DT::Set recurrence =&gt; DTSTART;timezone:date CRLF
        #                       RRULE:params CRLF
        #   note: add more lines if necessary:
        #             union =        more RRULE/RDATE lines
        #             complement =   more EXRULE/EXDATE lines
        #             intersection = ?
        #   note: timezone is specified by DTSTART only.

        # TODO: add support to DT::Event::Recurrence objects

        if ( $set-&gt;can( 'get_ical' ) &amp;&amp; defined $set-&gt;get_ical )
        {
            my %ical = $set-&gt;get_ical;
            for ( @{ $ical{include} } )
            {
                next unless $_;
                if ( ref( $_ ) )
                {
                    push @result, $self-&gt;format_recurrence( $_ );
                }
                else
                {
                    push @result, $_;
                }
            }
            if ( $ical{exclude} )
            {
                my @exclude;
                for ( @{ $ical{exclude} } )
                {
                    next unless $_;
                    if ( ref( $_ ) )
                    {
			push @exclude, $self-&gt;format_recurrence( $_ );
                    }
                    else
                    {
			push @exclude, $_;
                    }
                }
                s/^RDATE/EXDATE/ for @exclude;
                s/^RRULE/EXRULE/ for @exclude;
                push @result, @exclude;
            }
        }
        else
        {
            die "format_recurrence() - Format not implemented for this unbounded set";
        }

        # end: format recurrence
    }
    else
    {
        # DT::Set  =&gt;        RDATE:datetime,datetime,datetime CRLF
        # DT::SpanSet =&gt;     RDATE;VALUE=PERIOD:period,period CRLF
        #
        # not supported =&gt;   RDATE;VALUE=DATE:date,date,date CRLF
        #
        # DT::Set w/tz =&gt;     RDATE;timezone:date,date CRLF
        # DT::SpanSet w/tz =&gt; RDATE;VALUE=PERIOD;timezone:period,period CRLF

        my $iterator = $set-&gt;iterator;
        my $last_type = 'DateTime';
        my $last_tz =   'invalid';
        my $item;

        while( $item = $iterator-&gt;next )
        {
            if( $item-&gt;isa('DateTime') )
            {
                my ($base,$tz) = $self-&gt;_split_datetime_tz( $item );
                if( $last_tz eq $tz &amp;&amp;
                    $last_type eq 'DateTime' )
                {
                    $result[-1] .= ',' . $base;
                    $result[-1] .= 'Z' if $tz eq 'UTC';
                }
                else
                {
                    push @result, 'RDATE';
                    $result[-1] .= ';TZID='.$tz if $tz ne '' &amp;&amp; $tz ne 'UTC';
                    $result[-1] .= ':' . $base;
                    $result[-1] .= 'Z' if $tz eq 'UTC';
                    $last_tz =   $tz;
                    $last_type = 'DateTime';
                }
            }
            elsif( $item-&gt;isa('DateTime::Span') )
            {
                my $item_start = $item-&gt;start;
                my $item_end =   $item-&gt;end;
                if ( $item_start == $item_end )
                {
                    $item = $item_start;
                    # item looks like a datetime
                    redo;
                }
                my ($start,$tz) = $self-&gt;_split_datetime_tz( $item_start );
                $item_end-&gt;set_time_zone( $tz );
                my ($end,undef) = $self-&gt;_split_datetime_tz( $item_end );
                if( $last_tz eq $tz &amp;&amp;
                    $last_type eq 'DateTime::Span' )
                {
                    $result[-1] .= ',' . $start;
                    $result[-1] .= 'Z' if $tz eq 'UTC';
                    $result[-1] .= '/' . $end;
                    $result[-1] .= 'Z' if $tz eq 'UTC';
                }
                else
                {
                    push @result, 'RDATE;VALUE=PERIOD';
                    $result[-1] .= ';TZID='.$tz if $tz ne '' &amp;&amp; $tz ne 'UTC';
                    $result[-1] .= ':' . $start;
                    $result[-1] .= 'Z' if $tz eq 'UTC';
                    $result[-1] .= '/' . $end;
                    $result[-1] .= 'Z' if $tz eq 'UTC';
                    $last_tz =   $tz;
                    $last_type = 'DateTime::Span';
                }
            }
            else
            {
                die 'unexpected data type "'.ref($item).'" in set';
            }
        }

        # end: format list of dates
    }
    return join( "\n", @result ) if ! wantarray;
    return @result;
}

1;

__END__

=head1 NAME

DateTime::Format::ICal - Parse and format iCal datetime and duration strings

=head1 SYNOPSIS

  use DateTime::Format::ICal;

  my $dt = DateTime::Format::ICal-&gt;parse_datetime( '20030117T032900Z' );

  my $dur = DateTime::Format::ICal-&gt;parse_duration( '+P3WT4H55S' );

  # 20030117T032900Z
  DateTime::Format::ICal-&gt;format_datetime($dt);

  # +P3WT4H55S
  DateTime::Format::ICal-&gt;format_duration($dur);

=head1 DESCRIPTION

This module understands the ICal date/time and duration formats, as
defined in RFC 2445.  It can be used to parse these formats in order
to create the appropriate objects.

=head1 METHODS

This class offers the following methods.

=over 4

=item * parse_datetime($string)

Given an iCal datetime string, this method will return a new
C&lt;DateTime&gt; object.

If given an improperly formatted string, this method may die.

=item * parse_duration($string)

Given an iCal duration string, this method will return a new
C&lt;DateTime::Duration&gt; object.

If given an improperly formatted string, this method may die.

=item * parse_period($string)

Given an iCal period string, this method will return a new
C&lt;DateTime::Span&gt; object.

If given an improperly formatted string, this method may die.

=item * parse_recurrence( recurrence =&gt; $string, ... )

Given an iCal recurrence description, this method uses
C&lt;DateTime::Event::ICal&gt; to create a C&lt;DateTime::Set&gt; object
representing that recurrence.  Any parameters given to this method
beside "recurrence" will be passed directly to the 
C&lt;&lt; DateTime::Event::ICal-&gt;recur &gt;&gt; method.

If given an improperly formatted string, this method may die.

This method accepts optional parameters "dtstart" and "dtend".
These parameters must be C&lt;DateTime&gt; objects.

The iCal spec requires that "dtstart" always be included in the
recurrence set, unless this is an "exrule" statement.  Since we don't
know what kind of statement is being parsed, we do not include
C&lt;dtstart&gt; in the recurrence set.

=item * format_datetime($datetime)

Given a C&lt;DateTime&gt; object, this methods returns an iCal datetime
string.

The iCal spec requires that datetimes be formatted either as floating
times (no time zone), UTC (with a 'Z' suffix) or with a time zone id
at the beginning ('TZID=America/Chicago;...').  If this method is
asked to format a C&lt;DateTime&gt; object that has an offset-only time
zone, then the object will be converted to the UTC time zone
internally before formatting.

For example, this code:

    my $dt = DateTime-&gt;new( year =&gt; 1900, hour =&gt; 15, time_zone =&gt; '-0100' );

    print $ical-&gt;format_datetime($dt);

will print the string "19000101T160000Z".

=item * format_duration($duration)

Given a C&lt;DateTime::Duration&gt; object, this methods returns an iCal
duration string.

The iCal standard does not allow for months or years in a duration, so
if a duration for which C&lt;delta_months()&gt; is not zero is given, then
this method will die.

=item * format_period($span)

Given a C&lt;DateTime::Span&gt; object, this methods returns an iCal
period string, using the format C&lt;DateTime/DateTime&gt;.

=item * format_period_with_duration($span)

Given a C&lt;DateTime::Span&gt; object, this methods returns an iCal
period string, using the format C&lt;DateTime/Duration&gt;.

=item * format_recurrence($arg [,$arg...] )

This method returns a list of strings containing ICal statements.
In scalar context it returns a single string which may contain
embedded newlines.

The argument can be a C&lt;DateTime&gt; list, a C&lt;DateTime::Span&gt; list, a
C&lt;DateTime::Set&gt;, or a C&lt;DateTime::SpanSet&gt;.

ICal C&lt;DATE&gt; values are not supported. Whenever a date value is found,
a C&lt;DATE-TIME&gt; is generated.

If a recurrence has an associated C&lt;DTSTART&gt; or C&lt;DTEND&gt;, those values
must be formatted using C&lt;format_datetime()&gt;.  The
C&lt;format_recurrence()&gt; method will not do this for you.

If a C&lt;union&gt; or C&lt;complement&gt; of recurrences is being formatted, they
are assumed to have the same C&lt;DTSTART&gt; value.

Only C&lt;union&gt; and C&lt;complement&gt; operations are supported for
recurrences.  This is a limitation of the ICal specification.

If given a set it cannot format, this method may die.

Only C&lt;DateTime::Set::ICal&gt; objects are formattable.  A set may change
class after some set operations:

    $recurrence = $recurrence-&gt;union( $dt_set );
    # Ok - $recurrence still is a DT::Set::ICal

    $recurrence = $dt_set-&gt;union( $recurrence );
    # Not Ok! - $recurrence is a DT::Set now

The only unbounded recurrences currently supported are the ones
generated by the C&lt;DateTime::Event::ICal&gt; module.

You can add ICal formatting support to a custom recurrence by using
the C&lt;DateTime::Set::ICal&gt; module:

    $custom_recurrence =
        DateTime::Set::ICal-&gt;from_recurrence
            ( recurrence =&gt;
              sub { $_[0]-&gt;truncate( to =&gt; 'month' )-&gt;add( months =&gt; 1 ) }
            );
    $custom_recurrence-&gt;set_ical( include =&gt; [ 'FREQ=MONTHLY' ] );

=back

=head1 SUPPORT

Support for this module is provided via the datetime@perl.org email
list.  See http://lists.perl.org/ for more details.

=head1 AUTHORS

Dave Rolsky &lt;autarch@urth.org&gt; and Flavio Soibelmann Glock
&lt;fglock@pucrs.br&gt;

Some of the code in this module comes from Rich Bowen's C&lt;Date::ICal&gt;
module.

=head1 COPYRIGHT

Copyright (c) 2003 David Rolsky.  All rights reserved.  This program
is free software; you can redistribute it and/or modify it under the
same terms as Perl itself.

The full text of the license can be found in the LICENSE file included
with this module.

=head1 SEE ALSO

datetime@perl.org mailing list

http://datetime.perl.org/

=cut
</pre></body></html>