CGI.pl 14.3 KB
Newer Older
1 2
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
3 4 5 6 7 8 9 10 11 12
# 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/
#
# 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
# The Original Code is the Bugzilla Bug Tracking System.
14
#
15
# The Initial Developer of the Original Code is Netscape Communications
16 17 18 19
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
20
# Contributor(s): Terry Weissman <terry@mozilla.org>
21
#                 Dan Mosedale <dmose@mozilla.org>
22
#                 Joe Robins <jmrobins@tgix.com>
23
#                 Dave Miller <justdave@syndicomm.com>
24
#                 Christopher Aillon <christopher@aillon.com>
25
#                 Gervase Markham <gerv@gerv.net>
26
#                 Christian Reis <kiko@async.com.br>
27 28 29 30

# Contains some global routines used throughout the CGI scripts of Bugzilla.

use strict;
31 32
use lib ".";

terry%mozilla.org's avatar
terry%mozilla.org committed
33
# use Carp;                       # for confess
34

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

40 41
# Shut up misguided -w warnings about "used only once".  For some reason,
# "use vars" chokes on me when I try it here.
42

43
sub CGI_pl_sillyness {
44
    my $zz;
45
    $zz = $::buffer;
46 47
}

48 49 50 51
use CGI::Carp qw(fatalsToBrowser);

require 'globals.pl';

52 53
use vars qw($template $vars);

54 55 56 57
# If Bugzilla is shut down, do not go any further, just display a message
# to the user about the downtime.  (do)editparams.cgi is exempted from
# this message, of course, since it needs to be available in order for
# the administrator to open Bugzilla back up.
58
if (Param("shutdownhtml") && $0 !~ m:(^|[\\/])(do)?editparams\.cgi$:) {
59
    $::vars->{'message'} = "shutdown";
60 61
    
    # Return the appropriate HTTP response headers.
62
    print Bugzilla->cgi->header();
63 64 65
    
    # Generate and return an HTML message about the downtime.
    $::template->process("global/message.html.tmpl", $::vars)
66
      || ThrowTemplateError($::template->error());
67 68 69
    exit;
}

70 71 72 73 74 75 76 77 78 79 80
# Implementations of several of the below were blatently stolen from CGI.pm,
# by Lincoln D. Stein.

# Get rid of all the %xx encoding and the like from the given URL.
sub url_decode {
    my ($todecode) = (@_);
    $todecode =~ tr/+/ /;       # pluses become spaces
    $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
    return $todecode;
}

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
# check and see if a given field exists, is non-empty, and is set to a 
# legal value.  assume a browser bug and abort appropriately if not.
# if $legalsRef is not passed, just check to make sure the value exists and 
# is non-NULL
sub CheckFormField (\%$;\@) {
    my ($formRef,                # a reference to the form to check (a hash)
        $fieldname,              # the fieldname to check
        $legalsRef               # (optional) ref to a list of legal values 
       ) = @_;

    if ( !defined $formRef->{$fieldname} ||
         trim($formRef->{$fieldname}) eq "" ||
         (defined($legalsRef) && 
          lsearch($legalsRef, $formRef->{$fieldname})<0) ){

96 97
        SendSQL("SELECT description FROM fielddefs WHERE name=" . SqlQuote($fieldname));
        my $result = FetchOneColumn();
98
        my $field;
99
        if ($result) {
100
            $field = $result;
101 102
        }
        else {
103
            $field = $fieldname;
104
        }
105
        
106
        ThrowCodeError("illegal_field", { field => $field }, "abort");
107 108 109 110 111 112 113 114 115
      }
}

