report.cgi 13.9 KB
Newer Older
1
#!/usr/bin/perl -T
2 3 4
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
#
6 7
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
8

9
use 5.10.1;
10
use strict;
11 12
use warnings;

13
use lib qw(. lib);
14

15
use Bugzilla;
16
use Bugzilla::Constants;
17 18
use Bugzilla::Util;
use Bugzilla::Error;
19
use Bugzilla::Field;
20
use Bugzilla::Search;
21 22
use Bugzilla::Report;
use Bugzilla::Token;
23

24
use List::MoreUtils qw(uniq);
25

26
my $cgi      = Bugzilla->cgi;
27
my $template = Bugzilla->template;
28
my $vars     = {};
29

30 31
# Go straight back to query.cgi if we are adding a boolean chart.
if (grep(/^cmd-/, $cgi->param())) {
32 33 34 35 36 37 38 39
  my $params = $cgi->canonicalise_query("format", "ctype");
  my $location
    = "query.cgi?format="
    . $cgi->param('query_format')
    . ($params ? "&$params" : "");

  print $cgi->redirect($location);
  exit;
40 41
}

42
Bugzilla->login();
43
my $action = $cgi->param('action') || 'menu';
44
my $token  = $cgi->param('token');
45 46

if ($action eq "menu") {
47 48 49 50 51 52

  # No need to do any searching in this case, so bail out early.
  print $cgi->header();
  $template->process("reports/menu.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
  exit;
53 54 55

}
elsif ($action eq 'add') {
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  my $user = Bugzilla->login(LOGIN_REQUIRED);
  check_hash_token($token, ['save_report']);

  my $name  = clean_text($cgi->param('name'));
  my $query = $cgi->param('query');

  if (my ($report) = grep { lc($_->name) eq lc($name) } @{$user->reports}) {
    $report->set_query($query);
    $report->update;
    $vars->{'message'} = "report_updated";
  }
  else {
    my $report = Bugzilla::Report->create({name => $name, query => $query});
    $vars->{'message'} = "report_created";
  }
71

72
  $user->flush_reports_cache;
73

74
  print $cgi->header();
75

76
  $vars->{'reportname'} = $name;
77

78 79 80
  $template->process("global/message.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
  exit;
81 82
}
elsif ($action eq 'del') {
83 84 85
  my $user      = Bugzilla->login(LOGIN_REQUIRED);
  my $report_id = $cgi->param('saved_report_id');
  check_hash_token($token, ['delete_report', $report_id]);
86

87 88
  my $report = Bugzilla::Report->check({id => $report_id});
  $report->remove_from_db();
89

90
  $user->flush_reports_cache;
91

92
  print $cgi->header();
93

94 95
  $vars->{'message'}    = 'report_deleted';
  $vars->{'reportname'} = $report->name;
96

97 98 99
  $template->process("global/message.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
  exit;
100
}
101

102 103 104
# Sanitize the URL, to make URLs shorter.
$cgi->clean_search_url;

105 106 107 108 109
my $col_field = $cgi->param('x_axis_field') || '';
my $row_field = $cgi->param('y_axis_field') || '';
my $tbl_field = $cgi->param('z_axis_field') || '';

if (!($col_field || $row_field || $tbl_field)) {
110
  ThrowUserError("no_axes_defined");
111 112
}

113 114
# There is no UI for these parameters anymore,
# but they are still here just in case.
115
my $width  = $cgi->param('width')  || 1024;
116
my $height = $cgi->param('height') || 600;
117

118
(detaint_natural($width) && $width > 0) || ThrowUserError("invalid_dimensions");
119
$width <= 2000 || ThrowUserError("chart_too_large");
120

121
(detaint_natural($height) && $height > 0)
122
  || ThrowUserError("invalid_dimensions");
123
$height <= 2000 || ThrowUserError("chart_too_large");
124

125 126
my $formatparam = $cgi->param('format') || '';

127
# These shenanigans are necessary to make sure that both vertical and
128 129
# horizontal 1D tables convert to the correct dimension when you ask to
# display them as some sort of chart.
130
if ($formatparam eq "table") {
131 132 133 134 135 136
  if ($col_field && !$row_field) {

    # 1D *tables* should be displayed vertically (with a row_field only)
    $row_field = $col_field;
    $col_field = '';
  }
137 138
}
else {
139 140 141
  if (!Bugzilla->feature('graphical_reports')) {
    ThrowUserError('feature_disabled', {feature => 'graphical_reports'});
  }
142

143 144 145 146 147 148
  if ($row_field && !$col_field) {

    # 1D *charts* should be displayed horizontally (with an col_field only)
    $col_field = $row_field;
    $row_field = '';
  }
149
}
150

151
# Valid bug fields that can be reported on.
152
my $valid_columns = Bugzilla::Search::REPORT_COLUMNS;
153

154
# Validate the values in the axis fields or throw an error.
155
!$row_field
156
  || ($valid_columns->{$row_field} && trick_taint($row_field))
157
  || ThrowUserError("report_axis_invalid", {fld => "x", val => $row_field});
158
!$col_field
159
  || ($valid_columns->{$col_field} && trick_taint($col_field))
160
  || ThrowUserError("report_axis_invalid", {fld => "y", val => $col_field});
161
!$tbl_field
162
  || ($valid_columns->{$tbl_field} && trick_taint($tbl_field))
163
  || ThrowUserError("report_axis_invalid", {fld => "z", val => $tbl_field});
164

165
my @axis_fields = grep {$_} ($row_field, $col_field, $tbl_field);
166

167 168
# Clone the params, so that Bugzilla::Search can modify them
my $params = new Bugzilla::CGI($cgi);
169
my $search = new Bugzilla::Search(
170 171 172
  fields          => \@axis_fields,
  params          => scalar $params->Vars,
  allow_unlimited => 1,
173
);
174

175 176 177
$::SIG{TERM} = 'DEFAULT';
$::SIG{PIPE} = 'DEFAULT';

178 179
Bugzilla->switch_to_shadow_db();
my ($results, $extra_data) = $search->data;
180

181
# We have a hash of hashes for the data itself, and a hash to hold the
182
# row/col/table names.
183
my %data;
184
my %names;
185

186 187
# Read the bug data and count the bugs for each possible value of row, column
# and table.
188 189 190 191 192 193 194
#
# We detect a numerical field, and sort appropriately, if all the values are
# numeric.
my $col_isnumeric = 1;
my $row_isnumeric = 1;
my $tbl_isnumeric = 1;

195
# define which fields are multiselect
196 197 198 199 200 201 202 203
my @multi_selects
  = map { $_->name }
  @{Bugzilla->fields({
    obsolete => 0, type => [FIELD_TYPE_MULTI_SELECT, FIELD_TYPE_KEYWORDS]
  })};
my $col_ismultiselect = scalar grep { $col_field eq $_ } @multi_selects;
my $row_ismultiselect = scalar grep { $row_field eq $_ } @multi_selects;
my $tbl_ismultiselect = scalar grep { $tbl_field eq $_ } @multi_selects;
204 205


206
foreach my $result (@$results) {
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

  # handle empty dimension member names

  my @rows = check_value($row_field, $result, $row_ismultiselect);
  my @cols = check_value($col_field, $result, $col_ismultiselect);
  my @tbls = check_value($tbl_field, $result, $tbl_ismultiselect);

  my %in_total_row;
  my %in_total_col;
  for my $tbl (@tbls) {
    my %in_row_total;
    for my $col (@cols) {
      for my $row (@rows) {
        $data{$tbl}{$col}{$row}++;
        $names{"row"}{$row}++;
        $row_isnumeric &&= ($row =~ /^-?\d+(\.\d+)?$/o);
223
        if ($formatparam eq "table") {
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
          if (!$in_row_total{$row}) {
            $data{$tbl}{'-total-'}{$row}++;
            $in_row_total{$row} = 1;
          }
          if (!$in_total_row{$row}) {
            $data{'-total-'}{'-total-'}{$row}++;
            $in_total_row{$row} = 1;
          }
        }
      }
      if ($formatparam eq "table") {
        $data{$tbl}{$col}{'-total-'}++;
        if (!$in_total_col{$col}) {
          $data{'-total-'}{$col}{'-total-'}++;
          $in_total_col{$col} = 1;
239
        }
240 241 242
      }
      $names{"col"}{$col}++;
      $col_isnumeric &&= ($col =~ /^-?\d+(\.\d+)?$/o);
243
    }
244 245
    $names{"tbl"}{$tbl}++;
    $tbl_isnumeric &&= ($tbl =~ /^-?\d+(\.\d+)?$/o);
246
    if ($formatparam eq "table") {
247
      $data{$tbl}{'-total-'}{'-total-'}++;
248
    }
249 250 251 252
  }
  if ($formatparam eq "table") {
    $data{'-total-'}{'-total-'}{'-total-'}++;
  }
253 254
}

255 256 257
my @col_names = get_names($names{"col"}, $col_isnumeric, $col_field);
my @row_names = get_names($names{"row"}, $row_isnumeric, $row_field);
my @tbl_names = get_names($names{"tbl"}, $tbl_isnumeric, $tbl_field);
258 259 260 261 262

# The GD::Graph package requires a particular format of data, so once we've
# gathered everything into the hashes and made sure we know the size of the
# data, we reformat it into an array of arrays of arrays of data.
push(@tbl_names, "-total-") if (scalar(@tbl_names) > 1);
263

264 265
my @image_data;
foreach my $tbl (@tbl_names) {
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
  my @tbl_data;
  push(@tbl_data, \@col_names);
  foreach my $row (@row_names) {
    my @col_data;
    foreach my $col (@col_names) {
      $data{$tbl}{$col}{$row} = $data{$tbl}{$col}{$row} || 0;
      push(@col_data, $data{$tbl}{$col}{$row});
      if ($tbl ne "-total-") {

        # This is a bit sneaky. We spend every loop except the last
        # building up the -total- data, and then last time round,
        # we process it as another tbl, and push() the total values
        # into the image_data array.
        $data{"-total-"}{$col}{$row} += $data{$tbl}{$col}{$row};
      }
281
    }
282 283 284 285 286

    push(@tbl_data, \@col_data);
  }

  unshift(@image_data, \@tbl_data);
287 288
}

289
$vars->{'col_field'} = $col_field;
290 291
$vars->{'row_field'} = $row_field;
$vars->{'tbl_field'} = $tbl_field;
292
$vars->{'time'}      = localtime(time());
293

294 295 296
$vars->{'col_names'}         = \@col_names;
$vars->{'row_names'}         = \@row_names;
$vars->{'tbl_names'}         = \@tbl_names;
297
$vars->{'note_multi_select'} = $row_ismultiselect || $col_ismultiselect;
298

299
# Below a certain width, we don't see any bars, so there needs to be a minimum.
300
if ($formatparam eq "bar") {
301
  my $min_width = (scalar(@col_names) || 1) * 20;
302

303 304 305
  if (!$cgi->param('cumulate')) {
    $min_width *= (scalar(@row_names) || 1);
  }
306

307
  $vars->{'min_width'} = $min_width;
308 309
}

310 311 312
$vars->{'width'}           = $width;
$vars->{'height'}          = $height;
$vars->{'queries'}         = $extra_data;
313
$vars->{'saved_report_id'} = $cgi->param('saved_report_id');
314

315 316 317 318 319
if ( $cgi->param('debug')
  && Bugzilla->params->{debug_group}
  && Bugzilla->user->in_group(Bugzilla->params->{debug_group}))
{
  $vars->{'debug'} = 1;
320
}
321 322

if ($action eq "wrap") {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

  # So which template are we using? If action is "wrap", we will be using
  # no format (it gets passed through to be the format of the actual data),
  # and either report.csv.tmpl (CSV), or report.html.tmpl (everything else).
  # report.html.tmpl produces an HTML framework for either tables of HTML
  # data, or images generated by calling report.cgi again with action as
  # "plot".
  $formatparam =~ s/[^a-zA-Z\-]//g;
  $vars->{'format'} = $formatparam;
  $formatparam = '';

  # We need to keep track of the defined restrictions on each of the
  # axes, because buglistbase, below, throws them away. Without this, we
  # get buglistlinks wrong if there is a restriction on an axis field.
  $vars->{'col_vals'} = get_field_restrictions($col_field);
  $vars->{'row_vals'} = get_field_restrictions($row_field);
  $vars->{'tbl_vals'} = get_field_restrictions($tbl_field);

  # We need a number of different variants of the base URL for different
  # URLs in the HTML.
  $vars->{'buglistbase'} = $cgi->canonicalise_query(
    "x_axis_field", "y_axis_field", "z_axis_field", "ctype",
    "format",       "query_format", @axis_fields
  );
  $vars->{'imagebase'}
    = $cgi->canonicalise_query($tbl_field, "action", "ctype", "format", "width",
    "height");
  $vars->{'switchbase'}
    = $cgi->canonicalise_query("query_format", "action", "ctype", "format",
    "width", "height");
  $vars->{'data'} = \%data;
354 355
}
elsif ($action eq "plot") {
356 357 358 359 360 361

  # If action is "plot", we will be using a format as normal (pie, bar etc.)
  # and a ctype as normal (currently only png.)
  $vars->{'cumulate'}          = $cgi->param('cumulate')          ? 1 : 0;
  $vars->{'x_labels_vertical'} = $cgi->param('x_labels_vertical') ? 1 : 0;
  $vars->{'data'}              = \@image_data;
362 363
}
else {
364
  ThrowUserError('unknown_action', {action => $action});
365 366
}

367
my $format = $template->get_format("reports/report", $formatparam,
368
  scalar($cgi->param('ctype')));
369

370 371 372
# If we get a template or CGI error, it comes out as HTML, which isn't valid
# PNG data, and the browser just displays a "corrupt PNG" message. So, you can
# set debug=1 to always get an HTML content-type, and view the error.
373
$format->{'ctype'} = "text/html" if $cgi->param('debug');
374

375 376
$cgi->set_dated_content_disp("inline", "report", $format->{extension});
print $cgi->header($format->{'ctype'});
377 378 379

# Problems with this CGI are often due to malformed data. Setting debug=1
# prints out both data structures.
380
if ($cgi->param('debug')) {
381 382 383 384 385
  require Data::Dumper;
  say "<pre>data hash:";
  say html_quote(Data::Dumper::Dumper(%data));
  say "\ndata array:";
  say html_quote(Data::Dumper::Dumper(@image_data)) . "\n\n</pre>";
386 387
}

388
# All formats point to the same section of the documentation.
389
$vars->{'doc_section'} = 'using/reports-and-charts.html#reports';
390

391 392
disable_utf8() if ($format->{'ctype'} =~ /^image\//);

393 394
$template->process("$format->{'template'}", $vars)
  || ThrowTemplateError($template->error());
395 396 397


sub get_names {
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  my ($names, $isnumeric, $field_name) = @_;
  my ($field, @sorted);

  # XXX - This is a hack to handle the actual_time/work_time field,
  # because it's named 'actual_time' in Search.pm but 'work_time' in Field.pm.
  $_[2] = $field_name = 'work_time' if $field_name eq 'actual_time';

  # _realname fields aren't real Bugzilla::Field objects, but they are a
  # valid axis, so we don't vailidate them as Bugzilla::Field objects.
  $field = Bugzilla::Field->check($field_name)
    if ($field_name && $field_name !~ /_realname$/);

  if ($field && $field->is_select) {
    foreach my $value (@{$field->legal_values}) {
      push(@sorted, $value->name) if $names->{$value->name};
413
    }
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    unshift(@sorted, '---')
      if ($field_name eq 'resolution' || $field->type == FIELD_TYPE_MULTI_SELECT);
    @sorted = uniq @sorted;
  }
  elsif ($isnumeric) {

    # It's not a field we are preserving the order of, so sort it
    # numerically...
    @sorted = sort { $a <=> $b } keys %$names;
  }
  else {
    # ...or alphabetically, as appropriate.
    @sorted = sort keys %$names;
  }

  return @sorted;
430
}
431 432

sub check_value {
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
  my ($field, $result, $ismultiselect) = @_;

  my $value;
  if (!defined $field) {
    $value = '';
  }
  elsif ($field eq '') {
    $value = ' ';
  }
  else {
    $value = shift @$result;
    $value = ' ' if (!defined $value || $value eq '');
    $value = '---' if (($field eq 'resolution' || $ismultiselect) && $value eq ' ');
  }
  if ($ismultiselect) {

    # Some DB servers have a space after the comma, some others don't.
    return split(/, ?/, $value);
  }
  else {
    return ($value);
  }
455
}
456 457

sub get_field_restrictions {
458 459
  my $field = shift;
  my $cgi   = Bugzilla->cgi;
460

461 462
  return join('&amp;',
    map { url_quote($field) . '=' . url_quote($_) } $cgi->param($field));
463
}