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