1 package SL::ReportGenerator;
4 use List::Util qw(max);
10 # Cause locales.pl to parse these files:
11 # parse_html_template('report_generator/html_report')
12 # parse_html_template('report_generator/pdf_report')
19 $self->{myconfig} = shift;
20 $self->{form} = shift;
24 'std_column_visibility' => 0,
25 'output_format' => 'HTML',
26 'allow_pdf_export' => 1,
27 'allow_csv_export' => 1,
28 'html_template' => 'report_generator/html_report',
29 'pdf_template' => 'report_generator/pdf_report',
32 'orientation' => 'landscape',
36 'margin_bottom' => 1.5,
37 'margin_right' => 1.5,
47 'eol_style' => 'Unix',
53 'variable_list' => [],
56 $self->{data_present} = 0;
60 $self->set_options(@_) if (@_);
62 $self->_init_escaped_strings_map();
67 sub _init_escaped_strings_map {
70 $self->{escaped_strings_map} = {
83 my $iconv = $main::locale->{iconv_iso8859};
86 map { $self->{escaped_strings_map}->{$_} = $iconv->convert($self->{escaped_strings_map}->{$_}) } keys %{ $self->{escaped_strings_map} };
94 $self->{columns} = \%columns;
96 foreach my $column (values %{ $self->{columns} }) {
97 $column->{visible} = $self->{options}->{std_column_visibility} unless defined $column->{visible};
100 $self->set_column_order(sort keys %{ $self->{columns} });
103 sub set_column_order {
107 my %columns = map { $order++; ($_, $order) } @_;
109 foreach my $column (sort keys %{ $self->{columns} }) {
110 next if $columns{$column};
113 $columns{$column} = $order;
116 $self->{column_order} = [ sort { $columns{$a} <=> $columns{$b} } keys %columns ];
119 sub set_sort_indicator {
122 $self->{options}->{sort_indicator_column} = shift;
123 $self->{options}->{sort_indicator_direction} = shift;
131 while (my $arg = shift) {
134 if ('ARRAY' eq ref $arg) {
137 } elsif ('HASH' eq ref $arg) {
141 $self->{form}->error('Incorrect usage -- expecting hash or array ref');
144 my @columns_with_default_alignment = grep { defined $self->{columns}->{$_}->{align} } keys %{ $self->{columns} };
146 foreach my $row (@{ $row_set }) {
147 foreach my $column (@columns_with_default_alignment) {
148 $row->{$column} ||= { };
149 $row->{$column}->{align} = $self->{columns}->{$column}->{align} unless (defined $row->{$column}->{align});
152 foreach my $field (qw(data link)) {
153 map { $row->{$_}->{$field} = [ $row->{$_}->{$field} ] if (ref $row->{$_}->{$field} ne 'ARRAY') } keys %{ $row };
157 push @{ $self->{data} }, $row_set;
158 $last_row_set = $row_set;
160 $self->{data_present} = 1;
163 return $last_row_set;
169 push @{ $self->{data} }, { 'type' => 'separator' };
176 push @{ $self->{data} }, $data;
183 $self->{data_present} = 0;
190 map { $self->{options}->{$_} = $options{$_} } keys %options;
193 sub set_options_from_form {
196 my $form = $self->{form};
197 my $myconfig = $self->{myconfig};
199 foreach my $key (qw(output_format)) {
200 my $full_key = "report_generator_${key}";
201 $self->{options}->{$key} = $form->{$full_key} if (defined $form->{$full_key});
204 foreach my $format (qw(pdf csv)) {
205 my $opts = $self->{options}->{"${format}_export"};
206 foreach my $key (keys %{ $opts }) {
207 my $full_key = "report_generator_${format}_options_${key}";
208 $opts->{$key} = $key =~ /^margin/ ? $form->parse_amount($myconfig, $form->{$full_key}) : $form->{$full_key};
213 sub set_export_options {
218 'variable_list' => [ @_ ],
222 sub get_attachment_basename {
224 my $filename = $self->{options}->{attachment_basename} || 'report';
225 $filename =~ s|.*\\||;
226 $filename =~ s|.*/||;
231 sub generate_with_headers {
233 my $format = lc $self->{options}->{output_format};
234 my $form = $self->{form};
236 if (!$self->{columns}) {
237 $form->error('Incorrect usage -- no columns specified');
240 if ($format eq 'html') {
241 my $title = $form->{title};
242 $form->{title} = $self->{title} if ($self->{title});
244 $form->{title} = $title;
246 print $self->generate_html_content();
248 } elsif ($format eq 'csv') {
249 my $filename = $self->get_attachment_basename();
250 print qq|content-type: text/csv\n|;
251 print qq|content-disposition: attachment; filename=${filename}.csv\n\n|;
252 $self->generate_csv_content();
254 } elsif ($format eq 'pdf') {
255 $self->generate_pdf_content();
258 $form->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
262 sub get_visible_columns {
266 return grep { my $c = $self->{columns}->{$_}; $c && $c->{visible} && (($c->{visible} == 1) || ($c->{visible} =~ /\Q${format}\E/i)) } @{ $self->{column_order} };
273 $value = $self->{form}->quote_html($value);
275 $value =~ s/\n/<br>/g;
280 sub prepare_html_content {
283 my ($column, $name, @column_headers);
285 my $opts = $self->{options};
286 my @visible_columns = $self->get_visible_columns('HTML');
288 foreach $name (@visible_columns) {
289 $column = $self->{columns}->{$name};
293 'link' => $column->{link},
294 'text' => $column->{text},
295 'show_sort_indicator' => $name eq $opts->{sort_indicator_column},
296 'sort_indicator_direction' => $opts->{sort_indicator_direction},
299 push @column_headers, $header;
302 my ($outer_idx, $inner_idx) = (0, 0);
306 foreach my $row_set (@{ $self->{data} }) {
307 if ('HASH' eq ref $row_set) {
308 if ($row_set->{type} eq 'separator') {
309 if (! scalar @rows) {
310 $next_border_top = 1;
312 $rows[-1]->{BORDER_BOTTOM} = 1;
320 'IS_COLSPAN_DATA' => $row_set->{type} eq 'colspan_data',
321 'NUM_COLUMNS' => scalar @visible_columns,
322 'BORDER_TOP' => $next_border_top,
323 'data' => $row_set->{data},
326 push @rows, $row_data;
328 $next_border_top = 0;
335 foreach my $row (@{ $row_set }) {
338 foreach my $col_name (@visible_columns) {
339 my $col = $row->{$col_name};
340 $col->{CELL_ROWS} = [ ];
341 foreach my $i (0 .. scalar(@{ $col->{data} }) - 1) {
342 push @{ $col->{CELL_ROWS} }, {
343 'data' => $self->html_format($col->{data}->[$i]),
344 'link' => $col->{link}->[$i],
348 # Force at least a to be displayed so that browsers
349 # will format the table cell (e.g. borders etc).
350 if (!scalar @{ $col->{CELL_ROWS} }) {
351 push @{ $col->{CELL_ROWS} }, { 'data' => ' ' };
352 } elsif ((1 == scalar @{ $col->{CELL_ROWS} }) && (!defined $col->{CELL_ROWS}->[0]->{data} || ($col->{CELL_ROWS}->[0]->{data} eq ''))) {
353 $col->{CELL_ROWS}->[0]->{data} = ' ';
358 'COLUMNS' => [ map { $row->{$_} } @visible_columns ],
359 'outer_idx' => $outer_idx,
360 'outer_idx_odd' => $outer_idx % 2,
361 'inner_idx' => $inner_idx,
362 'BORDER_TOP' => $next_border_top,
365 push @rows, $row_data;
367 $next_border_top = 0;
371 my @export_variables = $self->{form}->flatten_variables(@{ $self->{export}->{variable_list} });
373 my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
376 'TITLE' => $opts->{title},
377 'TOP_INFO_TEXT' => $self->html_format($opts->{top_info_text}),
378 'RAW_TOP_INFO_TEXT' => $opts->{raw_top_info_text},
379 'BOTTOM_INFO_TEXT' => $self->html_format($opts->{bottom_info_text}),
380 'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
381 'ALLOW_PDF_EXPORT' => $allow_pdf_export,
382 'ALLOW_CSV_EXPORT' => $opts->{allow_csv_export},
383 'SHOW_EXPORT_BUTTONS' => ($allow_pdf_export || $opts->{allow_csv_export}) && $self->{data_present},
384 'COLUMN_HEADERS' => \@column_headers,
385 'NUM_COLUMNS' => scalar @column_headers,
387 'EXPORT_VARIABLES' => \@export_variables,
388 'EXPORT_VARIABLE_LIST' => join(' ', @{ $self->{export}->{variable_list} }),
389 'EXPORT_NEXTSUB' => $self->{export}->{nextsub},
390 'DATA_PRESENT' => $self->{data_present},
396 sub generate_html_content {
398 my $variables = $self->prepare_html_content();
400 return $self->{form}->parse_html_template($self->{options}->{html_template}, $variables);
403 sub verify_paper_size {
405 my $requested_paper_size = lc shift;
406 my $default_paper_size = shift;
408 my %allowed_paper_sizes = map { $_ => 1 } qw(a3 a4 letter legal);
410 return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
413 sub generate_pdf_content {
415 my $variables = $self->prepare_html_content();
416 my $form = $self->{form};
417 my $myconfig = $self->{myconfig};
418 my $opt = $self->{options}->{pdf_export};
420 my $opt_number = $opt->{number} ? 'number : 1' : '';
421 my $opt_landscape = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
423 my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
425 my $html2ps_config = <<"END"
435 type: ${opt_paper_size};
441 margin-top: $opt->{margin_top}cm;
442 margin-left: $opt->{margin_left}cm;
443 margin-bottom: $opt->{margin_bottom}cm;
444 margin-right: $opt->{margin_right}cm;
448 font-family: Helvetica;
449 font-size: $opt->{font_size}pt;
456 if ($opt->{print} && $opt->{printer_id}) {
457 $form->{printer_id} = $opt->{printer_id};
458 $form->get_printer_code($myconfig);
459 $printer_command = $form->{printer_command};
462 my $cfg_file_name = Common::tmpname() . '-html2ps-config';
463 my $cfg_file = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
465 $cfg_file->print($html2ps_config);
468 my $html_file_name = Common::tmpname() . '.html';
469 my $html_file = IO::File->new($html_file_name, 'w');
472 unlink $cfg_file_name;
473 $form->error($locale->text('Could not write the temporary HTML file.'));
476 $html_file->print($form->parse_html_template($self->{options}->{pdf_template}, $variables));
480 "\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
481 "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite -";
483 my $gs = IO::File->new("${cmdline} |");
487 if (!$printer_command) {
488 my $filename = $self->get_attachment_basename();
489 print qq|content-type: application/pdf\n|;
490 print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
492 while (my $line = <$gs>) {
497 while (my $line = <$gs>) {
503 unlink $cfg_file_name, $html_file_name;
505 if ($printer_command && $content) {
506 foreach my $i (1 .. max $opt->{copies}, 1) {
507 my $printer = IO::File->new("| ${printer_command}");
509 $form->error($locale->text('Could not spawn the printer command.'));
511 $printer->print($content);
515 $form->{report_generator_printed} = 1;
519 unlink $cfg_file_name, $html_file_name;
520 $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
524 sub unescape_string {
528 foreach my $key (keys %{ $self->{escaped_strings_map} }) {
529 $text =~ s/\Q$key\E/$self->{escaped_strings_map}->{$key}/g;
532 $text =~ s/\Q&\E/&/g;
537 sub generate_csv_content {
540 my %valid_sep_chars = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
541 my %valid_escape_chars = ('"' => 1, "'" => 1);
542 my %valid_quote_chars = ('"' => 1, "'" => 1);
544 my $opts = $self->{options}->{csv_export};
545 my $eol = $opts->{eol_style} eq 'DOS' ? "\r\n" : "\n";
546 my $sep_char = $valid_sep_chars{$opts->{sep_char}} ? $valid_sep_chars{$opts->{sep_char}} : ';';
547 my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char} : '"';
548 my $quote_char = $valid_quote_chars{$opts->{quote_char}} ? $opts->{quote_char} : '"';
550 $escape_char = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
552 my $csv = Text::CSV_XS->new({ 'binary' => 1,
553 'sep_char' => $sep_char,
554 'escape_char' => $escape_char,
555 'quote_char' => $quote_char,
558 my $stdout = wraphandle(\*STDOUT);
559 my @visible_columns = $self->get_visible_columns('CSV');
561 if ($opts->{headers}) {
562 $csv->print($stdout, [ map { $self->unescape_string($self->{columns}->{$_}->{text}) } @visible_columns ]);
565 foreach my $row_set (@{ $self->{data} }) {
566 next if ('ARRAY' ne ref $row_set);
567 foreach my $row (@{ $row_set }) {
569 foreach my $col (@visible_columns) {
570 push @data, join($eol, map { s/\r?\n/$eol/g; $_ } @{ $row->{$col}->{data} });
572 $csv->print($stdout, \@data);