Bug 14544: Get rid of GetShelf
[koha.git] / opac / opac-shareshelf.pl
1 #!/usr/bin/perl
2
3 # Copyright 2013 Rijksmuseum
4 #
5 # This file is part of Koha.
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
22 use constant KEYLENGTH     => 10;
23 use constant TEMPLATE_NAME => 'opac-shareshelf.tt';
24 use constant SHELVES_URL =>
25   '/cgi-bin/koha/opac-shelves.pl?display=privateshelves&viewshelf=';
26
27 use CGI qw ( -utf8 );
28 use Email::Valid;
29
30 use C4::Auth;
31 use C4::Context;
32 use C4::Letters;
33 use C4::Members ();
34 use C4::Output;
35 use C4::VirtualShelves;
36
37 use Koha::Virtualshelves;
38
39 #-------------------------------------------------------------------------------
40
41 my $pvar = _init( {} );
42 if ( !$pvar->{errcode} ) {
43     show_invite($pvar)    if $pvar->{op} eq 'invite';
44     confirm_invite($pvar) if $pvar->{op} eq 'conf_invite';
45     show_accept($pvar)    if $pvar->{op} eq 'accept';
46 }
47 load_template_vars($pvar);
48 output_html_with_http_headers $pvar->{query}, $pvar->{cookie},
49   $pvar->{template}->output;
50
51 #-------------------------------------------------------------------------------
52
53 sub _init {
54     my ($param) = @_;
55     my $query = new CGI;
56     $param->{query}       = $query;
57     $param->{shelfnumber} = $query->param('shelfnumber') || 0;
58     $param->{op}          = $query->param('op') || '';
59     $param->{addrlist}    = $query->param('invite_address') || '';
60     $param->{key}         = $query->param('key') || '';
61     $param->{appr_addr}   = [];
62     $param->{fail_addr}   = [];
63     $param->{errcode}     = check_common_errors($param);
64
65     # trim email address
66     if ( $param->{addrlist} ) {
67         $param->{addrlist} =~ s|^\s+||;
68         $param->{addrlist} =~ s|\s+$||;
69     }
70
71     #get some list details
72     my $shelf;
73     my $shelfnumber = $param->{shelfnumber};
74     $shelf = Koha::Virtualshelves->find( $shelfnumber ) unless $param->{errcode};
75     $param->{shelfname} = $shelf ? $shelf->shelfname : q||;
76     $param->{owner}     = $shelf ? $shelf->owner : -1;
77     $param->{category}  = $shelf ? $shelf->category : -1;
78
79     load_template($param);
80     return $param;
81 }
82
83 sub check_common_errors {
84     my ($param) = @_;
85     if ( $param->{op} !~ /^(invite|conf_invite|accept)$/ ) {
86         return 1;    #no operation specified
87     }
88     if ( $param->{shelfnumber} !~ /^\d+$/ ) {
89         return 2;    #invalid shelf number
90     }
91     if ( !C4::Context->preference('OpacAllowSharingPrivateLists') ) {
92         return 3;    #not or no longer allowed?
93     }
94     return;
95 }
96
97 sub show_invite {
98     my ($param) = @_;
99     return unless check_owner_category($param);
100 }
101
102 sub confirm_invite {
103     my ($param) = @_;
104     return unless check_owner_category($param);
105     process_addrlist($param);
106     if ( @{ $param->{appr_addr} } ) {
107         send_invitekey($param);
108     }
109     else {
110         $param->{errcode} = 6;    #not one valid address
111     }
112 }
113
114 sub show_accept {
115     my ($param) = @_;
116
117     my @rv = ShelfPossibleAction( $param->{loggedinuser},
118         $param->{shelfnumber}, 'acceptshare' );
119     $param->{errcode} = $rv[1] if !$rv[0];
120     return if $param->{errcode};
121
122     #errorcode 5: should be private list
123     #errorcode 8: should not be owner
124
125     my $dbkey = keytostring( stringtokey( $param->{key}, 0 ), 1 );
126     if ( AcceptShare( $param->{shelfnumber}, $dbkey, $param->{loggedinuser} ) )
127     {
128         notify_owner($param);
129
130         #redirect to view of this shared list
131         print $param->{query}->redirect(
132             -uri    => SHELVES_URL . $param->{shelfnumber},
133             -cookie => $param->{cookie}
134         );
135         exit;
136     }
137     else {
138         $param->{errcode} = 7;    #not accepted (key not found or expired)
139     }
140 }
141
142 sub notify_owner {
143     my ($param) = @_;
144
145     my $toaddr = C4::Members::GetNoticeEmailAddress( $param->{owner} );
146     return if !$toaddr;
147
148     #prepare letter
149     my $letter = C4::Letters::GetPreparedLetter(
150         module      => 'members',
151         letter_code => 'SHARE_ACCEPT',
152         branchcode  => C4::Context->userenv->{"branch"},
153         tables      => { borrowers => $param->{loggedinuser}, },
154         substitute  => { listname => $param->{shelfname}, },
155     );
156
157     #send letter to queue
158     C4::Letters::EnqueueLetter(
159         {
160             letter                 => $letter,
161             message_transport_type => 'email',
162             from_address => C4::Context->preference('KohaAdminEmailAddress'),
163             to_address   => $toaddr,
164         }
165     );
166 }
167
168 sub process_addrlist {
169     my ($param) = @_;
170     my @temp = split /[,:;]/, $param->{addrlist};
171     my @appr_addr;
172     my @fail_addr;
173     foreach my $a (@temp) {
174         $a =~ s/^\s+//;
175         $a =~ s/\s+$//;
176         if ( IsEmailAddress($a) ) {
177             push @appr_addr, $a;
178         }
179         else {
180             push @fail_addr, $a;
181         }
182     }
183     $param->{appr_addr} = \@appr_addr;
184     $param->{fail_addr} = \@fail_addr;
185 }
186
187 sub send_invitekey {
188     my ($param) = @_;
189     my $fromaddr = C4::Context->preference('KohaAdminEmailAddress');
190     my $url =
191         C4::Context->preference('OPACBaseURL')
192       . "/cgi-bin/koha/opac-shareshelf.pl?shelfnumber="
193       . $param->{shelfnumber}
194       . "&op=accept&key=";
195
196     #TODO Waiting for the right http or https solution (BZ 8952 a.o.)
197
198     my @ok;    #the addresses that were processed well
199     foreach my $a ( @{ $param->{appr_addr} } ) {
200         my @newkey = randomlist( KEYLENGTH, 64 );    #generate a new key
201
202         #add a preliminary share record
203         if ( !AddShare( $param->{shelfnumber}, keytostring( \@newkey, 1 ) ) ) {
204             push @{ $param->{fail_addr} }, $a;
205             next;
206         }
207         push @ok, $a;
208
209         #prepare letter
210         my $letter = C4::Letters::GetPreparedLetter(
211             module      => 'members',
212             letter_code => 'SHARE_INVITE',
213             branchcode  => C4::Context->userenv->{"branch"},
214             tables      => { borrowers => $param->{loggedinuser}, },
215             substitute  => {
216                 listname => $param->{shelfname},
217                 shareurl => $url . keytostring( \@newkey, 0 ),
218             },
219         );
220
221         #send letter to queue
222         C4::Letters::EnqueueLetter(
223             {
224                 letter                 => $letter,
225                 message_transport_type => 'email',
226                 from_address           => $fromaddr,
227                 to_address             => $a,
228             }
229         );
230     }
231     $param->{appr_addr} = \@ok;
232 }
233
234 sub check_owner_category {
235     my ($param) = @_;
236
237     #sharing user should be the owner
238     #list should be private
239     $param->{errcode} = 4 if $param->{owner} != $param->{loggedinuser};
240     $param->{errcode} = 5 if !$param->{errcode} && $param->{category} != 1;
241     return !defined $param->{errcode};
242 }
243
244 sub load_template {
245     my ($param) = @_;
246     ( $param->{template}, $param->{loggedinuser}, $param->{cookie} ) =
247       get_template_and_user(
248         {
249             template_name   => TEMPLATE_NAME,
250             query           => $param->{query},
251             type            => "opac",
252             authnotrequired => 0,                 #should be a user
253         }
254       );
255 }
256
257 sub load_template_vars {
258     my ($param) = @_;
259     my $template = $param->{template};
260     my $appr = join '; ', @{ $param->{appr_addr} };
261     my $fail = join '; ', @{ $param->{fail_addr} };
262     $template->param(
263         errcode         => $param->{errcode},
264         op              => $param->{op},
265         shelfnumber     => $param->{shelfnumber},
266         shelfname       => $param->{shelfname},
267         approvedaddress => $appr,
268         failaddress     => $fail,
269     );
270 }
271
272 sub IsEmailAddress {
273
274     #TODO candidate for a module?
275     return Email::Valid->address( $_[0] ) ? 1 : 0;
276 }
277
278 sub randomlist {
279
280     #uses rand, safe enough for this application but not for more sensitive data
281     my ( $length, $base ) = @_;
282     return map { int( rand($base) ); } 1 .. $length;
283 }
284
285 sub keytostring {
286     my ( $keyref, $flgBase64 ) = @_;
287     if ($flgBase64) {
288         my $alphabet = [ 'A' .. 'Z', 'a' .. 'z', 0 .. 9, '+', '/' ];
289         return join '', map { alphabet_char( $_, $alphabet ); } @$keyref;
290     }
291     return join '', map { sprintf( "%02d", $_ ); } @$keyref;
292 }
293
294 sub stringtokey {
295     my ( $str, $flgBase64 ) = @_;
296     my @temp = split '', $str || '';
297     if ($flgBase64) {
298         my $alphabet = [ 'A' .. 'Z', 'a' .. 'z', 0 .. 9, '+', '/' ];
299         return [ map { alphabet_ordinal( $_, $alphabet ); } @temp ];
300     }
301     return [] if $str !~ /^\d+$/;
302     my @retval;
303     for ( my $i = 0 ; $i < @temp - 1 ; $i += 2 ) {
304         push @retval, $temp[$i] * 10 + $temp[ $i + 1 ];
305     }
306     return \@retval;
307 }
308
309 sub alphabet_ordinal {
310     my ( $char, $alphabet ) = @_;
311     for my $ord ( 0 .. $#$alphabet ) {
312         return $ord if $char eq $alphabet->[$ord];
313     }
314     return '';    #ignore missing chars
315 }
316
317 sub alphabet_char {
318
319     #reverse operation for ordinal; ignore invalid numbers
320     my ( $num, $alphabet ) = @_;
321     return $num =~ /^\d+$/ && $num <= $#$alphabet ? $alphabet->[$num] : '';
322 }