CGI.pl 47.9 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 26 27 28 29

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

use diagnostics;
use strict;
terry%mozilla.org's avatar
terry%mozilla.org committed
30
# use Carp;                       # for confess
31 32
# Shut up misguided -w warnings about "used only once".  For some reason,
# "use vars" chokes on me when I try it here.
33 34 35

# commented out the following snippet of code. this tosses errors into the
# CGI if you are perl 5.6, and doesn't if you have perl 5.003. 
36
# We want to check for the existence of the LDAP modules here.
37 38 39
# eval "use Mozilla::LDAP::Conn";
# my $have_ldap = $@ ? 0 : 1;

40

41
sub CGI_pl_sillyness {
42 43
    my $zz;
    $zz = %::FILENAME;
terry%mozilla.org's avatar
terry%mozilla.org committed
44
    $zz = %::MFORM;
45
    $zz = %::dontchange;
46 47
}

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

require 'globals.pl';

sub GeneratePersonInput {
    my ($field, $required, $def_value, $extraJavaScript) = (@_);
54
    $extraJavaScript ||= "";
55
    if ($extraJavaScript ne "") {
56
        $extraJavaScript = "onChange=\"$extraJavaScript\"";
57 58 59 60 61
    }
    return "<INPUT NAME=\"$field\" SIZE=32 $extraJavaScript VALUE=\"$def_value\">";
}

sub GeneratePeopleInput {
62 63
    my ($field, $def_value) = (@_);
    return "<INPUT NAME=\"$field\" SIZE=45 VALUE=\"$def_value\">";
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
}




# 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;
}


# Quotify a string, suitable for putting into a URL.

sub url_quote {
    my($toencode) = (@_);
    $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}


92 93 94 95
sub ParseUrlString {
    my ($buffer, $f, $m) = (@_);
    undef %$f;
    undef %$m;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

    my %isnull;
    my $remaining = $buffer;
    while ($remaining ne "") {
	my $item;
	if ($remaining =~ /^([^&]*)&(.*)$/) {
	    $item = $1;
	    $remaining = $2;
	} else {
	    $item = $remaining;
	    $remaining = "";
	}

	my $name;
	my $value;
	if ($item =~ /^([^=]*)=(.*)$/) {
	    $name = $1;
	    $value = url_decode($2);
	} else {
	    $name = $item;
	    $value = "";
	}
	if ($value ne "") {
119 120 121
	    if (defined $f->{$name}) {
		$f->{$name} .= $value;
		my $ref = $m->{$name};
122 123
		push @$ref, $value;
	    } else {
124 125
		$f->{$name} = $value;
		$m->{$name} = [$value];
126 127 128 129 130
	    }
        } else {
            $isnull{$name} = 1;
        }
    }
131
    if (%isnull) {
132
        foreach my $name (keys(%isnull)) {
133 134 135
            if (!defined $f->{$name}) {
                $f->{$name} = "";
                $m->{$name} = [];
136 137 138 139 140 141
            }
        }
    }
}


142 143 144 145 146 147
sub ProcessFormFields {
    my ($buffer) = (@_);
    return ParseUrlString($buffer, \%::FORM, \%::MFORM);
}


148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
sub ProcessMultipartFormFields {
    my ($boundary) = (@_);
    $boundary =~ s/^-*//;
    my $remaining = $ENV{"CONTENT_LENGTH"};
    my $inheader = 1;
    my $itemname = "";
#    open(DEBUG, ">debug") || die "Can't open debugging thing";
#    print DEBUG "Boundary is '$boundary'\n";
    while ($remaining > 0 && ($_ = <STDIN>)) {
        $remaining -= length($_);
#        print DEBUG "< $_";
        if ($_ =~ m/^-*$boundary/) {
#            print DEBUG "Entered header\n";
            $inheader = 1;
            $itemname = "";
            next;
        }

        if ($inheader) {
            if (m/^\s*$/) {
                $inheader = 0;
#                print DEBUG "left header\n";
                $::FORM{$itemname} = "";
            }
            if (m/^Content-Disposition:\s*form-data\s*;\s*name\s*=\s*"([^\"]+)"/i) {
                $itemname = $1;
#                print DEBUG "Found itemname $itemname\n";
                if (m/;\s*filename\s*=\s*"([^\"]+)"/i) {
                    $::FILENAME{$itemname} = $1;
                }
            }
            
            next;
        }
        $::FORM{$itemname} .= $_;
    }
    delete $::FORM{""};
    # Get rid of trailing newlines.
    foreach my $i (keys %::FORM) {
        chomp($::FORM{$i});
        $::FORM{$i} =~ s/\r$//;
    }
}


193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
# 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) ){

        print "A legal $fieldname was not set; ";
        print Param("browserbugmessage");
211
        PutFooter();
212 213 214 215 216 217 218 219 220 221 222 223 224 225
        exit 0;
      }
}

# 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
       ) = @_;

    if ( !defined $formRef->{$fieldname} ) {
        print "$fieldname was not defined; ";
        print Param("browserbugmessage");
226
        PutFooter();
227 228 229
        exit 0;
      }
}
230

