Bug 1953: removing potential SQL injections from C4::Calendar::_init
[koha.git] / C4 / Calendar.pm
1 package C4::Calendar;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18 use strict;
19 require Exporter;
20 use vars qw($VERSION @EXPORT);
21
22 use Date::Calc qw( Date_to_Days );
23
24 # set the version for version checking
25 $VERSION = 3.00;
26
27 =head1 NAME
28
29 C4::Calendar::Calendar - Koha module dealing with holidays.
30
31 =head1 SYNOPSIS
32
33     use C4::Calendar::Calendar;
34
35 =head1 DESCRIPTION
36
37 This package is used to deal with holidays. Through this package, you can set all kind of holidays for the library.
38
39 =head1 FUNCTIONS
40
41 =over 2
42
43 =cut
44
45 @EXPORT = qw(&new 
46              &change_branchcode 
47              &get_week_days_holidays
48              &get_day_month_holidays
49              &get_exception_holidays 
50              &get_single_holidays
51              &insert_week_day_holiday
52              &insert_day_month_holiday
53              &insert_single_holiday
54              &insert_exception_holiday
55              &delete_holiday
56              &isHoliday
57              &addDate
58              &daysBetween);
59
60 =item new
61
62     $calendar = C4::Calendar->new(branchcode => $branchcode);
63
64 C<$branchcode> Is the branch code wich you want to use calendar.
65
66 =cut
67
68 sub new {
69     my $classname = shift @_;
70     my %options = @_;
71
72     my %hash;
73     my $self = bless(\%hash, $classname);
74
75     foreach my $optionName (keys %options) {
76         $self->{lc($optionName)} = $options{$optionName};
77     }
78
79     $self->_init;
80
81     return $self;
82 }
83
84 sub _init {
85     my $self = shift @_;
86
87     my $dbh = C4::Context->dbh();
88     my $week_days_sql = $dbh->prepare( 'SELECT weekday, title, description
89                                           FROM repeatable_holidays
90                                           WHERE ( branchcode = ? )
91                                             AND (NOT(ISNULL(weekday)))' );
92     $week_days_sql->execute( $self->{'branchcode'} );
93     my %week_days_holidays;
94     while (my ($weekday, $title, $description) = $week_days_sql->fetchrow) {
95         $week_days_holidays{$weekday}{title} = $title;
96         $week_days_holidays{$weekday}{description} = $description;
97     }
98     $week_days_sql->finish;
99     $self->{'week_days_holidays'} = \%week_days_holidays;
100
101     my $day_month_sql = $dbh->prepare( 'SELECT day, month, title, description
102                                          FROM repeatable_holidays
103                                          WHERE ( branchcode = ? )
104                                            AND ISNULL(weekday)' );
105     $day_month_sql->execute( $self->{'branchcode'} );
106     my %day_month_holidays;
107     while (my ($day, $month, $title, $description) = $day_month_sql->fetchrow) {
108         $day_month_holidays{"$month/$day"}{title} = $title;
109         $day_month_holidays{"$month/$day"}{description} = $description;
110     }
111     $day_month_sql->finish;
112     $self->{'day_month_holidays'} = \%day_month_holidays;
113
114     my $exception_holidays_sql = $dbh->prepare( 'SELECT day, month, year, title, description
115                                                    FROM special_holidays
116                                                    WHERE ( branchcode = ? )
117                                                      AnD (isexception = 1)' );
118     $exception_holidays_sql->execute( $self->{'branchcode'} );
119     my %exception_holidays;
120     while (my ($day, $month, $year, $title, $description) = $exception_holidays_sql->fetchrow) {
121         $exception_holidays{"$year/$month/$day"}{title} = $title;
122         $exception_holidays{"$year/$month/$day"}{description} = $description;
123     }
124     $exception_holidays_sql->finish;
125     $self->{'exception_holidays'} = \%exception_holidays;
126
127     my $holidays_sql = $dbh->prepare( 'SELECT day, month, year, title, description
128                                          FROM special_holidays
129                                          WHERE ( branchcode = ? )
130                                            AND (isexception = 0)' );
131     $holidays_sql->execute( $self->{'branchcode'} );
132     my %single_holidays;
133     while (my ($day, $month, $year, $title, $description) = $holidays_sql->fetchrow) {
134         $single_holidays{"$year/$month/$day"}{title} = $title;
135         $single_holidays{"$year/$month/$day"}{description} = $description;
136     }
137     $holidays_sql->finish;
138     $self->{'single_holidays'} = \%single_holidays;
139 }
140
141 =item change_branchcode
142
143     $calendar->change_branchcode(branchcode => $branchcode)
144
145 Change the calendar branch code. This means to change the holidays structure.
146
147 C<$branchcode> Is the branch code wich you want to use calendar.
148
149 =cut
150
151 sub change_branchcode {
152     my ($self, $branchcode) = @_;
153     my %options = @_;
154
155     foreach my $optionName (keys %options) {
156         $self->{lc($optionName)} = $options{$optionName};
157     }
158     $self->_init;
159
160     return $self;
161 }
162
163 =item get_week_days_holidays
164
165     $week_days_holidays = $calendar->get_week_days_holidays();
166
167 Returns a hash reference to week days holidays.
168
169 =cut
170
171 sub get_week_days_holidays {
172     my $self = shift @_;
173     my $week_days_holidays = $self->{'week_days_holidays'};
174     return $week_days_holidays;
175 }
176
177 =item get_day_month_holidays
178     
179     $day_month_holidays = $calendar->get_day_month_holidays();
180
181 Returns a hash reference to day month holidays.
182
183 =cut
184
185 sub get_day_month_holidays {
186     my $self = shift @_;
187     my $day_month_holidays = $self->{'day_month_holidays'};
188     return $day_month_holidays;
189 }
190
191 =item get_exception_holidays
192     
193     $exception_holidays = $calendar->exception_holidays();
194
195 Returns a hash reference to exception holidays. This kind of days are those
196 which stands for a holiday, but you wanted to make an exception for this particular
197 date.
198
199 =cut
200
201 sub get_exception_holidays {
202     my $self = shift @_;
203     my $exception_holidays = $self->{'exception_holidays'};
204     return $exception_holidays;
205 }
206
207 =item get_single_holidays
208     
209     $single_holidays = $calendar->get_single_holidays();
210
211 Returns a hash reference to single holidays. This kind of holidays are those which
212 happend just one time.
213
214 =cut
215
216 sub get_single_holidays {
217     my $self = shift @_;
218     my $single_holidays = $self->{'single_holidays'};
219     return $single_holidays;
220 }
221
222 =item insert_week_day_holiday
223
224     insert_week_day_holiday(weekday => $weekday,
225                             title => $title,
226                             description => $description);
227
228 Inserts a new week day for $self->{branchcode}.
229
230 C<$day> Is the week day to make holiday.
231
232 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
233
234 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
235
236 =cut
237
238 sub insert_week_day_holiday {
239     my $self = shift @_;
240     my %options = @_;
241
242     my $dbh = C4::Context->dbh();
243     my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (id,branchcode,weekday,day,month,title,description) values ( '',?,?,NULL,NULL,?,? )"); 
244         $insertHoliday->execute( $self->{branchcode}, $options{weekday},$options{title}, $options{description});
245     $insertHoliday->finish;
246
247     $self->{'week_days_holidays'}->{$options{weekday}}{title} = $options{title};
248     $self->{'week_days_holidays'}->{$options{weekday}}{description} = $options{description};
249     return $self;
250 }
251
252 =item insert_day_month_holiday
253
254     insert_day_month_holiday(day => $day,
255                              month => $month,
256                              title => $title,
257                              description => $description);
258
259 Inserts a new day month holiday for $self->{branchcode}.
260
261 C<$day> Is the day month to make the date to insert.
262
263 C<$month> Is month to make the date to insert.
264
265 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
266
267 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
268
269 =cut
270
271 sub insert_day_month_holiday {
272     my $self = shift @_;
273     my %options = @_;
274
275     my $dbh = C4::Context->dbh();
276     my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (id,branchcode,weekday,day,month,title,description) values ('', ?, NULL, ?, ?, ?,? )");
277         $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{title}, $options{description});
278     $insertHoliday->finish;
279
280     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title};
281     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{description} = $options{description};
282     return $self;
283 }
284
285 =item insert_single_holiday
286
287     insert_single_holiday(day => $day,
288                           month => $month,
289                           year => $year,
290                           title => $title,
291                           description => $description);
292
293 Inserts a new single holiday for $self->{branchcode}.
294
295 C<$day> Is the day month to make the date to insert.
296
297 C<$month> Is month to make the date to insert.
298
299 C<$year> Is year to make the date to insert.
300
301 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
302
303 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
304
305 =cut
306
307 sub insert_single_holiday {
308     my $self = shift @_;
309     my %options = @_;
310     
311         my $dbh = C4::Context->dbh();
312     my $isexception = 0;
313     my $insertHoliday = $dbh->prepare("insert into special_holidays (id,branchcode,day,month,year,isexception,title,description) values ('', ?,?,?,?,?,?,?)");
314         $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description});
315     $insertHoliday->finish;
316
317     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
318     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
319     return $self;
320 }
321
322 =item insert_exception_holiday
323
324     insert_exception_holiday(day => $day,
325                              month => $month,
326                              year => $year,
327                              title => $title,
328                              description => $description);
329
330 Inserts a new exception holiday for $self->{branchcode}.
331
332 C<$day> Is the day month to make the date to insert.
333
334 C<$month> Is month to make the date to insert.
335
336 C<$year> Is year to make the date to insert.
337
338 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
339
340 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
341
342 =cut
343
344 sub insert_exception_holiday {
345     my $self = shift @_;
346     my %options = @_;
347
348     my $dbh = C4::Context->dbh();
349     my $isexception = 1;
350     my $insertException = $dbh->prepare("insert into special_holidays (id,branchcode,day,month,year,isexception,title,description) values ('', ?,?,?,?,?,?,?)");
351         $insertException->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description});
352     $insertException->finish;
353
354     $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
355     $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
356     return $self;
357 }
358
359 =item delete_holiday
360
361     delete_holiday(weekday => $weekday
362                    day => $day,
363                    month => $month,
364                    year => $year);
365
366 Delete a holiday for $self->{branchcode}.
367
368 C<$weekday> Is the week day to delete.
369
370 C<$day> Is the day month to make the date to delete.
371
372 C<$month> Is month to make the date to delete.
373
374 C<$year> Is year to make the date to delete.
375
376 =cut
377
378 sub delete_holiday {
379     my $self = shift @_;
380     my %options = @_;
381
382     # Verify what kind of holiday that day is. For example, if it is
383     # a repeatable holiday, this should check if there are some exception
384         # for that holiday rule. Otherwise, if it is a regular holiday, it´s 
385     # ok just deleting it.
386
387     my $dbh = C4::Context->dbh();
388     my $isSingleHoliday = $dbh->prepare("select id from special_holidays where (branchcode = '$self->{branchcode}') and (day = $options{day}) and (month = $options{month}) and (year = $options{year})");
389     $isSingleHoliday->execute;
390     if ($isSingleHoliday->rows) {
391         my $id = $isSingleHoliday->fetchrow;
392         $isSingleHoliday->finish; # Close the last query
393
394         my $deleteHoliday = $dbh->prepare("delete from special_holidays where (id = $id)");
395         $deleteHoliday->execute;
396         $deleteHoliday->finish; # Close the last query
397         delete($self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"});
398     } else {
399         $isSingleHoliday->finish; # Close the last query
400
401         my $isWeekdayHoliday = $dbh->prepare("select id from repeatable_holidays where (branchcode = '$self->{branchcode}') and (weekday = $options{weekday})");
402         $isWeekdayHoliday->execute;
403         if ($isWeekdayHoliday->rows) {
404             my $id = $isWeekdayHoliday->fetchrow;
405             $isWeekdayHoliday->finish; # Close the last query
406
407             my $updateExceptions = $dbh->prepare("update special_holidays set isexception = 0 where (WEEKDAY(CONCAT(special_holidays.year,'-',special_holidays.month,'-',special_holidays.day)) = $options{weekday}) and (branchcode = '$self->{branchcode}')");
408             $updateExceptions->execute;
409             $updateExceptions->finish; # Close the last query
410
411             my $deleteHoliday = $dbh->prepare("delete from repeatable_holidays where (id = $id)");
412             $deleteHoliday->execute;
413             $deleteHoliday->finish;
414             delete($self->{'week_days_holidays'}->{$options{weekday}});
415         } else {
416             $isWeekdayHoliday->finish; # Close the last query
417
418             my $isDayMonthHoliday = $dbh->prepare("select id from repeatable_holidays where (branchcode = '$self->{branchcode}') and (day = '$options{day}') and (month = '$options{month}')");
419             $isDayMonthHoliday->execute;
420             if ($isDayMonthHoliday->rows) {
421                 my $id = $isDayMonthHoliday->fetchrow;
422                 $isDayMonthHoliday->finish;
423                 my $updateExceptions = $dbh->prepare("update special_holidays set isexception = 0 where (special_holidays.branchcode = '$self->{branchcode}') and (special_holidays.day = '$options{day}') and (special_holidays.month = '$options{month}')");
424                 $updateExceptions->execute;
425                 $updateExceptions->finish; # Close the last query
426
427                 my $deleteHoliday = $dbh->prepare("delete from repeatable_holidays where (id = '$id')");
428                 $deleteHoliday->execute;
429                 $deleteHoliday->finish; # Close the last query
430                 $isDayMonthHoliday->finish; # Close the last query
431                 delete($self->{'day_month_holidays'}->{"$options{month}/$options{day}"});
432             }
433         }
434     }
435     return $self;
436 }
437
438 =item isHoliday
439     
440     $isHoliday = isHoliday($day, $month $year);
441
442
443 C<$day> Is the day to check whether if is a holiday or not.
444
445 C<$month> Is the month to check whether if is a holiday or not.
446
447 C<$year> Is the year to check whether if is a holiday or not.
448
449 =cut
450
451 sub isHoliday {
452     my ($self, $day, $month, $year) = @_;
453         # FIXME - date strings are stored in non-padded metric format. should change to iso.
454         $month=$month+0;
455         $year=$year+0;
456         $day=$day+0;
457     my $weekday = &Date::Calc::Day_of_Week($year, $month, $day) % 7; 
458     my $weekDays = $self->get_week_days_holidays();
459     my $dayMonths = $self->get_day_month_holidays();
460     my $exceptions = $self->get_exception_holidays();
461     my $singles = $self->get_single_holidays();
462     if (defined($exceptions->{"$year/$month/$day"})) {
463         return 0;
464     } else {
465         if ((exists($weekDays->{$weekday})) ||
466             (exists($dayMonths->{"$month/$day"})) ||
467             (exists($singles->{"$year/$month/$day"}))) {
468                         return 1;
469         } else {
470             return 0;
471         }
472     }
473
474 }
475
476 =item addDate
477
478     my ($day, $month, $year) = $calendar->addDate($date, $offset)
479
480 C<$date> is a C4::Dates object representing the starting date of the interval.
481
482 C<$offset> Is the number of days that this function has to count from $date.
483
484 =cut
485
486 sub addDate {
487     my ($self, $startdate, $offset) = @_;
488     my ($year,$month,$day) = split("-",$startdate->output('iso'));
489         my $daystep = 1;
490         if ($offset < 0) { # In case $offset is negative
491        # $offset = $offset*(-1);
492                 $daystep = -1;
493     }
494         my $daysMode = C4::Context->preference('useDaysMode');
495     if ($daysMode eq 'Datedue') {
496         ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $offset );
497                 while ($self->isHoliday($day, $month, $year)) {
498                 ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $daystep);
499         }
500     } elsif($daysMode eq 'Calendar') {
501         while ($offset !=  0) {
502                 ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $daystep);
503             if (!($self->isHoliday($day, $month, $year))) {
504                 $offset = $offset - $daystep;
505                         }
506         }
507         } else { ## ($daysMode eq 'Days') 
508         ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $offset );
509     }
510     return(C4::Dates->new( sprintf("%04d-%02d-%02d",$year,$month,$day),'iso'));
511 }
512
513 =item daysBetween
514
515     my $daysBetween = $calendar->daysBetween($startdate, $enddate )
516
517 C<$startdate>  and C<$enddate> are C4::Dates objects that define the interval.
518
519 Returns the number of non-holiday days in the interval.
520 useDaysMode syspref has no effect here.
521 =cut
522
523 sub daysBetween {
524     my ( $self, $startdate, $enddate ) = @_ ; 
525         my ($yearFrom,$monthFrom,$dayFrom) = split("-",$startdate->output('iso'));
526         my ($yearTo,$monthTo,$dayTo) = split("-",$enddate->output('iso'));
527         if (Date_to_Days($yearFrom,$monthFrom,$dayFrom) > Date_to_Days($yearTo,$monthTo,$dayTo)) {
528                 return 0;
529                 # we don't go backwards  ( FIXME - handle this error better )
530         }
531     my $count = 0;
532     my $continue = 1;
533     while ($continue) {
534         if (($yearFrom != $yearTo) || ($monthFrom != $monthTo) || ($dayFrom != $dayTo)) {
535             if (!($self->isHoliday($dayFrom, $monthFrom, $yearFrom))) {
536                 $count++;
537             }
538             ($yearFrom, $monthFrom, $dayFrom) = &Date::Calc::Add_Delta_Days($yearFrom, $monthFrom, $dayFrom, 1);
539         } else {
540             $continue = 0;
541         }
542     }
543     return($count);
544 }
545
546 1;
547
548 __END__
549
550 =back
551
552 =head1 AUTHOR
553
554 Koha Physics Library UNLP <matias_veleda@hotmail.com>
555
556 =cut