Bug 11331 - CSV export for viewlog.pl is missing newlines
[koha.git] / tools / viewlog.pl
1 #!/usr/bin/perl
2
3 # Copyright 2010 BibLibre
4 # Copyright 2011 MJ Ray and software.coop
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use Modern::Perl;
22
23 use C4::Auth;
24 use CGI;
25 use Text::CSV::Encoded;
26 use C4::Context;
27 use C4::Koha;
28 use C4::Dates;
29 use C4::Output;
30 use C4::Log;
31 use C4::Items;
32 use C4::Branch;
33 use C4::Debug;
34 # use Data::Dumper;
35 use C4::Search;         # enabled_staff_search_views
36
37 use vars qw($debug $cgi_debug);
38
39 =head1 viewlog.pl
40
41 plugin that shows stats
42
43 =cut
44
45 my $input    = new CGI;
46
47 $debug or $debug = $cgi_debug;
48 my $do_it    = $input->param('do_it');
49 my @modules   = $input->param("modules");
50 my $user     = $input->param("user");
51 my @action   = $input->param("action");
52 my $object   = $input->param("object");
53 my $info     = $input->param("info");
54 my $datefrom = $input->param("from");
55 my $dateto   = $input->param("to");
56 my $basename = $input->param("basename");
57 #my $del      = $input->param("sep");
58 my $output   = $input->param("output") || "screen";
59 my $src      = $input->param("src");    # this param allows us to be told where we were called from -fbcit
60
61 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
62     {
63         template_name   => "tools/viewlog.tt",
64         query           => $input,
65         type            => "intranet",
66         authnotrequired => 0,
67         flagsrequired   => { tools => 'view_system_logs' },
68         debug           => 1,
69     }
70 );
71
72 if ($src eq 'circ') {   # if we were called from circulation, use the circulation menu and get data to populate it -fbcit
73     use C4::Members;
74     use C4::Members::Attributes qw(GetBorrowerAttributes);
75     my $borrowernumber = $object;
76     my $data = GetMember('borrowernumber'=>$borrowernumber);
77     my ($picture, $dberror) = GetPatronImage($data->{'borrowernumber'});
78     $template->param( picture => 1 ) if $picture;
79
80     if (C4::Context->preference('ExtendedPatronAttributes')) {
81         my $attributes = GetBorrowerAttributes($data->{'borrowernumber'});
82         $template->param(
83             ExtendedPatronAttributes => 1,
84             extendedattributes => $attributes
85         );
86     }
87
88     # Computes full borrower address
89     my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $data->{streettype} );
90     my $address = $data->{'streetnumber'} . " $roadtype " . $data->{'address'};
91
92     $template->param(   menu            => 1,
93                         title           => $data->{'title'},
94                         initials        => $data->{'initials'},
95                         surname         => $data->{'surname'},
96                         othernames      => $data->{'othernames'},
97                         borrowernumber  => $borrowernumber,
98                         firstname       => $data->{'firstname'},
99                         cardnumber      => $data->{'cardnumber'},
100                         categorycode    => $data->{'categorycode'},
101                         category_type   => $data->{'category_type'},
102                         categoryname    => $data->{'description'},
103                         address         => $address,
104                         address2        => $data->{'address2'},
105                         city            => $data->{'city'},
106                         state           => $data->{'state'},
107                         zipcode         => $data->{'zipcode'},
108                         country         => $data->{'country'},
109                         phone           => $data->{'phone'},
110                         phonepro        => $data->{'phonepro'},
111                         mobile          => $data->{'mobile'},
112                         email           => $data->{'email'},
113                         emailpro        => $data->{'emailpro'},
114                         branchcode      => $data->{'branchcode'},
115                         branchname              => GetBranchName($data->{'branchcode'}),
116                         RoutingSerials => C4::Context->preference('RoutingSerials'),
117     );
118 }
119
120 $template->param(
121     debug => $debug,
122     C4::Search::enabled_staff_search_views,
123 );
124
125 if ($do_it) {
126
127     my @data;
128     my ($results,$modules,$action);
129     if ($action[0] ne '') { $action = \@action; } # match All means no limit
130     if ($modules[0] ne '') { $modules = \@modules; } # match All means no limit
131     $results = GetLogs($datefrom,$dateto,$user,$modules,$action,$object,$info);
132     @data=@$results;
133     my $total = scalar @data;
134     foreach my $result (@data){
135     # Init additional columns for CSV export
136     $result->{'biblionumber'} = q{};
137     $result->{'biblioitemnumber'} = q{};
138     $result->{'barcode'} = q{};
139     $result->{'userfirstname'} = q{};
140     $result->{'usersurname'} = q{};
141     $result->{'borrowerfirstname'} = q{};
142     $result->{'borrowersurname'} = q{};
143
144         if (substr($result->{'info'}, 0, 4) eq 'item' || $result->{module} eq "CIRCULATION"){
145             # get item information so we can create a working link
146         my $itemnumber=$result->{'object'};
147         $itemnumber=$result->{'info'} if ($result->{module} eq "CIRCULATION");
148             my $item=GetItem($itemnumber);
149         if ($item) {
150             $result->{'biblionumber'}=$item->{'biblionumber'};
151             $result->{'biblioitemnumber'}=$item->{'biblionumber'};
152             $result->{'barcode'}=$item->{'barcode'};
153         }
154         }
155     #always add firstname and surname for librarian/user
156     if ($result->{'user'}){
157         my $userdetails = C4::Members::GetMemberDetails($result->{'user'});
158         if ($userdetails){
159             $result->{'userfirstname'} = $userdetails->{'firstname'};
160             $result->{'usersurname'} = $userdetails->{'surname'};
161         }
162     }
163     #add firstname and surname for borrower, when using the CIRCULATION, MEMBERS, FINES
164     if ($result->{module} eq "CIRCULATION" || $result->{module} eq "MEMBERS" || $result->{module} eq "FINES"){
165         if($result->{'object'}){
166             my $borrowerdetails = C4::Members::GetMemberDetails($result->{'object'});
167             if ($borrowerdetails){
168                 $result->{'borrowerfirstname'} = $borrowerdetails->{'firstname'};
169                 $result->{'borrowersurname'} = $borrowerdetails->{'surname'};
170             }
171         }
172     }
173     }
174     
175     if ( $output eq "screen" ) {
176         # Printing results to screen
177         $template->param (
178                         logview => 1,
179             total    => $total,
180             looprow  => \@data,
181             do_it    => 1,
182             datefrom => $datefrom,
183             dateto   => $dateto,
184             user     => $user,
185             object   => $object,
186             action   => \@action,
187             info     => $info,
188             src      => $src,
189         );
190             #module   => 'fix this', #this seems unused in actual code
191         foreach my $module (@modules) {
192                 $template->param($module  => 1);
193         }
194
195         output_html_with_http_headers $input, $cookie, $template->output;
196     } else {
197         # Printing to a csv file
198         my $content = q{};
199         my $delimiter = C4::Context->preference('delimiter') || ',';
200         if (@data) {
201             my $csv = Text::CSV::Encoded->new( { encoding_out => 'utf8', sep_char => $delimiter } );
202             $csv or die "Text::CSV::Encoded->new FAILED: " . Text::CSV::Encoded->error_diag();
203             # First line with heading
204             # Exporting bd id seems useless
205             my @headings = grep { $_ ne 'action_id' } sort keys $data[0];
206             if ( $csv->combine( @headings ) ) {
207                 $content .= $csv->string() . "\n";
208             }
209             # Lines of logs
210             foreach my $line (@data) {
211                 my @cells = map { $line->{$_} } @headings;
212                 if ( $csv->combine( @cells ) ) {
213                     $content .= $csv->string() . "\n";
214                 }
215             }
216         }
217         print $input->header(
218             -type       => 'text/csv',
219             -attachment => $basename . '.csv',
220         );
221         print $content;
222     }
223         exit;
224 } else {
225     #my @values;
226     #my %labels;
227     #my %select;
228         #initialize some paramaters that might not be used in the template - it seems to evaluate EXPR even if a false TMPL_IF
229         $template->param(
230                 total => 0,
231                 module => "",
232                 info => ""
233         );
234         output_html_with_http_headers $input, $cookie, $template->output;
235 }