import rt 3.8.7
[freeside.git] / rt / lib / RT / Date.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2
3 # COPYRIGHT:
4
5 # This software is Copyright (c) 1996-2009 Best Practical Solutions, LLC
6 #                                          <jesse@bestpractical.com>
7
8 # (Except where explicitly superseded by other copyright notices)
9
10
11 # LICENSE:
12
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28
29
30 # CONTRIBUTION SUBMISSION POLICY:
31
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46
47 # END BPS TAGGED BLOCK }}}
48
49 =head1 NAME
50
51   RT::Date - a simple Object Oriented date.
52
53 =head1 SYNOPSIS
54
55   use RT::Date
56
57 =head1 DESCRIPTION
58
59 RT Date is a simple Date Object designed to be speedy and easy for RT to use
60
61 The fact that it assumes that a time of 0 means "never" is probably a bug.
62
63
64 =head1 METHODS
65
66 =cut
67
68
69 package RT::Date;
70
71 use Time::Local;
72 use POSIX qw(tzset);
73
74 use strict;
75 use warnings;
76 use base qw/RT::Base/;
77
78 use vars qw($MINUTE $HOUR $DAY $WEEK $MONTH $YEAR);
79
80 $MINUTE = 60;
81 $HOUR   = 60 * $MINUTE;
82 $DAY    = 24 * $HOUR;
83 $WEEK   = 7 * $DAY;
84 $MONTH  = 30.4375 * $DAY;
85 $YEAR   = 365.25 * $DAY;
86
87 our @MONTHS = (
88     'Jan', # loc
89     'Feb', # loc
90     'Mar', # loc
91     'Apr', # loc
92     'May', # loc
93     'Jun', # loc
94     'Jul', # loc
95     'Aug', # loc
96     'Sep', # loc
97     'Oct', # loc
98     'Nov', # loc
99     'Dec', # loc
100 );
101
102 our @DAYS_OF_WEEK = (
103     'Sun', # loc
104     'Mon', # loc
105     'Tue', # loc
106     'Wed', # loc
107     'Thu', # loc
108     'Fri', # loc
109     'Sat', # loc
110 );
111
112 our @FORMATTERS = (
113     'DefaultFormat', # loc
114     'ISO',           # loc
115     'W3CDTF',        # loc
116     'RFC2822',       # loc
117     'RFC2616',       # loc
118     'iCal',          # loc
119 );
120 if ( eval 'use DateTime qw(); 1;' && eval 'use DateTime::Locale qw(); 1;' && 
121      DateTime->can('format_cldr') && DateTime::Locale::root->can('date_format_full') ) {
122     push @FORMATTERS, 'LocalizedDateTime'; # loc
123 }
124
125 =head2 new
126
127 Object constructor takes one argument C<RT::CurrentUser> object.
128
129 =cut
130
131 sub new {
132     my $proto = shift;
133     my $class = ref($proto) || $proto;
134     my $self  = {};
135     bless ($self, $class);
136     $self->CurrentUser(@_);
137     $self->Unix(0);
138     return $self;
139 }
140
141 =head2 Set
142
143 Takes a param hash with the fields C<Format>, C<Value> and C<Timezone>.
144
145 If $args->{'Format'} is 'unix', takes the number of seconds since the epoch.
146
147 If $args->{'Format'} is ISO, tries to parse an ISO date.
148
149 If $args->{'Format'} is 'unknown', require Time::ParseDate and make it figure
150 things out. This is a heavyweight operation that should never be called from
151 within RT's core. But it's really useful for something like the textbox date
152 entry where we let the user do whatever they want.
153
154 If $args->{'Value'} is 0, assumes you mean never.
155
156 =cut
157
158 sub Set {
159     my $self = shift;
160     my %args = (
161         Format   => 'unix',
162         Value    => time,
163         Timezone => 'user',
164         @_
165     );
166
167     return $self->Unix(0) unless $args{'Value'};
168
169     if ( $args{'Format'} =~ /^unix$/i ) {
170         return $self->Unix( $args{'Value'} );
171     }
172     elsif ( $args{'Format'} =~ /^(sql|datemanip|iso)$/i ) {
173         $args{'Value'} =~ s!/!-!g;
174
175         if (   ( $args{'Value'} =~ /^(\d{4})?(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/ )
176             || ( $args{'Value'} =~ /^(\d{4})?(\d\d)(\d\d)(\d\d):(\d\d):(\d\d)$/ )
177             || ( $args{'Value'} =~ /^(?:(\d{4})-)?(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/ )
178             || ( $args{'Value'} =~ /^(?:(\d{4})-)?(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)\+00$/ )
179           ) {
180
181             my ($year, $mon, $mday, $hours, $min, $sec)  = ($1, $2, $3, $4, $5, $6);
182
183             # use current year if string has no value
184             $year ||= (localtime time)[5] + 1900;
185
186             #timegm expects month as 0->11
187             $mon--;
188
189             #now that we've parsed it, deal with the case where everything was 0
190             return $self->Unix(0) if $mon < 0 || $mon > 11;
191
192             my $tz = lc $args{'Format'} eq 'datemanip'? 'user': 'utc';
193             $self->Unix( $self->Timelocal( $tz, $sec, $min, $hours, $mday, $mon, $year ) );
194
195             $self->Unix(0) unless $self->Unix > 0;
196         }
197         else {
198             $RT::Logger->warning(
199                 "Couldn't parse date '$args{'Value'}' as a $args{'Format'} format"
200             );
201             return $self->Unix(0);
202         }
203     }
204     elsif ( $args{'Format'} =~ /^unknown$/i ) {
205         require Time::ParseDate;
206         # the module supports only legacy timezones like PDT or EST...
207         # so we parse date as GMT and later apply offset, this only
208         # should be applied to absolute times, so compensate shift in NOW
209         my $now = time;
210         $now += ($self->Localtime( $args{Timezone}, $now ))[9];
211         my $date = Time::ParseDate::parsedate(
212             $args{'Value'},
213             GMT           => 1,
214             NOW           => $now,
215             UK            => RT->Config->Get('DateDayBeforeMonth'),
216             PREFER_PAST   => RT->Config->Get('AmbiguousDayInPast'),
217             PREFER_FUTURE => RT->Config->Get('AmbiguousDayInFuture'),
218         );
219         # apply timezone offset
220         $date -= ($self->Localtime( $args{Timezone}, $date ))[9];
221
222         $RT::Logger->debug(
223             "RT::Date used Time::ParseDate to make '$args{'Value'}' $date\n"
224         );
225
226         return $self->Set( Format => 'unix', Value => $date);
227     }
228     else {
229         $RT::Logger->error(
230             "Unknown Date format: $args{'Format'}\n"
231         );
232         return $self->Unix(0);
233     }
234
235     return $self->Unix;
236 }
237
238 =head2 SetToNow
239
240 Set the object's time to the current time. Takes no arguments
241 and returns unix time.
242
243 =cut
244
245 sub SetToNow {
246     return $_[0]->Unix(time);
247 }
248
249 =head2 SetToMidnight [Timezone => 'utc']
250
251 Sets the date to midnight (at the beginning of the day).
252 Returns the unixtime at midnight.
253
254 Arguments:
255
256 =over 4
257
258 =item Timezone
259
260 Timezone context C<user>, C<server> or C<UTC>. See also L</Timezone>.
261
262 =back
263
264 =cut
265
266 sub SetToMidnight {
267     my $self = shift;
268     my %args = ( Timezone => '', @_ );
269     my $new = $self->Timelocal(
270         $args{'Timezone'},
271         0,0,0,($self->Localtime( $args{'Timezone'} ))[3..9]
272     );
273     return $self->Unix( $new );
274 }
275
276 =head2 Diff
277
278 Takes either an C<RT::Date> object or the date in unixtime format as a string,
279 if nothing is specified uses the current time.
280
281 Returns the differnce between the time in the current object and that time
282 as a number of seconds. Returns C<undef> if any of two compared values is
283 incorrect or not set.
284
285 =cut
286
287 sub Diff {
288     my $self = shift;
289     my $other = shift;
290     $other = time unless defined $other;
291     if ( UNIVERSAL::isa( $other, 'RT::Date' ) ) {
292         $other = $other->Unix;
293     }
294     return undef unless $other=~ /^\d+$/ && $other > 0;
295
296     my $unix = $self->Unix;
297     return undef unless $unix > 0;
298
299     return $unix - $other;
300 }
301
302 =head2 DiffAsString
303
304 Takes either an C<RT::Date> object or the date in unixtime format as a string,
305 if nothing is specified uses the current time.
306
307 Returns the differnce between C<$self> and that time as a number of seconds as
308 a localized string fit for human consumption. Returns empty string if any of
309 two compared values is incorrect or not set.
310
311 =cut
312
313 sub DiffAsString {
314     my $self = shift;
315     my $diff = $self->Diff( @_ );
316     return '' unless defined $diff;
317
318     return $self->DurationAsString( $diff );
319 }
320
321 =head2 DurationAsString
322
323 Takes a number of seconds. Returns a localized string describing
324 that duration.
325
326 =cut
327
328 sub DurationAsString {
329     my $self     = shift;
330     my $duration = int shift;
331
332     my ( $negative, $s, $time_unit );
333     $negative = 1 if $duration < 0;
334     $duration = abs $duration;
335
336     if ( $duration < $MINUTE ) {
337         $s         = $duration;
338         $time_unit = $self->loc("sec");
339     }
340     elsif ( $duration < ( 2 * $HOUR ) ) {
341         $s         = int( $duration / $MINUTE + 0.5 );
342         $time_unit = $self->loc("min");
343     }
344     elsif ( $duration < ( 2 * $DAY ) ) {
345         $s         = int( $duration / $HOUR + 0.5 );
346         $time_unit = $self->loc("hours");
347     }
348     elsif ( $duration < ( 2 * $WEEK ) ) {
349         $s         = int( $duration / $DAY + 0.5 );
350         $time_unit = $self->loc("days");
351     }
352     elsif ( $duration < ( 2 * $MONTH ) ) {
353         $s         = int( $duration / $WEEK + 0.5 );
354         $time_unit = $self->loc("weeks");
355     }
356     elsif ( $duration < $YEAR ) {
357         $s         = int( $duration / $MONTH + 0.5 );
358         $time_unit = $self->loc("months");
359     }
360     else {
361         $s         = int( $duration / $YEAR + 0.5 );
362         $time_unit = $self->loc("years");
363     }
364
365     if ( $negative ) {
366         return $self->loc( "[_1] [_2] ago", $s, $time_unit );
367     }
368     else {
369         return $self->loc( "[_1] [_2]", $s, $time_unit );
370     }
371 }
372
373 =head2 AgeAsString
374
375 Takes nothing. Returns a string that's the differnce between the
376 time in the object and now.
377
378 =cut
379
380 sub AgeAsString { return $_[0]->DiffAsString }
381
382
383
384 =head2 AsString
385
386 Returns the object's time as a localized string with curent user's prefered
387 format and timezone.
388
389 If the current user didn't choose prefered format then system wide setting is
390 used or L</DefaultFormat> if the latter is not specified. See config option
391 C<DateTimeFormat>.
392
393 =cut
394
395 sub AsString {
396     my $self = shift;
397     my %args = (@_);
398
399     return $self->loc("Not set") unless $self->Unix > 0;
400
401     my $format = RT->Config->Get( 'DateTimeFormat', $self->CurrentUser ) || 'DefaultFormat';
402     $format = { Format => $format } unless ref $format;
403     %args = (%$format, %args);
404
405     return $self->Get( Timezone => 'user', %args );
406 }
407
408 =head2 GetWeekday DAY
409
410 Takes an integer day of week and returns a localized string for
411 that day of week. Valid values are from range 0-6, Note that B<0
412 is sunday>.
413
414 =cut
415
416 sub GetWeekday {
417     my $self = shift;
418     my $dow = shift;
419     
420     return $self->loc($DAYS_OF_WEEK[$dow])
421         if $DAYS_OF_WEEK[$dow];
422     return '';
423 }
424
425 =head2 GetMonth MONTH
426
427 Takes an integer month and returns a localized string for that month.
428 Valid values are from from range 0-11.
429
430 =cut
431
432 sub GetMonth {
433     my $self = shift;
434     my $mon = shift;
435
436     return $self->loc($MONTHS[$mon])
437         if $MONTHS[$mon];
438     return '';
439 }
440
441 =head2 AddSeconds SECONDS
442
443 Takes a number of seconds and returns the new unix time.
444
445 Negative value can be used to substract seconds.
446
447 =cut
448
449 sub AddSeconds {
450     my $self = shift;
451     my $delta = shift or return $self->Unix;
452     
453     $self->Set(Format => 'unix', Value => ($self->Unix + $delta));
454  
455     return ($self->Unix);
456 }
457
458 =head2 AddDays [DAYS]
459
460 Adds C<24 hours * DAYS> to the current time. Adds one day when
461 no argument is specified. Negative value can be used to substract
462 days.
463
464 Returns new unix time.
465
466 =cut
467
468 sub AddDays {
469     my $self = shift;
470     my $days = shift || 1;
471     return $self->AddSeconds( $days * $DAY );
472 }
473
474 =head2 AddDay
475
476 Adds 24 hours to the current time. Returns new unix time.
477
478 =cut
479
480 sub AddDay { return $_[0]->AddSeconds($DAY) }
481
482 =head2 Unix [unixtime]
483
484 Optionally takes a date in unix seconds since the epoch format.
485 Returns the number of seconds since the epoch
486
487 =cut
488
489 sub Unix {
490     my $self = shift; 
491     $self->{'time'} = int(shift || 0) if @_;
492     return $self->{'time'};
493 }
494
495 =head2 DateTime
496
497 Alias for L</Get> method. Arguments C<Date> and <Time>
498 are fixed to true values, other arguments could be used
499 as described in L</Get>.
500
501 =cut
502
503 sub DateTime {
504     my $self = shift;
505     unless (defined $self) {
506         use Carp; Carp::confess("undefined $self");
507     }
508     return $self->Get( @_, Date => 1, Time => 1 );
509 }
510
511 =head2 Date
512
513 Takes Format argument which allows you choose date formatter.
514 Pass throught other arguments to the formatter method.
515
516 Returns the object's formatted date. Default formatter is ISO.
517
518 =cut
519
520 sub Date {
521     my $self = shift;
522     return $self->Get( @_, Date => 1, Time => 0 );
523 }
524
525 =head2 Time
526
527
528 =cut
529
530 sub Time {
531     my $self = shift;
532     return $self->Get( @_, Date => 0, Time => 1 );
533 }
534
535 =head2 Get
536
537 Returnsa a formatted and localized string that represets time of
538 the current object.
539
540
541 =cut
542
543 sub Get
544 {
545     my $self = shift;
546     my %args = (Format => 'ISO', @_);
547     my $formatter = $args{'Format'};
548     $formatter = 'ISO' unless $self->can($formatter);
549     return $self->$formatter( %args );
550 }
551
552 =head2 Output formatters
553
554 Fomatter is a method that returns date and time in different configurable
555 format.
556
557 Each method takes several arguments:
558
559 =over 1
560
561 =item Date
562
563 =item Time
564
565 =item Timezone - Timezone context C<server>, C<user> or C<UTC>
566
567 =back
568
569 Formatters may also add own arguments to the list, for example
570 in RFC2822 format day of time in output is optional so it
571 understand boolean argument C<DayOfTime>.
572
573 =head3 Formatters
574
575 Returns an array of available formatters.
576
577 =cut
578
579 sub Formatters
580 {
581     my $self = shift;
582
583     return @FORMATTERS;
584 }
585
586 =head3 DefaultFormat
587
588 =cut
589
590 sub DefaultFormat
591 {
592     my $self = shift;
593     my %args = ( Date => 1,
594                  Time => 1,
595                  Timezone => '',
596                  Seconds => 1,
597                  @_,
598                );
599     
600        #  0    1    2     3     4    5     6     7      8      9
601     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
602                             $self->Localtime($args{'Timezone'});
603     $wday = $self->GetWeekday($wday);
604     $mon = $self->GetMonth($mon);
605     ($mday, $hour, $min, $sec) = map { sprintf "%02d", $_ } ($mday, $hour, $min, $sec);
606
607     if( $args{'Date'} && !$args{'Time'} ) {
608         return $self->loc('[_1] [_2] [_3] [_4]',
609                           $wday,$mon,$mday,$year);
610     } elsif( !$args{'Date'} && $args{'Time'} ) {
611         if( $args{'Seconds'} ) {
612             return $self->loc('[_1]:[_2]:[_3]',
613                               $hour,$min,$sec);
614         } else {
615             return $self->loc('[_1]:[_2]',
616                               $hour,$min);
617         }
618     } else {
619         if( $args{'Seconds'} ) {
620             return $self->loc('[_1] [_2] [_3] [_4]:[_5]:[_6] [_7]',
621                               $wday,$mon,$mday,$hour,$min,$sec,$year);
622         } else {
623             return $self->loc('[_1] [_2] [_3] [_4]:[_5] [_6]',
624                               $wday,$mon,$mday,$hour,$min,$year);
625         }
626     }
627 }
628
629 =head3 LocalizedDateTime
630
631 Returns date and time as string, with user localization.
632
633 Supports arguments: C<DateFormat> and C<TimeFormat> which may contains date and
634 time format as specified in DateTime::Locale (default to full_date_format and
635 medium_time_format), C<AbbrDay> and C<AbbrMonth> which may be set to 0 if
636 you want full Day/Month names instead of abbreviated ones.
637
638 Require optionnal DateTime::Locale module.
639
640 =cut
641
642 sub LocalizedDateTime
643 {
644     my $self = shift;
645     my %args = ( Date => 1,
646                  Time => 1,
647                  Timezone => '',
648                  DateFormat => 'date_format_full',
649                  TimeFormat => 'time_format_medium',
650                  AbbrDay => 1,
651                  AbbrMonth => 1,
652                  @_,
653                );
654
655     return $self->loc("DateTime module missing") unless ( eval 'use DateTime qw(); 1;' );
656     return $self->loc("DateTime::Locale module missing") unless ( eval 'use DateTime::Locale qw(); 1;' );
657     return $self->loc("DateTime doesn't support format_cldr, you must upgrade to use this feature") 
658         unless can DateTime::('format_cldr');
659
660
661     my $date_format = $args{'DateFormat'};
662     my $time_format = $args{'TimeFormat'};
663
664     my $lang = $self->CurrentUser->UserObj->Lang;
665     unless ($lang) {
666         require I18N::LangTags::Detect;
667         $lang = ( I18N::LangTags::Detect::detect(), 'en' )[0];
668     }
669     
670
671     my $formatter = DateTime::Locale->load($lang);
672     return $self->loc("DateTime::Locale doesn't support date_format_full, you must upgrade to use this feature") 
673         unless $formatter->can('date_format_full');
674     $date_format = $formatter->$date_format;
675     $time_format = $formatter->$time_format;
676     $date_format =~ s/EEEE/EEE/g if ( $args{'AbbrDay'} );
677     $date_format =~ s/MMMM/MMM/g if ( $args{'AbbrMonth'} );
678
679     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
680                             $self->Localtime($args{'Timezone'});
681     $mon++;
682     my $tz = $self->Timezone($args{'Timezone'});
683
684     # FIXME : another way to call this module without conflict with local
685     # DateTime method?
686     my $dt = new DateTime::( locale => $lang,
687                             time_zone => $tz,
688                             year => $year,
689                             month => $mon,
690                             day => $mday,
691                             hour => $hour,
692                             minute => $min,
693                             second => $sec,
694                             nanosecond => 0,
695                           );
696
697     if ( $args{'Date'} && !$args{'Time'} ) {
698         return $dt->format_cldr($date_format);
699     } elsif ( !$args{'Date'} && $args{'Time'} ) {
700         return $dt->format_cldr($time_format);
701     } else {
702         return $dt->format_cldr($date_format) . " " . $dt->format_cldr($time_format);
703     }
704 }
705
706 =head3 ISO
707
708 Returns the object's date in ISO format C<YYYY-MM-DD mm:hh:ss>.
709 ISO format is locale independant, but adding timezone offset info
710 is not implemented yet.
711
712 Supports arguments: C<Timezone>, C<Date>, C<Time> and C<Seconds>.
713 See </Output formatters> for description of arguments.
714
715 =cut
716
717 sub ISO {
718     my $self = shift;
719     my %args = ( Date => 1,
720                  Time => 1,
721                  Timezone => '',
722                  Seconds => 1,
723                  @_,
724                );
725        #  0    1    2     3     4    5     6     7      8      9
726     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
727                             $self->Localtime($args{'Timezone'});
728
729     #the month needs incrementing, as gmtime returns 0-11
730     $mon++;
731
732     my $res = '';
733     $res .= sprintf("%04d-%02d-%02d", $year, $mon, $mday) if $args{'Date'};
734     $res .= sprintf(' %02d:%02d', $hour, $min) if $args{'Time'};
735     $res .= sprintf(':%02d', $sec, $min) if $args{'Time'} && $args{'Seconds'};
736     $res =~ s/^\s+//;
737
738     return $res;
739 }
740
741 =head3 W3CDTF
742
743 Returns the object's date and time in W3C date time format
744 (L<http://www.w3.org/TR/NOTE-datetime>).
745
746 Format is locale independand and is close enought to ISO, but
747 note that date part is B<not optional> and output string
748 has timezone offset mark in C<[+-]hh:mm> format.
749
750 Supports arguments: C<Timezone>, C<Time> and C<Seconds>.
751 See </Output formatters> for description of arguments.
752
753 =cut
754
755 sub W3CDTF {
756     my $self = shift;
757     my %args = (
758         Time => 1,
759         Timezone => '',
760         Seconds => 1,
761         @_,
762         Date => 1,
763     );
764        #  0    1    2     3     4    5     6     7      8      9
765     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
766                             $self->Localtime( $args{'Timezone'} );
767
768     #the month needs incrementing, as gmtime returns 0-11
769     $mon++;
770
771     my $res = '';
772     $res .= sprintf("%04d-%02d-%02d", $year, $mon, $mday);
773     if ( $args{'Time'} ) {
774         $res .= sprintf('T%02d:%02d', $hour, $min);
775         $res .= sprintf(':%02d', $sec, $min) if $args{'Seconds'};
776         if ( $offset ) {
777             $res .= sprintf "%s%02d:%02d", $self->_SplitOffset( $offset );
778         } else {
779             $res .= 'Z';
780         }
781     }
782
783     return $res;
784 };
785
786
787 =head3 RFC2822 (MIME)
788
789 Returns the object's date and time in RFC2822 format,
790 for example C<Sun, 06 Nov 1994 08:49:37 +0000>.
791 Format is locale independand as required by RFC. Time
792 part always has timezone offset in digits with sign prefix.
793
794 Supports arguments: C<Timezone>, C<Date>, C<Time>, C<DayOfWeek>
795 and C<Seconds>. See </Output formatters> for description of
796 arguments.
797
798 =cut
799
800 sub RFC2822 {
801     my $self = shift;
802     my %args = ( Date => 1,
803                  Time => 1,
804                  Timezone => '',
805                  DayOfWeek => 1,
806                  Seconds => 1,
807                  @_,
808                );
809
810        #  0    1    2     3     4    5     6     7      8     9
811     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
812                             $self->Localtime($args{'Timezone'});
813
814     my ($date, $time) = ('','');
815     $date .= "$DAYS_OF_WEEK[$wday], " if $args{'DayOfWeek'} && $args{'Date'};
816     $date .= "$mday $MONTHS[$mon] $year" if $args{'Date'};
817
818     if ( $args{'Time'} ) {
819         $time .= sprintf("%02d:%02d", $hour, $min);
820         $time .= sprintf(":%02d", $sec) if $args{'Seconds'};
821         $time .= sprintf " %s%02d%02d", $self->_SplitOffset( $offset );
822     }
823
824     return join ' ', grep $_, ($date, $time);
825 }
826
827 =head3 RFC2616 (HTTP)
828
829 Returns the object's date and time in RFC2616 (HTTP/1.1) format,
830 for example C<Sun, 06 Nov 1994 08:49:37 GMT>. While the RFC describes
831 version 1.1 of HTTP, but the same form date can be used in version 1.0.
832
833 Format is fixed length, locale independand and always represented in GMT
834 what makes it quite useless for users, but any date in HTTP transfers
835 must be presented using this format.
836
837     HTTP-date = rfc1123 | ...
838     rfc1123   = wkday "," SP date SP time SP "GMT"
839     date      = 2DIGIT SP month SP 4DIGIT
840                 ; day month year (e.g., 02 Jun 1982)
841     time      = 2DIGIT ":" 2DIGIT ":" 2DIGIT
842                 ; 00:00:00 - 23:59:59
843     wkday     = "Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun"
844     month     = "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun"
845               | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
846
847 Supports arguments: C<Date> and C<Time>, but you should use them only for
848 some personal reasons, RFC2616 doesn't define any optional parts.
849 See </Output formatters> for description of arguments.
850
851 =cut
852
853 sub RFC2616 {
854     my $self = shift;
855     my %args = ( Date => 1, Time => 1,
856                  @_,
857                  Timezone => 'utc',
858                  Seconds => 1, DayOfWeek => 1,
859                );
860
861     my $res = $self->RFC2822( @_ );
862     $res =~ s/\s*[+-]\d\d\d\d$/ GMT/ if $args{'Time'};
863     return $res;
864 }
865
866 =head4 iCal
867
868 Returns the object's date and time in iCalendar format,
869
870 Supports arguments: C<Date> and C<Time>.
871 See </Output formatters> for description of arguments.
872
873 =cut
874
875 sub iCal {
876     my $self = shift;
877     my %args = (
878         Date => 1, Time => 1,
879         @_,
880     );
881     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
882         $self->Localtime( 'utc' );
883
884     #the month needs incrementing, as gmtime returns 0-11
885     $mon++;
886
887     my $res;
888     if ( $args{'Date'} && !$args{'Time'} ) {
889         $res = sprintf( '%04d%02d%02d', $year, $mon, $mday );
890     }
891     elsif ( !$args{'Date'} && $args{'Time'} ) {
892         $res = sprintf( 'T%02d%02d%02dZ', $hour, $min, $sec );
893     }
894     else {
895         $res = sprintf( '%04d%02d%02dT%02d%02d%02dZ', $year, $mon, $mday, $hour, $min, $sec );
896     }
897     return $res;
898 }
899
900 # it's been added by mistake in 3.8.0
901 sub iCalDate { return (shift)->iCal( Time => 0, @_ ) }
902
903 sub _SplitOffset {
904     my ($self, $offset) = @_;
905     my $sign = $offset < 0? '-': '+';
906     $offset = int( (abs $offset) / 60 + 0.001 );
907     my $mins = $offset % 60;
908     my $hours = int( $offset/60 + 0.001 );
909     return $sign, $hours, $mins; 
910 }
911
912 =head2 Timezones handling
913
914 =head3 Localtime $context [$time]
915
916 Takes one mandatory argument C<$context>, which determines whether
917 we want "user local", "system" or "UTC" time. Also, takes optional
918 argument unix C<$time>, default value is the current unix time.
919
920 Returns object's date and time in the format provided by perl's
921 builtin functions C<localtime> and C<gmtime> with two exceptions:
922
923 1) "Year" is a four-digit year, rather than "years since 1900"
924
925 2) The last element of the array returned is C<offset>, which
926 represents timezone offset against C<UTC> in seconds.
927
928 =cut
929
930 sub Localtime
931 {
932     my $self = shift;
933     my $tz = $self->Timezone(shift);
934
935     my $unix = shift || $self->Unix;
936     $unix = 0 unless $unix >= 0;
937     
938     my @local;
939     if ($tz eq 'UTC') {
940         @local = gmtime($unix);
941     } else {
942         {
943             local $ENV{'TZ'} = $tz;
944             ## Using POSIX::tzset fixes a bug where the TZ environment variable
945             ## is cached.
946             POSIX::tzset();
947             @local = localtime($unix);
948         }
949         POSIX::tzset(); # return back previouse value
950     }
951     $local[5] += 1900; # change year to 4+ digits format
952     my $offset = Time::Local::timegm_nocheck(@local) - $unix;
953     return @local, $offset;
954 }
955
956 =head3 Timelocal $context @time
957
958 Takes argument C<$context>, which determines whether we should
959 treat C<@time> as "user local", "system" or "UTC" time.
960
961 C<@time> is array returned by L<Localtime> functions. Only first
962 six elements are mandatory - $sec, $min, $hour, $mday, $mon and $year.
963 You may pass $wday, $yday and $isdst, these are ignored.
964
965 If you pass C<$offset> as ninth argument, it's used instead of
966 C<$context>. It's done such way as code 
967 C<$self->Timelocal('utc', $self->Localtime('server'))> doesn't
968 makes much sense and most probably would produce unexpected
969 result, so the method ignore 'utc' context and uses offset
970 returned by L<Localtime> method.
971
972 =cut
973
974 sub Timelocal {
975     my $self = shift;
976     my $tz = shift;
977     if ( defined $_[9] ) {
978         return timegm(@_[0..5]) - $_[9];
979     } else {
980         $tz = $self->Timezone( $tz );
981         if ( $tz eq 'UTC' ) {
982             return Time::Local::timegm(@_[0..5]);
983         } else {
984             my $rv;
985             {
986                 local $ENV{'TZ'} = $tz;
987                 ## Using POSIX::tzset fixes a bug where the TZ environment variable
988                 ## is cached.
989                 POSIX::tzset();
990                 $rv = Time::Local::timelocal(@_[0..5]);
991             };
992             POSIX::tzset(); # switch back to previouse value
993             return $rv;
994         }
995     }
996 }
997
998
999 =head3 Timezone $context
1000
1001 Returns the timezone name.
1002
1003 Takes one argument, C<$context> argument which could be C<user>, C<server> or C<utc>.
1004
1005 =over
1006
1007 =item user
1008
1009 Default value is C<user> that mean it returns current user's Timezone value.
1010
1011 =item server
1012
1013 If context is C<server> it returns value of the C<Timezone> RT config option.
1014
1015 =item  utc
1016
1017 If both server's and user's timezone names are undefined returns 'UTC'.
1018
1019 =back
1020
1021 =cut
1022
1023 sub Timezone {
1024     my $self = shift;
1025     my $context = lc(shift);
1026
1027     $context = 'utc' unless $context =~ /^(?:utc|server|user)$/i;
1028
1029     my $tz;
1030     if( $context eq 'user' ) {
1031         $tz = $self->CurrentUser->UserObj->Timezone;
1032     } elsif( $context eq 'server') {
1033         $tz = RT->Config->Get('Timezone');
1034     } else {
1035         $tz = 'UTC';
1036     }
1037     $tz ||= RT->Config->Get('Timezone') || 'UTC';
1038     $tz = 'UTC' if lc $tz eq 'gmt';
1039     return $tz;
1040 }
1041
1042
1043 eval "require RT::Date_Vendor";
1044 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Date_Vendor.pm});
1045 eval "require RT::Date_Local";
1046 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Date_Local.pm});
1047
1048 1;