b1f1701ddc59fccbef04d44627745c787b0f39b8
[koha.git] / opac / opac-suggestions.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20
21 use CGI qw ( -utf8 );
22 use Encode qw( encode );
23 use C4::Auth;    # get_template_and_user
24 use C4::Members;
25 use C4::Koha;
26 use C4::Output;
27 use C4::Suggestions;
28 use C4::Koha;
29 use C4::Scrubber;
30 use C4::Search qw( FindDuplicate );
31
32 use Koha::AuthorisedValues;
33 use Koha::Libraries;
34 use Koha::Patrons;
35
36 use Koha::DateUtils;
37
38 my $input           = CGI->new;
39 my $op              = $input->param('op') || 'else';
40 my $biblionumber    = $input->param('biblionumber');
41 my $suggestion      = $input->Vars;
42 my $negcaptcha      = $input->param('negcap');
43 my $suggested_by_anyone = $input->param('suggested_by_anyone') || 0;
44 my $title_filter    = $input->param('title_filter');
45 my $need_confirm    = 0;
46
47 # If a spambot accidentally populates the 'negcap' field in the sugesstions form, then silently skip and return.
48 if ($negcaptcha ) {
49     print $input->redirect("/cgi-bin/koha/opac-suggestions.pl");
50     exit;
51 }
52
53 #If suggestions are turned off we redirect to 404 error. This will also redirect guest suggestions
54 if ( ! C4::Context->preference('suggestion') ) {
55     print $input->redirect("/cgi-bin/koha/errors/404.pl");
56     exit;
57 }
58
59 my ( $template, $borrowernumber, $cookie, @messages );
60 my $deleted = $input->param('deleted');
61 my $submitted = $input->param('submitted');
62
63 if ( ( C4::Context->preference("AnonSuggestions") and Koha::Patrons->find( C4::Context->preference("AnonymousPatron") ) ) or ( C4::Context->preference("OPACViewOthersSuggestions") and $op eq 'else' ) ) {
64     ( $template, $borrowernumber, $cookie ) = get_template_and_user(
65         {
66             template_name   => "opac-suggestions.tt",
67             query           => $input,
68             type            => "opac",
69             authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
70         }
71     );
72 }
73 else {
74     ( $template, $borrowernumber, $cookie ) = get_template_and_user(
75         {
76             template_name   => "opac-suggestions.tt",
77             query           => $input,
78             type            => "opac",
79         }
80     );
81 }
82
83 # don't pass 'negcap' column to DB, else DBI::Class will error
84 # DBIx::Class::Row::store_column(): No such column 'negcap' on Koha::Schema::Result::Suggestion at  Koha/C4/Suggestions.pm
85 delete $suggestion->{negcap};
86 delete $suggestion->{$_} foreach qw<op suggested_by_anyone confirm>;
87
88 if ( $op eq 'else' ) {
89     if ( C4::Context->preference("OPACViewOthersSuggestions") ) {
90         if ( $borrowernumber ) {
91             # A logged in user is able to see suggestions from others
92             $suggestion->{suggestedby} = $suggested_by_anyone
93                 ? undef
94                 : $borrowernumber;
95         }
96         else {
97             # Non logged in user is able to see all suggestions
98             $suggestion->{suggestedby} = undef;
99         }
100     }
101     else {
102         if ( $borrowernumber ) {
103             $suggestion->{suggestedby} = $borrowernumber;
104         }
105         else {
106             $suggestion->{suggestedby} = -1;
107         }
108     }
109 } else {
110     if ( $borrowernumber ) {
111         $suggestion->{suggestedby} = $borrowernumber;
112     }
113     else {
114         $suggestion->{suggestedby} = C4::Context->preference("AnonymousPatron");
115     }
116 }
117
118 if ( $op eq "add_validate" && not $biblionumber ) { # If we are creating the suggestion from an existing record we do not want to search for duplicates
119     $op = 'add_confirm';
120     my $biblio = MarcRecordFromNewSuggestion($suggestion);
121     if ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) {
122         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
123         $need_confirm = 1;
124         $op = 'add';
125     }
126 }
127
128 my $patrons_pending_suggestions_count = 0;
129 my $patrons_total_suggestions_count = 0;
130 if ( $borrowernumber ){
131     if ( C4::Context->preference("MaxTotalSuggestions") ne '' && C4::Context->preference("NumberOfSuggestionDays") ne '' ) {
132         my $suggesteddate_from = dt_from_string()->subtract(days=>C4::Context->preference("NumberOfSuggestionDays"));
133         $suggesteddate_from = output_pref({ dt => $suggesteddate_from, dateformat => 'iso', dateonly => 1 });
134         $patrons_total_suggestions_count = Koha::Suggestions->search({ suggestedby => $borrowernumber, suggesteddate => { '>=' => $suggesteddate_from } })->count;
135
136     }
137     if ( C4::Context->preference("MaxOpenSuggestions") ne '' ) {
138         $patrons_pending_suggestions_count = Koha::Suggestions->search({ suggestedby => $borrowernumber, STATUS => 'ASKED' } )->count ;
139     }
140 }
141
142 if ( $op eq "add_confirm" ) {
143     my $suggestions_loop = &SearchSuggestion($suggestion);
144     if ( C4::Context->preference("MaxTotalSuggestions") ne '' && $patrons_total_suggestions_count >= C4::Context->preference("MaxTotalSuggestions") )
145     {
146         push @messages, { type => 'error', code => 'total_suggestions' };
147     }
148     elsif ( C4::Context->preference("MaxOpenSuggestions") ne '' && $patrons_pending_suggestions_count >= C4::Context->preference("MaxOpenSuggestions") ) #only check limit for signed in borrowers
149     {
150         push @messages, { type => 'error', code => 'too_many' };
151     }
152     elsif ( @$suggestions_loop >= 1 ) {
153
154         #some suggestion are answering the request Donot Add
155         for my $suggestion (@$suggestions_loop) {
156             push @messages,
157               {
158                 type => 'error',
159                 code => 'already_exists',
160                 id   => $suggestion->{suggestionid}
161               };
162             last;
163         }
164     }
165     else {
166         my $scrubber = C4::Scrubber->new();
167         foreach my $suggest ( keys %$suggestion ) {
168
169             # Don't know why the encode is needed for Perl v5.10 here
170             $suggestion->{$suggest} = Encode::encode( "utf8",
171                 $scrubber->scrub( $suggestion->{$suggest} ) );
172         }
173         $suggestion->{suggesteddate} = dt_from_string;
174         $suggestion->{branchcode} = $input->param('branchcode') || C4::Context->userenv->{"branch"};
175
176         &NewSuggestion($suggestion);
177         $patrons_pending_suggestions_count++;
178         $patrons_total_suggestions_count++;
179
180         # delete empty fields, to avoid filter in "SearchSuggestion"
181         foreach my $field ( qw( title author publishercode copyrightdate place collectiontitle isbn STATUS ) ) {
182             delete $suggestion->{$field}; #clear search filters (except borrower related) to show all suggestions after placing a new one
183         }
184         $suggestions_loop = &SearchSuggestion($suggestion);
185
186         push @messages, { type => 'info', code => 'success_on_inserted' };
187
188     }
189     $op = 'else';
190 }
191
192 my $suggestions_loop = &SearchSuggestion(
193     {
194         suggestedby => $suggestion->{suggestedby},
195         title       => $title_filter,
196     }
197 );
198 if ( $op eq "delete_confirm" ) {
199     my @delete_field = $input->multi_param("delete_field");
200     foreach my $delete_field (@delete_field) {
201         &DelSuggestion( $borrowernumber, $delete_field );
202     }
203     $op = 'else';
204     print $input->redirect("/cgi-bin/koha/opac-suggestions.pl?op=else");
205     exit;
206 }
207
208 map{
209     my $s = $_;
210     my $library = Koha::Libraries->find($s->{branchcodesuggestedby});
211     $library ? $s->{branchcodesuggestedby} = $library->branchname : ()
212 } @$suggestions_loop;
213
214 foreach my $suggestion(@$suggestions_loop) {
215     if($suggestion->{'suggestedby'} == $borrowernumber) {
216         $suggestion->{'showcheckbox'} = $borrowernumber;
217     } else {
218         $suggestion->{'showcheckbox'} = 0;
219     }
220     if($suggestion->{'patronreason'}){
221         my $av = Koha::AuthorisedValues->search({ category => 'OPAC_SUG', authorised_value => $suggestion->{patronreason} });
222         $suggestion->{'patronreason'} = $av->count ? $av->next->opac_description : '';
223     }
224 }
225
226 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG", "opac");
227
228 my @mandatoryfields;
229 {
230     last unless ($op eq 'add');
231     my $fldsreq_sp = C4::Context->preference("OPACSuggestionMandatoryFields") || 'title';
232     @mandatoryfields = sort split(/\s*\,\s*/, $fldsreq_sp);
233     foreach (@mandatoryfields) {
234         $template->param( $_."_required" => 1);
235     }
236     if ( $biblionumber ) {
237         my $biblio = Koha::Biblios->find($biblionumber);
238         $template->param(
239             biblionumber    => $biblio->biblionumber,
240             title           => $biblio->title,
241             author          => $biblio->author,
242             copyrightdate   => $biblio->copyrightdate,
243             isbn            => $biblio->biblioitem->isbn,
244             publishercode   => $biblio->biblioitem->publishercode,
245             collectiontitle => $biblio->biblioitem->collectiontitle,
246             place           => $biblio->biblioitem->place,
247         );
248     }
249 }
250
251 my @unwantedfields;
252 {
253     last unless ($op eq 'add');
254     my $fldsreq_sp = C4::Context->preference("OPACSuggestionUnwantedFields");
255     @unwantedfields = sort split(/\s*\,\s*/, $fldsreq_sp);
256     foreach (@unwantedfields) {
257         $template->param( $_."_hidden" => 1);
258     }
259 }
260
261 $template->param(
262     %$suggestion,
263     suggestions_loop      => $suggestions_loop,
264     patron_reason_loop    => $patron_reason_loop,
265     "op_$op"              => 1,
266     $op                   => 1,
267     messages              => \@messages,
268     suggestionsview       => 1,
269     suggested_by_anyone   => $suggested_by_anyone,
270     title_filter          => $title_filter,
271     patrons_pending_suggestions_count => $patrons_pending_suggestions_count,
272     need_confirm => $need_confirm,
273     patrons_total_suggestions_count => $patrons_total_suggestions_count,
274 );
275
276 output_html_with_http_headers $input, $cookie, $template->output, undef, { force_no_caching => 1 };
277