Bug 30540: eval on set_time_zone
[koha.git] / Koha / DateUtils.pm
1 package Koha::DateUtils;
2
3 # Copyright (c) 2011 PTFS-Europe Ltd.
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
18
19 use Modern::Perl;
20 use DateTime;
21 use C4::Context;
22 use Koha::Exceptions;
23
24 use vars qw(@ISA @EXPORT_OK);
25 BEGIN {
26     require Exporter;
27     @ISA = qw(Exporter);
28
29     @EXPORT_OK = qw(
30         dt_from_string
31         output_pref
32         format_sqldatetime
33     );
34 }
35
36 =head1 DateUtils
37
38 Koha::DateUtils - Transitional wrappers to ease use of DateTime
39
40 =head1 DESCRIPTION
41
42 Koha has historically only used dates not datetimes and been content to
43 handle these as strings. It also has confused formatting with actual dates
44 this is a temporary module for wrappers to hide the complexity of switch to DateTime
45
46 =cut
47
48 =head2 dt_ftom_string
49
50 $dt = dt_from_string($date_string, [$format, $timezone ]);
51
52 Passed a date string returns a DateTime object format and timezone default
53 to the system preferences. If the date string is empty DateTime->now is returned
54
55 =cut
56
57 sub dt_from_string {
58     my ( $date_string, $date_format, $tz ) = @_;
59
60     return if $date_string and $date_string =~ m|^0000-0|;
61
62     my $do_fallback = defined($date_format) ? 0 : 1;
63     my $server_tz = C4::Context->tz;
64     $tz = C4::Context->tz unless $tz;
65
66     return DateTime->now( time_zone => $tz ) unless $date_string;
67
68     $date_format = C4::Context->preference('dateformat') unless $date_format;
69
70     if ( ref($date_string) eq 'DateTime' ) {    # already a dt return it
71         return $date_string;
72     }
73
74     my $regex;
75
76     # The fallback format is sql/iso
77     my $fallback_re = qr|
78         (?<year>\d{4})
79         -
80         (?<month>\d{2})
81         -
82         (?<day>\d{2})
83     |xms;
84
85     if ( $date_format eq 'metric' ) {
86         # metric format is "dd/mm/yyyy[ hh:mm:ss]"
87         $regex = qr|
88             (?<day>\d{2})
89             /
90             (?<month>\d{2})
91             /
92             (?<year>\d{4})
93         |xms;
94     }
95     elsif ( $date_format eq 'dmydot' ) {
96         # dmydot format is "dd.mm.yyyy[ hh:mm:ss]"
97         $regex = qr|
98             (?<day>\d{2})
99             .
100             (?<month>\d{2})
101             .
102             (?<year>\d{4})
103         |xms;
104     }
105     elsif ( $date_format eq 'us' ) {
106         # us format is "mm/dd/yyyy[ hh:mm:ss]"
107         $regex = qr|
108             (?<month>\d{2})
109             /
110             (?<day>\d{2})
111             /
112             (?<year>\d{4})
113         |xms;
114     }
115     elsif ( $date_format eq 'rfc3339' ) {
116         $regex = qr/
117             (?<year>\d{4})
118             -
119             (?<month>\d{2})
120             -
121             (?<day>\d{2})
122             ([Tt\s])
123             (?<hour>\d{2})
124             :
125             (?<minute>\d{2})
126             :
127             (?<second>\d{2})
128             (\.\d{1,3})?(([Zz]$)|((?<offset>[\+|\-])(?<hours>[01][0-9]|2[0-3]):(?<minutes>[0-5][0-9])))
129         /xms;
130
131         # Default to UTC (when 'Z' is passed) for inbound timezone.
132         # The regex above succeeds for both 'z', 'Z' and '+/-' offset.
133         # We set tz as though Z was passed by default and then correct it later if an offset is detected
134         # by the presence fo the <offset> variable.
135         $tz = DateTime::TimeZone->new( name => 'UTC' );
136     }
137     elsif ( $date_format eq 'iso' or $date_format eq 'sql' ) {
138         # iso or sql format are yyyy-dd-mm[ hh:mm:ss]"
139         $regex = $fallback_re;
140     }
141     else {
142         die "Invalid dateformat parameter ($date_format)";
143     }
144
145     # Add the facultative time part including time zone offset; ISO8601 allows +02 or +0200 too
146     my $time_re = qr{
147             (
148                 [Tt]?
149                 \s*
150                 (?<hour>\d{2})
151                 :
152                 (?<minute>\d{2})
153                 (
154                     :
155                     (?<second>\d{2})
156                 )?
157                 (
158                     \s
159                     (?<ampm>\w{2})
160                 )?
161                 (
162                     (?<utc>[Zz]$)|((?<offset>[\+|\-])(?<hours>[01][0-9]|2[0-3]):?(?<minutes>[0-5][0-9])?)
163                 )?
164             )?
165     }xms;
166     $regex .= $time_re unless ( $date_format eq 'rfc3339' );
167     $fallback_re .= $time_re;
168
169     # Ensure we only accept date strings and not other characters.
170     $regex = '^' . $regex . '$';
171     $fallback_re = '^' . $fallback_re . '$';
172
173     my %dt_params;
174     my $ampm;
175     if ( $date_string =~ $regex ) {
176         %dt_params = (
177             year   => $+{year},
178             month  => $+{month},
179             day    => $+{day},
180             hour   => $+{hour},
181             minute => $+{minute},
182             second => $+{second},
183         );
184         $ampm = $+{ampm};
185         if ( $+{utc} ) {
186             $tz = DateTime::TimeZone->new( name => 'UTC' );
187         }
188         if ( $+{offset} ) {
189             # If offset given, set inbound timezone using it.
190             $tz = DateTime::TimeZone->new( name => $+{offset} . $+{hours} . ( $+{minutes} || '00' ) );
191         }
192     } elsif ( $do_fallback && $date_string =~ $fallback_re ) {
193         %dt_params = (
194             year   => $+{year},
195             month  => $+{month},
196             day    => $+{day},
197             hour   => $+{hour},
198             minute => $+{minute},
199             second => $+{second},
200         );
201         $ampm = $+{ampm};
202     }
203     else {
204         die "The given date ($date_string) does not match the date format ($date_format)";
205     }
206
207     # system allows the 0th of the month
208     $dt_params{day} = '01' if $dt_params{day} eq '00';
209
210     # Set default hh:mm:ss to 00:00:00
211     my $date_only = ( !defined( $dt_params{hour} )
212         && !defined( $dt_params{minute} )
213         && !defined( $dt_params{second} ) );
214     $dt_params{hour}   = 00 unless defined $dt_params{hour};
215     $dt_params{minute} = 00 unless defined $dt_params{minute};
216     $dt_params{second} = 00 unless defined $dt_params{second};
217
218     if ( $ampm ) {
219         if ( $ampm eq 'AM' ) {
220             $dt_params{hour} = 00 if $dt_params{hour} == 12;
221         } elsif ( $dt_params{hour} != 12 ) { # PM
222             $dt_params{hour} += 12;
223             $dt_params{hour} = 00 if $dt_params{hour} == 24;
224         }
225     }
226
227     my $floating = 0;
228     my $dt = eval {
229         DateTime->new(
230             %dt_params,
231             # No TZ for dates 'infinite' => see bug 13242
232             ( $dt_params{year} < 9999 ? ( time_zone => $tz ) : () ),
233         );
234     };
235     if ($@) {
236         $tz = DateTime::TimeZone->new( name => 'floating' );
237         $floating = 1;
238         $dt = DateTime->new(
239             %dt_params,
240             # No TZ for dates 'infinite' => see bug 13242
241             ( $dt_params{year} < 9999 ? ( time_zone => $tz ) : () ),
242         );
243     }
244
245     # Convert to configured timezone (unless we started with a dateonly string or had to drop to floating time)
246     $dt->set_time_zone($server_tz) unless ( $date_only || $floating );
247
248     return $dt;
249 }
250
251 =head2 output_pref
252
253 $date_string = output_pref({ dt => $dt [, dateformat => $date_format, timeformat => $time_format, dateonly => 0|1, as_due_date => 0|1 ] });
254 $date_string = output_pref( $dt );
255
256 Returns a string containing the time & date formatted as per the C4::Context setting,
257 or C<undef> if C<undef> was provided.
258
259 This routine can either be passed a DateTime object or or a hashref.  If it is
260 passed a hashref, the expected keys are a mandatory 'dt' for the DateTime,
261 an optional 'dateformat' to override the dateformat system preference, an
262 optional 'timeformat' to override the TimeFormat system preference value,
263 and an optional 'dateonly' to specify that only the formatted date string
264 should be returned without the time.
265
266 =cut
267
268 sub output_pref {
269     my $params = shift;
270     my ( $dt, $str, $force_pref, $force_time, $dateonly, $as_due_date );
271     if ( ref $params eq 'HASH' ) {
272         $dt         = $params->{dt};
273         $str        = $params->{str};
274         $force_pref = $params->{dateformat};         # if testing we want to override Context
275         $force_time = $params->{timeformat};
276         $dateonly   = $params->{dateonly} || 0;    # if you don't want the hours and minutes
277         $as_due_date = $params->{as_due_date} || 0; # don't display the hours and minutes if eq to 23:59 or 11:59 (depending the TimeFormat value)
278     } else {
279         $dt = $params;
280     }
281
282     Koha::Exceptions::WrongParameter->throw( 'output_pref should not be called with both dt and str parameter' ) if $dt and $str;
283
284     if ( $str ) {
285         local $@;
286         $dt = eval { dt_from_string( $str ) };
287         Koha::Exceptions::WrongParameter->throw("Invalid date '$str' passed to output_pref" ) if $@;
288     }
289
290     return if !defined $dt; # NULL date
291     Koha::Exceptions::WrongParameter->throw( "output_pref is called with '$dt' (ref ". ( ref($dt) ? ref($dt):'SCALAR')."), not a DateTime object")  if ref($dt) ne 'DateTime';
292
293     # FIXME: see bug 13242 => no TZ for dates 'infinite'
294     if ( $dt->ymd !~ /^9999/ ) {
295         my $tz = $dateonly ? DateTime::TimeZone->new(name => 'floating') : C4::Context->tz;
296         eval { $dt->set_time_zone( $tz ); }
297     }
298
299     my $pref =
300       defined $force_pref ? $force_pref : C4::Context->preference('dateformat');
301
302     my $time_format = $force_time || C4::Context->preference('TimeFormat') || q{};
303     my $time = ( $time_format eq '12hr' ) ? '%I:%M %p' : '%H:%M';
304     my $date;
305     if ( $pref =~ m/^iso/ ) {
306         $date = $dateonly
307           ? $dt->strftime("%Y-%m-%d")
308           : $dt->strftime("%Y-%m-%d $time");
309     }
310     elsif ( $pref =~ m/^rfc3339/ ) {
311         if (!$dateonly) {
312             $date = $dt->strftime('%FT%T%z');
313             substr($date, -2, 0, ':'); # timezone "HHmm" => "HH:mm"
314         }
315         else {
316             $date = $dt->strftime("%Y-%m-%d");
317         }
318     }
319     elsif ( $pref =~ m/^metric/ ) {
320         $date = $dateonly
321           ? $dt->strftime("%d/%m/%Y")
322           : $dt->strftime("%d/%m/%Y $time");
323     }
324     elsif ( $pref =~ m/^dmydot/ ) {
325         $date = $dateonly
326           ? $dt->strftime("%d.%m.%Y")
327           : $dt->strftime("%d.%m.%Y $time");
328     }
329
330     elsif ( $pref =~ m/^us/ ) {
331         $date = $dateonly
332           ? $dt->strftime("%m/%d/%Y")
333           : $dt->strftime("%m/%d/%Y $time");
334     }
335     else {
336         $date = $dateonly
337           ? $dt->strftime("%Y-%m-%d")
338           : $dt->strftime("%Y-%m-%d $time");
339     }
340
341     if ( $as_due_date ) {
342         $time_format eq '12hr'
343             ? $date =~ s| 11:59 PM$||
344             : $date =~ s| 23:59$||;
345     }
346
347     return $date;
348 }
349
350 =head2 format_sqldatetime
351
352 $string = format_sqldatetime( $string_as_returned_from_db );
353
354 a convenience routine for calling dt_from_string and formatting the result
355 with output_pref as it is a frequent activity in scripts
356
357 =cut
358
359 sub format_sqldatetime {
360     my $str        = shift;
361     my $force_pref = shift;    # if testing we want to override Context
362     my $force_time = shift;
363     my $dateonly   = shift;
364
365     if ( defined $str && $str =~ m/^\d{4}-\d{2}-\d{2}/ ) {
366         my $dt = dt_from_string( $str, 'sql' );
367         return q{} unless $dt;
368         $dt->truncate( to => 'minute' );
369         return output_pref({
370             dt => $dt,
371             dateformat => $force_pref,
372             timeformat => $force_time,
373             dateonly => $dateonly
374         });
375     }
376     return q{};
377 }
378
379 1;