reports.cgi 9.52 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
4 5 6 7
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
8
#
9 10 11 12
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
13 14 15 16
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
17 18 19
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
20 21
#
# Contributor(s): Harrison Page <harrison@netscape.com>,
22
# Terry Weissman <terry@mozilla.org>,
23 24
# Dawn Endico <endico@mozilla.org>
# Bryce Nesbitt <bryce@nextbus.COM>,
25
# Joe Robins <jmrobins@tgix.com>,
26 27 28 29 30 31 32
# Gervase Markham <gerv@gerv.net> and Adam Spiers <adam@spiers.net>
#    Added ability to chart any combination of resolutions/statuses.
#    Derive the choice of resolutions/statuses from the -All- data file
#    Removed hardcoded order of resolutions/statuses when reading from
#    daily stats file, so now works independently of collectstats.pl
#    version
#    Added image caching by date and datasets
33 34
# Myk Melez <myk@mozilla.org):
#    Implemented form field validation and reorganized code.
35 36

use strict;
37

38 39
use lib qw(.);

40 41
use Bugzilla::Config qw(:DEFAULT $datadir);

42
require "globals.pl";
43

44 45 46 47 48
eval "use GD";
$@ && ThrowCodeError("gd_not_installed");
eval "use Chart::Lines";
$@ && ThrowCodeError("chart_lines_not_installed");

49
my $dir = "$datadir/mining";
50
my $graph_dir = "graphs";
51

52 53
use Bugzilla;

54 55
# If we're using bug groups for products, we should apply those restrictions
# to viewing reports, as well.  Time to check the login in that case.
56
my $user = Bugzilla->login();
57

58
GetVersionTable();
59

60
Bugzilla->switch_to_shadow_db();
61

62
my $cgi = Bugzilla->cgi;
63
my $template = Bugzilla->template;
64
my $vars = {};
65

66
# We only want those products that the user has permissions for.
67
my @myproducts;
68
push( @myproducts, "-All-");
69 70
# Extract product names from objects and add them to the list.
push( @myproducts, map { $_->name } @{$user->get_selectable_products} );
71

72
if (! defined $cgi->param('product')) {
73

74
    choose_product(@myproducts);
75
    $template->put_footer();
76 77

} else {
78
    my $product = $cgi->param('product');
79 80 81 82

    # For security and correctness, validate the value of the "product" form variable.
    # Valid values are those products for which the user has permissions which appear
    # in the "product" drop-down menu on the report generation form.
83 84
    grep($_ eq $product, @myproducts)
      || ThrowUserError("invalid_product_name", {product => $product});
85

86 87
    # We've checked that the product exists, and that the user can see it
    # This means that is OK to detaint
88
    trick_taint($product);
89

90
    print $cgi->header(-Content_Disposition=>'inline; filename=bugzilla_report.html');
91

92
    $template->put_header("Bug Charts");
93
    $vars->{'header_done'} = 1;
94

95
    show_chart($product);
96

97
    $template->put_footer();
98
}
99

100

101 102 103 104
##################################
# user came in with no form data #
##################################

105
sub choose_product {
106 107
    my @myproducts = (@_);
    
108
    my $datafile = daily_stats_filename('-All-');
109

110
    # Can we do bug charts?  
111 112 113 114 115 116
    (-d $dir && -d $graph_dir) 
      || ThrowCodeError("chart_dir_nonexistent", 
                        {dir => $dir, graph_dir => $graph_dir});
      
    open(DATA, "$dir/$datafile")
      || ThrowCodeError("chart_file_open_fail", {filename => "$dir/$datafile"});
117
 
118
    print $cgi->header();
119
    $template->put_header("Bug Charts");
120
    $vars->{'header_done'} = 1;
121

122
    print <<FIN;
123
<center>
124
<h1>Welcome to the Bugzilla Charting Kitchen</h1>
125 126 127 128 129 130
<form method=get action=reports.cgi>
<table border=1 cellpadding=5>
<tr>
<td align=center><b>Product:</b></td>
<td align=center>
<select name="product">
131 132 133 134 135 136
FIN
foreach my $product (@myproducts) {
    $product = html_quote($product);
    print qq{<option value="$product">$product</option>};
}
print <<FIN;
137 138 139 140
</select>
</td>
</tr>
<tr>
141 142 143
  <td align=center><b>Chart datasets:</b></td>
  <td align=center>
  <select name="datasets" multiple size=5>
144
FIN
145

146
      my @datasets = ();
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
      while (<DATA>) {
          if (/^# fields?: (.+)\s*$/) {
              @datasets = grep ! /date/i, (split /\|/, $1);
              last;
          }
      }

      close(DATA);

      my %default_sel = map { $_ => 1 }
                            qw/UNCONFIRMED NEW ASSIGNED REOPENED/;
      foreach my $dataset (@datasets) {
          my $sel = $default_sel{$dataset} ? ' selected' : '';
          print qq{<option value="$dataset:"$sel>$dataset</option>\n};
      }

      print <<FIN;
      </select>
      </td>
      </tr>
168 169 170 171 172 173
<tr>
<td colspan=2 align=center>
<input type=submit value=Continue>
</td>
</tr>
</table>
174
</center>
175 176 177
</form>
<p>
FIN
178
}
179

180 181 182 183 184
sub daily_stats_filename {
    my ($prodname) = @_;
    $prodname =~ s/\//-/gs;
    return $prodname;
}
185

