No need to utf8 encode, this breaks xls file
[manu/RT-Extension-SearchResults-XLS.git] / html / Search / Results.xls
index 9951a77..785092e 100644 (file)
@@ -1,40 +1,40 @@
 %# BEGIN BPS TAGGED BLOCK {{{
-%# 
+%#
 %# COPYRIGHT:
-%# 
-%# This software is Copyright (c) 1996-2008 Best Practical Solutions, LLC
-%#                                          <jesse@bestpractical.com>
-%# 
+%#
+%# This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
+%#                                          <sales@bestpractical.com>
+%#
 %# (Except where explicitly superseded by other copyright notices)
-%# 
-%# 
+%#
+%#
 %# LICENSE:
-%# 
+%#
 %# This work is made available to you under the terms of Version 2 of
 %# the GNU General Public License. A copy of that license should have
 %# been provided with this software, but in any event can be snarfed
 %# from www.gnu.org.
-%# 
+%#
 %# This work is distributed in the hope that it will be useful, but
 %# WITHOUT ANY WARRANTY; without even the implied warranty of
 %# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 %# General Public License for more details.
-%# 
+%#
 %# You should have received a copy of the GNU General Public License
 %# along with this program; if not, write to the Free Software
 %# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 %# 02110-1301 or visit their web page on the internet at
 %# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
-%# 
-%# 
+%#
+%#
 %# CONTRIBUTION SUBMISSION POLICY:
-%# 
+%#
 %# (The following paragraph is not intended to limit the rights granted
 %# to you to modify and distribute this software under the terms of
 %# the GNU General Public License and is only of importance to you if
 %# you choose to contribute your changes and enhancements to the
 %# community by submitting them to Best Practical Solutions, LLC.)
-%# 
+%#
 %# By intentionally submitting any modifications, corrections or
 %# derivatives to this work, or any other work intended for use with
 %# Request Tracker, to Best Practical Solutions, LLC, you confirm that
 %# royalty-free, perpetual, license to use, copy, create derivative
 %# works based on those contributions, and sublicense and distribute
 %# those contributions and any derivatives thereof.
-%# 
+%#
 %# END BPS TAGGED BLOCK }}}
 <%ARGS>
+$Format => undef
+$Query => ''
 $OrderBy => 'id'
 $Order => 'ASC'
+$PreserveNewLines => 0
 </%ARGS>
+<%ONCE>
+my $no_html = HTML::Scrubber->new( deny => '*' );
+</%ONCE>
 <%INIT>
+require HTML::Entities;
 
 use Spreadsheet::WriteExcel;
 my $xls;
@@ -58,83 +65,91 @@ open ($fh, ">",  \$xls) or die "$!";
 my $workbook = Spreadsheet::WriteExcel->new($fh) or die $!;
 my $worksheet = $workbook->add_worksheet();
 
