80f1816475b3e5a6e3f92792b7c4bc3872bee317
[freeside.git] / rt / lib / RT / Date.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2011 Best Practical Solutions, LLC
6 #                                          <sales@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 SetToStart PERIOD[, Timezone => 'utc' ]
277
278 Set to the beginning of the current PERIOD, which can be 
279 "year", "month", "day", "hour", or "minute".
280
281 =cut
282
283 sub SetToStart {
284     my $self = shift;
285     my $p = uc(shift);
286     my %args = @_;
287     my $tz = $args{'Timezone'} || '';
288     my @localtime = $self->Localtime($tz);
289     #remove 'offset' so that DST is figured based on the resulting time.
290     pop @localtime;
291
292     # This is the cleanest way to implement it, I swear.
293     {
294         $localtime[0]=0;
295         last if ($p eq 'MINUTE');
296         $localtime[1]=0;
297         last if ($p eq 'HOUR');
298         $localtime[2]=0;
299         last if ($p eq 'DAY');
300         $localtime[3]=1;
301         last if ($p eq 'MONTH');
302         $localtime[4]=0;
303         last if ($p eq 'YEAR');
304         $RT::Logger->warning("Couldn't find start date of '$p'.");
305         return;
306     }
307     my $new = $self->Timelocal($tz, @localtime);
308     return $self->Unix($new);
309 }
310
311 =head2 Diff
312
313 Takes either an C<RT::Date> object or the date in unixtime format as a string,
314 if nothing is specified uses the current time.
315
316 Returns the differnce between the time in the current object and that time
317 as a number of seconds. Returns C<undef> if any of two compared values is
318 incorrect or not set.
319
320 =cut
321
322 sub Diff {
323     my $self = shift;
324     my $other = shift;
325     $other = time unless defined $other;
326     if ( UNIVERSAL::isa( $other, 'RT::Date' ) ) {
327         $other = $other->Unix;
328     }
329     return undef unless $other=~ /^\d+$/ && $other > 0;
330
331     my $unix = $self->Unix;
332     return undef unless $unix > 0;
333
334     return $unix - $other;
335 }
336
337 =head2 DiffAsString
338
339 Takes either an C<RT::Date> object or the date in unixtime format as a string,
340 if nothing is specified uses the current time.
341
342 Returns the differnce between C<$self> and that time as a number of seconds as
343 a localized string fit for human consumption. Returns empty string if any of
344 two compared values is incorrect or not set.
345
346 =cut
347
348 sub DiffAsString {
349     my $self = shift;
350     my $diff = $self->Diff( @_ );
351     return '' unless defined $diff;
352
353     return $self->DurationAsString( $diff );
354 }
355
356 =head2 DurationAsString
357
358 Takes a number of seconds. Returns a localized string describing
359 that duration.
360
361 =cut
362
363 sub DurationAsString {
364     my $self     = shift;
365     my $duration = int shift;
366
367     my ( $negative, $s, $time_unit );
368     $negative = 1 if $duration < 0;
369     $duration = abs $duration;
370
371     if ( $duration < $MINUTE ) {
372         $s         = $duration;
373         $time_unit = $self->loc("sec");
374     }
375     elsif ( $duration < ( 2 * $HOUR ) ) {
376         $s         = int( $duration / $MINUTE + 0.5 );
377         $time_unit = $self->loc("min");
378     }
379     elsif ( $duration < ( 2 * $DAY ) ) {
380         $s         = int( $duration / $HOUR + 0.5 );
381         $time_unit = $self->loc("hours");
382     }
383     elsif ( $duration < ( 2 * $WEEK ) ) {
384         $s         = int( $duration / $DAY + 0.5 );
385         $time_unit = $self->loc("days");
386     }
387     elsif ( $duration < ( 2 * $MONTH ) ) {
388         $s         = int( $duration / $WEEK + 0.5 );
389         $time_unit = $self->loc("weeks");
390     }
391     elsif ( $duration < $YEAR ) {
392         $s         = int( $duration / $MONTH + 0.5 );
393         $time_unit = $self->loc("months");
394     }
395     else {
396         $s         = int( $duration / $YEAR + 0.5 );
397         $time_unit = $self->loc("years");
398     }
399
400     if ( $negative ) {
401         return $self->loc( "[_1] [_2] ago", $s, $time_unit );
402     }
403     else {
404         return $self->loc( "[_1] [_2]", $s, $time_unit );
405     }
406 }
407
408 =head2 AgeAsString
409
410 Takes nothing. Returns a string that's the differnce between the
411 time in the object and now.
412
413 =cut
414
415 sub AgeAsString { return $_[0]->DiffAsString }
416
417
418
419 =head2 AsString
420
421 Returns the object's time as a localized string with curent user's prefered
422 format and timezone.
423
424 If the current user didn't choose prefered format then system wide setting is
425 used or L</DefaultFormat> if the latter is not specified. See config option
426 C<DateTimeFormat>.
427
428 =cut
429
430 sub AsString {
431     my $self = shift;
432     my %args = (@_);
433
434     return $self->loc("Not set") unless $self->Unix > 0;
435
436     my $format = RT->Config->Get( 'DateTimeFormat', $self->CurrentUser ) || 'DefaultFormat';
437     $format = { Format => $format } unless ref $format;
438     %args = (%$format, %args);
439
440     return $self->Get( Timezone => 'user', %args );
441 }
442
443 =head2 GetWeekday DAY
444
445 Takes an integer day of week and returns a localized string for
446 that day of week. Valid values are from range 0-6, Note that B<0
447 is sunday>.
448
449 =cut
450
451 sub GetWeekday {
452     my $self = shift;
453     my $dow = shift;
454     
455     return $self->loc($DAYS_OF_WEEK[$dow])
456         if $DAYS_OF_WEEK[$dow];
457     return '';
458 }
459
460 =head2 GetMonth MONTH
461
462 Takes an integer month and returns a localized string for that month.
463 Valid values are from from range 0-11.
464
465 =cut
466
467 sub GetMonth {
468     my $self = shift;
469     my $mon = shift;
470
471     return $self->loc($MONTHS[$mon])
472         if $MONTHS[$mon];
473     return '';
474 }
475
476 =head2 AddSeconds SECONDS
477
478 Takes a number of seconds and returns the new unix time.
479
480 Negative value can be used to substract seconds.
481
482 =cut
483
484 sub AddSeconds {
485     my $self = shift;
486     my $delta = shift or return $self->Unix;
487     
488     $self->Set(Format => 'unix', Value => ($self->Unix + $delta));
489  
490     return ($self->Unix);
491 }
492
493 =head2 AddDays [DAYS]
494
495 Adds C<24 hours * DAYS> to the current time. Adds one day when
496 no argument is specified. Negative value can be used to substract
497 days.
498
499 Returns new unix time.
500
501 =cut
502
503 sub AddDays {
504     my $self = shift;
505     my $days = shift || 1;
506     return $self->AddSeconds( $days * $DAY );
507 }
508
509 =head2 AddDay
510
511 Adds 24 hours to the current time. Returns new unix time.
512
513 =cut
514
515 sub AddDay { return $_[0]->AddSeconds($DAY) }
516
517 =head2 AddMonth
518
519 Adds one month to the current time. Returns new 
520 unix time.
521
522 =cut
523
524 sub AddMonth {    
525     my $self = shift;
526     my %args = @_;
527     my @localtime = $self->Localtime($args{'Timezone'});
528     # remove offset, as with SetToStart
529     pop @localtime;
530     
531     $localtime[4]++; #month
532     if ( $localtime[4] == 12 ) {
533       $localtime[4] = 0;
534       $localtime[5]++; #year
535     }
536
537     my $new = $self->Timelocal($args{'Timezone'}, @localtime);
538     return $self->Unix($new);
539 }
540
541 =head2 Unix [unixtime]
542
543 Optionally takes a date in unix seconds since the epoch format.
544 Returns the number of seconds since the epoch
545
546 =cut
547
548 sub Unix {
549     my $self = shift; 
550     $self->{'time'} = int(shift || 0) if @_;
551     return $self->{'time'};
552 }
553
554 =head2 DateTime
555
556 Alias for L</Get> method. Arguments C<Date> and <Time>
557 are fixed to true values, other arguments could be used
558 as described in L</Get>.
559
560 =cut
561
562 sub DateTime {
563     my $self = shift;
564     unless (defined $self) {
565         use Carp; Carp::confess("undefined $self");
566     }
567     return $self->Get( @_, Date => 1, Time => 1 );
568 }
569
570 =head2 Date
571
572 Takes Format argument which allows you choose date formatter.
573 Pass throught other arguments to the formatter method.
574
575 Returns the object's formatted date. Default formatter is ISO.
576
577 =cut
578
579 sub Date {
580     my $self = shift;
581     return $self->Get( @_, Date => 1, Time => 0 );
582 }
583
584 =head2 Time
585
586
587 =cut
588
589 sub Time {
590     my $self = shift;
591     return $self->Get( @_, Date => 0, Time => 1 );
592 }
593
594 =head2 Get
595
596 Returnsa a formatted and localized string that represets time of
597 the current object.
598
599
600 =cut
601
602 sub Get
603 {
604     my $self = shift;
605     my %args = (Format => 'ISO', @_);
606     my $formatter = $args{'Format'};
607     unless ( $self->ValidFormatter($formatter) ) {
608         RT->Logger->warning("Invalid date formatter '$formatter', falling back to ISO");
609         $formatter = 'ISO';
610     }
611     $formatter = 'ISO' unless $self->can($formatter);
612     return $self->$formatter( %args );
613 }
614
615 =head2 Output formatters
616
617 Fomatter is a method that returns date and time in different configurable
618 format.
619
620 Each method takes several arguments:
621
622 =over 1
623
624 =item Date
625
626 =item Time
627
628 =item Timezone - Timezone context C<server>, C<user> or C<UTC>
629
630 =back
631
632 Formatters may also add own arguments to the list, for example
633 in RFC2822 format day of time in output is optional so it
634 understand boolean argument C<DayOfTime>.
635
636 =head3 Formatters
637
638 Returns an array of available formatters.
639
640 =cut
641
642 sub Formatters
643 {
644     my $self = shift;
645
646     return @FORMATTERS;
647 }
648
649 =head3 ValidFormatter FORMAT
650
651 Returns a true value if C<FORMAT> is a known formatter.  Otherwise returns
652 false.
653
654 =cut
655
656 sub ValidFormatter {
657     my $self   = shift;
658     my $format = shift;
659     return (grep { $_ eq $format } $self->Formatters and $self->can($format))
660                 ? 1 : 0;
661 }
662
663 =head3 DefaultFormat
664
665 =cut
666
667 sub DefaultFormat
668 {
669     my $self = shift;
670     my %args = ( Date => 1,
671                  Time => 1,
672                  Timezone => '',
673                  Seconds => 1,
674                  @_,
675                );
676     
677        #  0    1    2     3     4    5     6     7      8      9
678     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
679                             $self->Localtime($args{'Timezone'});
680     $wday = $self->GetWeekday($wday);
681     $mon = $self->GetMonth($mon);
682     ($mday, $hour, $min, $sec) = map { sprintf "%02d", $_ } ($mday, $hour, $min, $sec);
683
684     if( $args{'Date'} && !$args{'Time'} ) {
685         return $self->loc('[_1] [_2] [_3] [_4]',
686                           $wday,$mon,$mday,$year);
687     } elsif( !$args{'Date'} && $args{'Time'} ) {
688         if( $args{'Seconds'} ) {
689             return $self->loc('[_1]:[_2]:[_3]',
690                               $hour,$min,$sec);
691         } else {
692             return $self->loc('[_1]:[_2]',
693                               $hour,$min);
694         }
695     } else {
696         if( $args{'Seconds'} ) {
697             return $self->loc('[_1] [_2] [_3] [_4]:[_5]:[_6] [_7]',
698                               $wday,$mon,$mday,$hour,$min,$sec,$year);
699         } else {
700             return $self->loc('[_1] [_2] [_3] [_4]:[_5] [_6]',
701                               $wday,$mon,$mday,$hour,$min,$year);
702         }
703     }
704 }
705
706 =head3 LocalizedDateTime
707
708 Returns date and time as string, with user localization.
709
710 Supports arguments: C<DateFormat> and C<TimeFormat> which may contains date and
711 time format as specified in DateTime::Locale (default to full_date_format and
712 medium_time_format), C<AbbrDay> and C<AbbrMonth> which may be set to 0 if
713 you want full Day/Month names instead of abbreviated ones.
714
715 Require optionnal DateTime::Locale module.
716
717 =cut
718
719 sub LocalizedDateTime
720 {
721     my $self = shift;
722     my %args = ( Date => 1,
723                  Time => 1,
724                  Timezone => '',
725                  DateFormat => '',
726                  TimeFormat => '',
727                  AbbrDay => 1,
728                  AbbrMonth => 1,
729                  @_,
730                );
731
732     return $self->loc("DateTime module missing") unless ( eval 'use DateTime qw(); 1;' );
733     return $self->loc("DateTime::Locale module missing") unless ( eval 'use DateTime::Locale qw(); 1;' );
734     return $self->loc("DateTime doesn't support format_cldr, you must upgrade to use this feature") 
735         unless can DateTime::('format_cldr');
736
737     # Require valid names for the format methods
738     my $date_format = $args{DateFormat} =~ /^\w+$/
739                     ? $args{DateFormat} : 'date_format_full';
740
741     my $time_format = $args{TimeFormat} =~ /^\w+$/
742                     ? $args{TimeFormat} : 'time_format_medium';
743
744     my $lang = $self->CurrentUser->UserObj->Lang;
745     unless ($lang) {
746         require I18N::LangTags::Detect;
747         $lang = ( I18N::LangTags::Detect::detect(), 'en' )[0];
748     }
749     
750
751     my $formatter = DateTime::Locale->load($lang);
752     return $self->loc("DateTime::Locale doesn't support date_format_full, you must upgrade to use this feature") 
753         unless $formatter->can('date_format_full');
754     $date_format = $formatter->$date_format;
755     $time_format = $formatter->$time_format;
756     $date_format =~ s/EEEE/EEE/g if ( $args{'AbbrDay'} );
757     $date_format =~ s/MMMM/MMM/g if ( $args{'AbbrMonth'} );
758
759     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
760                             $self->Localtime($args{'Timezone'});
761     $mon++;
762     my $tz = $self->Timezone($args{'Timezone'});
763
764     # FIXME : another way to call this module without conflict with local
765     # DateTime method?
766     my $dt = new DateTime::( locale => $lang,
767                             time_zone => $tz,
768                             year => $year,
769                             month => $mon,
770                             day => $mday,
771                             hour => $hour,
772                             minute => $min,
773                             second => $sec,
774                             nanosecond => 0,
775                           );
776
777     if ( $args{'Date'} && !$args{'Time'} ) {
778         return $dt->format_cldr($date_format);
779     } elsif ( !$args{'Date'} && $args{'Time'} ) {
780         return $dt->format_cldr($time_format);
781     } else {
782         return $dt->format_cldr($date_format) . " " . $dt->format_cldr($time_format);
783     }
784 }
785
786 =head3 ISO
787
788 Returns the object's date in ISO format C<YYYY-MM-DD mm:hh:ss>.
789 ISO format is locale independant, but adding timezone offset info
790 is not implemented yet.
791
792 Supports arguments: C<Timezone>, C<Date>, C<Time> and C<Seconds>.
793 See </Output formatters> for description of arguments.
794
795 =cut
796
797 sub ISO {
798     my $self = shift;
799     my %args = ( Date => 1,
800                  Time => 1,
801                  Timezone => '',
802                  Seconds => 1,
803                  @_,
804                );
805        #  0    1    2     3     4    5     6     7      8      9
806     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
807                             $self->Localtime($args{'Timezone'});
808
809     #the month needs incrementing, as gmtime returns 0-11
810     $mon++;
811
812     my $res = '';
813     $res .= sprintf("%04d-%02d-%02d", $year, $mon, $mday) if $args{'Date'};
814     $res .= sprintf(' %02d:%02d', $hour, $min) if $args{'Time'};
815     $res .= sprintf(':%02d', $sec, $min) if $args{'Time'} && $args{'Seconds'};
816     $res =~ s/^\s+//;
817
818     return $res;
819 }
820
821 =head3 W3CDTF
822
823 Returns the object's date and time in W3C date time format
824 (L<http://www.w3.org/TR/NOTE-datetime>).
825
826 Format is locale independand and is close enought to ISO, but
827 note that date part is B<not optional> and output string
828 has timezone offset mark in C<[+-]hh:mm> format.
829
830 Supports arguments: C<Timezone>, C<Time> and C<Seconds>.
831 See </Output formatters> for description of arguments.
832
833 =cut
834
835 sub W3CDTF {
836     my $self = shift;
837     my %args = (
838         Time => 1,
839         Timezone => '',
840         Seconds => 1,
841         @_,
842         Date => 1,
843     );
844        #  0    1    2     3     4    5     6     7      8      9
845     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
846                             $self->Localtime( $args{'Timezone'} );
847
848     #the month needs incrementing, as gmtime returns 0-11
849     $mon++;
850
851     my $res = '';
852     $res .= sprintf("%04d-%02d-%02d", $year, $mon, $mday);
853     if ( $args{'Time'} ) {
854         $res .= sprintf('T%02d:%02d', $hour, $min);
855         $res .= sprintf(':%02d', $sec, $min) if $args{'Seconds'};
856         if ( $offset ) {
857             $res .= sprintf "%s%02d:%02d", $self->_SplitOffset( $offset );
858         } else {
859             $res .= 'Z';
860         }
861     }
862
863     return $res;
864 };
865
866
867 =head3 RFC2822 (MIME)
868
869 Returns the object's date and time in RFC2822 format,
870 for example C<Sun, 06 Nov 1994 08:49:37 +0000>.
871 Format is locale independand as required by RFC. Time
872 part always has timezone offset in digits with sign prefix.
873
874 Supports arguments: C<Timezone>, C<Date>, C<Time>, C<DayOfWeek>
875 and C<Seconds>. See </Output formatters> for description of
876 arguments.
877
878 =cut
879
880 sub RFC2822 {
881     my $self = shift;
882     my %args = ( Date => 1,
883                  Time => 1,
884                  Timezone => '',
885                  DayOfWeek => 1,
886                  Seconds => 1,
887                  @_,
888                );
889
890        #  0    1    2     3     4    5     6     7      8     9
891     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
892                             $self->Localtime($args{'Timezone'});
893
894     my ($date, $time) = ('','');
895     $date .= "$DAYS_OF_WEEK[$wday], " if $args{'DayOfWeek'} && $args{'Date'};
896     $date .= "$mday $MONTHS[$mon] $year" if $args{'Date'};
897
898     if ( $args{'Time'} ) {
899         $time .= sprintf("%02d:%02d", $hour, $min);
900         $time .= sprintf(":%02d", $sec) if $args{'Seconds'};
901         $time .= sprintf " %s%02d%02d", $self->_SplitOffset( $offset );
902     }
903
904     return join ' ', grep $_, ($date, $time);
905 }
906
907 =head3 RFC2616 (HTTP)
908
909 Returns the object's date and time in RFC2616 (HTTP/1.1) format,
910 for example C<Sun, 06 Nov 1994 08:49:37 GMT>. While the RFC describes
911 version 1.1 of HTTP, but the same form date can be used in version 1.0.
912
913 Format is fixed length, locale independand and always represented in GMT
914 what makes it quite useless for users, but any date in HTTP transfers
915 must be presented using this format.
916
917     HTTP-date = rfc1123 | ...
918     rfc1123   = wkday "," SP date SP time SP "GMT"
919     date      = 2DIGIT SP month SP 4DIGIT
920                 ; day month year (e.g., 02 Jun 1982)
921     time      = 2DIGIT ":" 2DIGIT ":" 2DIGIT
922                 ; 00:00:00 - 23:59:59
923     wkday     = "Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun"
924     month     = "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun"
925               | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
926
927 Supports arguments: C<Date> and C<Time>, but you should use them only for
928 some personal reasons, RFC2616 doesn't define any optional parts.
929 See </Output formatters> for description of arguments.
930
931 =cut
932
933 sub RFC2616 {
934     my $self = shift;
935     my %args = ( Date => 1, Time => 1,
936                  @_,
937                  Timezone => 'utc',
938                  Seconds => 1, DayOfWeek => 1,
939                );
940
941     my $res = $self->RFC2822( %args );
942     $res =~ s/\s*[+-]\d\d\d\d$/ GMT/ if $args{'Time'};
943     return $res;
944 }
945
946 =head4 iCal
947
948 Returns the object's date and time in iCalendar format,
949
950 Supports arguments: C<Date> and C<Time>.
951 See </Output formatters> for description of arguments.
952
953 =cut
954
955 sub iCal {
956     my $self = shift;
957     my %args = (
958         Date => 1, Time => 1,
959         @_,
960     );
961     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydaym,$isdst,$offset) =
962         $self->Localtime( 'utc' );
963
964     #the month needs incrementing, as gmtime returns 0-11
965     $mon++;
966
967     my $res;
968     if ( $args{'Date'} && !$args{'Time'} ) {
969         $res = sprintf( '%04d%02d%02d', $year, $mon, $mday );
970     }
971     elsif ( !$args{'Date'} && $args{'Time'} ) {
972         $res = sprintf( 'T%02d%02d%02dZ', $hour, $min, $sec );
973     }
974     else {
975         $res = sprintf( '%04d%02d%02dT%02d%02d%02dZ', $year, $mon, $mday, $hour, $min, $sec );
976     }
977     return $res;
978 }
979
980 # it's been added by mistake in 3.8.0
981 sub iCalDate { return (shift)->iCal( Time => 0, @_ ) }
982
983 sub _SplitOffset {
984     my ($self, $offset) = @_;
985     my $sign = $offset < 0? '-': '+';
986     $offset = int( (abs $offset) / 60 + 0.001 );
987     my $mins = $offset % 60;
988     my $hours = int( $offset/60 + 0.001 );
989     return $sign, $hours, $mins; 
990 }
991
992 =head2 Timezones handling
993
994 =head3 Localtime $context [$time]
995
996 Takes one mandatory argument C<$context>, which determines whether
997 we want "user local", "system" or "UTC" time. Also, takes optional
998 argument unix C<$time>, default value is the current unix time.
999
1000 Returns object's date and time in the format provided by perl's
1001 builtin functions C<localtime> and C<gmtime> with two exceptions:
1002
1003 1) "Year" is a four-digit year, rather than "years since 1900"
1004
1005 2) The last element of the array returned is C<offset>, which
1006 represents timezone offset against C<UTC> in seconds.
1007
1008 =cut
1009
1010 sub Localtime
1011 {
1012     my $self = shift;
1013     my $tz = $self->Timezone(shift);
1014
1015     my $unix = shift || $self->Unix;
1016     $unix = 0 unless $unix >= 0;
1017     
1018     my @local;
1019     if ($tz eq 'UTC') {
1020         @local = gmtime($unix);
1021     } else {
1022         {
1023             local $ENV{'TZ'} = $tz;
1024             ## Using POSIX::tzset fixes a bug where the TZ environment variable
1025             ## is cached.
1026             POSIX::tzset();
1027             @local = localtime($unix);
1028         }
1029         POSIX::tzset(); # return back previouse value
1030     }
1031     $local[5] += 1900; # change year to 4+ digits format
1032     my $offset = Time::Local::timegm_nocheck(@local) - $unix;
1033     return @local, $offset;
1034 }
1035
1036 =head3 Timelocal $context @time
1037
1038 Takes argument C<$context>, which determines whether we should
1039 treat C<@time> as "user local", "system" or "UTC" time.
1040
1041 C<@time> is array returned by L<Localtime> functions. Only first
1042 six elements are mandatory - $sec, $min, $hour, $mday, $mon and $year.
1043 You may pass $wday, $yday and $isdst, these are ignored.
1044
1045 If you pass C<$offset> as ninth argument, it's used instead of
1046 C<$context>. It's done such way as code 
1047 C<$self->Timelocal('utc', $self->Localtime('server'))> doesn't
1048 makes much sense and most probably would produce unexpected
1049 result, so the method ignore 'utc' context and uses offset
1050 returned by L<Localtime> method.
1051
1052 =cut
1053
1054 sub Timelocal {
1055     my $self = shift;
1056     my $tz = shift;
1057     if ( defined $_[9] ) {
1058         return timegm(@_[0..5]) - $_[9];
1059     } else {
1060         $tz = $self->Timezone( $tz );
1061         if ( $tz eq 'UTC' ) {
1062             return Time::Local::timegm(@_[0..5]);
1063         } else {
1064             my $rv;
1065             {
1066                 local $ENV{'TZ'} = $tz;
1067                 ## Using POSIX::tzset fixes a bug where the TZ environment variable
1068                 ## is cached.
1069                 POSIX::tzset();
1070                 $rv = Time::Local::timelocal(@_[0..5]);
1071             };
1072             POSIX::tzset(); # switch back to previouse value
1073             return $rv;
1074         }
1075     }
1076 }
1077
1078
1079 =head3 Timezone $context
1080
1081 Returns the timezone name.
1082
1083 Takes one argument, C<$context> argument which could be C<user>, C<server> or C<utc>.
1084
1085 =over
1086
1087 =item user
1088
1089 Default value is C<user> that mean it returns current user's Timezone value.
1090
1091 =item server
1092
1093 If context is C<server> it returns value of the C<Timezone> RT config option.
1094
1095 =item  utc
1096
1097 If both server's and user's timezone names are undefined returns 'UTC'.
1098
1099 =back
1100
1101 =cut
1102
1103 sub Timezone {
1104     my $self = shift;
1105     my $context = lc(shift);
1106
1107     $context = 'utc' unless $context =~ /^(?:utc|server|user)$/i;
1108
1109     my $tz;
1110     if( $context eq 'user' ) {
1111         $tz = $self->CurrentUser->UserObj->Timezone;
1112     } elsif( $context eq 'server') {
1113         $tz = RT->Config->Get('Timezone');
1114     } else {
1115         $tz = 'UTC';
1116     }
1117     $tz ||= RT->Config->Get('Timezone') || 'UTC';
1118     $tz = 'UTC' if lc $tz eq 'gmt';
1119     return $tz;
1120 }
1121
1122
1123 RT::Base->_ImportOverlays();
1124
1125 1;