Bug 17561: (follow-up) Pass itemnumber on returns and correct itemnumber param in...
[koha.git] / circ / returns.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #           2006 SAN-OP
5 #           2007-2010 BibLibre, Paul POULAIN
6 #           2010 Catalyst IT
7 #           2011 PTFS-Europe Ltd.
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24 =head1 returns.pl
25
26 script to execute returns of books
27
28 =cut
29
30 use Modern::Perl;
31
32 # FIXME There are weird things going on with $patron and $borrowernumber in this script
33
34 use CGI qw ( -utf8 );
35 use DateTime;
36 use C4::Context;
37 use C4::Auth qw/:DEFAULT get_session/;
38 use C4::Output;
39 use C4::Circulation;
40 use C4::Print;
41 use C4::Reserves;
42 use C4::Biblio;
43 use C4::Items;
44 use C4::Members;
45 use C4::Members::Messaging;
46 use C4::Koha;   # FIXME : is it still useful ?
47 use C4::RotatingCollections;
48 use Koha::AuthorisedValues;
49 use Koha::DateUtils;
50 use Koha::Calendar;
51 use Koha::BiblioFrameworks;
52 use Koha::Holds;
53 use Koha::Items;
54 use Koha::Patrons;
55
56 my $query = new CGI;
57
58 #getting the template
59 my ( $template, $librarian, $cookie, $flags ) = get_template_and_user(
60     {
61         template_name   => "circ/returns.tt",
62         query           => $query,
63         type            => "intranet",
64         authnotrequired => 0,
65         flagsrequired   => { circulate => "circulate_remaining_permissions" },
66     }
67 );
68
69 my $sessionID = $query->cookie("CGISESSID");
70 my $session = get_session($sessionID);
71 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
72     # no branch set we can't return
73     print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
74     exit;
75 }
76
77 # Print a reserve slip on this page
78 if ( $query->param('print_slip') ) {
79     $template->param(
80         print_slip     => 1,
81         borrowernumber => scalar $query->param('borrowernumber'), # FIXME We should send a Koha::Patron and raise an error if not exist.
82         biblionumber   => scalar $query->param('biblionumber'),
83         itemnumber     => scalar $query->param('itemnumber'),
84     );
85 }
86
87 #####################
88 #Global vars
89 my $printers = GetPrinters();
90 my $userenv = C4::Context->userenv;
91 my $userenv_branch = $userenv->{'branch'} // '';
92 my $printer = $userenv->{'branchprinter'} // '';
93 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
94
95 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
96  #
97 # Some code to handle the error if there is no branch or printer setting.....
98 #
99
100 # Set up the item stack ....
101 my %returneditems;
102 my %riduedate;
103 my %riborrowernumber;
104 my @inputloop;
105 foreach ( $query->param ) {
106     my $counter;
107     if (/ri-(\d*)/) {
108         $counter = $1;
109         if ($counter > 20) {
110             next;
111         }
112     }
113     else {
114         next;
115     }
116
117     my %input;
118     my $barcode        = $query->param("ri-$counter");
119     my $duedate        = $query->param("dd-$counter");
120     my $borrowernumber = $query->param("bn-$counter");
121     $counter++;
122
123     # decode barcode    ## Didn't we already decode them before passing them back last time??
124     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
125     $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
126
127     ######################
128     #Are these lines still useful ?
129     $returneditems{$counter}    = $barcode;
130     $riduedate{$counter}        = $duedate;
131     $riborrowernumber{$counter} = $borrowernumber;
132
133     #######################
134     $input{counter}        = $counter;
135     $input{barcode}        = $barcode;
136     $input{duedate}        = $duedate;
137     $input{borrowernumber} = $borrowernumber;
138     push( @inputloop, \%input );
139 }
140
141 ############
142 # Deal with the requests....
143
144 if ($query->param('WT-itemNumber')){
145         updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
146 }
147
148 if ( $query->param('reserve_id') ) {
149     my $itemnumber     = $query->param('itemnumber');
150     my $borrowernumber = $query->param('borrowernumber');
151     my $reserve_id     = $query->param('reserve_id');
152     my $diffBranchReturned = $query->param('diffBranch');
153     my $cancel_reserve = $query->param('cancel_reserve');
154     # fix up item type for display
155     my $item = Koha::Items->find( $itemnumber );
156     my $biblio = $item->biblio;
157
158     if ( $cancel_reserve ) {
159         my $hold = Koha::Holds->find( $reserve_id );
160         if ( $hold ) {
161             $hold->cancel( { charge_cancel_fee => !$forgivemanualholdsexpire } );
162         } # FIXME else?
163     } else {
164         my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
165         # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
166         # i.e., whether to apply waiting status
167         ModReserveAffect( $itemnumber, $borrowernumber, $diffBranchSend, $reserve_id );
168     }
169 #   check if we have other reserves for this document, if we have a return send the message of transfer
170     my ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
171
172     my $patron = Koha::Patrons->find( $nextreservinfo );
173     my $name   = $patron ? $patron->surname . ", " . $patron->title . " " . $patron->firstname : '';
174     if ( $messages->{'transfert'} ) {
175         $template->param(
176             itemtitle      => $biblio->title,
177             itemnumber     => $item->itemnumber,
178             itembiblionumber => $biblio->biblionumber,
179             iteminfo       => $biblio->author,
180             name           => $name,
181             patron         => $patron,
182             diffbranch     => 1,
183         );
184     }
185 }
186
187 my $borrower;
188 my $returned = 0;
189 my $messages;
190 my $issue;
191 my $itemnumber;
192 my $barcode     = $query->param('barcode');
193 my $exemptfine  = $query->param('exemptfine');
194 if (
195   $exemptfine &&
196   !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
197 ) {
198     # silently prevent unauthorized operator from forgiving overdue
199     # fines by manually tweaking form parameters
200     undef $exemptfine;
201 }
202 my $dropboxmode = $query->param('dropboxmode');
203 my $dotransfer  = $query->param('dotransfer');
204 my $canceltransfer = $query->param('canceltransfer');
205 my $dest = $query->param('dest');
206 my $calendar    = Koha::Calendar->new( branchcode => $userenv_branch );
207 #dropbox: get last open day (today - 1)
208 my $today       = DateTime->now( time_zone => C4::Context->tz());
209 my $dropboxdate = $calendar->addDate($today, -1);
210
211 my $return_date_override = $query->param('return_date_override');
212 my $return_date_override_remember =
213   $query->param('return_date_override_remember');
214 if ($return_date_override) {
215     if ( C4::Context->preference('SpecifyReturnDate') ) {
216         my $return_date_override_dt = eval {dt_from_string( $return_date_override ) };
217         if ( $return_date_override_dt ) {
218             # note that we've overriden the return date
219             $template->param( return_date_was_overriden => 1);
220             # Save the original format if we are remembering for this series
221             $template->param(
222                 return_date_override          => $return_date_override,
223                 return_date_override_remember => 1
224             ) if ($return_date_override_remember);
225
226             $return_date_override =
227               DateTime::Format::MySQL->format_datetime( $return_date_override_dt );
228         }
229     }
230     else {
231         $return_date_override = q{};
232     }
233 }
234
235 if ($dotransfer){
236 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
237     my $transferitem = $query->param('transferitem');
238     my $tobranch     = $query->param('tobranch');
239     ModItemTransfer($transferitem, $userenv_branch, $tobranch);
240 }
241
242 if ($canceltransfer){
243     $itemnumber=$query->param('itemnumber');
244     DeleteTransfer($itemnumber);
245     if($dest eq "ttr"){
246         print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
247         exit;
248     } else {
249         $template->param( transfercancelled => 1);
250     }
251 }
252
253 # actually return book and prepare item table.....
254 my $returnbranch;
255 if ($barcode) {
256     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
257     $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
258     my $item = Koha::Items->find({ barcode => $barcode });
259
260     if ( $item ) {
261         $itemnumber = $item->itemnumber;
262         # Check if we should display a checkin message, based on the the item
263         # type of the checked in item
264         my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype );
265         if ( $itemtype && $itemtype->checkinmsg ) {
266             $template->param(
267                 checkinmsg     => $itemtype->checkinmsg,
268                 checkinmsgtype => $itemtype->checkinmsgtype,
269             );
270         }
271
272         # make sure return branch respects home branch circulation rules, default to homebranch
273         my $hbr = GetBranchItemRule($item->homebranch, $itemtype ? $itemtype->itemtype : undef )->{'returnbranch'} || "homebranch";
274         $returnbranch = $hbr ne 'noreturn' ? $item->$hbr : $userenv_branch; # can be noreturn, homebranch or holdingbranch
275
276         my $materials = $item->materials;
277         my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $materials });
278         $materials = $descriptions->{lib} // $materials;
279
280         my $checkout = $item->checkout;
281         my $biblio   = $item->biblio;
282         $template->param(
283             title            => $biblio->title,
284             homebranch       => $item->homebranch,
285             holdingbranch    => $item->holdingbranch,
286             returnbranch     => $returnbranch,
287             author           => $biblio->author,
288             itembarcode      => $item->barcode,
289             itemtype         => $item->effective_itemtype,
290             ccode            => $item->ccode,
291             itembiblionumber => $biblio->biblionumber,
292             biblionumber     => $biblio->biblionumber,
293             additional_materials => $materials,
294             issue            => $checkout,
295         );
296     } # FIXME else we should not call AddReturn but set BadBarcode directly instead
297
298     my %input = (
299         counter => 0,
300         first   => 1,
301         barcode => $barcode,
302     );
303
304
305     # do the return
306     ( $returned, $messages, $issue, $borrower ) =
307       AddReturn( $barcode, $userenv_branch, $exemptfine, $dropboxmode, $return_date_override, $dropboxdate );
308
309     if ($returned) {
310         my $time_now = DateTime->now( time_zone => C4::Context->tz )->truncate( to => 'minute');
311         my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
312         my $duedate = $date_due_dt->strftime('%Y-%m-%d %H:%M');
313         $returneditems{0}      = $barcode;
314         $riborrowernumber{0}   = $borrower->{'borrowernumber'};
315         $riduedate{0}          = $duedate;
316         $input{borrowernumber} = $borrower->{'borrowernumber'};
317         $input{duedate}        = $duedate;
318         unless ( $dropboxmode ) {
319             $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, DateTime->now()) == -1);
320         } else {
321             $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
322         }
323         push( @inputloop, \%input );
324
325         if ( C4::Context->preference("FineNotifyAtCheckin") ) {
326             my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
327             my $balance = $patron->account->balance;
328
329             if ($balance > 0) {
330                 $template->param( fines => sprintf("%.2f", $balance) );
331                 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
332             }
333         }
334
335         if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
336             #Check for waiting holds
337             my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
338             my $waiting_holds = $patron->holds->search({ found => 'W', branchcode => $userenv_branch })->count;
339             if ($waiting_holds > 0) {
340                 $template->param(
341                     waiting_holds       => $waiting_holds,
342                     holdsborrowernumber => $borrower->{'borrowernumber'},
343                     holdsfirstname => $borrower->{'firstname'},
344                     holdssurname => $borrower->{'surname'},
345                 );
346             }
347         }
348     } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} ) {
349         $input{duedate}   = 0;
350         $returneditems{0} = $barcode;
351         $riduedate{0}     = 0;
352         push( @inputloop, \%input );
353     }
354     $template->param( privacy => $borrower->{privacy} );
355 }
356 $template->param( inputloop => \@inputloop );
357
358 my $found    = 0;
359 my $waiting  = 0;
360 my $reserved = 0;
361
362 # new op dev : we check if the document must be returned to his homebranch directly,
363 #  if the document is transfered, we have warning message .
364
365 if ( $messages->{'WasTransfered'} ) {
366     $template->param(
367         found          => 1,
368         transfer       => 1,
369         itemnumber     => $itemnumber,
370     );
371 }
372
373 if ( $messages->{'NeedsTransfer'} ){
374     $template->param(
375         found          => 1,
376         needstransfer  => $messages->{'NeedsTransfer'},
377         itemnumber     => $itemnumber,
378     );
379 }
380
381 if ( $messages->{'Wrongbranch'} ){
382     $template->param(
383         wrongbranch => 1,
384         rightbranch => $messages->{'Wrongbranch'}->{'Rightbranch'},
385     );
386 }
387
388 # case of wrong transfert, if the document wasn't transfered to the right library (according to branchtransfer (tobranch) BDD)
389
390 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
391     $template->param(
392         WrongTransfer  => 1,
393         TransferWaitingAt => $messages->{'WrongTransfer'},
394         WrongTransferItem => $messages->{'WrongTransferItem'},
395         itemnumber => $itemnumber,
396     );
397
398     my $reserve    = $messages->{'ResFound'};
399     if ( $reserve ) {
400         my $patron = Koha::Patrons->find( $reserve->{'borrowernumber'} );
401         my $name = $patron->surname . ", " . $patron->title . " " . $patron->firstname;
402         $template->param(
403             patron => $patron,
404         );
405     }
406     $template->param(
407         wtransfertFrom  => $userenv_branch,
408     );
409 }
410
411 #
412 # reserve found and item arrived at the expected branch
413 #
414 if ( $messages->{'ResFound'}) {
415     my $reserve    = $messages->{'ResFound'};
416     my $patron = Koha::Patrons->find( $reserve->{borrowernumber} );
417     my $holdmsgpreferences =  C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $reserve->{'borrowernumber'}, message_name   => 'Hold_Filled' } );
418     if ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
419         if ( $reserve->{'ResFound'} eq "Waiting" ) {
420             $template->param(
421                 waiting      => ($userenv_branch eq $reserve->{'branchcode'} ? 1 : 0 ),
422             );
423         } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
424             $template->param(
425                 intransit    => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
426                 transfertodo => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
427                 reserve_id   => $reserve->{reserve_id},
428                 reserved     => 1,
429             );
430         }
431
432         # same params for Waiting or Reserved
433         $template->param(
434             # FIXME The full patron object should be passed to the template
435             found          => 1,
436             patron         => $patron,
437             barcode        => $barcode,
438             destbranch     => $reserve->{'branchcode'},
439             itemnumber     => $reserve->{'itemnumber'},
440             reservenotes   => $reserve->{'reservenotes'},
441             reserve_id     => $reserve->{reserve_id},
442             bormessagepref => $holdmsgpreferences->{'transports'},
443         );
444     } # else { ; }  # error?
445 }
446
447 # Error Messages
448 my @errmsgloop;
449 foreach my $code ( keys %$messages ) {
450     my %err;
451     my $exit_required_p = 0;
452     if ( $code eq 'BadBarcode' ) {
453         $err{badbarcode} = 1;
454         $err{msg}        = $messages->{'BadBarcode'};
455     }
456     elsif ( $code eq 'NotIssued' ) {
457         $err{notissued} = 1;
458         $err{msg} = '';
459     }
460     elsif ( $code eq 'LocalUse' ) {
461         $err{localuse} = 1;
462     }
463     elsif ( $code eq 'WasLost' ) {
464         $err{waslost} = 1;
465         $exit_required_p = 1 if C4::Context->preference("BlockReturnOfLostItems");
466     }
467     elsif ( $code eq 'LostItemFeeRefunded' ) {
468         $template->param( LostItemFeeRefunded => 1 );
469     }
470     elsif ( $code eq 'ResFound' ) {
471         ;    # FIXME... anything to do here?
472     }
473     elsif ( $code eq 'WasReturned' ) {
474         ;    # FIXME... anything to do here?
475     }
476     elsif ( $code eq 'WasTransfered' ) {
477         ;    # FIXME... anything to do here?
478     }
479     elsif ( $code eq 'withdrawn' ) {
480         $err{withdrawn} = 1;
481         $exit_required_p = 1 if C4::Context->preference("BlockReturnOfWithdrawnItems");
482     }
483     elsif ( $code eq 'WrongTransfer' ) {
484         ;    # FIXME... anything to do here?
485     }
486     elsif ( $code eq 'WrongTransferItem' ) {
487         ;    # FIXME... anything to do here?
488     }
489     elsif ( $code eq 'NeedsTransfer' ) {
490     }
491     elsif ( $code eq 'Wrongbranch' ) {
492     }
493     elsif ( $code eq 'Debarred' ) {
494         $err{debarred}            = $messages->{'Debarred'};
495         $err{debarcardnumber}     = $borrower->{cardnumber};
496         $err{debarborrowernumber} = $borrower->{borrowernumber};
497         $err{debarname}           = "$borrower->{firstname} $borrower->{surname}";
498     }
499     elsif ( $code eq 'PrevDebarred' ) {
500         $err{prevdebarred}        = $messages->{'PrevDebarred'};
501     }
502     elsif ( $code eq 'ForeverDebarred' ) {
503         $err{foreverdebarred}        = $messages->{'ForeverDebarred'};
504     }
505     elsif ( $code eq 'NotForLoanStatusUpdated' ) {
506         $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
507     }
508     elsif ( $code eq 'DataCorrupted' ) {
509         $err{data_corrupted} = 1;
510     }
511     else {
512         die "Unknown error code $code";    # note we need all the (empty) elsif's above, or we die.
513         # This forces the issue of staying in sync w/ Circulation.pm
514     }
515     if (%err) {
516         push( @errmsgloop, \%err );
517     }
518     last if $exit_required_p;
519 }
520 $template->param( errmsgloop => \@errmsgloop );
521
522 #set up so only the last 8 returned items display (make for faster loading pages)
523 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
524 my $count = 0;
525 my @riloop;
526 my $shelflocations =
527   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
528 foreach ( sort { $a <=> $b } keys %returneditems ) {
529     my %ri;
530     if ( $count++ < $returned_counter ) {
531         my $bar_code = $returneditems{$_};
532         if ($riduedate{$_}) {
533             my $duedate = dt_from_string( $riduedate{$_}, 'sql');
534             $ri{year}  = $duedate->year();
535             $ri{month} = $duedate->month();
536             $ri{day}   = $duedate->day();
537             $ri{hour}   = $duedate->hour();
538             $ri{minute}   = $duedate->minute();
539             $ri{duedate} = output_pref($duedate);
540             my $patron = Koha::Patrons->find( $riborrowernumber{$_} );
541             unless ( $dropboxmode ) {
542                 $ri{return_overdue} = 1 if (DateTime->compare($duedate, DateTime->now()) == -1);
543             } else {
544                 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
545             }
546             $ri{patron} = $patron,
547             $ri{borissuescount} = $patron->checkouts->count;
548         }
549         else {
550             $ri{borrowernumber} = $riborrowernumber{$_};
551         }
552
553         my $item = Koha::Items->find({ barcode => $bar_code });
554         my $biblio = $item->biblio;
555         # FIXME pass $item to the template and we are done here...
556         $ri{itembiblionumber}    = $biblio->biblionumber;
557         $ri{itemtitle}           = $biblio->title;
558         $ri{itemauthor}          = $biblio->author;
559         $ri{itemcallnumber}      = $item->itemcallnumber;
560         $ri{dateaccessioned}     = $item->dateaccessioned;
561         $ri{itemtype}            = $item->effective_itemtype;
562         $ri{itemnote}            = $item->itemnotes;
563         $ri{itemnotes_nonpublic} = $item->itemnotes_nonpublic;
564         $ri{ccode}               = $item->ccode;
565         $ri{enumchron}           = $item->enumchron;
566         $ri{itemnumber}          = $item->itemnumber;
567         $ri{barcode}             = $bar_code;
568         $ri{homebranch}          = $item->homebranch;
569         $ri{holdingbranch}       = $item->holdingbranch;
570
571         $ri{location} = $item->location;
572         my $shelfcode = $ri{'location'};
573         $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
574
575     }
576     else {
577         last;
578     }
579     push @riloop, \%ri;
580 }
581
582 $template->param(
583     riloop         => \@riloop,
584     printer        => $printer,
585     errmsgloop     => \@errmsgloop,
586     exemptfine     => $exemptfine,
587     dropboxmode    => $dropboxmode,
588     dropboxdate    => output_pref($dropboxdate),
589     forgivemanualholdsexpire => $forgivemanualholdsexpire,
590     overduecharges => $overduecharges,
591     AudioAlerts        => C4::Context->preference("AudioAlerts"),
592 );
593
594 $itemnumber = GetItemnumberFromBarcode( $barcode );
595 if ( $itemnumber ) {
596     my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
597     if ( $holdingBranch and $collectionBranch ) {
598         $holdingBranch //= '';
599         $collectionBranch //= $returnbranch;
600         if ( ! ( $holdingBranch eq $collectionBranch ) ) {
601             $template->param(
602               collectionItemNeedsTransferred => 1,
603               collectionBranch => $collectionBranch,
604               itemnumber => $itemnumber,
605             );
606         }
607     }
608 }
609
610 # Checking if there is a Fast Cataloging Framework
611 $template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' );
612
613 # actually print the page!
614 output_html_with_http_headers $query, $cookie, $template->output;