# check and see if a given field is defined, and abort if not
sub CheckFormFieldDefined (\%$) {
    my ($formRef,                # a reference to the form to check (a hash)
        $fieldname,              # the fieldname to check
       ) = @_;

116
    if (!defined $formRef->{$fieldname}) {
117
        ThrowCodeError("undefined_field", { field => $fieldname });
118
    }
119
}
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
sub BugAliasToID {
    # Queries the database for the bug with a given alias, and returns
    # the ID of the bug if it exists or the undefined value if it doesn't.
    
    my ($alias) = @_;
    
    return undef unless Param("usebugaliases");
    
    PushGlobalSQLState();
    SendSQL("SELECT bug_id FROM bugs WHERE alias = " . SqlQuote($alias));
    my $id = FetchOneColumn();
    PopGlobalSQLState();
    
    return $id;
}

137
sub ValidateBugID {
138 139 140
    # Validates and verifies a bug ID, making sure the number is a 
    # positive integer, that it represents an existing bug in the
    # database, and that the user is authorized to access that bug.
141
    # We detaint the number here, too
142

143 144 145 146 147 148
    my ($id, $skip_authorization) = @_;
    
    # Get rid of white-space around the ID.
    $id = trim($id);
    
    # If the ID isn't a number, it might be an alias, so try to convert it.
149 150 151
    my $alias = $id;
    if (!detaint_natural($id)) {
        $id = BugAliasToID($alias);
152
        $id || ThrowUserError("invalid_bug_id_or_alias", {'bug_id' => $id});
153 154 155 156 157 158
    }
    
    # Modify the calling code's original variable to contain the trimmed,
    # converted-from-alias ID.
    $_[0] = $id;
    
159 160
    # First check that the bug exists
    SendSQL("SELECT bug_id FROM bugs WHERE bug_id = $id");
161

162
    FetchOneColumn()
163
      || ThrowUserError("invalid_bug_id_non_existent", {'bug_id' => $id});
164

165 166
    return if $skip_authorization;
    
167
    return if CanSeeBug($id, $::userid);
168 169 170 171

    # The user did not pass any of the authorization tests, which means they
    # are not authorized to see the bug.  Display an error and stop execution.
    # The error the user sees depends on whether or not they are logged in
172 173
    # (i.e. $::userid contains the user's positive integer ID).
    if ($::userid) {
174
        ThrowUserError("bug_access_denied", {'bug_id' => $id});
175
    } else {
176
        ThrowUserError("bug_access_query", {'bug_id' => $id});
177
    }
178 179
}

180 181 182 183 184 185
sub ValidateComment {
    # Make sure a comment is not too large (greater than 64K).
    
    my ($comment) = @_;
    
    if (defined($comment) && length($comment) > 65535) {
186
        ThrowUserError("comment_too_long");
187 188 189
    }
}

190 191 192
sub PasswordForLogin {
    my ($login) = (@_);
    SendSQL("select cryptpassword from profiles where login_name = " .
193
            SqlQuote($login));
194 195 196 197 198
    my $result = FetchOneColumn();
    if (!defined $result) {
        $result = "";
    }
    return $result;
199 200
}

201
sub quietly_check_login {
202
    return Bugzilla->login($_[0] ? LOGIN_OPTIONAL : LOGIN_NORMAL);
203 204
}

