forked from bywatersolutions/koha-plugin-room-reservations
/
calendar.pl
executable file
·703 lines (535 loc) · 19.3 KB
/
calendar.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
#!/usr/bin/perl
#
# Copyright 2017 Marywood University
#
# This file is not part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.
use Modern::Perl;
use Carp;
use C4::Context;
use C4::Output;
use C4::Auth;
use Koha::Email;
use Mail::Sendmail;
use MIME::QuotedPrint;
use MIME::Base64;
use Koha::Patrons;
use Koha::Patron::Category;
use Koha::Patron::Categories;
use Koha::DateUtils;
use Cwd qw( abs_path );
use File::Basename qw( dirname );
use POSIX 'strftime';
use CGI qw ( -utf8 );
use Calendar::Simple;
my @months = qw(January February March April May June July August September October November December);
my $pluginDir = dirname(abs_path($0));
my $template_name = $pluginDir . '/calendar.tt';
my $template2_name = $pluginDir . '/calendar-sendconfirmation.tt';
my $rooms_table = 'booking_rooms';
my $bookings_table = 'bookings';
my $equipment_table = 'booking_equipment';
my $roomequipment_table = 'booking_room_equipment';
my $valid; # used to check if booking still valid prior to insertion of new booking
my $cgi = new CGI;
# initial value -- calendar is displayed while $op is undef
# otherwise one of the form pages is displayed
my $op = $cgi->param('op');
my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
{
template_name => $template_name,
query => $cgi,
type => "opac",
authnotrequired => 0,
is_plugin => 1,
}
);
if ( !defined($op) ) {
my $mon = shift || (localtime)[4] + 1;
my $yr = shift || (localtime)[5] + 1900;
my @month = calendar($mon, $yr);
my @month_days;
foreach(@month) {
push(@month_days, map { $_ ? sprintf "%d", $_ : '' } @$_);
}
my $calendarBookings = getConfirmedCalendarBookingsByMonthAndYear($mon, $yr);
my $month = sprintf("%02s", $mon);
my $userenv = C4::Context->userenv;
my $number = $userenv->{number};
my $patron = Koha::Patrons->find($number);
my $category = $patron->category->categorycode;
my $isRestricted = checkForRestrictedCategory($category);
my $restricted_message = getRestrictedMessage();
if ($isRestricted > 0) {
$template->param(
is_restricted => 1,
is_restricted_message => $restricted_message,
patron_category => $category,
);
}
else {
$template->param(
is_restricted => undef,
patron_category => $category,
);
}
$template->param(
current_month_cal => \@month_days,
calendar_bookings => $calendarBookings,
active_month => $months[$mon - 1],
active_year => $yr + 0,
month_is_active => 1,
plugin_dir => $pluginDir,
op => $op,
);
}
elsif ( $op eq 'availability-search' ) {
my $equipment = loadAllEquipment();
my $capacities = loadAllMaxCapacities();
my $max_num_days = getFutureDays() || '0';
my $max_time = getMaxTime() || '0';
if ( $max_num_days eq '0' ) {
$max_num_days = '';
}
if ( $max_time eq '0' ) {
$max_time = '';
}
$template->param(
op => $op,
available_room_equipment => $equipment,
all_room_capacities => $capacities,
max_days => $max_num_days,
max_time => $max_time,
);
}
elsif ( $op eq 'availability-search-results' ) {
my $start_date = $cgi->param('availability-search-start-date');
my $start_time = $cgi->param('availability-search-start-time');
my $end_date = $cgi->param('availability-search-end-date');
my $end_time = $cgi->param('availability-search-end-time');
my $room_capacity = $cgi->param('availability-search-room-capacity');
my @equipment = $cgi->param('availability-search-selected-equipment') || ();
my $event_start = sprintf("%s %s", $start_date, $start_time);
my $event_end = sprintf("%s %s", $end_date, $end_time);
# converts '/' to '-'
(my $availability_format_start_date = $start_date) =~ s/\//\-/g;
(my $availability_format_end_date = $end_date) =~ s/\//\-/g;
# re-arranges from MM-DD-YYYY to YYYY-MM-DD
($availability_format_start_date = $availability_format_start_date) =~ s/(\d\d)-(\d\d)-(\d\d\d\d)/$3-$1-$2/;
($availability_format_end_date = $availability_format_end_date) =~ s/(\d\d)-(\d\d)-(\d\d\d\d)/$3-$1-$2/;
# used exclusively for getAvailableRooms -- BUG excluding T from the DATETIME start/end field returns wrong results?
my $availability_format_start = sprintf("%sT%s", $availability_format_start_date, $start_time);
my $availability_format_end = sprintf("%sT%s", $availability_format_end_date, $end_time);
# generates a DateTime object from a string
$event_start = dt_from_string($event_start);
$event_end = dt_from_string($event_end);
my $displayed_event_start = output_pref({ dt => $event_start, dateformat => 'us', timeformat => '12hr' });
my $displayed_event_end = output_pref({ dt => $event_end, dateformat => 'us', timeformat => '12hr' });
my $availableRooms = getAvailableRooms($availability_format_start, $availability_format_end, $room_capacity, \@equipment);
# boolean -- returns 1 (one) if true or 0 (zero) if false
my $roomsAreAvailable = areAnyRoomsAvailable($availableRooms);
$template->param(
op => $op,
available_rooms => $availableRooms,
are_rooms_available => $roomsAreAvailable,
displayed_start => $displayed_event_start,
displayed_end => $displayed_event_end,
event_start_time => $event_start,
event_end_time => $event_end,
start_date => $availability_format_start_date,
);
}
elsif ( $op eq 'room-selection-confirmation' ) {
my $selected_id = $cgi->param('selected-room-id');
my $displayed_start = $cgi->param('displayed-start');
my $displayed_end = $cgi->param('displayed-end');
my $event_start = $cgi->param('event-start-time');
my $event_end = $cgi->param('event-end-time');
my $start_date = $cgi->param('start-date');
my $displayed_event_time = "$displayed_start - $displayed_end";
my $user_fn = C4::Context->userenv->{'firstname'} || q{};
my $user_ln = C4::Context->userenv->{'surname'} || q{};
my $user_bn = C4::Context->userenv->{'number'};
my $user = "$user_fn $user_ln";
my $email = C4::Context->userenv->{'emailaddress'};
my $selectedRoomNumber = getRoomNumberById($selected_id);
my $count_limit = getDailyReservationLimit();
my $current_user_daily_limit = getUserDailyResLimit($user_bn, $start_date);
$template->param(
op => $op,
current_user => $user,
current_user_fn => $user_fn,
current_user_ln => $user_ln,
current_user_email => $email,
selected_room_id => $selected_id,
selected_room_no => $selectedRoomNumber,
displayed_time => $displayed_event_time,
selected_start_time => $event_start,
selected_end_time => $event_end,
displayed_start => $displayed_start,
displayed_end => $displayed_end,
count_limit => $count_limit,
user_daily_limit => $current_user_daily_limit,
);
}
elsif( $op eq 'reservation-confirmed' ) {
my $borrowernumber = C4::Context->userenv->{'number'};
my $roomid = $cgi->param('confirmed-room-id');
my $start = $cgi->param('confirmed-start');
my $end = $cgi->param('confirmed-end');
my $sendCopy = $cgi->param('send-confirmation-copy') || q{};
my $submitButton = $cgi->param('confirmationSubmit');
my $user = $cgi->param('confirmed-user');
my $roomnumber = $cgi->param('confirmed-roomnumber');
my $displayed_start = $cgi->param('confirmed-displayed-start');
my $displayed_end = $cgi->param('confirmed-displayed-end');
my $patronEmail = $cgi->param('confirmed-email');
if ( $submitButton eq 'Start over' ) {
$op = 'availability-search';
}
else {
$valid = preBookingAvailabilityCheck($roomid, $start, $end);
if ($valid) {
addBooking($borrowernumber, $roomid, $start, $end);
}
else {
$template->param(
invalid_booking => 1,
);
}
}
if ( $sendCopy eq '1' && $valid ) {
my $email = Koha::Email->new();
my $user_email = C4::Context->preference('KohaAdminEmailAddress');
# KohaAdmin address is the default - no need to set
my %mail = $email->create_message_headers({
to => $patronEmail,
});
$mail{'X-Abuse-Report'} = C4::Context->preference('KohaAdminEmailAddress');
# Since we are already logged in, no need to check credentials again
# when loading a second template.
my $template2 = C4::Templates::gettemplate(
$template2_name, 'opac', $cgi, 1
);
my $timestamp = getCurrentTimestamp();
$template2->param(
user => $user,
room => $roomnumber,
from => $displayed_start,
to => $displayed_end,
confirmed_timestamp => $timestamp,
);
# Getting template result
my $template_res = $template2->output();
my $body;
# Analysing information and getting mail properties
if ($template_res =~ /<SUBJECT>(.*)<END_SUBJECT>/s) {
$mail{subject} = $1;
$mail{subject} =~ s|\n?(.*)\n?|$1|;
$mail{subject} = Encode::encode("UTF-8", $mail{subject});
}
else { $mail{'subject'} = "no subject"; }
my $email_header = "";
if ( $template_res =~ /<HEADER>(.*)<END_HEADER>/s ) {
$email_header = $1;
$email_header =~ s|\n?(.*)\n?|$1|;
$email_header = encode_qp(Encode::encode("UTF-8", $email_header));
}
my $email_file = "bookingconfirmation.txt";
if ( $template_res =~ /<FILENAME>(.*)<END_FILENAME>/s ) {
$email_file = $1;
$email_file =~ s|\n?(.*)\n?|$1|;
}
if ( $template_res =~ /<MESSAGE>(.*)<END_MESSAGE>/s ) {
$body = $1;
$body =~ s|\n?(.*)\n?|$1|;
$body = encode_qp(Encode::encode("UTF-8", $body));
}
$mail{body} = $body;
my $boundary = "====" . time() . "====";
$mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";
$boundary = '--' . $boundary;
$mail{body} = <<END_OF_BODY;
$boundary
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
$email_header
$body
$boundary--
END_OF_BODY
## This version includes file attachment (if necessary)
# $boundary
# MIME-Version: 1.0
# Content-Type: text/plain; charset="UTF-8"
# Content-Transfer-Encoding: quoted-printable
# $email_header
# $body
# $boundary
# Content-Type: application/octet-stream; name="basket.iso2709"
# Content-Transfer-Encoding: base64
# Content-Disposition: attachment; filename="basket.iso2709"
# $isofile
# $boundary--
# END_OF_BODY
# Sending mail (if not empty basket)
if (sendmail %mail) {
# do something if it works....
$template->param(
SENT => "1",
patron_email => $patronEmail,
);
}
else {
# do something if it doesnt work....
carp "Error sending mail: an error has occurred";
carp "Error sending mail: $Mail::Sendmail::error" if $Mail::Sendmail::error;
$template->param( error => 1 );
}
}
$template->param(
op => $op,
);
}
sub checkForRestrictedCategory {
my ( $category ) = @_;
my $dbh = C4::Context->dbh;
my $sth = '';
my $query = "
SELECT COUNT(categorycode)
FROM categories, plugin_data
WHERE plugin_class = 'Koha::Plugin::Com::MarywoodUniversity::RoomReservations'
AND plugin_key LIKE 'rcat_%'
AND plugin_value = categorycode
AND plugin_value = ?;
";
$sth = $dbh->prepare($query);
$sth->execute($category);
my $rows = $sth->fetchrow_arrayref->[0];
if ( $rows != 0 ) {
return 1; # restricted
}
else {
return 0; # not restricted
}
}
sub getRestrictedMessage {
my $dbh = C4::Context->dbh;
my $sql = "SELECT plugin_value FROM plugin_data WHERE plugin_class = ? AND plugin_key = ?";
my $sth = $dbh->prepare($sql);
$sth->execute( 'Koha::Plugin::Com::MarywoodUniversity::RoomReservations', 'restricted_message' );
my $row = $sth->fetchrow_hashref();
return $row->{'plugin_value'};
}
sub getFutureDays {
my $dbh = C4::Context->dbh;
my $sql = "SELECT plugin_value FROM plugin_data WHERE plugin_class = ? AND plugin_key = ?";
my $sth = $dbh->prepare($sql);
$sth->execute( 'Koha::Plugin::Com::MarywoodUniversity::RoomReservations', 'max_future_days' );
my $row = $sth->fetchrow_hashref();
return $row->{'plugin_value'};
}
sub getMaxTime {
my $dbh = C4::Context->dbh;
my $sql = "SELECT plugin_value FROM plugin_data WHERE plugin_class = ? AND plugin_key = ?";
my $sth = $dbh->prepare($sql);
$sth->execute( 'Koha::Plugin::Com::MarywoodUniversity::RoomReservations', 'max_time' );
my $row = $sth->fetchrow_hashref();
return $row->{'plugin_value'};
}
sub getDailyReservationLimit {
my $dbh = C4::Context->dbh;
my $sql = "SELECT plugin_value FROM plugin_data WHERE plugin_class = ? AND plugin_key = ?";
my $sth = $dbh->prepare($sql);
$sth->execute( 'Koha::Plugin::Com::MarywoodUniversity::RoomReservations', 'count_limit' );
my $row = $sth->fetchrow_hashref();
return $row->{'plugin_value'};
}
sub getUserDailyResLimit {
my ($bn, $date) = @_;
$date = "$date%";
my $dbh = C4::Context->dbh;
my $sql = "SELECT COUNT(*) AS daily_total FROM bookings WHERE borrowernumber = ? AND start LIKE ?";
my $sth = $dbh->prepare($sql);
$sth->execute( $bn, $date );
my $row = $sth->fetchrow_hashref();
return $row->{'daily_total'};
}
sub areAnyRoomsAvailable {
my ( $rooms ) = @_;
if ( @$rooms > 0 ) {
# return true
return 1;
}
else {
# return false
return 0;
}
}
sub getConfirmedCalendarBookingsByMonthAndYear {
my ($month, $year) = @_;
## zero-pad the month to be DATETIME-friendly (two-digit)
$month = sprintf("%02s", $month);
# load access to database
my $dbh = C4::Context->dbh;
## database statement handler
my $sth = '';
## Returns hashref of the fields:
## roomnumber, monthdate, bookedtime
my $query =
'SELECT
r.roomnumber,
DATE_FORMAT(b.start, "%e") AS monthdate,
CONCAT(DATE_FORMAT(b.start, "%h:%i %p"), " - ", DATE_FORMAT(b.end, "%h:%i %p")) AS bookedtime
FROM ' . "$rooms_table AS r, $bookings_table AS b " .
'WHERE r.roomid = b.roomid
AND start BETWEEN \'' . "$year-$month-01 00:00:00' AND '" . "$year-$month-31 23:59:59'" .
'ORDER BY b.roomid ASC, start ASC';
$sth = $dbh->prepare($query);
$sth->execute();
my @calendarBookings;
while ( my $row = $sth->fetchrow_hashref() ) {
push ( @calendarBookings, $row );
}
return \@calendarBookings;
}
sub preBookingAvailabilityCheck {
my ( $roomid, $start, $end ) = @_;
my $dbh = C4::Context->dbh;
## database statement handler
my $sth = '';
my $query = "
SELECT COUNT(*)
FROM $bookings_table
WHERE roomid = $roomid
AND \'$end\' > start
AND \'$start\' < end;
";
$sth = $dbh->prepare($query);
$sth->execute();
my ($count) = $sth->fetchrow_array();
if ($count > 0) { # a conflicting booking was found
return 0;
}
else { # no conflict found
return 1;
}
}
sub addBooking {
my ( $borrowernumber, $roomid, $start, $end ) = @_;
my $dbh = C4::Context->dbh;
$dbh->do("
INSERT INTO $bookings_table (borrowernumber, roomid, start, end)
VALUES ($borrowernumber, $roomid, " . "'" . $start . "'" . "," . "'" . $end . "'" . ');');
}
sub getRoomNumberById {
my ( $roomid ) = @_;
# load access to database
my $dbh = C4::Context->dbh;
## database statement handler
my $sth = '';
my $query = "
SELECT roomnumber
FROM $rooms_table
WHERE roomid = $roomid;
";
$sth = $dbh->prepare($query);
$sth->execute();
my @roomNumberFromId;
while ( my $row = $sth->fetchrow_hashref() ) {
push ( @roomNumberFromId, $row );
}
return \@roomNumberFromId;
}
sub getAvailableRooms {
my ( $start, $end, $capacity, $equipment ) = @_;
## load access to database
my $dbh = C4::Context->dbh;
## database statement handler
my $sth = '';
my $query = "
SELECT *
FROM $rooms_table
WHERE maxcapacity = $capacity
AND roomid NOT IN
(SELECT roomid
FROM $bookings_table
WHERE
\'$end\' > start AND \'$start\' < end)";
# if dereferenced array ref has zero elements (length evaluated in scalar context)
if ( @$equipment > 0 ) {
# counts number of elements
my $totalElements = scalar @{ $equipment };
$query .= " AND roomid IN (SELECT roomid
FROM $roomequipment_table
WHERE";
foreach my $piece (@$equipment) {
if ( --$totalElements == 0 ) {
$query .= " equipmentid = $piece)";
}
else {
$query .= " equipmentid = $piece AND";
}
$totalElements--;
}
}
$query .= ' GROUP BY roomnumber;';
$sth = $dbh->prepare($query);
$sth->execute();
my @allAvailableRooms;
while ( my $row = $sth->fetchrow_hashref() ) {
push ( @allAvailableRooms, $row );
}
return \@allAvailableRooms;
}
sub loadAllMaxCapacities {
## load access to database
my $dbh = C4::Context->dbh;
## database statement handler
my $sth = '';
my $query = "
SELECT DISTINCT maxcapacity
FROM $rooms_table;
";
$sth = $dbh->prepare($query);
$sth->execute();
my @allMaxCapacities;
while ( my $row = $sth->fetchrow_hashref() ) {
push ( @allMaxCapacities, $row );
}
return \@allMaxCapacities;
}
sub loadAllEquipment {
## load access to database
my $dbh = C4::Context->dbh;
## database statement handler
my $sth = '';
my $query = "
SELECT *
FROM $equipment_table;
";
$sth = $dbh->prepare($query);
$sth->execute();
my @allAvailableEquipmentNames;
while ( my $row = $sth->fetchrow_hashref() ) {
push ( @allAvailableEquipmentNames, $row );
}
return \@allAvailableEquipmentNames;
}
sub getCurrentTimestamp {
my $timestamp = strftime('%m/%d/%Y %I:%M:%S %p', localtime);
return $timestamp;
}
output_html_with_http_headers $cgi, $cookie, $template->output;