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',
33 'font_name' => 'Verdana',
37 'margin_bottom' => 1.5,
38 'margin_right' => 1.5,
48 'eol_style' => 'Unix',
54 'variable_list' => [],
57 $self->{data_present} = 0;
61 $self->set_options(@_) if (@_);
63 $self->_init_escaped_strings_map();
68 sub _init_escaped_strings_map {
71 $self->{escaped_strings_map} = {
84 my $iconv = $main::locale->{iconv_iso8859};
87 map { $self->{escaped_strings_map}->{$_} = $iconv->convert($self->{escaped_strings_map}->{$_}) } keys %{ $self->{escaped_strings_map} };
95 $self->{columns} = \%columns;
97 foreach my $column (values %{ $self->{columns} }) {
98 $column->{visible} = $self->{options}->{std_column_visibility} unless defined $column->{visible};
101 $self->set_column_order(sort keys %{ $self->{columns} });
104 sub set_column_order {
108 my %columns = map { $order++; ($_, $order) } @_;
110 foreach my $column (sort keys %{ $self->{columns} }) {
111 next if $columns{$column};
114 $columns{$column} = $order;
117 $self->{column_order} = [ sort { $columns{$a} <=> $columns{$b} } keys %columns ];
120 sub set_sort_indicator {
123 $self->{options}->{sort_indicator_column} = shift;
124 $self->{options}->{sort_indicator_direction} = shift;
132 while (my $arg = shift) {
135 if ('ARRAY' eq ref $arg) {
138 } elsif ('HASH' eq ref $arg) {
142 $self->{form}->error('Incorrect usage -- expecting hash or array ref');
145 my @columns_with_default_alignment = grep { defined $self->{columns}->{$_}->{align} } keys %{ $self->{columns} };
147 foreach my $row (@{ $row_set }) {
148 foreach my $column (@columns_with_default_alignment) {
149 $row->{$column} ||= { };
150 $row->{$column}->{align} = $self->{columns}->{$column}->{align} unless (defined $row->{$column}->{align});
153 foreach my $field (qw(data link)) {
154 map { $row->{$_}->{$field} = [ $row->{$_}->{$field} ] if (ref $row->{$_}->{$field} ne 'ARRAY') } keys %{ $row };
158 push @{ $self->{data} }, $row_set;
159 $last_row_set = $row_set;
161 $self->{data_present} = 1;
164 return $last_row_set;
170 push @{ $self->{data} }, { 'type' => 'separator' };
177 push @{ $self->{data} }, $data;
184 $self->{data_present} = 0;
191 while (my ($key, $value) = each %options) {
192 if ($key eq 'pdf_export') {
193 map { $self->{options}->{pdf_export}->{$_} = $value->{$_} } keys %{ $value };
195 $self->{options}->{$key} = $value;
200 sub set_options_from_form {
203 my $form = $self->{form};
204 my $myconfig = $self->{myconfig};
206 foreach my $key (qw(output_format)) {
207 my $full_key = "report_generator_${key}";
208 $self->{options}->{$key} = $form->{$full_key} if (defined $form->{$full_key});
211 foreach my $format (qw(pdf csv)) {
212 my $opts = $self->{options}->{"${format}_export"};
213 foreach my $key (keys %{ $opts }) {
214 my $full_key = "report_generator_${format}_options_${key}";
215 $opts->{$key} = $key =~ /^margin/ ? $form->parse_amount($myconfig, $form->{$full_key}) : $form->{$full_key};
220 sub set_export_options {
225 'variable_list' => [ @_ ],
229 sub get_attachment_basename {
231 my $filename = $self->{options}->{attachment_basename} || 'report';
232 $filename =~ s|.*\\||;
233 $filename =~ s|.*/||;
238 sub generate_with_headers {
240 my $format = lc $self->{options}->{output_format};
241 my $form = $self->{form};
243 if (!$self->{columns}) {
244 $form->error('Incorrect usage -- no columns specified');
247 if ($format eq 'html') {
248 my $title = $form->{title};
249 $form->{title} = $self->{title} if ($self->{title});
251 $form->{title} = $title;
253 print $self->generate_html_content();
255 } elsif ($format eq 'csv') {
256 my $filename = $self->get_attachment_basename();
257 print qq|content-type: text/csv\n|;
258 print qq|content-disposition: attachment; filename=${filename}.csv\n\n|;
259 $self->generate_csv_content();
261 } elsif ($format eq 'pdf') {
262 $self->generate_pdf_content();
265 $form->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
269 sub get_visible_columns {
273 return grep { my $c = $self->{columns}->{$_}; $c && $c->{visible} && (($c->{visible} == 1) || ($c->{visible} =~ /\Q${format}\E/i)) } @{ $self->{column_order} };
280 $value = $self->{form}->quote_html($value);
282 $value =~ s/\n/<br>/g;
287 sub prepare_html_content {
290 my ($column, $name, @column_headers);
292 my $opts = $self->{options};
293 my @visible_columns = $self->get_visible_columns('HTML');
295 foreach $name (@visible_columns) {
296 $column = $self->{columns}->{$name};
300 'link' => $column->{link},
301 'text' => $column->{text},
302 'show_sort_indicator' => $name eq $opts->{sort_indicator_column},
303 'sort_indicator_direction' => $opts->{sort_indicator_direction},
306 push @column_headers, $header;
309 my ($outer_idx, $inner_idx) = (0, 0);
313 foreach my $row_set (@{ $self->{data} }) {
314 if ('HASH' eq ref $row_set) {
315 if ($row_set->{type} eq 'separator') {
316 if (! scalar @rows) {
317 $next_border_top = 1;
319 $rows[-1]->{BORDER_BOTTOM} = 1;
327 'IS_COLSPAN_DATA' => $row_set->{type} eq 'colspan_data',
328 'NUM_COLUMNS' => scalar @visible_columns,
329 'BORDER_TOP' => $next_border_top,
330 'data' => $row_set->{data},
333 push @rows, $row_data;
335 $next_border_top = 0;
342 foreach my $row (@{ $row_set }) {
345 foreach my $col_name (@visible_columns) {
346 my $col = $row->{$col_name};
347 $col->{CELL_ROWS} = [ ];
348 foreach my $i (0 .. scalar(@{ $col->{data} }) - 1) {
349 push @{ $col->{CELL_ROWS} }, {
350 'data' => $self->html_format($col->{data}->[$i]),
351 'link' => $col->{link}->[$i],
355 # Force at least a to be displayed so that browsers
356 # will format the table cell (e.g. borders etc).
357 if (!scalar @{ $col->{CELL_ROWS} }) {
358 push @{ $col->{CELL_ROWS} }, { 'data' => ' ' };
359 } elsif ((1 == scalar @{ $col->{CELL_ROWS} }) && (!defined $col->{CELL_ROWS}->[0]->{data} || ($col->{CELL_ROWS}->[0]->{data} eq ''))) {
360 $col->{CELL_ROWS}->[0]->{data} = ' ';
365 'COLUMNS' => [ map { $row->{$_} } @visible_columns ],
366 'outer_idx' => $outer_idx,
367 'outer_idx_odd' => $outer_idx % 2,
368 'inner_idx' => $inner_idx,
369 'BORDER_TOP' => $next_border_top,
372 push @rows, $row_data;
374 $next_border_top = 0;
378 my @export_variables = $self->{form}->flatten_variables(@{ $self->{export}->{variable_list} });
380 my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
382 eval { require PDF::API2; require PDF::Table; };
383 $allow_pdf_export |= 1 if (! $@);
386 'TITLE' => $opts->{title},
387 'TOP_INFO_TEXT' => $self->html_format($opts->{top_info_text}),
388 'RAW_TOP_INFO_TEXT' => $opts->{raw_top_info_text},
389 'BOTTOM_INFO_TEXT' => $self->html_format($opts->{bottom_info_text}),
390 'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
391 'ALLOW_PDF_EXPORT' => $allow_pdf_export,
392 'ALLOW_CSV_EXPORT' => $opts->{allow_csv_export},
393 'SHOW_EXPORT_BUTTONS' => ($allow_pdf_export || $opts->{allow_csv_export}) && $self->{data_present},
394 'COLUMN_HEADERS' => \@column_headers,
395 'NUM_COLUMNS' => scalar @column_headers,
397 'EXPORT_VARIABLES' => \@export_variables,
398 'EXPORT_VARIABLE_LIST' => join(' ', @{ $self->{export}->{variable_list} }),
399 'EXPORT_NEXTSUB' => $self->{export}->{nextsub},
400 'DATA_PRESENT' => $self->{data_present},
406 sub generate_html_content {
408 my $variables = $self->prepare_html_content();
410 return $self->{form}->parse_html_template($self->{options}->{html_template}, $variables);
416 return $_[0] * 72 / 2.54;
419 sub render_pdf_with_pdf_api2 {
421 my $variables = $self->prepare_html_content();
422 my $form = $self->{form};
423 my $myconfig = $self->{myconfig};
425 my $opts = $self->{options};
426 my $pdfopts = $opts->{pdf_export};
428 my (@data, @column_props, @cell_props);
431 my $cell_props_row = [];
432 my @visible_columns = $self->get_visible_columns('HTML');
434 foreach $name (@visible_columns) {
435 $column = $self->{columns}->{$name};
437 push @{ $data_row }, $column->{text};
438 push @{ $cell_props_row }, {};
439 push @column_props, { 'justify' => $column->{align} eq 'right' ? 'right' : 'left' };
442 push @data, $data_row;
443 push @cell_props, $cell_props_row;
445 my $num_columns = scalar @column_props;
447 foreach my $row_set (@{ $self->{data} }) {
448 if ('HASH' eq ref $row_set) {
449 if ($row_set->{type} eq 'colspan_data') {
450 push @data, [ $row_set->{data} ];
452 $cell_props_row = [];
453 push @cell_props, $cell_props_row;
455 foreach (0 .. $num_columns - 1) {
456 push @{ $cell_props_row }, { 'background_color' => '#000000',
457 'font_color' => '#ffffff', };
463 foreach my $row (@{ $row_set }) {
465 push @data, $data_row;
468 foreach my $col_name (@visible_columns) {
469 my $col = $row->{$col_name};
470 push @{ $data_row }, join("\n", @{ $col->{data} });
472 $column_props[$col_idx]->{justify} = 'right' if ($col->{align} eq 'right');
477 $cell_props_row = [];
478 push @cell_props, $cell_props_row;
480 foreach (0 .. $num_columns - 1) {
481 push @{ $cell_props_row }, { };
486 foreach my $i (0 .. scalar(@data) - 1) {
487 my $aref = $data[$i];
488 my $num_columns_here = scalar @{ $aref };
490 if ($num_columns_here < $num_columns) {
491 push @{ $aref }, ('') x ($num_columns - $num_columns_here);
492 } elsif ($num_columns_here > $num_columns) {
493 splice @{ $aref }, $num_columns;
498 'a3' => [ 842, 1190 ],
499 'a4' => [ 595, 842 ],
500 'a5' => [ 420, 595 ],
501 'letter' => [ 612, 792 ],
502 'legal' => [ 612, 1008 ],
505 my %supported_fonts = map { $_ => 1 } qw(courier georgia helvetica times verdana);
507 my $paper_size = defined $pdfopts->{paper_size} && defined $papersizes->{lc $pdfopts->{paper_size}} ? lc $pdfopts->{paper_size} : 'a4';
508 my ($paper_width, $paper_height);
510 if (lc $pdfopts->{orientation} eq 'landscape') {
511 ($paper_width, $paper_height) = @{$papersizes->{$paper_size}}[1, 0];
513 ($paper_width, $paper_height) = @{$papersizes->{$paper_size}}[0, 1];
516 my $margin_top = _cm2bp($pdfopts->{margin_top} || 1.5);
517 my $margin_bottom = _cm2bp($pdfopts->{margin_bottom} || 1.5);
518 my $margin_left = _cm2bp($pdfopts->{margin_left} || 1.5);
519 my $margin_right = _cm2bp($pdfopts->{margin_right} || 1.5);
521 my $table = PDF::Table->new();
522 my $pdf = PDF::API2->new();
523 my $page = $pdf->page();
525 $pdf->mediabox($paper_width, $paper_height);
527 my $font = $pdf->corefont(defined $pdfopts->{font_name} && $supported_fonts{lc $pdfopts->{font_name}} ? ucfirst $pdfopts->{font_name} : 'Verdana',
528 '-encoding' => $main::dbcharset || 'ISO-8859-15');
529 my $font_size = $pdfopts->{font_size} || 7;
530 my $title_font_size = $font_size + 1;
532 my $font_height = $font_size + 2 * $padding;
533 my $title_font_height = $font_size + 2 * $padding;
535 my $header_height = 2 * $title_font_height if ($opts->{title});
536 my $footer_height = 2 * $font_height if ($pdfopts->{number});
538 my $top_text_height = 0;
540 if ($self->{options}->{top_info_text}) {
541 my $top_text = $self->{options}->{top_info_text};
542 $top_text =~ s/\r//g;
543 $top_text =~ s/\n+$//;
545 my @lines = split m/\n/, $top_text;
546 $top_text_height = $font_height * scalar @lines;
548 foreach my $line_no (0 .. scalar(@lines) - 1) {
549 my $y_pos = $paper_height - $margin_top - $header_height - $line_no * $font_height;
550 my $text_obj = $page->text();
552 $text_obj->font($font, $font_size);
553 $text_obj->translate($margin_left, $y_pos);
554 $text_obj->text($lines[$line_no]);
562 'w' => $paper_width - $margin_left - $margin_right,
563 'start_y' => $paper_height - $margin_top - $header_height - $top_text_height,
564 'next_y' => $paper_height - $margin_top - $header_height,
565 'start_h' => $paper_height - $margin_top - $margin_bottom - $header_height - $footer_height - $top_text_height,
566 'next_h' => $paper_height - $margin_top - $margin_bottom - $header_height - $footer_height,
568 'background_color_odd' => '#ffffff',
569 'background_color_even' => '#eeeeee',
571 'font_size' => $font_size,
572 'font_color' => '#000000',
574 'bg_color' => '#ffffff',
576 'font_color' => '#000000',
578 'column_props' => \@column_props,
579 'cell_props' => \@cell_props,
582 foreach my $page_num (1..$pdf->pages()) {
583 my $curpage = $pdf->openpage($page_num);
585 if ($pdfopts->{number}) {
586 my $label = $main::locale->text("Page #1/#2", $page_num, $pdf->pages());
587 my $text_obj = $curpage->text();
589 $text_obj->font($font, $font_size);
590 $text_obj->translate(($paper_width - $margin_left - $margin_right) / 2 + $margin_left - $text_obj->advancewidth($label) / 2, $margin_bottom);
591 $text_obj->text($label);
594 if ($opts->{title}) {
595 my $text_obj = $curpage->text();
597 $text_obj->font($font, $title_font_size);
598 $text_obj->translate(($paper_width - $margin_left - $margin_right) / 2 + $margin_left - $text_obj->advancewidth($opts->{title}) / 2,
599 $paper_height - $margin_top);
600 $text_obj->text($opts->{title}, '-underline' => 1);
604 my $content = $pdf->stringify();
607 if ($pdfopts->{print} && $pdfopts->{printer_id}) {
608 $form->{printer_id} = $pdfopts->{printer_id};
609 $form->get_printer_code($myconfig);
610 $printer_command = $form->{printer_command};
613 if ($printer_command) {
614 $self->_print_content('printer_command' => $printer_command,
615 'content' => $content,
616 'copies' => $pdfopts->{copies});
617 $form->{report_generator_printed} = 1;
620 my $filename = $self->get_attachment_basename();
622 print qq|content-type: application/pdf\n|;
623 print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
629 sub verify_paper_size {
631 my $requested_paper_size = lc shift;
632 my $default_paper_size = shift;
634 my %allowed_paper_sizes = map { $_ => 1 } qw(a3 a4 a5 letter legal);
636 return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
639 sub render_pdf_with_html2ps {
641 my $variables = $self->prepare_html_content();
642 my $form = $self->{form};
643 my $myconfig = $self->{myconfig};
644 my $opt = $self->{options}->{pdf_export};
646 my $opt_number = $opt->{number} ? 'number : 1' : '';
647 my $opt_landscape = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
649 my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
651 my $html2ps_config = <<"END"
661 type: ${opt_paper_size};
667 margin-top: $opt->{margin_top}cm;
668 margin-left: $opt->{margin_left}cm;
669 margin-bottom: $opt->{margin_bottom}cm;
670 margin-right: $opt->{margin_right}cm;
674 font-family: Helvetica;
675 font-size: $opt->{font_size}pt;
682 if ($opt->{print} && $opt->{printer_id}) {
683 $form->{printer_id} = $opt->{printer_id};
684 $form->get_printer_code($myconfig);
685 $printer_command = $form->{printer_command};
688 my $cfg_file_name = Common::tmpname() . '-html2ps-config';
689 my $cfg_file = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
691 $cfg_file->print($html2ps_config);
694 my $html_file_name = Common::tmpname() . '.html';
695 my $html_file = IO::File->new($html_file_name, 'w');
698 unlink $cfg_file_name;
699 $form->error($locale->text('Could not write the temporary HTML file.'));
702 $html_file->print($form->parse_html_template($self->{options}->{pdf_template}, $variables));
706 "\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
707 "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite -";
709 my $gs = IO::File->new("${cmdline} |");
713 if (!$printer_command) {
714 my $filename = $self->get_attachment_basename();
715 print qq|content-type: application/pdf\n|;
716 print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
718 while (my $line = <$gs>) {
723 while (my $line = <$gs>) {
729 unlink $cfg_file_name, $html_file_name;
731 if ($printer_command && $content) {
732 $self->_print_content('printer_command' => $printer_command,
733 'content' => $content,
734 'copies' => $opt->{copies});
735 $form->{report_generator_printed} = 1;
739 unlink $cfg_file_name, $html_file_name;
740 $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
748 foreach my $i (1 .. max $params{copies}, 1) {
749 my $printer = IO::File->new("| $params{printer_command}");
750 $main::form->error($main::locale->text('Could not spawn the printer command.')) if (!$printer);
751 $printer->print($params{content});
756 sub generate_pdf_content {
759 eval { require PDF::API2; require PDF::Table; };
762 return $self->render_pdf_with_html2ps(@_);
764 return $self->render_pdf_with_pdf_api2(@_);
768 sub unescape_string {
772 foreach my $key (keys %{ $self->{escaped_strings_map} }) {
773 $text =~ s/\Q$key\E/$self->{escaped_strings_map}->{$key}/g;
776 $text =~ s/\Q&\E/&/g;
781 sub generate_csv_content {
784 my %valid_sep_chars = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
785 my %valid_escape_chars = ('"' => 1, "'" => 1);
786 my %valid_quote_chars = ('"' => 1, "'" => 1);
788 my $opts = $self->{options}->{csv_export};
789 my $eol = $opts->{eol_style} eq 'DOS' ? "\r\n" : "\n";
790 my $sep_char = $valid_sep_chars{$opts->{sep_char}} ? $valid_sep_chars{$opts->{sep_char}} : ';';
791 my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char} : '"';
792 my $quote_char = $valid_quote_chars{$opts->{quote_char}} ? $opts->{quote_char} : '"';
794 $escape_char = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
796 my $csv = Text::CSV_XS->new({ 'binary' => 1,
797 'sep_char' => $sep_char,
798 'escape_char' => $escape_char,
799 'quote_char' => $quote_char,
802 my $stdout = wraphandle(\*STDOUT);
803 my @visible_columns = $self->get_visible_columns('CSV');
805 if ($opts->{headers}) {
806 $csv->print($stdout, [ map { $self->unescape_string($self->{columns}->{$_}->{text}) } @visible_columns ]);
809 foreach my $row_set (@{ $self->{data} }) {
810 next if ('ARRAY' ne ref $row_set);
811 foreach my $row (@{ $row_set }) {
813 foreach my $col (@visible_columns) {
814 push @data, join($eol, map { s/\r?\n/$eol/g; $_ } @{ $row->{$col}->{data} });
816 $csv->print($stdout, \@data);