-my $Tickets = RT::Tickets->new( $session{'CurrentUser'} );
-$Tickets->FromSQL( $ARGS{'Query'} );
-if ( $OrderBy =~ /\|/ ) {
 
-  # Multiple Sorts
-  my @OrderBy = split /\|/, $OrderBy;
-  my @Order   = split /\|/, $Order;
-  $Tickets->OrderByCols(
-    map { { FIELD => $OrderBy[$_], ORDER => $Order[$_] } }
-      ( 0 .. $#OrderBy ) );
-}
-else {
-  $Tickets->OrderBy( FIELD => $OrderBy, ORDER => $Order );
-}
+$r->content_type('application/vnd.ms-excel');
 
-my @rows;
-my %known_cfs;
+my $DisplayFormat = $m->comp('/Elements/ScrubHTML', Content => $Format);
 
-my @attrs = qw( id QueueObj->Name Subject Status TimeEstimated TimeWorked TimeLeft Priority FinalPriority OwnerObj->Name 
-                Requestors->MemberEmailAddressesAsString Cc->MemberEmailAddressesAsString AdminCc->MemberEmailAddressesAsString
-                DueObj->ISO ToldObj->ISO CreatedObj->ISO ResolvedObj->ISO LastUpdatedObj->ISO);
+my @Format = $m->comp('/Elements/CollectionAsTable/ParseFormat', Format => $DisplayFormat);
 
-$r->content_type('application/vnd.ms-excel');
-while ( my $Ticket = $Tickets->Next()) {
-    my $row;
-    foreach my $attr (@attrs) {
-        if ($attr =~ /(.*)->ISO$/ and $Ticket->$1->Unix <= 0) {
-            $row->{$attr} = "";
-        } else {
-            my $method = '$Ticket->'.$attr.'()';
-            $method =~ s/->ISO\(\)$/->ISO( Timezone => 'user' )/;
-            $row->{$attr} = eval $method;
-            if ($@) {die "Failed to find $attr - ". $@}; 
-        }
+my @columns;
+
+my $should_loc = { map { $_ => 1 } qw(Status) };
+
+my $col_entry = sub {
+    my $col = shift;
+    # in tsv output, "#" is often a comment character but we use it for "id"
+    delete $col->{title}
+        if $col->{title} and $col->{title} =~ /^\s*#\s*$/;
+    return {
+        header => loc($col->{title} || $col->{attribute}),
+        map    => $m->comp(
+            "/Elements/ColumnMap",
+            Name  => $col->{attribute},
+            Attr  => 'value'
+        ),
+        should_loc => $should_loc->{$col->{attribute}},
     }
+};
 
-    my $cfs = $Ticket->QueueObj->TicketCustomFields();
-    while (my $cf = $cfs->Next) {
-        $known_cfs{$cf->Id} = $cf->Name;
-        my @content;
-        my $values = $Ticket->CustomFieldValues($cf->Id);
-        while (my $value = $values->Next) {
-            push @content, $value->Content;
+if ($PreserveNewLines) {
+    my $col = [];
+    push @columns, $col;
+    for (@Format) {
+        if ($_->{title} eq 'NEWLINE') {
+            $col = [];
+            push @columns, $col;
+        }
+        else {
+            push @$col, $col_entry->($_);
         }
-        $row->{'CustomField-'.$cf->Id} = join(', ',@content);
     }
-    push @rows, $row;
+}
+else {
+    push @columns, [map { $_->{attribute}
+                          ? $col_entry->($_)
+                          : () } @Format];
 }
 
-{ 
-    my @header;
-    my $ws_col = 0;
-    foreach my $attr (@attrs) {
-        my $label = $attr;
-        $label =~ s'Obj-.(?:AsString|Name|ISO)''g;
-        $label =~ s'-\>MemberEmailAddressesAsString''g;
-        $worksheet->write(0, $ws_col, $label);
-        $ws_col++;
-    }
-    foreach my $id (sort keys %known_cfs) {
-        $worksheet->write(0, $ws_col, "CF-".$known_cfs{$id});
+my $ws_col = 0;
+for (@columns) {
+    foreach my $ws_val (map { $_->{header} } @$_) {
+        $worksheet->write_string(0, $ws_col, $ws_val);
         $ws_col++;
     }
 }
 
+my $Tickets = RT::Tickets->new( $session{'CurrentUser'} );
+$Tickets->FromSQL( $Query );
+if ( $OrderBy =~ /\|/ ) {
+    # Multiple Sorts
+    my @OrderBy = split /\|/, $OrderBy;
+    my @Order   = split /\|/, $Order;
+    $Tickets->OrderByCols(
+        map { { FIELD => $OrderBy[$_], ORDER => $Order[$_] } }
+        ( 0 .. $#OrderBy )
+    );
+}
+else {
+    $Tickets->OrderBy( FIELD => $OrderBy, ORDER => $Order );
+}
+
 my $ws_row = 1;
-foreach my $row (@rows) {
-    my $ws_col = 0;
-    my @row;
-    foreach my $attr(@attrs) {
-        $worksheet->write($ws_row, $ws_col, $row->{"$attr"});
-        $ws_col++;
-    }
-    foreach my $id (sort keys %known_cfs) {
-        my $val = $row->{'CustomField-'.$id};
-        $worksheet->write($ws_row, $ws_col, $val);
-        $ws_col++;
+my $ii = 0;
+while (my $row = $Tickets->Next) {
+    $ws_col = 0;
+    for my $col (@columns) {
+        for (@$col) {
+            my $val = ProcessColumnMapValue($_->{map}, Arguments => [$row, $ii++], Escape => 0);
+            $val = loc($val) if $_->{should_loc};
+            # remove tabs from all field values, they screw up the tsv
+            $val = '' unless defined $val;
+            $val =~ s/(?:\n|\r)//g; $val =~ s{\t}{    }g;
+            $val = $no_html->scrub($val);
+            $val = HTML::Entities::decode_entities($val);
+            $worksheet->write_string($ws_row, $ws_col, $val);
+            $ws_col++;
+        }
     }
     $ws_row++;
 }
@@ -143,4 +158,5 @@ $workbook->close;
 close($fh);
 $m->print($xls);
 $m->abort();
+
 </%INIT>