205 206
sub CheckEmailSyntax {
    my ($addr) = (@_);
207
    my $match = Param('emailregexp');
208
    if ($addr !~ /$match/ || $addr =~ /[\\\(\)<>&,;:"\[\] \t\r\n]/) {
209
        ThrowUserError("illegal_email_address", { addr => $addr });
210 211 212
    }
}

213 214 215
sub MailPassword {
    my ($login, $password) = (@_);
    my $urlbase = Param("urlbase");
216 217 218 219 220
    my $template = Param("passwordmail");
    my $msg = PerformSubsts($template,
                            {"mailaddress" => $login . Param('emailsuffix'),
                             "login" => $login,
                             "password" => $password});
221

222
    open SENDMAIL, "|/usr/lib/sendmail -t -i";
223 224 225 226
    print SENDMAIL $msg;
    close SENDMAIL;
}

227
sub confirm_login {
228
    return Bugzilla->login(LOGIN_REQUIRED);
229 230 231
}

sub PutHeader {
232
    ($vars->{'title'}, $vars->{'h1'}, $vars->{'h2'}) = (@_);
233 234 235
     
    $::template->process("global/header.html.tmpl", $::vars)
      || ThrowTemplateError($::template->error());
236
    $vars->{'header_done'} = 1;
237 238
}

239
sub PutFooter {
240 241
    $::template->process("global/footer.html.tmpl", $::vars)
      || ThrowTemplateError($::template->error());
242 243
}

244 245 246 247 248
sub CheckIfVotedConfirmed {
    my ($id, $who) = (@_);
    SendSQL("SELECT bugs.votes, bugs.bug_status, products.votestoconfirm, " .
            "       bugs.everconfirmed " .
            "FROM bugs, products " .
249
            "WHERE bugs.bug_id = $id AND products.id = bugs.product_id");
250 251 252 253 254 255
    my ($votes, $status, $votestoconfirm, $everconfirmed) = (FetchSQLData());
    if ($votes >= $votestoconfirm && $status eq $::unconfirmedstate) {
        SendSQL("UPDATE bugs SET bug_status = 'NEW', everconfirmed = 1 " .
                "WHERE bug_id = $id");
        my $fieldid = GetFieldID("bug_status");
        SendSQL("INSERT INTO bugs_activity " .
256
                "(bug_id,who,bug_when,fieldid,removed,added) VALUES " .
257 258 259 260
                "($id,$who,now(),$fieldid,'$::unconfirmedstate','NEW')");
        if (!$everconfirmed) {
            $fieldid = GetFieldID("everconfirmed");
            SendSQL("INSERT INTO bugs_activity " .
261
                    "(bug_id,who,bug_when,fieldid,removed,added) VALUES " .
262 263
                    "($id,$who,now(),$fieldid,'0','1')");
        }
264
        
265
        AppendComment($id, DBID_to_name($who),
266
                      "*** This bug has been confirmed by popular vote. ***", 0);
267 268 269
                      
        $vars->{'type'} = "votes";
        $vars->{'id'} = $id;
270
        $vars->{'mailrecipients'} = { 'changer' => $who };
271 272 273
        
        $template->process("bug/process/results.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
274 275 276
    }

}
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
sub LogActivityEntry {
    my ($i,$col,$removed,$added,$whoid,$timestamp) = @_;
    # in the case of CCs, deps, and keywords, there's a possibility that someone    # might try to add or remove a lot of them at once, which might take more
    # space than the activity table allows.  We'll solve this by splitting it
    # into multiple entries if it's too long.
    while ($removed || $added) {
        my ($removestr, $addstr) = ($removed, $added);
        if (length($removestr) > 254) {
            my $commaposition = FindWrapPoint($removed, 254);
            $removestr = substr($removed,0,$commaposition);
            $removed = substr($removed,$commaposition);
            $removed =~ s/^[,\s]+//; # remove any comma or space
        } else {
            $removed = ""; # no more entries
        }
        if (length($addstr) > 254) {
            my $commaposition = FindWrapPoint($added, 254);
            $addstr = substr($added,0,$commaposition);
            $added = substr($added,$commaposition);
            $added =~ s/^[,\s]+//; # remove any comma or space
        } else {
            $added = ""; # no more entries
        }
        $addstr = SqlQuote($addstr);
        $removestr = SqlQuote($removestr);
        my $fieldid = GetFieldID($col);
        SendSQL("INSERT INTO bugs_activity " .
                "(bug_id,who,bug_when,fieldid,removed,added) VALUES " .
                "($i,$whoid," . SqlQuote($timestamp) . ",$fieldid,$removestr,$addstr)");
    }
}
308

309
sub GetBugActivity {
310 311
    my ($id, $starttime) = (@_);
    my $datepart = "";
312 313 314

    die "Invalid id: $id" unless $id=~/^\s*\d+\s*$/;

315
    if (defined $starttime) {
316
        $datepart = "and bugs_activity.bug_when > " . SqlQuote($starttime);
317
    }
318
    
319
    my $query = "
320
        SELECT IFNULL(fielddefs.description, bugs_activity.fieldid),
321
                fielddefs.name,
322
                bugs_activity.attach_id,
323
                DATE_FORMAT(bugs_activity.bug_when,'%Y.%m.%d %H:%i'),
324
                bugs_activity.removed, bugs_activity.added,
325
                profiles.login_name
326 327 328
        FROM bugs_activity LEFT JOIN fielddefs ON 
                                     bugs_activity.fieldid = fielddefs.fieldid,
             profiles
329 330 331
        WHERE bugs_activity.bug_id = $id $datepart
              AND profiles.userid = bugs_activity.who
        ORDER BY bugs_activity.bug_when";
332 333 334

    SendSQL($query);
    
335 336 337
    my @operations;
    my $operation = {};
    my $changes = [];
338
    my $incomplete_data = 0;
339
    
340
    while (my ($field, $fieldname, $attachid, $when, $removed, $added, $who) 
341 342 343
                                                               = FetchSQLData())
    {
        my %change;
344
        my $activity_visible = 1;
345
        
346 347 348 349
        # check if the user should see this field's activity
        if ($fieldname eq 'remaining_time' ||
            $fieldname eq 'estimated_time' ||
            $fieldname eq 'work_time') {
350

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
            if (!UserInGroup(Param('timetrackinggroup'))) {
                $activity_visible = 0;
            } else {
                $activity_visible = 1;
            }
        } else {
            $activity_visible = 1;
        }
                
        if ($activity_visible) {
            # This gets replaced with a hyperlink in the template.
            $field =~ s/^Attachment// if $attachid;

            # Check for the results of an old Bugzilla data corruption bug
            $incomplete_data = 1 if ($added =~ /^\?/ || $removed =~ /^\?/);
366
        
367 368 369 370 371 372 373 374 375 376
            # An operation, done by 'who' at time 'when', has a number of
            # 'changes' associated with it.
            # If this is the start of a new operation, store the data from the
            # previous one, and set up the new one.
            if ($operation->{'who'} 
                && ($who ne $operation->{'who'} 
                    || $when ne $operation->{'when'})) 
            {
                $operation->{'changes'} = $changes;
                push (@operations, $operation);
377
            
378 379 380 381
                # Create new empty anonymous data structures.
                $operation = {};
                $changes = [];
            }  
382
        
383 384
            $operation->{'who'} = $who;
            $operation->{'when'} = $when;            
385
        
386 387 388 389 390 391 392
            $change{'field'} = $field;
            $change{'fieldname'} = $fieldname;
            $change{'attachid'} = $attachid;
            $change{'removed'} = $removed;
            $change{'added'} = $added;
            push (@$changes, \%change);
        }   
393
    }
394 395 396 397
    
    if ($operation->{'who'}) {
        $operation->{'changes'} = $changes;
        push (@operations, $operation);
398
    }
399 400
    
    return(\@operations, $incomplete_data);
401 402
}

403 404
############# Live code below here (that is, not subroutine defs) #############

405
use Bugzilla;
406

407
# XXX - mod_perl - reset this between runs
408
$::cgi = Bugzilla->cgi;
409

410 411 412
# Set up stuff for compatibility with the old CGI.pl code
# This code will be removed as soon as possible, in favour of
# using the CGI.pm stuff directly
413

414 415 416 417 418 419
# XXX - mod_perl - reset these between runs

foreach my $name ($::cgi->param()) {
    my @val = $::cgi->param($name);
    $::FORM{$name} = join('', @val);
    $::MFORM{$name} = \@val;
420 421
}

422 423 424 425
$::buffer = $::cgi->query_string();

foreach my $name ($::cgi->cookie()) {
    $::COOKIE{$name} = $::cgi->cookie($name);
426 427
}

428 429 430
# This could be needed in any CGI, so we set it here.
$vars->{'help'} = $::cgi->param('help') ? 1 : 0;

431
1;