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