1 package SL::ReportGenerator;
4 use List::Util qw(max);
15 $self->{myconfig} = shift;
16 $self->{form} = shift;
20 'std_column_visibility' => 0,
21 'output_format' => 'HTML',
22 'allow_pdf_export' => 1,
23 'allow_csv_export' => 1,
26 'orientation' => 'landscape',
30 'margin_bottom' => 1.5,
31 'margin_right' => 1.5,
41 'eol_style' => 'Unix',
47 'variable_list' => [],
50 $self->{data_present} = 0;
54 $self->set_options(@_) if (@_);
56 $self->_init_escaped_strings_map();
61 sub _init_escaped_strings_map {
64 $self->{escaped_strings_map} = {
77 my $iconv = $main::locale->{iconv_iso8859};
80 map { $self->{escaped_strings_map}->{$_} = $iconv->convert($self->{escaped_strings_map}->{$_}) } keys %{ $self->{escaped_strings_map} };
88 $self->{columns} = \%columns;
90 foreach my $column (values %{ $self->{columns} }) {
91 $column->{visible} = $self->{options}->{std_column_visibility} unless defined $column->{visible};
94 $self->set_column_order(sort keys %{ $self->{columns} });
97 sub set_column_order {
101 my %columns = map { $order++; ($_, $order) } @_;
103 foreach my $column (sort keys %{ $self->{columns} }) {
104 next if $columns{$column};
107 $columns{$column} = $order;
110 $self->{column_order} = [ sort { $columns{$a} <=> $columns{$b} } keys %columns ];
113 sub set_sort_indicator {
116 $self->{options}->{sort_indicator_column} = shift;
117 $self->{options}->{sort_indicator_direction} = shift;
125 while (my $arg = shift) {
128 if ('ARRAY' eq ref $arg) {
131 } elsif ('HASH' eq ref $arg) {
135 $self->{form}->error('Incorrect usage -- expecting hash or array ref');
138 my @columns_with_default_alignment = grep { defined $self->{columns}->{$_}->{align} } keys %{ $self->{columns} };
140 foreach my $row (@{ $row_set }) {
141 foreach my $column (@columns_with_default_alignment) {
142 $row->{$column} ||= { };
143 $row->{$column}->{align} = $self->{columns}->{$column}->{align} unless (defined $row->{$column}->{align});
146 foreach my $field (qw(data link)) {
147 map { $row->{$_}->{$field} = [ $row->{$_}->{$field} ] if (ref $row->{$_}->{$field} ne 'ARRAY') } keys %{ $row };
151 push @{ $self->{data} }, $row_set;
152 $last_row_set = $row_set;
154 $self->{data_present} = 1;
157 return $last_row_set;
163 push @{ $self->{data} }, { 'type' => 'separator' };
170 push @{ $self->{data} }, $data;
177 $self->{data_present} = 0;
184 map { $self->{options}->{$_} = $options{$_} } keys %options;
187 sub set_options_from_form {
190 my $form = $self->{form};
191 my $myconfig = $self->{myconfig};
193 foreach my $key (qw(output_format)) {
194 my $full_key = "report_generator_${key}";
195 $self->{options}->{$key} = $form->{$full_key} if (defined $form->{$full_key});
198 foreach my $format (qw(pdf csv)) {
199 my $opts = $self->{options}->{"${format}_export"};
200 foreach my $key (keys %{ $opts }) {
201 my $full_key = "report_generator_${format}_options_${key}";
202 $opts->{$key} = $key =~ /^margin/ ? $form->parse_amount($myconfig, $form->{$full_key}) : $form->{$full_key};
207 sub set_export_options {
212 'variable_list' => [ @_ ],
216 sub get_attachment_basename {
218 my $filename = $self->{options}->{attachment_basename} || 'report';
219 $filename =~ s|.*\\||;
220 $filename =~ s|.*/||;
225 sub generate_with_headers {
227 my $format = lc $self->{options}->{output_format};
228 my $form = $self->{form};
230 if (!$self->{columns}) {
231 $form->error('Incorrect usage -- no columns specified');
234 if ($format eq 'html') {
235 my $title = $form->{title};
236 $form->{title} = $self->{title} if ($self->{title});
238 $form->{title} = $title;
240 print $self->generate_html_content();
242 } elsif ($format eq 'csv') {
243 my $filename = $self->get_attachment_basename();
244 print qq|content-type: text/csv\n|;
245 print qq|content-disposition: attachment; filename=${filename}.csv\n\n|;
246 $self->generate_csv_content();
248 } elsif ($format eq 'pdf') {
249 $self->generate_pdf_content();
252 $form->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
256 sub get_visible_columns {
260 return grep { my $c = $self->{columns}->{$_}; $c && $c->{visible} && (($c->{visible} == 1) || ($c->{visible} =~ /\Q${format}\E/i)) } @{ $self->{column_order} };
267 $value = $self->{form}->quote_html($value);
269 $value =~ s/\n/<br>/g;
274 sub prepare_html_content {
277 my ($column, $name, @column_headers);
279 my $opts = $self->{options};
280 my @visible_columns = $self->get_visible_columns('HTML');
282 foreach $name (@visible_columns) {
283 $column = $self->{columns}->{$name};
287 'link' => $column->{link},
288 'text' => $column->{text},
289 'show_sort_indicator' => $name eq $opts->{sort_indicator_column},
290 'sort_indicator_direction' => $opts->{sort_indicator_direction},
293 push @column_headers, $header;
296 my ($outer_idx, $inner_idx) = (0, 0);
300 foreach my $row_set (@{ $self->{data} }) {
301 if ('HASH' eq ref $row_set) {
302 if ($row_set->{type} eq 'separator') {
303 if (! scalar @rows) {
304 $next_border_top = 1;
306 $rows[-1]->{BORDER_BOTTOM} = 1;
314 'IS_COLSPAN_DATA' => $row_set->{type} eq 'colspan_data',
315 'NUM_COLUMNS' => scalar @visible_columns,
316 'BORDER_TOP' => $next_border_top,
317 'data' => $row_set->{data},
320 push @rows, $row_data;
322 $next_border_top = 0;
329 foreach my $row (@{ $row_set }) {
332 foreach my $col_name (@visible_columns) {
333 my $col = $row->{$col_name};
334 $col->{CELL_ROWS} = [ ];
335 foreach my $i (0 .. scalar(@{ $col->{data} }) - 1) {
336 push @{ $col->{CELL_ROWS} }, {
337 'data' => $self->html_format($col->{data}->[$i]),
338 'link' => $col->{link}->[$i],
342 # Force at least a to be displayed so that browsers
343 # will format the table cell (e.g. borders etc).
344 if (!scalar @{ $col->{CELL_ROWS} }) {
345 push @{ $col->{CELL_ROWS} }, { 'data' => ' ' };
346 } elsif ((1 == scalar @{ $col->{CELL_ROWS} }) && !$col->{CELL_ROWS}->[0]->{data}) {
347 $col->{CELL_ROWS}->[0]->{data} = ' ';
352 'COLUMNS' => [ map { $row->{$_} } @visible_columns ],
353 'outer_idx' => $outer_idx,
354 'outer_idx_odd' => $outer_idx % 2,
355 'inner_idx' => $inner_idx,
356 'BORDER_TOP' => $next_border_top,
359 push @rows, $row_data;
361 $next_border_top = 0;
365 my @export_variables = $self->{form}->flatten_variables(@{ $self->{export}->{variable_list} });
367 my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
370 'TITLE' => $opts->{title},
371 'TOP_INFO_TEXT' => $self->html_format($opts->{top_info_text}),
372 'RAW_TOP_INFO_TEXT' => $opts->{raw_top_info_text},
373 'BOTTOM_INFO_TEXT' => $self->html_format($opts->{bottom_info_text}),
374 'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
375 'ALLOW_PDF_EXPORT' => $allow_pdf_export,
376 'ALLOW_CSV_EXPORT' => $opts->{allow_csv_export},
377 'SHOW_EXPORT_BUTTONS' => ($allow_pdf_export || $opts->{allow_csv_export}) && $self->{data_present},
378 'COLUMN_HEADERS' => \@column_headers,
379 'NUM_COLUMNS' => scalar @column_headers,
381 'EXPORT_VARIABLES' => \@export_variables,
382 'EXPORT_VARIABLE_LIST' => join(' ', @{ $self->{export}->{variable_list} }),
383 'EXPORT_NEXTSUB' => $self->{export}->{nextsub},
384 'DATA_PRESENT' => $self->{data_present},
390 sub generate_html_content {
392 my $variables = $self->prepare_html_content();
394 return $self->{form}->parse_html_template('report_generator/html_report', $variables);
397 sub verify_paper_size {
399 my $requested_paper_size = lc shift;
400 my $default_paper_size = shift;
402 my %allowed_paper_sizes = map { $_ => 1 } qw(a3 a4 letter legal);
404 return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
407 sub generate_pdf_content {
409 my $variables = $self->prepare_html_content();
410 my $form = $self->{form};
411 my $myconfig = $self->{myconfig};
412 my $opt = $self->{options}->{pdf_export};
414 my $opt_number = $opt->{number} ? 'number : 1' : '';
415 my $opt_landscape = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
417 my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
419 my $html2ps_config = <<"END"
429 type: ${opt_paper_size};
435 margin-top: $opt->{margin_top}cm;
436 margin-left: $opt->{margin_left}cm;
437 margin-bottom: $opt->{margin_bottom}cm;
438 margin-right: $opt->{margin_right}cm;
442 font-family: Helvetica;
443 font-size: $opt->{font_size}pt;
450 if ($opt->{print} && $opt->{printer_id}) {
451 $form->{printer_id} = $opt->{printer_id};
452 $form->get_printer_code($myconfig);
453 $printer_command = $form->{printer_command};
456 my $cfg_file_name = Common::tmpname() . '-html2ps-config';
457 my $cfg_file = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
459 $cfg_file->print($html2ps_config);
462 my $html_file_name = Common::tmpname() . '.html';
463 my $html_file = IO::File->new($html_file_name, 'w');
466 unlink $cfg_file_name;
467 $form->error($locale->text('Could not write the temporary HTML file.'));
470 $html_file->print($form->parse_html_template('report_generator/pdf_report', $variables));
474 "\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
475 "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite -";
477 my $gs = IO::File->new("${cmdline} |");
481 if (!$printer_command) {
482 my $filename = $self->get_attachment_basename();
483 print qq|content-type: application/pdf\n|;
484 print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
486 while (my $line = <$gs>) {
491 while (my $line = <$gs>) {
497 unlink $cfg_file_name, $html_file_name;
499 if ($printer_command && $content) {
500 foreach my $i (1 .. max $opt->{copies}, 1) {
501 my $printer = IO::File->new("| ${printer_command}");
503 $form->error($locale->text('Could not spawn the printer command.'));
505 $printer->print($content);
509 $form->{report_generator_printed} = 1;
513 unlink $cfg_file_name, $html_file_name;
514 $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
518 sub unescape_string {
522 foreach my $key (keys %{ $self->{escaped_strings_map} }) {
523 $text =~ s/\Q$key\E/$self->{escaped_strings_map}->{$key}/g;
526 $text =~ s/\Q&\E/&/g;
531 sub generate_csv_content {
534 my %valid_sep_chars = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
535 my %valid_escape_chars = ('"' => 1, "'" => 1);
536 my %valid_quote_chars = ('"' => 1, "'" => 1);
538 my $opts = $self->{options}->{csv_export};
539 my $eol = $opts->{eol_style} eq 'DOS' ? "\r\n" : "\n";
540 my $sep_char = $valid_sep_chars{$opts->{sep_char}} ? $valid_sep_chars{$opts->{sep_char}} : ';';
541 my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char} : '"';
542 my $quote_char = $valid_quote_chars{$opts->{quote_char}} ? $opts->{quote_char} : '"';
544 $escape_char = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
546 my $csv = Text::CSV_XS->new({ 'binary' => 1,
547 'sep_char' => $sep_char,
548 'escape_char' => $escape_char,
549 'quote_char' => $quote_char,
552 my $stdout = wraphandle(\*STDOUT);
553 my @visible_columns = $self->get_visible_columns('CSV');
555 if ($opts->{headers}) {
556 $csv->print($stdout, [ map { $self->unescape_string($self->{columns}->{$_}->{text}) } @visible_columns ]);
559 foreach my $row_set (@{ $self->{data} }) {
560 next if ('ARRAY' ne ref $row_set);
561 foreach my $row (@{ $row_set }) {
563 foreach my $col (@visible_columns) {
564 push @data, join($eol, map { s/\r?\n/$eol/g; $_ } @{ $row->{$col}->{data} });
566 $csv->print($stdout, \@data);