Bug 22990: Add CSRF protection to boraccount, pay and suggestion
[koha.git] / suggestion / suggestion.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 # Copyright 2006-2010 BibLibre
5
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21 require Exporter;
22 use CGI qw ( -utf8 );
23 use C4::Auth qw( get_template_and_user );
24 use C4::Output qw( output_html_with_http_headers output_and_exit_if_error );
25 use C4::Suggestions;
26 use C4::Koha qw( GetAuthorisedValues );
27 use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget );
28 use C4::Search qw( FindDuplicate GetDistinctValues );
29 use C4::Members;
30 use Koha::DateUtils qw( dt_from_string );
31 use Koha::AuthorisedValues;
32 use Koha::Acquisition::Currencies;
33 use Koha::Libraries;
34 use Koha::Patrons;
35 use Koha::Suggestions;
36
37 use URI::Escape qw( uri_escape );
38
39 sub Init{
40     my $suggestion= shift @_;
41     # "Managed by" is used only when a suggestion is being edited (not when created)
42     if ($suggestion->{'suggesteddate'} eq "") {
43         # new suggestion
44         $suggestion->{suggesteddate} = dt_from_string;
45         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
46     }
47     else {
48         # editing of an existing suggestion
49         $suggestion->{manageddate} = dt_from_string;
50         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
51     }
52     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
53 }
54
55 sub GetCriteriumDesc{
56     my ($criteriumvalue,$displayby)=@_;
57     if ($displayby =~ /status/i) {
58         unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
59             my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
60             return $av->count ? $av->next->lib : 'Unknown';
61         }
62         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
63     }
64     if ( $displayby =~ /branchcode/ ) {
65         return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__";
66     }
67     if ( $displayby =~ /itemtype/ ) {
68         my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
69         return $av->count ? $av->next->lib : 'Unknown';
70     }
71     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
72         my $patron = Koha::Patrons->find( $criteriumvalue );
73         return "" unless $patron;
74         return $patron->surname . ", " . $patron->firstname;
75     }
76     if ( $displayby =~ /budgetid/) {
77         my $budget = GetBudget($criteriumvalue);
78         return "" unless $budget;
79         return $$budget{budget_name};
80     }
81 }
82
83 my $input           = CGI->new;
84 my $redirect  = $input->param('redirect');
85 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
86 my $op              = $input->param('op')||'else';
87 my @editsuggestions = $input->multi_param('suggestionid');
88 my $suggestedby     = $input->param('suggestedby');
89 my $returnsuggestedby = $input->param('returnsuggestedby');
90 my $returnsuggested = $input->param('returnsuggested');
91 my $managedby       = $input->param('managedby');
92 my $displayby       = $input->param('displayby') || '';
93 my $tabcode         = $input->param('tabcode');
94 my $save_confirmed  = $input->param('save_confirmed') || 0;
95 my $notify          = $input->param('notify');
96 my $filter_archived = $input->param('filter_archived') || 0;
97
98 my $reasonsloop     = GetAuthorisedValues("SUGGEST");
99
100 # filter informations which are not suggestion related.
101 my $suggestion_ref  = { %{$input->Vars} }; # Copying, otherwise $input will be modified
102
103 # get only the columns of Suggestion
104 my $schema = Koha::Database->new()->schema;
105 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
106 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
107 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
108
109 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode notify filter_archived );
110 foreach (keys %$suggestion_ref){
111     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
112 }
113 delete $suggestion_only->{branchcode} if $suggestion_only->{branchcode} eq '__ANY__';
114 delete $suggestion_only->{budgetid}   if $suggestion_only->{budgetid}   eq '__ANY__';
115 while ( my ( $k, $v ) = each %$suggestion_only ) {
116     delete $suggestion_only->{$k} if $v eq '';
117 }
118
119 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
120         {
121             template_name   => "suggestion/suggestion.tt",
122             query           => $input,
123             type            => "intranet",
124             flagsrequired   => { suggestions => 'suggestions_manage' },
125         }
126     );
127
128 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
129 $template->param('borrowernumber' => $borrowernumber);
130 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
131
132 #########################################
133 ##  Operations
134 ##
135
136 if ( $op =~ /save/i ) {
137     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
138     my @messages;
139     my $biblio = MarcRecordFromNewSuggestion({
140             title => $suggestion_only->{title},
141             author => $suggestion_only->{author},
142             itemtype => $suggestion_only->{itemtype},
143             isbn => $suggestion_only->{isbn},
144     });
145
146     my $manager = Koha::Patrons->find( $suggestion_only->{managedby} );
147     if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) {
148         push @messages, { type => 'error', code => 'manager_not_enough_permissions' };
149         $template->param(
150             messages => \@messages,
151         );
152         delete $suggestion_ref->{suggesteddate};
153         delete $suggestion_ref->{manageddate};
154         delete $suggestion_ref->{managedby};
155         Init($suggestion_ref);
156     }
157     elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
158         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
159         $template->param(
160             messages => \@messages,
161             need_confirm => 1
162         );
163         delete $suggestion_ref->{suggesteddate};
164         delete $suggestion_ref->{manageddate};
165         Init($suggestion_ref);
166     }
167     else {
168
169         for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
170             # FIXME Do we need this?
171             $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
172                 if $suggestion_only->{$date_key};
173         }
174
175         if ( $suggestion_only->{"STATUS"} ) {
176             if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
177                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
178                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
179             }
180             $suggestion_only->{manageddate} = dt_from_string;
181             $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
182         }
183
184         my $otherreason = $input->param('other_reason');
185         if ($suggestion_only->{reason} eq 'other' && $otherreason) {
186             $suggestion_only->{reason} = $otherreason;
187         }
188
189         if ( $suggestion_only->{'suggestionid'} > 0 ) {
190
191             $suggestion_only->{lastmodificationdate} = dt_from_string;
192             $suggestion_only->{lastmodificationby}   = C4::Context->userenv->{number};
193             $suggestion_only->{branchcode} = undef
194               if exists $suggestion_only->{branchcode}
195               && $suggestion_only->{branchcode} eq "";
196
197             &ModSuggestion($suggestion_only);
198
199             if ( $notify ) {
200                 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
201                 my $email_address = $patron->notice_email_address;
202                 if ($patron->notice_email_address) {
203
204                     my $letter = C4::Letters::GetPreparedLetter(
205                         module      => 'suggestions',
206                         letter_code => 'NOTIFY_MANAGER',
207                         branchcode  => $patron->branchcode,
208                         lang        => $patron->lang,
209                         tables      => {
210                             suggestions => $suggestion_only->{suggestionid},
211                             branches    => $patron->branchcode,
212                             borrowers   => $patron->borrowernumber,
213                         },
214                     );
215                     C4::Letters::EnqueueLetter(
216                         {
217                             letter                 => $letter,
218                             borrowernumber         => $patron->borrowernumber,
219                             message_transport_type => 'email'
220                         }
221                     );
222                 }
223             }
224         } else {
225             ###FIXME:Search here if suggestion already exists.
226             my $suggestions= Koha::Suggestions->search_limited( $suggestion_only );
227             if ( $suggestions->count ) {
228                 #some suggestion are answering the request Donot Add
229                 my @messages;
230                 while ( my $suggestion = $suggestions->next ) {
231                     push @messages, { type => 'error', code => 'already_exists', id => $suggestion->suggestionid };
232                 }
233                 $template->param( messages => \@messages );
234             }
235             else {
236                 ## Adding some informations related to suggestion
237                 Koha::Suggestion->new($suggestion_only)->store();
238             }
239             # empty fields, to avoid filter in "SearchSuggestion"
240         }
241         map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
242         $op = 'else';
243
244         if( $redirect eq 'purchase_suggestions' ) {
245             print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
246         }
247     }
248 }
249 elsif ($op=~/add/) {
250     #Adds suggestion
251     Init($suggestion_ref);
252     $op ='save';
253 }
254 elsif ($op=~/edit/) {
255     #Edit suggestion
256     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
257     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
258     $suggestion_ref->{reasonsloop} = $reasonsloop;
259     my $other_reason = 1;
260     foreach my $reason ( @{ $reasonsloop } ) {
261         if ($suggestion_ref->{reason} eq $reason->{lib}) {
262             $other_reason = 0;
263         }
264     }
265     $other_reason = 0 unless $suggestion_ref->{reason};
266     $template->param(other_reason => $other_reason);
267     Init($suggestion_ref);
268     $op ='save';
269 }  
270 elsif ($op eq "update_status" ) {
271     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
272     my $suggestion;
273     # set accepted/rejected/managed informations if applicable
274     # ie= if the librarian has chosen some action on the suggestions
275     my $STATUS      = $input->param('STATUS');
276     my $accepted_by = $input->param('acceptedby');
277     if ( $STATUS eq "ACCEPTED" ) {
278         $suggestion = {
279             accepteddate => dt_from_string,
280             acceptedby => C4::Context->userenv->{number},
281         };
282     }
283     elsif ( $STATUS eq "REJECTED" ) {
284         $suggestion = {
285             rejecteddate => dt_from_string,
286             rejectedby   => C4::Context->userenv->{number},
287         };
288     }
289     if ($STATUS) {
290         $suggestion->{manageddate} = dt_from_string;
291         $suggestion->{managedby}   = C4::Context->userenv->{number};
292         $suggestion->{STATUS}      = $STATUS;
293     }
294     if ( my $reason = $input->param("reason") ) {
295         if ( $reason eq "other" ) {
296             $reason = $input->param("other_reason");
297         }
298         $suggestion->{reason} = $reason;
299     }
300
301     foreach my $suggestionid (@editsuggestions) {
302         next unless $suggestionid;
303         $suggestion->{suggestionid} = $suggestionid;
304         &ModSuggestion($suggestion);
305     }
306     redirect_with_params($input);
307 }elsif ($op eq "delete" ) {
308     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
309     foreach my $delete_field (@editsuggestions) {
310         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
311     }
312     redirect_with_params($input);
313 }
314 elsif ($op eq "archive" ) {
315     Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
316
317     redirect_with_params($input);
318 }
319 elsif ($op eq "unarchive" ) {
320     Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
321
322     redirect_with_params($input);
323 }
324 elsif ( $op eq 'update_itemtype' ) {
325     my $new_itemtype = $input->param('suggestion_itemtype');
326     foreach my $suggestionid (@editsuggestions) {
327         next unless $suggestionid;
328         &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
329     }
330     redirect_with_params($input);
331 }
332 elsif ( $op eq 'update_manager' ) {
333     my $managedby = $input->param('suggestion_managedby');
334     foreach my $suggestionid (@editsuggestions) {
335         next unless $suggestionid;
336         &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
337     }
338     redirect_with_params($input);
339 }
340 elsif ( $op eq 'show' ) {
341     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
342     my $budget = GetBudget $$suggestion_ref{budgetid};
343     $$suggestion_ref{budgetname} = $$budget{budget_name};
344     Init($suggestion_ref);
345 }
346 if ($op=~/else/) {
347     $op='else';
348
349     $displayby||="STATUS";
350     # distinct values of display by
351     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
352     my (@criteria_dv, $criteria_has_empty);
353     foreach (@$criteria_list) {
354         if ($_->{value}) {
355             push @criteria_dv, $_->{value};
356         } else {
357             $criteria_has_empty = 1;
358         }
359     }
360     # aggregate null and empty values under empty value
361     push @criteria_dv, '' if $criteria_has_empty;
362
363     # Hack to not modify GetDistinctValues for this specific case
364     if (   $displayby eq 'branchcode'
365         && C4::Context->preference('IndependentBranches')
366         && not C4::Context->IsSuperLibrarian )
367     {
368         @criteria_dv = ( C4::Context->userenv->{'branch'} );
369     }
370     # Pending tab first
371     if ( $displayby eq 'STATUS' ) {
372         @criteria_dv = grep { $_ ne 'ASKED' } @criteria_dv;
373         unshift @criteria_dv, 'ASKED';
374     }
375
376     unless ( exists $suggestion_ref->{branchcode} ) {
377         $suggestion_ref->{branchcode} = C4::Context->userenv->{'branch'};
378     }
379
380     my @allsuggestions;
381     foreach my $criteriumvalue ( @criteria_dv ) {
382         my $search_params = {%$suggestion_ref};
383
384         next
385           if $search_params->{STATUS}
386           && $displayby eq 'STATUS'
387           && $criteriumvalue ne $search_params->{STATUS};
388
389         # By default, display suggestions from current working branch
390         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
391
392         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
393
394         $search_params->{$displayby} = $criteriumvalue;
395
396         # filter on date fields
397         foreach my $field (qw( suggesteddate manageddate accepteddate )) {
398             my $from    = delete $search_params->{"${field}_from"};
399             my $to      = delete $search_params->{"${field}_to"};
400
401             my $from_dt = $from && eval { dt_from_string($from) };
402             my $to_dt   = $to && eval { dt_from_string($to) };
403
404             if ( $from_dt || $to_dt ) {
405                 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
406                 if ( $from_dt && $to_dt ) {
407                     $search_params->{$field} = { -between => [ $dtf->format_date($from_dt), $dtf->format_date($to_dt) ] };
408                 } elsif ( $from_dt ) {
409                     $search_params->{$field} = { '>=' => $dtf->format_date($from_dt) };
410                 } elsif ( $to_dt ) {
411                     $search_params->{$field} = { '<=' => $dtf->format_date($to_dt) };
412                 }
413             }
414         }
415         if ( $search_params->{budgetid} && $search_params->{budgetid} eq '__NONE__' ) {
416             $search_params->{budgetid} = [undef, '' ];
417         }
418         for my $f (qw (branchcode budgetid)) {
419             delete $search_params->{$f}
420               if $search_params->{$f} eq '__ANY__'
421               || $search_params->{$f} eq '';
422         }
423
424         $search_params->{archived} = 0 if !$filter_archived;
425         my @suggestions = Koha::Suggestions->search_limited($search_params)->as_list;
426
427         push @allsuggestions,
428           {
429             "suggestiontype"      => $criteriumvalue || "suggest",
430             "suggestiontypelabel" => GetCriteriumDesc( $criteriumvalue, $displayby ) || "",
431             'suggestions'         => \@suggestions,
432             'reasonsloop'         => $reasonsloop,
433           }
434           if scalar @suggestions > 0;
435
436         delete $$suggestion_ref{$displayby} unless $definedvalue;
437     }
438
439     $template->param(
440         "displayby"=> $displayby,
441         "notabs"=> $displayby eq "",
442         suggestions       => \@allsuggestions,
443     );
444 }
445
446 $template->param(
447     "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
448   for qw(managedby suggestedby acceptedby lastmodificationby);
449
450 $template->param(
451     %$suggestion_ref,
452     filter_archived => $filter_archived,
453     "op"             =>$op,
454 );
455
456 if(defined($returnsuggested) and $returnsuggested ne "noone")
457 {
458     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
459 }
460
461 $template->param(
462     branchfilter => $branchfilter,
463 );
464
465 $template->param( returnsuggestedby => $returnsuggestedby );
466
467 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
468 $template->param(patron_reason_loop=>$patron_reason_loop);
469
470 # Budgets for filtering
471 my $budgets = GetBudgets;
472 my @budgets_loop;
473 foreach my $budget ( @{$budgets} ) {
474     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
475
476     ## Please see file perltidy.ERR
477     $budget->{'selected'} = 1
478         if ($$suggestion_ref{'budgetid'}
479         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
480
481     push @budgets_loop, $budget;
482 }
483 $template->param( budgetsloop => \@budgets_loop);
484
485 # Budgets for suggestion add or edition
486 my $sugg_budget_loop = [];
487 my $sugg_budgets     = GetBudgetHierarchy();
488 foreach my $r ( @{$sugg_budgets} ) {
489     next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
490     my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
491     push @{$sugg_budget_loop},
492       {
493         b_id     => $r->{budget_id},
494         b_txt    => $r->{budget_name},
495         b_active => $r->{budget_period_active},
496         selected => $selected,
497       };
498 }
499 @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
500 $template->param( sugg_budgets => $sugg_budget_loop);
501
502 if( $suggestion_ref->{STATUS} ) {
503     $template->param(
504         "statusselected_".$suggestion_ref->{STATUS} => 1,
505         selected_status => $suggestion_ref->{STATUS}, # We need template var selected_status in the second part of the template where template var suggestion.STATUS is out of scope
506     );
507 }
508
509 my $currencies = Koha::Acquisition::Currencies->search;
510 $template->param(
511     currencies   => $currencies,
512     suggestion   => $suggestion_ref,
513     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
514     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
515 );
516
517 # lists of distinct values (without empty) for filters
518 my %hashlists;
519 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
520     my $values_list;
521     $values_list = GetDistinctValues( "suggestions." . $field );
522     my @codes_list = map {
523         {   'code' => $$_{'value'},
524             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
525             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
526         }
527     } grep {
528         $$_{'value'}
529     } @$values_list;
530     $hashlists{ lc($field) . "_loop" } = \@codes_list;
531 }
532
533 $template->param(
534     %hashlists,
535     borrowernumber           => ($input->param('borrowernumber') // undef),
536     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
537 );
538 output_html_with_http_headers $input, $cookie, $template->output;
539
540 sub redirect_with_params {
541     my ( $input ) = @_;
542     my $params = '';
543     foreach my $key (
544         qw(
545         displayby branchcode title author isbn publishercode copyrightdate
546         collectiontitle suggestedby suggesteddate_from suggesteddate_to
547         manageddate_from manageddate_to accepteddate_from
548         accepteddate_to budgetid filter_archived
549         )
550       )
551     {
552         $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
553           if defined($input->param($key));
554     }
555     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
556 }