186
sub show_chart {
187 188 189
    my ($product) = @_;

    if (! defined $cgi->param('datasets')) {
190
        ThrowUserError("missing_datasets", $vars);
191
    }
192
    my $datasets = join('', $cgi->param('datasets'));
193

194 195 196 197
  print <<FIN;
<center>
FIN

198
    my $type = chart_image_type();
199 200
    my $data_file = daily_stats_filename($product);
    my $image_file = chart_image_name($data_file, $type, $datasets);
201
    my $url_image = "$graph_dir/" . url_quote($image_file);
202

203
    if (! -e "$graph_dir/$image_file") {
204 205
        generate_chart("$dir/$data_file", "$graph_dir/$image_file", $type,
                       $product, $datasets);
206 207 208
    }
    
    print <<FIN;
209
<img src="$url_image">
210 211 212
<br clear=left>
<br>
FIN
213
}
214

215 216 217 218
sub chart_image_type {
    # what chart type should we be generating?
    my $testimg = Chart::Lines->new(2,2);
    my $type = $testimg->can('gif') ? "gif" : "png";
219

220 221 222
    undef $testimg;
    return $type;
}
223

224
sub chart_image_name {
225
    my ($data_file, $type, $datasets) = @_;
226

227 228 229 230 231 232 233
    # This routine generates a filename from the requested fields. The problem
    # is that we have to check the safety of doing this. We can't just require
    # that the fields exist, because what stats were collected could change
    # over time (eg by changing the resolutions available)
    # Instead, just require that each field name consists only of letters
    # and number

234
    if ($datasets !~ m/^[A-Za-z0-9:]+$/) {
235 236
        $vars->{'datasets'} = $datasets;
        ThrowUserError('invalid_datasets', $vars);
237
    }
238

239
    # Since we pass the tests, consider it OK
240
    trick_taint($datasets);
241

242 243
    # Cache charts by generating a unique filename based on what they
    # show. Charts should be deleted by collectstats.pl nightly.
244
    my $id = join ("_", split (":", $datasets));
245 246 247 248 249 250 251 252 253 254 255 256

    return "${data_file}_${id}.$type";
}

sub day_of_year {
    my ($mday, $month, $year) = (localtime())[3 .. 5];
    $month += 1;
    $year += 1900;
    my $date = sprintf "%02d%02d%04d", $mday, $month, $year;
}

sub generate_chart {
257
    my ($data_file, $image_file, $type, $product, $datasets) = @_;
258 259
    
    if (! open FILE, $data_file) {
260 261 262 263
        if ($product eq '-All-') {
            $product = '';
        }

264 265
        $vars->{'product'} = $product;
        ThrowCodeError("chart_data_not_generated", $vars);
266 267 268 269
    }

    my @fields;
    my @labels = qw(DATE);
270
    my %datasets = map { $_ => 1 } split /:/, $datasets;
271 272 273 274 275 276 277

    my %data = ();
    while (<FILE>) {
        chomp;
        next unless $_;
        if (/^#/) {
            if (/^# fields?: (.*)\s*$/) {
278
                @fields = split /\||\r/, $1;
279 280 281 282
                unless ($fields[0] =~ /date/i) {
                    $vars->{'file'} = $data_file;
                    ThrowCodeError("chart_datafile_corrupt", $vars);
                }
283 284 285 286 287
                push @labels, grep($datasets{$_}, @fields);
            }
            next;
        }

288 289 290 291
        unless (@fields) {
            $vars->{'file'} = $data_file;
            ThrowCodeError("chart_datafile_corrupt", $vars);
        }
292 293 294 295 296 297 298 299 300 301 302
        
        my @line = split /\|/;
        my $date = $line[0];
        my ($yy, $mm, $dd) = $date =~ /^\d{2}(\d{2})(\d{2})(\d{2})$/;
        push @{$data{DATE}}, "$mm/$dd/$yy";
        
        for my $i (1 .. $#fields) {
            my $field = $fields[$i];
            if (! defined $line[$i] or $line[$i] eq '') {
                # no data point given, don't plot (this will probably
                # generate loads of Chart::Base warnings, but that's not
303
                # our fault.)
304 305 306 307 308 309 310 311 312 313 314 315 316
                push @{$data{$field}}, undef;
            }
            else {
                push @{$data{$field}}, $line[$i];
            }
        }
    }
    
    shift @labels;

    close FILE;

    if (! @{$data{DATE}}) {
317
        ThrowUserError("insufficient_data_points", $vars);
318 319 320 321 322 323 324 325 326 327 328 329 330
    }
    
    my $img = Chart::Lines->new (800, 600);
    my $i = 0;

    my $MAXTICKS = 20;      # Try not to show any more x ticks than this.
    my $skip = 1;
    if (@{$data{DATE}} > $MAXTICKS) {
        $skip = int((@{$data{DATE}} + $MAXTICKS - 1) / $MAXTICKS);
    }

    my %settings =
        (
331
         "title" => "Status Counts for $product",
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
         "x_label" => "Dates",
         "y_label" => "Bug Counts",
         "legend_labels" => \@labels,
         "skip_x_ticks" => $skip,
         "y_grid_lines" => "true",
         "grey_background" => "false",
         "colors" => {
                      # default dataset colours are too alike
                      dataset4 => [0, 0, 0], # black
                     },
        );
    
    $img->set (%settings);
    $img->$type($image_file, [ @data{('DATE', @labels)} ]);
}