import rt 3.6.6
[freeside.git] / rt / lib / RT / Date.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2
3 # COPYRIGHT:
4 #  
5 # This software is Copyright (c) 1996-2007 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/copyleft/gpl.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 =head1 NAME
49
50   RT::Date - a simple Object Oriented date.
51
52 =head1 SYNOPSIS
53
54   use RT::Date
55
56 =head1 DESCRIPTION
57
58 RT Date is a simple Date Object designed to be speedy and easy for RT to use
59
60 The fact that it assumes that a time of 0 means "never" is probably a bug.
61
62 =begin testing
63
64 ok (require RT::Date);
65
66 =end testing
67
68 =head1 METHODS
69
70 =cut
71
72
73 package RT::Date;
74
75 use Time::Local;
76
77 use RT::Base;
78
79 use strict;
80 use vars qw/@ISA/;
81 @ISA = qw/RT::Base/;
82
83 use vars qw($MINUTE $HOUR $DAY $WEEK $MONTH $YEAR);
84
85 $MINUTE = 60;
86 $HOUR   = 60 * $MINUTE;
87 $DAY    = 24 * $HOUR;
88 $WEEK   = 7 * $DAY;
89 $MONTH  = 4 * $WEEK;
90 $YEAR   = 365 * $DAY;
91
92 # {{{ sub new 
93
94 sub new  {
95   my $proto = shift;
96   my $class = ref($proto) || $proto;
97   my $self  = {};
98   bless ($self, $class);
99   $self->CurrentUser(@_);
100   $self->Unix(0);
101   return $self;
102 }
103
104 # }}}
105
106 # {{{ sub Set
107
108 =head2 sub Set
109
110 takes a param hash with the fields 'Format' and 'Value'
111
112 if $args->{'Format'} is 'unix', takes the number of seconds since the epoch 
113
114 If $args->{'Format'} is ISO, tries to parse an ISO date.
115
116 If $args->{'Format'} is 'unknown', require Time::ParseDate and make it figure
117 things out. This is a heavyweight operation that should never be called from
118 within RT's core. But it's really useful for something like the textbox date
119 entry where we let the user do whatever they want.
120
121 If $args->{'Value'}  is 0, assumes you mean never.
122
123 =begin testing
124
125 use_ok(RT::Date);
126 my $date = RT::Date->new($RT::SystemUser);
127 $date->Set(Format => 'unix', Value => '0');
128 ok ($date->ISO eq '1970-01-01 00:00:00', "Set a date to midnight 1/1/1970 GMT");
129
130 =end testing
131
132 =cut
133
134 sub Set {
135     my $self = shift;
136     my %args = ( Format => 'unix',
137                  Value  => time,
138                  @_ );
139     if ( !$args{'Value'}
140          || ( ( $args{'Value'} =~ /^\d*$/ ) and ( $args{'Value'} == 0 ) ) ) {
141         $self->Unix(-1);
142         return ( $self->Unix() );
143     }
144
145     if ( $args{'Format'} =~ /^unix$/i ) {
146         $self->Unix( $args{'Value'} );
147     }
148
149     elsif ( $args{'Format'} =~ /^(sql|datemanip|iso)$/i ) {
150         $args{'Value'} =~ s!/!-!g;
151
152         if (( $args{'Value'} =~ /^(\d{4}?)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/ )
153             || ( $args{'Value'} =~
154                  /^(\d{4}?)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/ )
155             || ( $args{'Value'} =~
156                  /^(\d{4}?)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)\+00$/ )
157             || ($args{'Value'} =~ /^(\d{4}?)(\d\d)(\d\d)(\d\d):(\d\d):(\d\d)$/ )
158           ) {
159
160             my $year  = $1;
161             my $mon   = $2;
162             my $mday  = $3;
163             my $hours = $4;
164             my $min   = $5;
165             my $sec   = $6;
166
167             #timegm expects month as 0->11
168             $mon--;
169
170             #now that we've parsed it, deal with the case where everything
171             #was 0
172             if ( $mon == -1 ) {
173                 $self->Unix(-1);
174             }
175             else {
176
177                 #Dateamnip strings aren't in GMT.
178                 if ( $args{'Format'} =~ /^datemanip$/i ) {
179                     $self->Unix(
180                           timelocal( $sec, $min, $hours, $mday, $mon, $year ) );
181                 }
182
183                 #ISO and SQL dates are in GMT
184                 else {
185                     $self->Unix(
186                              timegm( $sec, $min, $hours, $mday, $mon, $year ) );
187                 }
188
189                 $self->Unix(-1) unless $self->Unix;
190             }
191         }
192         else {
193             use Carp;
194             Carp::cluck;
195             $RT::Logger->debug(
196                      "Couldn't parse date $args{'Value'} as a $args{'Format'}");
197
198         }
199     }
200     elsif ( $args{'Format'} =~ /^unknown$/i ) {
201         require Time::ParseDate;
202
203         #Convert it to an ISO format string
204
205         my $date = Time::ParseDate::parsedate($args{'Value'},
206                         UK => $RT::DateDayBeforeMonth,
207                         PREFER_PAST => $RT::AmbiguousDayInPast,
208                         PREFER_FUTURE => !($RT::AmbiguousDayInPast));
209
210         #This date has now been set to a date in the _local_ timezone.
211         #since ISO dates are known to be in GMT (for RT's purposes);
212
213         $RT::Logger->debug( "RT::Date used date::parse to make "
214                             . $args{'Value'}
215                             . " $date\n" );
216
217         return ( $self->Set( Format => 'unix', Value => "$date" ) );
218     }
219     else {
220         die "Unknown Date format: " . $args{'Format'} . "\n";
221     }
222
223     return ( $self->Unix() );
224 }
225
226 # }}}
227
228 # {{{ sub SetToMidnight 
229
230 =head2 SetToMidnight [Timezone => 'utc']
231
232 Sets the date to midnight (at the beginning of the day).
233 Returns the unixtime at midnight.
234
235 Arguments:
236
237 =over 4
238
239 =item Timezone - Timezone context C<server> or C<UTC>
240
241 =cut
242
243 sub SetToMidnight {
244     my $self = shift;
245     my %args = ( Timezone => 'UTC', @_ );
246     if ( lc $args{'Timezone'} eq 'server' ) {
247         $self->Unix( Time::Local::timelocal( 0,0,0,(localtime $self->Unix)[3..7] ) );
248     } else {
249         $self->Unix( Time::Local::timegm( 0,0,0,(gmtime $self->Unix)[3..7] ) );
250     }
251     return ($self->Unix);
252 }
253
254
255 # }}}
256
257 # {{{ sub SetToNow
258 sub SetToNow {
259         my $self = shift;
260         return($self->Set(Format => 'unix', Value => time))
261 }
262 # }}}
263
264 # {{{ sub Diff
265
266 =head2 Diff
267
268 Takes either an RT::Date object or the date in unixtime format as a string
269
270 Returns the differnce between $self and that time as a number of seconds
271
272 =cut
273
274 sub Diff {
275     my $self = shift;
276     my $other = shift;
277
278     if (ref($other) eq 'RT::Date') {
279         $other=$other->Unix;
280     }
281     return ($self->Unix - $other);
282 }
283 # }}}
284
285 # {{{ sub DiffAsString
286
287 =head2 sub DiffAsString
288
289 Takes either an RT::Date object or the date in unixtime format as a string
290
291 Returns the differnce between $self and that time as a number of seconds as
292 as string fit for human consumption
293
294 =cut
295
296 sub DiffAsString {
297     my $self = shift;
298     my $other = shift;
299
300
301     if ($other < 1) {
302         return ("");
303     }
304     if ($self->Unix < 1) {
305         return("");
306     }
307     my $diff = $self->Diff($other);
308
309     return ($self->DurationAsString($diff));
310 }
311 # }}}
312
313 # {{{ sub DurationAsString
314
315
316 =head2 DurationAsString
317
318 Takes a number of seconds. returns a string describing that duration
319
320 =cut
321
322 sub DurationAsString {
323
324     my $self     = shift;
325     my $duration = shift;
326
327     my ( $negative, $s );
328
329     $negative = 1 if ( $duration < 0 );
330
331     $duration = abs($duration);
332
333     my $time_unit;
334     if ( $duration < $MINUTE ) {
335         $s         = $duration;
336         $time_unit = $self->loc("sec");
337     }
338     elsif ( $duration < ( 2 * $HOUR ) ) {
339         $s         = int( $duration / $MINUTE );
340         $time_unit = $self->loc("min");
341     }
342     elsif ( $duration < ( 2 * $DAY ) ) {
343         $s         = int( $duration / $HOUR );
344         $time_unit = $self->loc("hours");
345     }
346     elsif ( $duration < ( 2 * $WEEK ) ) {
347         $s         = int( $duration / $DAY );
348         $time_unit = $self->loc("days");
349     }
350     elsif ( $duration < ( 2 * $MONTH ) ) {
351         $s         = int( $duration / $WEEK );
352         $time_unit = $self->loc("weeks");
353     }
354     elsif ( $duration < $YEAR ) {
355         $s         = int( $duration / $MONTH );
356         $time_unit = $self->loc("months");
357     }
358     else {
359         $s         = int( $duration / $YEAR );
360         $time_unit = $self->loc("years");
361     }
362
363     if ($negative) {
364         return $self->loc( "[_1] [_2] ago", $s, $time_unit );
365     }
366     else {
367         return $self->loc( "[_1] [_2]", $s, $time_unit );
368     }
369 }
370
371 # }}}
372
373 # {{{ sub AgeAsString
374
375 =head2 sub AgeAsString
376
377 Takes nothing
378
379 Returns a string that's the differnce between the time in the object and now
380
381 =cut
382
383 sub AgeAsString {
384     my $self = shift;
385     return ($self->DiffAsString(time));
386     }
387 # }}}
388
389 # {{{ sub AsString
390
391 =head2 sub AsString
392
393 Returns the object\'s time as a string with the current timezone.
394
395 =cut
396
397 sub AsString {
398     my $self = shift;
399     return ($self->loc("Not set")) if ($self->Unix <= 0);
400
401     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($self->Unix);
402
403     return $self->loc("[_1] [_2] [_3] [_4]:[_5]:[_6] [_7]", $self->GetWeekday($wday), $self->GetMonth($mon), map {sprintf "%02d", $_} ($mday, $hour, $min, $sec), ($year+1900));
404 }
405 # }}}
406
407 # {{{ GetWeekday
408
409 =head2 GetWeekday DAY
410
411 Takes an integer day of week and returns a localized string for that day of week
412
413 =cut
414
415 sub GetWeekday {
416     my $self = shift;
417     my $dow = shift;
418     
419     return $self->loc('Mon.') if ($dow == 1);
420     return $self->loc('Tue.') if ($dow == 2);
421     return $self->loc('Wed.') if ($dow == 3);
422     return $self->loc('Thu.') if ($dow == 4);
423     return $self->loc('Fri.') if ($dow == 5);
424     return $self->loc('Sat.') if ($dow == 6);
425     return $self->loc('Sun.') if ($dow == 0);
426 }
427
428 # }}}
429
430 # {{{ GetMonth
431
432 =head2 GetMonth DAY
433
434 Takes an integer month and returns a localized string for that month 
435
436 =cut
437
438 sub GetMonth {
439     my $self = shift;
440    my $mon = shift;
441
442     # We do this rather than an array so that we don't call localize 12x what we need to
443     return $self->loc('Jan.') if ($mon == 0);
444     return $self->loc('Feb.') if ($mon == 1);
445     return $self->loc('Mar.') if ($mon == 2);
446     return $self->loc('Apr.') if ($mon == 3);
447     return $self->loc('May.') if ($mon == 4);
448     return $self->loc('Jun.') if ($mon == 5);
449     return $self->loc('Jul.') if ($mon == 6);
450     return $self->loc('Aug.') if ($mon == 7);
451     return $self->loc('Sep.') if ($mon == 8);
452     return $self->loc('Oct.') if ($mon == 9);
453     return $self->loc('Nov.') if ($mon == 10);
454     return $self->loc('Dec.') if ($mon == 11);
455 }
456
457 # }}}
458
459 # {{{ sub AddSeconds
460
461 =head2 sub AddSeconds
462
463 Takes a number of seconds as a string
464
465 Returns the new time
466
467 =cut
468
469 sub AddSeconds {
470     my $self = shift;
471     my $delta = shift;
472     
473     $self->Set(Format => 'unix', Value => ($self->Unix + $delta));
474     
475     return ($self->Unix);
476     
477
478 }
479
480 # }}}
481
482 # {{{ sub AddDays
483
484 =head2 AddDays $DAYS
485
486 Adds 24 hours * $DAYS to the current time
487
488 =cut
489
490 sub AddDays {
491     my $self = shift;
492     my $days = shift;
493     $self->AddSeconds($days * $DAY);
494     
495 }
496
497 # }}}
498
499 # {{{ sub AddDay
500
501 =head2 AddDay
502
503 Adds 24 hours to the current time
504
505 =cut
506
507 sub AddDay {
508     my $self = shift;
509     $self->AddSeconds($DAY);
510     
511 }
512
513 # }}}
514
515 # {{{ sub Unix
516
517 =head2 sub Unix [unixtime]
518
519 Optionally takes a date in unix seconds since the epoch format.
520 Returns the number of seconds since the epoch
521
522 =cut
523
524 sub Unix {
525     my $self = shift;
526     
527     $self->{'time'} = shift if (@_);
528     
529     return ($self->{'time'});
530 }
531 # }}}
532
533 # {{{ sub ISO
534
535 =head2 ISO
536
537 Takes nothing
538
539 Returns the object's date in ISO format
540
541 =cut
542
543 sub ISO {
544     my $self=shift;
545     my    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst, $date) ;
546     
547     return ('1970-01-01 00:00:00') if ($self->Unix == -1);
548
549     #  0    1    2     3     4    5     6     7     8
550     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($self->Unix);
551     #make the year YYYY
552     $year+=1900;
553
554     #the month needs incrementing, as gmtime returns 0-11
555     $mon++;
556         
557     $date = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year,$mon,$mday, $hour,$min,$sec);
558     
559     return ($date);
560 }
561
562 # }}}
563
564 # {{{ sub Date
565
566 =head2 Date
567
568 Takes nothing
569
570 Returns the object's date in yyyy-mm-dd format; this is the same as
571 the ISO format without the time
572
573 =cut
574
575 sub Date {
576     my $self = shift;
577     my ($date, $time) = split ' ', $self->ISO;
578     return $date;
579 }
580
581 # }}}}
582
583 # {{{ sub Time
584
585 =head2 Time
586
587 Takes nothing
588
589 Returns the object's time in hh:mm:ss format; this is the same as
590 the ISO format without the date
591
592 =cut
593
594 sub Time {
595     my $self = shift;
596     my ($date, $time) = split ' ', $self->ISO;
597     return $time;
598 }
599
600 # }}}}
601
602 # {{{ sub W3CDTF
603
604 =head2 W3CDTF
605
606 Takes nothing
607
608 Returns the object's date in W3C DTF format
609
610 =cut
611
612 sub W3CDTF {
613     my $self = shift;
614     my $date = $self->ISO . 'Z';
615     $date =~ s/ /T/;
616     return $date;
617 };
618
619 # }}}
620
621 # {{{ sub LocalTimezone 
622
623 =head2 LocalTimezone
624
625   Returns the current timezone. For now, draws off a system timezone, RT::Timezone. Eventually, this may
626 pull from a 'Timezone' attribute of the CurrentUser
627
628 =cut
629
630 sub LocalTimezone {
631     my $self = shift;
632
633     return $self->CurrentUser->Timezone
634         if $self->CurrentUser and $self->CurrentUser->can('Timezone');
635
636     return ($RT::Timezone);
637 }
638
639 # }}}
640
641 eval "require RT::Date_Vendor";
642 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Date_Vendor.pm});
643 eval "require RT::Date_Local";
644 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Date_Local.pm});
645
646 1;