6f6e91b45a585f9dfd9795f4a3d202778ae40c28
[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;
23 use C4::Auth qw( get_template_and_user );
24 use C4::Members;
25 use C4::Koha qw( GetAuthorisedValues );
26 use C4::Output qw( output_html_with_http_headers );
27 use C4::Suggestions qw(
28     DelSuggestion
29     MarcRecordFromNewSuggestion
30     NewSuggestion
31     SearchSuggestion
32 );
33 use C4::Koha qw( GetAuthorisedValues );
34 use C4::Scrubber;
35 use C4::Search qw( FindDuplicate );
36
37 use Koha::AuthorisedValues;
38 use Koha::Libraries;
39 use Koha::Patrons;
40
41 use Koha::DateUtils qw( dt_from_string output_pref );
42
43 my $input           = CGI->new;
44 my $op              = $input->param('op') || 'else';
45 my $biblionumber    = $input->param('biblionumber');
46 my $negcaptcha      = $input->param('negcap');
47 my $suggested_by_anyone = $input->param('suggested_by_anyone') || 0;
48 my $title_filter    = $input->param('title_filter');
49 my $need_confirm    = 0;
50
51 my $suggestion = {
52     title           => scalar $input->param('title'),
53     author          => scalar $input->param('author'),
54     copyrightdate   => scalar $input->param('copyrightdate'),
55     isbn            => scalar $input->param('isbn'),
56     publishercode   => scalar $input->param('publishercode'),
57     collectiontitle => scalar $input->param('collectiontitle'),
58     place           => scalar $input->param('place'),
59     quantity        => scalar $input->param('quantity'),
60     itemtype        => scalar $input->param('itemtype'),
61     branchcode      => scalar $input->param('branchcode'),
62     patronreason    => scalar $input->param('patronreason'),
63     note            => scalar $input->param('note'),
64 };
65
66 # If a spambot accidentally populates the 'negcap' field in the sugesstions form, then silently skip and return.
67 if ($negcaptcha ) {
68     print $input->redirect("/cgi-bin/koha/opac-suggestions.pl");
69     exit;
70 }
71
72 #If suggestions are turned off we redirect to 404 error. This will also redirect guest suggestions
73 if ( ! C4::Context->preference('suggestion') ) {
74     print $input->redirect("/cgi-bin/koha/errors/404.pl");
75     exit;
76 }
77
78 my ( $template, $borrowernumber, $cookie, @messages );
79 my $deleted = $input->param('deleted');
80 my $submitted = $input->param('submitted');
81
82 if ( ( C4::Context->preference("AnonSuggestions") and Koha::Patrons->find( C4::Context->preference("AnonymousPatron") ) ) or ( C4::Context->preference("OPACViewOthersSuggestions") and $op eq 'else' ) ) {
83     ( $template, $borrowernumber, $cookie ) = get_template_and_user(
84         {
85             template_name   => "opac-suggestions.tt",
86             query           => $input,
87             type            => "opac",
88             authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
89         }
90     );
91 }
92 else {
93     ( $template, $borrowernumber, $cookie ) = get_template_and_user(
94         {
95             template_name   => "opac-suggestions.tt",
96             query           => $input,
97             type            => "opac",
98         }
99     );
100 }
101
102 if ( $op eq 'else' ) {
103     if ( C4::Context->preference("OPACViewOthersSuggestions") ) {
104         if ( $borrowernumber ) {
105             # A logged in user is able to see suggestions from others
106             $suggestion->{suggestedby} = $suggested_by_anyone
107                 ? undef
108                 : $borrowernumber;
109         }
110         else {
111             # Non logged in user is able to see all suggestions
112             $suggestion->{suggestedby} = undef;
113         }
114     }
115     else {
116         if ( $borrowernumber ) {
117             $suggestion->{suggestedby} = $borrowernumber;
118         }
119         else {
120             $suggestion->{suggestedby} = -1;
121         }
122     }
123 } else {
124     if ( $borrowernumber ) {
125         $suggestion->{suggestedby} = $borrowernumber;
126     }
127     else {
128         $suggestion->{suggestedby} = C4::Context->preference("AnonymousPatron");
129     }
130 }
131
132 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
133     $op = 'add_confirm';
134     my $biblio = MarcRecordFromNewSuggestion($suggestion);
135     if ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) {
136         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
137         $need_confirm = 1;
138         $op = 'add';
139     }
140 }
141
142 my $patrons_pending_suggestions_count = 0;
143 my $patrons_total_suggestions_count = 0;
144 if ( $borrowernumber ){
145     if ( C4::Context->preference("MaxTotalSuggestions") ne '' && C4::Context->preference("NumberOfSuggestionDays") ne '' ) {
146         my $suggesteddate_from = dt_from_string()->subtract(days=>C4::Context->preference("NumberOfSuggestionDays"));
147         $suggesteddate_from = output_pref({ dt => $suggesteddate_from, dateformat => 'iso', dateonly => 1 });
148         $patrons_total_suggestions_count = Koha::Suggestions->search({ suggestedby => $borrowernumber, suggesteddate => { '>=' => $suggesteddate_from } })->count;
149
150     }
151     if ( C4::Context->preference("MaxOpenSuggestions") ne '' ) {
152         $patrons_pending_suggestions_count = Koha::Suggestions->search({ suggestedby => $borrowernumber, STATUS => 'ASKED' } )->count ;
153     }
154 }
155
156 if ( $op eq "add_confirm" ) {
157     my $suggestions_loop = &SearchSuggestion($suggestion);
158     if ( C4::Context->preference("MaxTotalSuggestions") ne '' && $patrons_total_suggestions_count >= C4::Context->preference("MaxTotalSuggestions") )
159     {
160         push @messages, { type => 'error', code => 'total_suggestions' };
161     }
162     elsif ( C4::Context->preference("MaxOpenSuggestions") ne '' && $patrons_pending_suggestions_count >= C4::Context->preference("MaxOpenSuggestions") ) #only check limit for signed in borrowers
163     {
164         push @messages, { type => 'error', code => 'too_many' };
165     }
166     elsif ( @$suggestions_loop >= 1 ) {
167
168         #some suggestion are answering the request Donot Add
169         for my $s (@$suggestions_loop) {
170             push @messages,
171               {
172                 type => 'error',
173                 code => 'already_exists',
174                 id   => $s->{suggestionid}
175               };
176             last;
177         }
178     }
179     else {
180         for my $f ( split(/\s*\,\s*/, C4::Context->preference("OPACSuggestionUnwantedFields") ) ) {
181             delete $suggestion->{$f};
182         }
183
184         my $scrubber = C4::Scrubber->new();
185         foreach my $suggest ( keys %$suggestion ) {
186
187             # Don't know why the encode is needed for Perl v5.10 here
188             $suggestion->{$suggest} = Encode::encode( "utf8",
189                 $scrubber->scrub( $suggestion->{$suggest} ) );
190         }
191         $suggestion->{suggesteddate} = dt_from_string;
192         $suggestion->{branchcode} = $input->param('branchcode') || C4::Context->userenv->{"branch"};
193         $suggestion->{STATUS} = 'ASKED';
194
195         &NewSuggestion($suggestion);
196         $patrons_pending_suggestions_count++;
197         $patrons_total_suggestions_count++;
198
199         # delete empty fields, to avoid filter in "SearchSuggestion"
200         foreach my $field ( qw( title author publishercode copyrightdate place collectiontitle isbn STATUS ) ) {
201             delete $suggestion->{$field}; #clear search filters (except borrower related) to show all suggestions after placing a new one
202         }
203         $suggestions_loop = &SearchSuggestion($suggestion);
204
205         push @messages, { type => 'info', code => 'success_on_inserted' };
206
207     }
208     $op = 'else';
209 }
210
211 my $suggestions_loop = &SearchSuggestion(
212     {
213         suggestedby => $suggestion->{suggestedby},
214         title       => $title_filter,
215     }
216 );
217 if ( $op eq "delete_confirm" ) {
218     my @delete_field = $input->multi_param("delete_field");
219     foreach my $delete_field (@delete_field) {
220         &DelSuggestion( $borrowernumber, $delete_field );
221     }
222     $op = 'else';
223     print $input->redirect("/cgi-bin/koha/opac-suggestions.pl?op=else");
224     exit;
225 }
226
227 map{
228     my $s = $_;
229     my $library = Koha::Libraries->find($s->{branchcodesuggestedby});
230     $library ? $s->{branchcodesuggestedby} = $library->branchname : ()
231 } @$suggestions_loop;
232
233 foreach my $suggestion(@$suggestions_loop) {
234     if($suggestion->{'suggestedby'} == $borrowernumber) {
235         $suggestion->{'showcheckbox'} = $borrowernumber;
236     } else {
237         $suggestion->{'showcheckbox'} = 0;
238     }
239     if($suggestion->{'patronreason'}){
240         my $av = Koha::AuthorisedValues->search({ category => 'OPAC_SUG', authorised_value => $suggestion->{patronreason} });
241         $suggestion->{'patronreason'} = $av->count ? $av->next->opac_description : '';
242     }
243 }
244
245 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG", "opac");
246
247 my @mandatoryfields;
248 {
249     last unless ($op eq 'add');
250     my $fldsreq_sp = C4::Context->preference("OPACSuggestionMandatoryFields") || 'title';
251     @mandatoryfields = sort split(/\s*\,\s*/, $fldsreq_sp);
252     foreach (@mandatoryfields) {
253         $template->param( $_."_required" => 1);
254     }
255     if ( $biblionumber ) {
256         my $biblio = Koha::Biblios->find($biblionumber);
257         $template->param(
258             biblionumber    => $biblio->biblionumber,
259             title           => $biblio->title,
260             author          => $biblio->author,
261             copyrightdate   => $biblio->copyrightdate,
262             isbn            => $biblio->biblioitem->isbn,
263             publishercode   => $biblio->biblioitem->publishercode,
264             collectiontitle => $biblio->biblioitem->collectiontitle,
265             place           => $biblio->biblioitem->place,
266         );
267     }
268 }
269
270 my @unwantedfields;
271 {
272     last unless ($op eq 'add');
273     my $fldsreq_sp = C4::Context->preference("OPACSuggestionUnwantedFields");
274     @unwantedfields = sort split(/\s*\,\s*/, $fldsreq_sp);
275     foreach (@unwantedfields) {
276         $template->param( $_."_hidden" => 1);
277     }
278 }
279
280 $template->param(
281     %$suggestion,
282     suggestions_loop      => $suggestions_loop,
283     patron_reason_loop    => $patron_reason_loop,
284     "op_$op"              => 1,
285     $op                   => 1,
286     messages              => \@messages,
287     suggestionsview       => 1,
288     suggested_by_anyone   => $suggested_by_anyone,
289     title_filter          => $title_filter,
290     patrons_pending_suggestions_count => $patrons_pending_suggestions_count,
291     need_confirm => $need_confirm,
292     patrons_total_suggestions_count => $patrons_total_suggestions_count,
293 );
294
295 output_html_with_http_headers $input, $cookie, $template->output, undef, { force_no_caching => 1 };
296