231
sub ValidateBugID {
232 233 234 235 236 237 238
    # 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.

    my ($id) = @_;

    # Make sure the bug number is a positive integer.
239 240
    # Whitespace can be ignored because the SQL server will ignore it.
    $id =~ /^\s*([1-9][0-9]*)\s*$/
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
      || DisplayError("The bug number is invalid.") 
      && exit;

    # Get the values of the usergroupset and userid global variables
    # and write them to local variables for use within this function,
    # setting those local variables to the default value of zero if
    # the global variables are undefined.

    # "usergroupset" stores the set of groups the user is a member of,
    # while "userid" stores the user's unique ID.  These variables are
    # set globally by either confirm_login() or quietly_check_login(),
    # one of which should be run before calling this function; otherwise
    # this function will treat the user as if they were not logged in
    # and throw an error if they try to access a bug that requires
    # permissions/authorization to access.
    my $usergroupset = $::usergroupset || 0;
    my $userid = $::userid || 0;

    # Query the database for the bug, retrieving a boolean value that
    # represents whether or not the user is authorized to access the bug.  

    # Users are authorized to access bugs if they are a member of all 
    # groups to which the bug is restricted.  User group membership and 
    # bug restrictions are stored as bits within bitsets, so authorization
    # can be determined by comparing the intersection of the user's
    # bitset with the bug's bitset.  If the result matches the bug's bitset
    # the user is a member of all groups to which the bug is restricted
    # and is authorized to access the bug.

270 271 272 273 274 275
    # A user is also authorized to access a bug if she is the reporter, 
    # assignee, QA contact, or member of the cc: list of the bug and the bug 
    # allows users in those roles to see the bug.  The boolean fields 
    # reporter_accessible, assignee_accessible, qacontact_accessible, and 
    # cclist_accessible identify whether or not those roles can see the bug.

276 277 278 279 280
    # Bit arithmetic is performed by MySQL instead of Perl because bitset
    # fields in the database are 64 bits wide (BIGINT), and Perl installations
    # may or may not support integers larger than 32 bits.  Using bitsets
    # and doing bitset arithmetic is probably not cross-database compatible,
    # however, so these mechanisms are likely to change in the future.
281 282 283 284 285 286 287 288

    # Get data from the database about whether or not the user belongs to
    # all groups the bug is in, and who are the bug's reporter and qa_contact
    # along with which roles can always access the bug.
    SendSQL("SELECT ((groupset & $usergroupset) = groupset) , reporter , assigned_to , qa_contact , 
                    reporter_accessible , assignee_accessible , qacontact_accessible , cclist_accessible 
             FROM   bugs 
             WHERE  bug_id = $id");
289 290 291 292 293 294

    # Make sure the bug exists in the database.
    MoreSQLData()
      || DisplayError("Bug #$id does not exist.")
      && exit;

295 296 297
    my ($isauthorized, $reporter, $assignee, $qacontact, $reporter_accessible, 
        $assignee_accessible, $qacontact_accessible, $cclist_accessible) = FetchSQLData();

298 299 300 301 302 303 304 305 306 307
    # Finish validation and return if the user is a member of all groups to which the bug belongs.
    return if $isauthorized;

    # Finish validation and return if the user is in a role that has access to the bug.
    if ($userid) {
        return 
	  if ($reporter_accessible && $reporter == $userid)
            || ($assignee_accessible && $assignee == $userid)
              || ($qacontact_accessible && $qacontact == $userid);
    }
308 309 310 311 312 313 314 315 316 317 318

    # Try to authorize the user one more time by seeing if they are on 
    # the cc: list.  If so, finish validation and return.
    if ( $cclist_accessible ) {
        my @cclist;
        SendSQL("SELECT cc.who 
                 FROM   bugs , cc
                 WHERE  bugs.bug_id = $id
                 AND    cc.bug_id = bugs.bug_id
                ");
        while (my ($ccwho) = FetchSQLData()) {
319 320 321
            # more efficient to just check the var here instead of
            # creating a potentially huge array to grep against
            return if ($userid == $ccwho);
322
        }
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    }

    # 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
    # (i.e. $userid contains the user's positive integer ID).
    if ($userid) {
        DisplayError("You are not authorized to access bug #$id.");
    } else {
        DisplayError(
          qq|You are not authorized to access bug #$id.  To see this bug, you
          must first <a href="show_bug.cgi?id=$id&GoAheadAndLogIn=1">log in 
          to an account</a> with the appropriate permissions.|
        );
    }
    exit;

341 342
}

343 344 345 346 347 348 349
# check and see if a given string actually represents a positive
# integer, and abort if not.
# 
sub CheckPosInt($) {
    my ($number) = @_;              # the fieldname to check

    if ( $number !~ /^[1-9][0-9]*$/ ) {
justdave%syndicomm.com's avatar
justdave%syndicomm.com committed
350
        print "Received string \"$number\" when positive integer expected; ";
351
        print Param("browserbugmessage");
352
        PutFooter();
353 354 355
        exit 0;
      }
}
356

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
sub FormData {
    my ($field) = (@_);
    return $::FORM{$field};
}

sub html_quote {
    my ($var) = (@_);
    $var =~ s/\&/\&amp;/g;
    $var =~ s/</\&lt;/g;
    $var =~ s/>/\&gt;/g;
    return $var;
}

sub value_quote {
    my ($var) = (@_);
    $var =~ s/\&/\&amp;/g;
    $var =~ s/</\&lt;/g;
    $var =~ s/>/\&gt;/g;
    $var =~ s/"/\&quot;/g;
376 377 378
    # See bug http://bugzilla.mozilla.org/show_bug.cgi?id=4928 for 
    # explanaion of why bugzilla does this linebreak substitution. 
    # This caused form submission problems in mozilla (bug 22983, 32000).
379 380
    $var =~ s/\r\n/\&#013;/g;
    $var =~ s/\n\r/\&#013;/g;
381
    $var =~ s/\r/\&#013;/g;
382
    $var =~ s/\n/\&#013;/g;
383 384 385 386
    return $var;
}

sub navigation_header {
387 388
    if (defined $::COOKIE{"BUGLIST"} && $::COOKIE{"BUGLIST"} ne "" &&
        defined $::FORM{'id'}) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
	my @bugs = split(/:/, $::COOKIE{"BUGLIST"});
	my $cur = lsearch(\@bugs, $::FORM{"id"});
	print "<B>Bug List:</B> (@{[$cur + 1]} of @{[$#bugs + 1]})\n";
	print "<A HREF=\"show_bug.cgi?id=$bugs[0]\">First</A>\n";
	print "<A HREF=\"show_bug.cgi?id=$bugs[$#bugs]\">Last</A>\n";
	if ($cur > 0) {
	    print "<A HREF=\"show_bug.cgi?id=$bugs[$cur - 1]\">Prev</A>\n";
	} else {
	    print "<I><FONT COLOR=\#777777>Prev</FONT></I>\n";
	}
	if ($cur < $#bugs) {
	    $::next_bug = $bugs[$cur + 1];
	    print "<A HREF=\"show_bug.cgi?id=$::next_bug\">Next</A>\n";
	} else {
	    print "<I><FONT COLOR=\#777777>Next</FONT></I>\n";
	}
405
        print qq{&nbsp;&nbsp;<A HREF="buglist.cgi?regetlastlist=1">Show list</A>\n};
406 407 408 409 410
    }
    print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF=query.cgi>Query page</A>\n";
    print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF=enter_bug.cgi>Enter new bug</A>\n"
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
sub make_checkboxes {
    my ($src,$default,$isregexp,$name) = (@_);
    my $last = "";
    my $capitalized = "";
    my $popup = "";
    my $found = 0;
    $default = "" if !defined $default;

    if ($src) {
        foreach my $item (@$src) {
            if ($item eq "-blank-" || $item ne $last) {
                if ($item eq "-blank-") {
                    $item = "";
                }
                $last = $item;
                $capitalized = $item;
                $capitalized =~ tr/A-Z/a-z/;
                $capitalized =~ s/^(.?)(.*)/\u$1$2/;
                if ($isregexp ? $item =~ $default : $default eq $item) {
430
                    $popup .= "<INPUT NAME=$name TYPE=CHECKBOX VALUE=\"$item\" CHECKED>$capitalized<br>";
431 432 433 434 435 436 437 438
                    $found = 1;
                } else {
                    $popup .= "<INPUT NAME=$name TYPE=CHECKBOX VALUE=\"$item\">$capitalized<br>";
                }
            }
        }
    }
    if (!$found && $default ne "") {
439
	$popup .= "<INPUT NAME=$name TYPE=CHECKBOX CHECKED>$default";
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    }
    return $popup;
}

#
# make_selection_widget: creates an HTML selection widget from a list of text strings.
# $groupname is the name of the setting (form value) that this widget will control
# $src is the list of options
# you can specify a $default value which is either a string or a regex pattern to match to
#    identify the default value
# $capitalize lets you optionally capitalize the option strings; the default is the value
#    of Param("capitalizelists")
# $multiple is 1 if several options are selectable (default), 0 otherwise.
# $size is used for lists to control how many items are shown. The default is 7. A list of
#    size 1 becomes a popup menu.
# $preferLists is 1 if selection lists should be used in favor of radio buttons and
#    checkboxes, and 0 otherwise. The default is the value of Param("preferlists").
#
# The actual widget generated depends on the parameter settings:
# 
#        MULTIPLE     PREFERLISTS    SIZE     RESULT
#       0 (single)        0           =1      Popup Menu (normal for list of size 1)
#       0 (single)        0           >1      Radio buttons
#       0 (single)        1           =1      Popup Menu (normal for list of size 1)
#       0 (single)        1           n>1     List of size n, single selection
#       1 (multi)         0           n/a     Check boxes; size ignored
#       1 (multi)         1           n/a     List of size n, multiple selection, of size n
#
sub make_selection_widget {
    my ($groupname,$src,$default,$isregexp,$multiple, $size, $capitalize, $preferLists) = (@_);
    my $last = "";
    my $popup = "";
    my $found = 0;
    my $displaytext = "";
    $groupname = "" if !defined $groupname;
    $default = "" if !defined $default;
    $capitalize = Param("capitalizelists") if !defined $capitalize;
    $multiple = 1 if !defined $multiple;
    $preferLists = Param("preferlists") if !defined $preferLists;
    $size = 7 if !defined $size;
    my $type = "LIST";
    if (!$preferLists) {
        if ($multiple) {
            $type = "CHECKBOX";
        } else {
            if ($size > 1) {
                $type = "RADIO";
            }
        }
    }

    if ($type eq "LIST") {
        $popup .= "<SELECT NAME=\"$groupname\"";
        if ($multiple) {
            $popup .= " MULTIPLE";
        }
        $popup .= " SIZE=$size>\n";
    }
    if ($src) {
        foreach my $item (@$src) {
            if ($item eq "-blank-" || $item ne $last) {
                if ($item eq "-blank-") {
                    $item = "";
                }
                $last = $item;
                $displaytext = $item;
                if ($capitalize) {
                    $displaytext =~ tr/A-Z/a-z/;
                    $displaytext =~ s/^(.?)(.*)/\u$1$2/;
                }   

                if ($isregexp ? $item =~ $default : $default eq $item) {
                    if ($type eq "CHECKBOX") {
                        $popup .= "<INPUT NAME=$groupname type=checkbox VALUE=\"$item\" CHECKED>$displaytext<br>";
                    } elsif ($type eq "RADIO") {
                        $popup .= "<INPUT NAME=$groupname type=radio VALUE=\"$item\" check>$displaytext<br>";
                    } else {
                        $popup .= "<OPTION SELECTED VALUE=\"$item\">$displaytext";
                    }
                    $found = 1;
                } else {
                    if ($type eq "CHECKBOX") {
                        $popup .= "<INPUT NAME=$groupname type=checkbox VALUE=\"$item\">$displaytext<br>";
                    } elsif ($type eq "RADIO") {
                        $popup .= "<INPUT NAME=$groupname type=radio VALUE=\"$item\">$displaytext<br>";
                    } else {
                        $popup .= "<OPTION VALUE=\"$item\">$displaytext";
                    }
                }
            }
        }
    }
    if (!$found && $default ne "") {
        if ($type eq "CHECKBOX") {
            $popup .= "<INPUT NAME=$groupname type=checkbox CHECKED>$default";
        } elsif ($type eq "RADIO") {
            $popup .= "<INPUT NAME=$groupname type=radio checked>$default";
        } else {
            $popup .= "<OPTION SELECTED>$default";
        }
    }
    if ($type eq "LIST") {
        $popup .= "</SELECT>";
    }
    return $popup;
}

547

548 549
$::CheckOptionValues = 1;

550 551 552 553 554
sub make_options {
    my ($src,$default,$isregexp) = (@_);
    my $last = "";
    my $popup = "";
    my $found = 0;
555
    $default = "" if !defined $default;
556 557 558 559 560 561 562 563 564 565 566 567 568 569

    if ($src) {
        foreach my $item (@$src) {
            if ($item eq "-blank-" || $item ne $last) {
                if ($item eq "-blank-") {
                    $item = "";
                }
                $last = $item;
                if ($isregexp ? $item =~ $default : $default eq $item) {
                    $popup .= "<OPTION SELECTED VALUE=\"$item\">$item";
                    $found = 1;
                } else {
                    $popup .= "<OPTION VALUE=\"$item\">$item";
                }
570 571 572 573
            }
        }
    }
    if (!$found && $default ne "") {
574
      if ( Param("strictvaluechecks") && $::CheckOptionValues &&
575 576
           ($default ne $::dontchange) && ($default ne "-All-") &&
           ($default ne "DUPLICATE") ) {
577 578 579 580
        print "Possible bug database corruption has been detected.  " .
              "Please send mail to " . Param("maintainer") . " with " .
              "details of what you were doing when this message " . 
              "appeared.  Thank you.\n";
581 582 583 584 585
        if (!$src) {
            $src = ["???null???"];
        }
        print "<pre>src = " . value_quote(join(' ', @$src)) . "\n";
        print "default = " . value_quote($default) . "</pre>";
586
        PutFooter();
terry%mozilla.org's avatar
terry%mozilla.org committed
587
#        confess "Gulp.";
588 589 590
        exit 0;
              
      } else {
591
	$popup .= "<OPTION SELECTED>$default";
592
      }
593 594 595 596 597 598 599
    }
    return $popup;
}


sub make_popup {
    my ($name,$src,$default,$listtype,$onchange) = (@_);
600
    my $popup = "<SELECT NAME=$name";
601
    if ($listtype > 0) {
602
        $popup .= " SIZE=5";
603 604 605 606 607 608 609 610 611 612 613 614 615 616
        if ($listtype == 2) {
            $popup .= " MULTIPLE";
        }
    }
    if (defined $onchange && $onchange ne "") {
        $popup .= " onchange=$onchange";
    }
    $popup .= ">" . make_options($src, $default,
                                 ($listtype == 2 && $default ne ""));
    $popup .= "</SELECT>";
    return $popup;
}


617 618 619 620 621 622 623 624 625 626
sub BuildPulldown {
    my ($name, $valuelist, $default) = (@_);

    my $entry = qq{<SELECT NAME="$name">};
    foreach my $i (@$valuelist) {
        my ($tag, $desc) = (@$i);
        my $selectpart = "";
        if ($tag eq $default) {
            $selectpart = " SELECTED";
        }
627 628 629
        if (!defined $desc) {
            $desc = $tag;
        }
630 631 632 633 634 635 636 637 638
        $entry .= qq{<OPTION$selectpart VALUE="$tag">$desc\n};
    }
    $entry .= qq{</SELECT>};
    return $entry;
}




639 640 641 642
sub PasswordForLogin {
    my ($login) = (@_);
    SendSQL("select cryptpassword from profiles where login_name = " .
	    SqlQuote($login));
643 644 645 646 647
    my $result = FetchOneColumn();
    if (!defined $result) {
        $result = "";
    }
    return $result;
648 649
}

650 651 652 653

sub quietly_check_login() {
    $::usergroupset = '0';
    my $loginok = 0;
654
    $::disabledreason = '';
655
    $::userid = 0;
656 657 658
    if (defined $::COOKIE{"Bugzilla_login"} &&
	defined $::COOKIE{"Bugzilla_logincookie"}) {
        ConnectToDatabase();
659 660 661
        if (!defined $ENV{'REMOTE_HOST'}) {
            $ENV{'REMOTE_HOST'} = $ENV{'REMOTE_ADDR'};
        }
662 663
        SendSQL("SELECT profiles.userid, profiles.groupset, " .
                "profiles.login_name, " .
664
                "profiles.login_name = " .
665
		SqlQuote($::COOKIE{"Bugzilla_login"}) .
666 667
		" AND profiles.cryptpassword = logincookies.cryptpassword " .
		"AND logincookies.hostname = " .
668
		SqlQuote($ENV{"REMOTE_HOST"}) .
669
                ", profiles.disabledtext " .
670
		" FROM profiles, logincookies WHERE logincookies.cookie = " .
671
		SqlQuote($::COOKIE{"Bugzilla_logincookie"}) .
672
		" AND profiles.userid = logincookies.userid");
673 674
        my @row;
        if (@row = FetchSQLData()) {
675
            my ($userid, $groupset, $loginname, $ok, $disabledtext) = (@row);
676 677 678
            if ($ok) {
                if ($disabledtext eq '') {
                    $loginok = 1;
679
                    $::userid = $userid;
680 681 682 683 684 685 686
                    $::usergroupset = $groupset;
                    $::COOKIE{"Bugzilla_login"} = $loginname; # Makes sure case
                                                              # is in
                                                              # canonical form.
                } else {
                    $::disabledreason = $disabledtext;
                }
687 688 689
            }
        }
    }
690 691 692 693 694
    # if 'who' is passed in, verify that it's a good value
    if ($::FORM{'who'}) {
        my $whoid = DBname_to_id($::FORM{'who'});
        delete $::FORM{'who'} unless $whoid;
    }
695 696 697
    if (!$loginok) {
        delete $::COOKIE{"Bugzilla_login"};
    }
698 699 700 701 702 703
    return $loginok;
}




704 705
sub CheckEmailSyntax {
    my ($addr) = (@_);
706
    my $match = Param('emailregexp');
707
    if ($addr !~ /$match/ || $addr =~ /[\\\(\)<>&,;:"\[\] \t\r\n]/) {
708 709
        print "Content-type: text/html\n\n";

710 711 712
        # For security, escape HTML special characters.
        $addr = html_quote($addr);

713
        PutHeader("Check e-mail syntax");
714 715
        print "The e-mail address you entered\n";
        print "(<b>$addr</b>) didn't match our minimal\n";
716
        print "syntax checking for a legal email address.\n";
717 718 719 720 721
        print Param('emailregexpdesc') . "\n";
        print "It must also not contain any of these special characters: " .
              "<tt>\\ ( ) &amp; &lt; &gt; , ; : \" [ ]</tt> " .
              "or any whitespace.\n";
        print "<p>Please click <b>Back</b> and try again.\n";
722
        PutFooter();
723 724 725 726 727 728
        exit;
    }
}



729 730 731
sub MailPassword {
    my ($login, $password) = (@_);
    my $urlbase = Param("urlbase");
732 733 734 735 736
    my $template = Param("passwordmail");
    my $msg = PerformSubsts($template,
                            {"mailaddress" => $login . Param('emailsuffix'),
                             "login" => $login,
                             "password" => $password});
737 738 739 740 741 742 743 744 745 746 747 748

    open SENDMAIL, "|/usr/lib/sendmail -t";
    print SENDMAIL $msg;
    close SENDMAIL;

    print "The password for the e-mail address\n";
    print "$login has been e-mailed to that address.\n";
    print "<p>When the e-mail arrives, you can click <b>Back</b>\n";
    print "and enter your password in the form there.\n";
}


749 750 751 752 753 754 755
sub confirm_login {
    my ($nexturl) = (@_);

# Uncommenting the next line can help debugging...
#    print "Content-type: text/plain\n\n";

    ConnectToDatabase();
756 757 758 759 760 761
    # I'm going to reorganize some of this stuff a bit.  Since we're adding
    # a second possible validation method (LDAP), we need to move some of this
    # to a later section.  -Joe Robins, 8/3/00
    my $enteredlogin = "";
    my $realcryptpwd = "";

762 763 764 765 766 767 768 769 770 771 772 773 774
    # If the form contains Bugzilla login and password fields, use Bugzilla's 
    # built-in authentication to authenticate the user (otherwise use LDAP below).
    if (defined $::FORM{"Bugzilla_login"} && defined $::FORM{"Bugzilla_password"}) {
        # Make sure the user's login name is a valid email address.
        $enteredlogin = $::FORM{"Bugzilla_login"};
        CheckEmailSyntax($enteredlogin);

        # Retrieve the user's ID and crypted password from the database.
        my $userid;
        SendSQL("SELECT userid, cryptpassword FROM profiles 
                 WHERE login_name = " . SqlQuote($enteredlogin));
        ($userid, $realcryptpwd) = FetchSQLData();

775 776 777 778 779 780
        # Make sure the user exists or throw an error (but do not admit it was a username
        # error to make it harder for a cracker to find account names by brute force).
        $userid
          || DisplayError("The username or password you entered is not valid.")
          && exit;

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
        # If this is a new user, generate a password, insert a record
        # into the database, and email their password to them.
        if ( defined $::FORM{"PleaseMailAPassword"} && !$userid ) {
            my $password = InsertNewUser($enteredlogin, "");
            print "Content-Type: text/html\n\n";
            PutHeader("Account Created");
            MailPassword($enteredlogin, $password);
            PutFooter();
            exit;
        }

        # Otherwise, authenticate the user.
        else {
            # Get the salt from the user's crypted password.
            my $salt = $realcryptpwd;

            # Using the salt, crypt the password the user entered.
            my $enteredCryptedPassword = crypt( $::FORM{"Bugzilla_password"} , $salt );

            # Make sure the passwords match or throw an error.
            ($enteredCryptedPassword eq $realcryptpwd)
              || DisplayError("The username or password you entered is not valid.")
              && exit;

            # If the user has successfully logged in, delete any password tokens
            # lying around in the system for them.
            use Token;
            my $token = Token::HasPasswordToken($userid);
            while ( $token ) {
                Token::Cancel($token, "user logged in");
                $token = Token::HasPasswordToken($userid);
            }
        }
814 815 816 817 818 819

     } elsif (Param("useLDAP") &&
              defined $::FORM{"LDAP_login"} &&
              defined $::FORM{"LDAP_password"}) {
       # If we're using LDAP for login, we've got an entirely different
       # set of things to check.
820 821

# see comment at top of file near eval
822 823
       # First, if we don't have the LDAP modules available to us, we can't
       # do this.
824 825 826 827 828 829 830 831 832
#       if(!$have_ldap) {
#         print "Content-type: text/html\n\n";
#         PutHeader("LDAP not enabled");
#         print "The necessary modules for LDAP login are not installed on ";
#         print "this machine.  Please send mail to ".Param("maintainer");
#         print " and notify him of this problem.\n";
#         PutFooter();
#         exit;
#       }
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947

       # Next, we need to bind anonymously to the LDAP server.  This is
       # because we need to get the Distinguished Name of the user trying
       # to log in.  Some servers (such as iPlanet) allow you to have unique
       # uids spread out over a subtree of an area (such as "People"), so
       # just appending the Base DN to the uid isn't sufficient to get the
       # user's DN.  For servers which don't work this way, there will still
       # be no harm done.
       my $LDAPserver = Param("LDAPserver");
       if ($LDAPserver eq "") {
         print "Content-type: text/html\n\n";
         PutHeader("LDAP server not defined");
         print "The LDAP server for authentication has not been defined.  ";
         print "Please contact ".Param("maintainer")." ";
         print "and notify him of this problem.\n";
         PutFooter();
         exit;
       }

       my $LDAPport = "389";  #default LDAP port
       if($LDAPserver =~ /:/) {
         ($LDAPserver, $LDAPport) = split(":",$LDAPserver);
       }
       my $LDAPconn = new Mozilla::LDAP::Conn($LDAPserver,$LDAPport);
       if(!$LDAPconn) {
         print "Content-type: text/html\n\n";
         PutHeader("Unable to connect to LDAP server");
         print "I was unable to connect to the LDAP server for user ";
         print "authentication.  Please contact ".Param("maintainer");
         print " and notify him of this problem.\n";
         PutFooter();
         exit;
       }

       # We've got our anonymous bind;  let's look up this user.
       my $dnEntry = $LDAPconn->search(Param("LDAPBaseDN"),"subtree","uid=".$::FORM{"LDAP_login"});
       if(!$dnEntry) {
         print "Content-type: text/html\n\n";
         PutHeader("Login Failed");
         print "The username or password you entered is not valid.\n";
         print "Please click <b>Back</b> and try again.\n";
         PutFooter();
         exit;
       }

       # Now we get the DN from this search.  Once we've got that, we're
       # done with the anonymous bind, so we close it.
       my $userDN = $dnEntry->getDN;
       $LDAPconn->close;

       # Now we attempt to bind as the specified user.
       $LDAPconn = new Mozilla::LDAP::Conn($LDAPserver,$LDAPport,$userDN,$::FORM{"LDAP_password"});
       if(!$LDAPconn) {
         print "Content-type: text/html\n\n";
         PutHeader("Login Failed");
         print "The username or password you entered is not valid.\n";
         print "Please click <b>Back</b> and try again.\n";
         PutFooter();
         exit;
       }

       # And now we're going to repeat the search, so that we can get the
       # mail attribute for this user.
       my $userEntry = $LDAPconn->search(Param("LDAPBaseDN"),"subtree","uid=".$::FORM{"LDAP_login"});
       if(!$userEntry->exists(Param("LDAPmailattribute"))) {
         print "Content-type: text/html\n\n";
         PutHeader("LDAP authentication error");
         print "I was unable to retrieve the ".Param("LDAPmailattribute");
         print " attribute from the LDAP server.  Please contact ";
         print Param("maintainer")." and notify him of this error.\n";
         PutFooter();
         exit;
       }

       # Mozilla::LDAP::Entry->getValues returns an array for the attribute
       # requested, even if there's only one entry.
       $enteredlogin = ($userEntry->getValues(Param("LDAPmailattribute")))[0];

       # We're going to need the cryptpwd for this user from the database
       # so that we can set the cookie below, even though we're not going
       # to use it for authentication.
       $realcryptpwd = PasswordForLogin($enteredlogin);

       # If we don't get a result, then we've got a user who isn't in
       # Bugzilla's database yet, so we've got to add them.
       if($realcryptpwd eq "") {
         # We'll want the user's name for this.
         my $userRealName = ($userEntry->getValues("displayName"))[0];
         if($userRealName eq "") {
           $userRealName = ($userEntry->getValues("cn"))[0];
         }
         InsertNewUser($enteredlogin, $userRealName);
         $realcryptpwd = PasswordForLogin($enteredlogin);
       }
     } # end LDAP authentication

     # And now, if we've logged in via either method, then we need to set
     # the cookies.
     if($enteredlogin ne "") {
       $::COOKIE{"Bugzilla_login"} = $enteredlogin;
       if (!defined $ENV{'REMOTE_HOST'}) {
         $ENV{'REMOTE_HOST'} = $ENV{'REMOTE_ADDR'};
       }
       SendSQL("insert into logincookies (userid,cryptpassword,hostname) values (@{[DBNameToIdAndCheck($enteredlogin)]}, @{[SqlQuote($realcryptpwd)]}, @{[SqlQuote($ENV{'REMOTE_HOST'})]})");
       SendSQL("select LAST_INSERT_ID()");
       my $logincookie = FetchOneColumn();

       $::COOKIE{"Bugzilla_logincookie"} = $logincookie;
       print "Set-Cookie: Bugzilla_login=$enteredlogin ; path=/; expires=Sun, 30-Jun-2029 00:00:00 GMT\n";
       print "Set-Cookie: Bugzilla_logincookie=$logincookie ; path=/; expires=Sun, 30-Jun-2029 00:00:00 GMT\n";

       # This next one just cleans out any old bugzilla passwords that may
       # be sitting around in the cookie files, from the bad old days when
       # we actually stored the password there.
       print "Set-Cookie: Bugzilla_password= ; path=/; expires=Sun, 30-Jun-80 00:00:00 GMT\n";
948 949 950
    }


951
    my $loginok = quietly_check_login();
952

953
    if ($loginok != 1) {
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
        if ($::disabledreason) {
            print "Set-Cookie: Bugzilla_login= ; path=/; expires=Sun, 30-Jun-80 00:00:00 GMT
Set-Cookie: Bugzilla_logincookie= ; path=/; expires=Sun, 30-Jun-80 00:00:00 GMT
Set-Cookie: Bugzilla_password= ; path=/; expires=Sun, 30-Jun-80 00:00:00 GMT
Content-type: text/html

";
            PutHeader("Your account has been disabled");
            print $::disabledreason;
            print "<HR>\n";
            print "If you believe your account should be restored, please\n";
            print "send email to " . Param("maintainer") . " explaining\n";
            print "why.\n";
            PutFooter();
            exit();
        }
970
        print "Content-type: text/html\n\n";
971
        PutHeader("Login");
972 973 974 975 976
        if(Param("useLDAP")) {
          print "I need a legitimate LDAP username and password to continue.\n";
        } else {
          print "I need a legitimate e-mail address and password to continue.\n";
        }
977 978
        if (!defined $nexturl || $nexturl eq "") {
	    # Sets nexturl to be argv0, stripping everything up to and
979 980
	    # including the last slash (or backslash on Windows).
	    $0 =~ m:[^/\\]*$:;
981 982 983
	    $nexturl = $&;
        }
        my $method = "POST";
984 985 986 987 988 989 990 991
# We always want to use POST here, because we're submitting a password and don't
# want to see it in the location bar in the browser in case a co-worker is looking
# over your shoulder.  If you have cookies off and need to bookmark the query, you
# can bookmark it from the screen asking for your password, and it should still
# work.  See http://bugzilla.mozilla.org/show_bug.cgi?id=15980
#        if (defined $ENV{"REQUEST_METHOD"} && length($::buffer) > 1) {
#            $method = $ENV{"REQUEST_METHOD"};
#        }
992 993 994
        print "
<FORM action=$nexturl method=$method>
<table>
995 996 997 998 999 1000
<tr>";
        if(Param("useLDAP")) {
          print "
<td align=right><b>Username:</b></td>
<td><input size=10 name=LDAP_login></td>
</tr>
1001
<tr>
1002 1003 1004 1005
<td align=right><b>Password:</b></td>
<td><input type=password size=10 name=LDAP_password></td>";
        } else {
          print "
1006 1007 1008 1009 1010
<td align=right><b>E-mail address:</b></td>
<td><input size=35 name=Bugzilla_login></td>
</tr>
<tr>
<td align=right><b>Password:</b></td>
1011 1012 1013
<td><input type=password size=35 name=Bugzilla_password></td>";
        }
        print "
1014 1015 1016
</tr>
</table>
";
1017 1018 1019 1020 1021
        # Add all the form fields into the form as hidden fields
        # (except for Bugzilla_login and Bugzilla_password which we
        # already added as text fields above).
        foreach my $i ( grep( $_ !~ /^Bugzilla_/ , keys %::FORM ) ) {
            print qq|<input type="hidden" name="$i" value="@{[value_quote($::FORM{$i})]}">\n|;
1022
        }
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

        print qq|
          <input type="submit" name="GoAheadAndLogIn" value="Login">
          </form>
        |;

        # Allow the user to request a token to change their password (unless
        # we are using LDAP, in which case the user must use LDAP to change it).
        unless( Param("useLDAP") ) {
            print qq|
              <hr>
              <form method="get" action="token.cgi">
                <input type="hidden" name="a" value="reqpw">
1036
                If you have forgotten your password,
1037 1038 1039 1040 1041
                enter your login name below and submit a request 
                to change your password.<br>
                <input size="35" name="loginname">
                <input type="submit" value="Submit Request">
              </form>
1042 1043
              <hr>
              If you don't have a Bugzilla account, you can <a href="createaccount.cgi">create a new account</a>.
1044
            |;
1045
        }
1046 1047 1048 1049

        # This seems like as good as time as any to get rid of old
        # crufty junk in the logincookies table.  Get rid of any entry
        # that hasn't been used in a month.
1050 1051 1052 1053
        if ($::dbwritesallowed) {
            SendSQL("DELETE FROM logincookies " .
                    "WHERE TO_DAYS(NOW()) - TO_DAYS(lastused) > 30");
        }
1054 1055

        
1056
        PutFooter();
1057 1058 1059 1060
        exit;
    }

    # Update the timestamp on our logincookie, so it'll keep on working.
1061 1062 1063 1064
    if ($::dbwritesallowed) {
        SendSQL("UPDATE logincookies SET lastused = null " .
                "WHERE cookie = $::COOKIE{'Bugzilla_logincookie'}");
    }
1065
    return $::userid;
1066 1067 1068 1069
}


sub PutHeader {
1070
    my ($title, $h1, $h2, $extra, $jscript) = (@_);
1071 1072 1073 1074 1075 1076 1077

    if (!defined $h1) {
	$h1 = $title;
    }
    if (!defined $h2) {
	$h2 = "";
    }
1078 1079 1080
    if (!defined $extra) {
	$extra = "";
    }
1081
    $jscript ||= "";
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    # If we are shutdown, we want a very basic page to give that
    # information.  Also, the page title should indicate that
    # we are down.  
    if (Param('shutdownhtml')) {
        $title = "Bugzilla is Down";
        $h1 = "Bugzilla is currently down";
        $h2 = "";
        $extra = "";
        $jscript = "";
    }
1092

1093
    print "<HTML><HEAD>\n<TITLE>$title</TITLE>\n";
1094
    print Param("headerhtml") . "\n$jscript\n</HEAD>\n";
1095
    print "<BODY " . Param("bodyhtml") . " $extra>\n";
1096

1097
    print PerformSubsts(Param("bannerhtml"), undef);
1098

1099
    print "<TABLE BORDER=0 CELLSPACING=0 WIDTH=\"100%\">\n";
1100
    print " <TR>\n";
1101
    print "  <TD WIDTH=10% VALIGN=TOP ALIGN=LEFT>\n";
1102
    print "   <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=2>\n";
1103 1104
    print "    <TR><TD VALIGN=TOP ALIGN=LEFT NOWRAP>\n";
    print "     <FONT SIZE=+1><B>$h1</B></FONT>";
1105 1106 1107
    print "    </TD></TR>\n";
    print "   </TABLE>\n";
    print "  </TD>\n";
1108 1109
    print "  <TD VALIGN=CENTER>&nbsp;</TD>\n";
    print "  <TD VALIGN=CENTER ALIGN=LEFT>\n";
1110

1111 1112
    print "$h2\n";
    print "</TD></TR></TABLE>\n";
1113

1114
    if (Param("shutdownhtml")) {
1115 1116 1117 1118
        # If we are dealing with the params page, we want
        # to ignore shutdownhtml
        if ($0 !~ m:[\\/](do)?editparams.cgi$:) {
            print "<p>\n";
1119 1120 1121 1122
            print Param("shutdownhtml");
            exit;
        }
    }
1123 1124 1125
}


1126
sub PutFooter {
1127 1128
    print PerformSubsts(Param("footerhtml"));
    SyncAnyPendingShadowChanges();
1129 1130 1131
}


1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
sub DisplayError {
  my ($message, $title) = (@_);
  $title ||= "Error";

  print "Content-type: text/html\n\n";
  PutHeader($title);

  print PerformSubsts( Param("errorhtml") , {errormsg => $message} );

  PutFooter();

  return 1;
}

1146 1147 1148 1149
sub PuntTryAgain ($) {
    my ($str) = (@_);
    print PerformSubsts(Param("errorhtml"),
                        {errormsg => $str});
1150
    SendSQL("UNLOCK TABLES");
1151 1152 1153 1154 1155
    PutFooter();
    exit;
}


1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
sub CheckIfVotedConfirmed {
    my ($id, $who) = (@_);
    SendSQL("SELECT bugs.votes, bugs.bug_status, products.votestoconfirm, " .
            "       bugs.everconfirmed " .
            "FROM bugs, products " .
            "WHERE bugs.bug_id = $id AND products.product = bugs.product");
    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 " .
1168
                "(bug_id,who,bug_when,fieldid,removed,added) VALUES " .
1169 1170 1171 1172
                "($id,$who,now(),$fieldid,'$::unconfirmedstate','NEW')");
        if (!$everconfirmed) {
            $fieldid = GetFieldID("everconfirmed");
            SendSQL("INSERT INTO bugs_activity " .
1173
                    "(bug_id,who,bug_when,fieldid,removed,added) VALUES " .
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
                    "($id,$who,now(),$fieldid,'0','1')");
        }
        AppendComment($id, DBID_to_name($who),
                      "*** This bug has been confirmed by popular vote. ***");
        print "<TABLE BORDER=1><TD><H2>Bug $id has been confirmed by votes.</H2>\n";
        system("./processmail", $id);
        print "<TD><A HREF=\"show_bug.cgi?id=$id\">Go To BUG# $id</A></TABLE>\n";
    }

}



1187 1188 1189
sub DumpBugActivity {
    my ($id, $starttime) = (@_);
    my $datepart = "";
1190 1191 1192

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

1193
    if (defined $starttime) {
1194
        $datepart = "and bugs_activity.bug_when >= $starttime";
1195 1196
    }
    my $query = "
1197 1198
        SELECT IFNULL(fielddefs.description, bugs_activity.fieldid),
                bugs_activity.attach_id,
1199
                bugs_activity.bug_when,
1200
                bugs_activity.removed, bugs_activity.added,
1201
                profiles.login_name
1202 1203 1204
        FROM bugs_activity LEFT JOIN fielddefs ON 
                                     bugs_activity.fieldid = fielddefs.fieldid,
             profiles
1205 1206 1207
        WHERE bugs_activity.bug_id = $id $datepart
              AND profiles.userid = bugs_activity.who
        ORDER BY bugs_activity.bug_when";
1208 1209 1210

    SendSQL($query);
    
1211 1212 1213 1214 1215 1216 1217 1218
    # Instead of outright printing this, we are going to store it in a $html
    # variable and print it and the end.  This is so we can explain ? (if nesc.)
    # at the top of the activity table rather than the botom.
    my $html = "";
    $html .= "<table border cellpadding=4>\n";
    $html .= "<tr>\n";
    $html .= "    <th>Who</th><th>What</th><th>Removed</th><th>Added</th><th>When</th>\n";
    $html .= "</tr>\n";
1219 1220
    
    my @row;
1221
    my $incomplete_data = 0;
1222
    while (@row = FetchSQLData()) {
1223 1224 1225
        my ($field,$attachid,$when,$removed,$added,$who) = (@row);
        $field =~ s/^Attachment/<a href="attachment.cgi?id=$attachid&action=view">Attachment #$attachid<\/a>/ 
          if (Param('useattachmenttracker') && $attachid);
1226 1227
        $removed = html_quote($removed);
        $added = html_quote($added);
1228 1229
        $removed = "&nbsp;" if $removed eq "";
        $added = "&nbsp;" if $added eq "";
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
        if ($added =~ /^\?/ || $removed =~ /^\?/) {
            $incomplete_data = 1;
        }
        $html .= "<tr>\n";
        $html .= "<td>$who</td>\n";
        $html .= "<td>$field</td>\n";
        $html .= "<td>$removed</td>\n";
        $html .= "<td>$added</td>\n";
        $html .= "<td>$when</td>\n";
        $html .= "</tr>\n";
    }
    $html .= "</table>\n";
    if ($incomplete_data) {
        print "There was a bug in older versions of Bugzilla which caused activity data \n";
        print "to be lost if there was a large number of cc's or dependencies.  That \n";
        print "has been fixed, however, there was some data already lost on this bug \n";
        print "that could not be regenerated.  The changes that the script could not \n";
        print "reliably determine are prefixed by '?'\n";
        print "<p>\n";
1249
    }
1250
    print $html;
1251 1252 1253
}


1254 1255
sub GetCommandMenu {
    my $loggedin = quietly_check_login();
1256 1257 1258
    my $html = "";
    $html .= <<"--endquote--";
<FORM METHOD=GET ACTION="show_bug.cgi">
1259
<TABLE width="100%"><TR><TD>
1260
Actions:
1261 1262
</TD><TD VALIGN="middle" NOWRAP>
<a href='enter_bug.cgi'>New</a> | <a href='query.cgi'>Query</a> |
1263 1264
--endquote--

1265 1266 1267 1268
    if (-e "query2.cgi") {
        $html .= "[<a href='query2.cgi'>beta</a>]";
    }
    
1269
    $html .=
1270
        qq{ <INPUT TYPE=SUBMIT VALUE="Find"> bug \# <INPUT NAME=id SIZE=6>};
1271

1272 1273 1274 1275 1276
    $html .= " | <a href='reports.cgi'>Reports</a>"; 
    if ($loggedin) {
        if ($::anyvotesallowed) {
            $html .= " | <A HREF=\"showvotes.cgi\">My votes</A>";
        }
1277
    }
1278
    if ($loggedin) {
1279
    	#a little mandatory SQL, used later on
1280 1281 1282
        SendSQL("SELECT mybugslink, userid, blessgroupset FROM profiles " .
                "WHERE login_name = " . SqlQuote($::COOKIE{'Bugzilla_login'}));
        my ($mybugslink, $userid, $blessgroupset) = (FetchSQLData());
1283 1284
        
        #Begin settings
1285
        $html .= "</TD><TD>&nbsp;</TD><TD VALIGN=middle><NOBR>Edit <a href='userprefs.cgi'>prefs</a></NOBR>";
1286 1287 1288
        if (UserInGroup("tweakparams")) {
            $html .= ", <a href=editparams.cgi>parameters</a>";
        }
1289
        if (UserInGroup("editusers") || $blessgroupset) {
1290 1291
            $html .= ", <a href=editusers.cgi>users</a>";
        }
1292
        if (UserInGroup("editcomponents")) {
1293
            $html .= ", <a href=editproducts.cgi>components</a>";
1294 1295
            $html .= ", <a href=editattachstatuses.cgi><NOBR>attachment statuses</NOBR></a>"
              if Param('useattachmenttracker');
1296
        }
1297 1298 1299
        if (UserInGroup("creategroups")) {
            $html .= ", <a href=editgroups.cgi>groups</a>";
        }
1300
        if (UserInGroup("editkeywords")) {
1301
            $html .= ", <a href=editkeywords.cgi>keywords</a>";
1302
        }
1303 1304 1305 1306
        if (UserInGroup("tweakparams")) {
            $html .= " | <a href=sanitycheck.cgi><NOBR>Sanity check</NOBR></a>";
        }

1307
        $html .= " | <NOBR><a href=relogin.cgi>Log out</a> $::COOKIE{'Bugzilla_login'}</NOBR>";
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
        $html .= "</TD></TR>";
        
		#begin preset queries
        my $mybugstemplate = Param("mybugstemplate");
        my %substs;
        $substs{'userid'} = url_quote($::COOKIE{"Bugzilla_login"});
        if (!defined $::anyvotesallowed) {
            GetVersionTable();
        }
        $html .= "</TR><TR>";
        $html .= "<TD>Preset Queries: </TD>";
1319
        $html .= "<TD colspan=3>\n";
1320 1321 1322 1323 1324 1325
        if ($mybugslink) {
            my $mybugsurl = PerformSubsts($mybugstemplate, \%substs);
            $html = $html . "<A HREF='$mybugsurl'><NOBR>My bugs</NOBR></A>";
        }
        SendSQL("SELECT name FROM namedqueries " .
                "WHERE userid = $userid AND linkinfooter");
1326
        my $anynamedqueries = 0;
1327 1328
        while (MoreSQLData()) {
            my ($name) = (FetchSQLData());
1329 1330 1331
            if ($anynamedqueries || $mybugslink) { $html .= " | " }
            $anynamedqueries = 1;
            $html .= "<A HREF=\"buglist.cgi?&cmdtype=runnamed&namedcmd=" .
1332 1333 1334
                     url_quote($name) . "\"><NOBR>$name</NOBR></A>";
        }
        $html .= "</TR>\n<TR>";
1335
    } else {
1336
    $html .= "</TD><TD>&nbsp;</TD><TD valign=middle align=right>\n";
1337
        $html .=
1338
            " <a href=\"createaccount.cgi\"><NOBR>New account</NOBR></a>\n";
1339 1340
        $html .=
            " | <NOBR><a href=query.cgi?GoAheadAndLogIn=1>Log in</a></NOBR>";
1341
        $html .= "</TD></TR>";
1342
    }
1343 1344
    $html .= "</FORM>\n";
    $html .= "</TABLE>";                
1345 1346 1347
    return $html;
}

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
############# Live code below here (that is, not subroutine defs) #############


$| = 1;

# Uncommenting this next line can help debugging.
# print "Content-type: text/html\n\nHello mom\n";

# foreach my $k (sort(keys %ENV)) {
#     print "$k $ENV{$k}<br>\n";
# }

if (defined $ENV{"REQUEST_METHOD"}) {
    if ($ENV{"REQUEST_METHOD"} eq "GET") {
        if (defined $ENV{"QUERY_STRING"}) {
            $::buffer = $ENV{"QUERY_STRING"};
        } else {
            $::buffer = "";
        }
1367
        ProcessFormFields $::buffer;
1368
    } else {
1369
        if (exists($ENV{"CONTENT_TYPE"}) && $ENV{"CONTENT_TYPE"} =~
1370 1371 1372 1373 1374 1375 1376 1377
            m@multipart/form-data; boundary=\s*([^; ]+)@) {
            ProcessMultipartFormFields($1);
            $::buffer = "";
        } else {
            read STDIN, $::buffer, $ENV{"CONTENT_LENGTH"} ||
                die "Couldn't get form data";
            ProcessFormFields $::buffer;
        }
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
    }
}


if (defined $ENV{"HTTP_COOKIE"}) {
    foreach my $pair (split(/;/, $ENV{"HTTP_COOKIE"})) {
	$pair = trim($pair);
	if ($pair =~ /^([^=]*)=(.*)$/) {
	    $::COOKIE{$1} = $2;
	} else {
	    $::COOKIE{$pair} = "";
	}
    }
}

1;