reports.cgi 8.07 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 22 23 24 25 26 27 28 29
# Contributor(s): Harrison Page <harrison@netscape.com>
#                 Terry Weissman <terry@mozilla.org>
#                 Dawn Endico <endico@mozilla.org>
#                 Bryce Nesbitt <bryce@nextbus.com>
#                 Joe Robins <jmrobins@tgix.com>
#                 Gervase Markham <gerv@gerv.net>
#                 Adam Spiers <adam@spiers.net>
#                 Myk Melez <myk@mozilla.org>
#                 Frédéric Buclin <LpSolit@gmail.com>
30 31

use strict;
32

33
use lib qw(. lib);
34

35 36 37 38
use Bugzilla;
use Bugzilla::Constants;
use Bugzilla::Util;
use Bugzilla::Error;
39
use Bugzilla::Status;
40

41 42 43 44 45 46 47
# 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.
my $user = Bugzilla->login();

if (!Bugzilla->feature('old_charts')) {
    ThrowCodeError('feature_disabled', { feature => 'old_charts' });
}
48

49 50 51
my $dir       = bz_locations()->{'datadir'} . "/mining";
my $graph_url = 'graphs';
my $graph_dir = bz_locations()->{'libpath'} . '/' .$graph_url;
52

53
Bugzilla->switch_to_shadow_db();
54

55
my $cgi = Bugzilla->cgi;
56
my $template = Bugzilla->template;
57
my $vars = {};
58

59
# We only want those products that the user has permissions for.
60
my @myproducts;
61
push( @myproducts, "-All-");
62 63
# Extract product names from objects and add them to the list.
push( @myproducts, map { $_->name } @{$user->get_selectable_products} );
64

65
if (! defined $cgi->param('product')) {
66 67 68 69 70
    # Can we do bug charts?
    (-d $dir && -d $graph_dir) 
      || ThrowCodeError('chart_dir_nonexistent',
                        {dir => $dir, graph_dir => $graph_dir});

71
    my %default_sel = map { $_ => 1 } BUG_STATE_OPEN;
72 73 74 75 76 77 78 79 80 81 82 83 84

    my @datasets;
    my @data = get_data($dir);

    foreach my $dataset (@data) {
        my $datasets = {};
        $datasets->{'value'} = $dataset;
        $datasets->{'selected'} = $default_sel{$dataset} ? 1 : 0;
        push(@datasets, $datasets);
    }

    $vars->{'datasets'} = \@datasets;
    $vars->{'products'} = \@myproducts;
85

86
    print $cgi->header();
87

88 89 90 91 92
    $template->process('reports/old-charts.html.tmpl', $vars)
      || ThrowTemplateError($template->error());
    exit;
}
else {
93
    my $product = $cgi->param('product');
94 95 96 97

    # 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.
98 99
    grep($_ eq $product, @myproducts)
      || ThrowUserError("invalid_product_name", {product => $product});
100

101 102
    # We've checked that the product exists, and that the user can see it
    # This means that is OK to detaint
103
    trick_taint($product);
104

105
    defined($cgi->param('datasets')) || ThrowUserError('missing_datasets');
106

107
    my $datasets = join('', $cgi->param('datasets'));
108

109
    my $data_file = daily_stats_filename($product);
110
    my $image_file = chart_image_name($data_file, $datasets);
111
    my $url_image = correct_urlbase() . "$graph_url/$image_file";
112

113
    if (! -e "$graph_dir/$image_file") {
114
        generate_chart("$dir/$data_file", "$graph_dir/$image_file", $product, $datasets);
115
    }
116

117
    $vars->{'url_image'} = $url_image;
118

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

121 122 123 124
    $template->process('reports/old-charts.html.tmpl', $vars)
      || ThrowTemplateError($template->error());
    exit;
}
125

126 127 128 129 130 131 132 133
#####################
#    Subroutines    #
#####################

sub get_data {
    my $dir = shift;

    my @datasets;
134
    my $datafile = daily_stats_filename('-All-');
135 136
    open(DATA, '<', "$dir/$datafile")
      || ThrowCodeError('chart_file_open_fail', {filename => "$dir/$datafile"});
137

138 139 140 141 142 143 144 145
    while (<DATA>) {
        if (/^# fields?: (.+)\s*$/) {
            @datasets = grep ! /date/i, (split /\|/, $1);
            last;
        }
    }
    close(DATA);
    return @datasets;
146
}
147

148 149 150 151 152
sub daily_stats_filename {
    my ($prodname) = @_;
    $prodname =~ s/\//-/gs;
    return $prodname;
}
153

154
sub chart_image_name {
155
    my ($data_file, $datasets) = @_;
156

157 158 159 160
    # 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)
161 162
    # Instead, just require that each field name consists only of letters,
    # numbers, underscores and hyphens.
163

164
    if ($datasets !~ m/^[A-Za-z0-9:_-]+$/) {
165
        ThrowUserError('invalid_datasets', {'datasets' => $datasets});
166
    }
167

168
    # Since we pass the tests, consider it OK
169
    trick_taint($datasets);
170

171 172
    # Cache charts by generating a unique filename based on what they
    # show. Charts should be deleted by collectstats.pl nightly.
173
    my $id = join ("_", split (":", $datasets));
174

175
    return "${data_file}_${id}.png";
176 177 178
}

sub generate_chart {
179
    my ($data_file, $image_file, $product, $datasets) = @_;
180

181
    if (! open FILE, $data_file) {
182 183 184
        if ($product eq '-All-') {
            $product = '';
        }
185
        ThrowCodeError('chart_data_not_generated', {'product' => $product});
186 187 188 189
    }

    my @fields;
    my @labels = qw(DATE);
190
    my %datasets = map { $_ => 1 } split /:/, $datasets;
191 192 193 194 195 196 197

    my %data = ();
    while (<FILE>) {
        chomp;
        next unless $_;
        if (/^#/) {
            if (/^# fields?: (.*)\s*$/) {
198
                @fields = split /\||\r/, $1;
199
                $data{$_} ||= [] foreach @fields;
200
                unless ($fields[0] =~ /date/i) {
201
                    ThrowCodeError('chart_datafile_corrupt', {'file' => $data_file});
202
                }
203 204 205 206 207
                push @labels, grep($datasets{$_}, @fields);
            }
            next;
        }

208
        unless (@fields) {
209
            ThrowCodeError('chart_datafile_corrupt', {'file' => $data_file});
210
        }
211

212 213 214 215 216 217 218 219 220 221
        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
222
                # our fault.)
223 224 225 226 227 228 229 230 231 232 233 234 235
                push @{$data{$field}}, undef;
            }
            else {
                push @{$data{$field}}, $line[$i];
            }
        }
    }
    
    shift @labels;

    close FILE;

    if (! @{$data{DATE}}) {
236
        ThrowUserError('insufficient_data_points');
237
    }
238

239 240 241 242 243 244 245 246 247 248 249
    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 =
        (
250
         "title" => "Status Counts for $product",
251 252 253 254 255 256 257 258 259 260 261 262 263
         "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);
264
    $img->png($image_file, [ @data{('DATE', @labels)} ]);
265
}