Bug 15451: Rewrite the csv profile tool script
[koha.git] / tools / upload-file.pl
1 #!/usr/bin/perl
2
3 # Copyright (C) 2007 LibLime
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 CGI qw ( -utf8 );
23 use CGI::Cookie;
24 use Encode;
25 use JSON;
26 use URI::Escape;
27
28 use C4::Context;
29 use C4::Auth qw/check_cookie_auth haspermission/;
30 use Koha::Upload;
31
32 # upload-file.pl must authenticate the user
33 # before processing the POST request,
34 # and quickly bounce if the user is
35 # not authorized.  Consequently, unlike
36 # most of the other CGI scripts, upload-file.pl
37 # requires that the session cookie already
38 # has been created.
39
40 my %cookies = CGI::Cookie->fetch;
41 my $sid = $cookies{'CGISESSID'}->value;
42 my ( $auth_status, $sessionID ) = check_cookie_auth( $sid );
43 my $uid = C4::Auth::get_session($sid)->param('id');
44 my $allowed = Koha::Upload->allows_add_by( $uid );
45
46 if( $auth_status ne 'ok' || !$allowed ) {
47     send_reply( 'denied' );
48     exit 0;
49 }
50
51 my $upload = Koha::Upload->new( upload_pars($ENV{QUERY_STRING}) );
52 if( !$upload || !$upload->cgi || !$upload->count ) {
53     # not one upload succeeded
54     send_reply( 'failed', undef, $upload? $upload->err: undef );
55 } else {
56     # in case of multiple uploads, at least one got through
57     send_reply( 'done', $upload->result, $upload->err );
58 }
59 exit 0;
60
61 sub send_reply {    # response will be sent back as JSON
62     my ( $upload_status, $data, $error ) = @_;
63     my $reply = CGI->new("");
64     print $reply->header( -type => 'text/html', -charset => 'UTF-8' );
65     print JSON::encode_json({
66         status => $upload_status,
67         fileid => $data,
68         errors => $error,
69    });
70 }
71
72 sub upload_pars { # this sub parses QUERY_STRING in order to build the
73                   # parameter hash for Koha::Upload
74     my ( $qstr ) = @_;
75     $qstr = Encode::decode_utf8( uri_unescape( $qstr ) );
76     # category could include a utf8 character
77     my $rv = {};
78     foreach my $p ( qw[public category temp] ) {
79         if( $qstr =~ /(^|&)$p=(\w+)(&|$)/ ) {
80             $rv->{$p} = $2;
81         }
82     }
83     return $rv;
84 }