globals.pl 49.4 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
#                 Jake <jake@acutex.net>
23
#                 Bradley Baetz <bbaetz@cs.mcgill.ca>
24
#                 Christopher Aillon <christopher@aillon.com>
25 26 27 28 29

# Contains some global variables and routines used throughout bugzilla.

use diagnostics;
use strict;
30 31 32 33 34 35

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

sub globals_pl_sillyness {
    my $zz;
36
    $zz = @main::SqlStateStack;
37 38
    $zz = @main::chooseone;
    $zz = @main::default_column_list;
39
    $zz = $main::defaultqueryname;
40
    $zz = @main::dontchange;
41
    $zz = %main::keywordsbyname;
42 43
    $zz = @main::legal_bug_status;
    $zz = @main::legal_components;
44
    $zz = @main::legal_keywords;
45 46 47 48 49 50 51 52 53
    $zz = @main::legal_opsys;
    $zz = @main::legal_platform;
    $zz = @main::legal_priority;
    $zz = @main::legal_product;
    $zz = @main::legal_severity;
    $zz = @main::legal_target_milestone;
    $zz = @main::legal_versions;
    $zz = @main::milestoneurl;
    $zz = @main::prodmaxvotes;
54
    $zz = $main::superusergroupset;
55
    $zz = $main::userid;
56 57
}

58 59 60 61 62
#
# Here are the --LOCAL-- variables defined in 'localconfig' that we'll use
# here
# 

tara%tequilarista.org's avatar
tara%tequilarista.org committed
63
$::db_host = "localhost";
64
$::db_port = 3306;
tara%tequilarista.org's avatar
tara%tequilarista.org committed
65 66 67
$::db_name = "bugs";
$::db_user = "bugs";
$::db_pass = "";
68 69 70

do 'localconfig';

71
use DBI;
72 73

use Date::Format;               # For time2str().
74
use Date::Parse;               # For str2time().
75
#use Carp;                       # for confess
76
use RelationSet;
77

78
# Some environment variables are not taint safe
79
delete @::ENV{'PATH', 'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
80

81
# Contains the version string for the current running Bugzilla.
82
$::param{'version'} = '2.15';
83

84 85
$::dontchange = "--do_not_change--";
$::chooseone = "--Choose_one:--";
86
$::defaultqueryname = "(Default query)";
87
$::unconfirmedstate = "UNCONFIRMED";
88
$::dbwritesallowed = 1;
89

90 91 92 93
# Adding a global variable for the value of the superuser groupset.
# Joe Robins, 7/5/00
$::superusergroupset = "9223372036854775807";

94 95 96 97 98 99
#sub die_with_dignity {
#    my ($err_msg) = @_;
#    print $err_msg;
#    confess($err_msg);
#}
#$::SIG{__DIE__} = \&die_with_dignity;
100

101
sub ConnectToDatabase {
102
    my ($useshadow) = (@_);
103
    if (!defined $::db) {
tara%tequilarista.org's avatar
tara%tequilarista.org committed
104
        my $name = $::db_name;
105
        if ($useshadow && Param("shadowdb") && Param("queryagainstshadowdb")) {
106 107 108
            $name = Param("shadowdb");
            $::dbwritesallowed = 0;
        }
109
        $::db = DBI->connect("DBI:mysql:host=$::db_host;database=$name;port=$::db_port", $::db_user, $::db_pass)
110
            || die "Bugzilla is currently broken. Please try again later. " . 
111 112
      "If the problem persists, please contact " . Param("maintainer") .
      ". The error you should quote is: " . $DBI::errstr;
113 114 115
    }
}

116
sub ReconnectToShadowDatabase {
117
    if (Param("shadowdb") && Param("queryagainstshadowdb")) {
118 119 120 121 122
        SendSQL("USE " . Param("shadowdb"));
        $::dbwritesallowed = 0;
    }
}

123 124 125
my $shadowchanges = 0;
sub SyncAnyPendingShadowChanges {
    if ($shadowchanges) {
126 127 128 129 130 131 132 133
        my $pid;
        FORK: {
            if ($pid = fork) { # create a fork
                # parent code runs here
                $shadowchanges = 0;
                return;
            } elsif (defined $pid) {
                # child process code runs here
134 135 136 137 138
                exec("./syncshadowdb","--") or die "Unable to exec syncshadowdb: $!";
                # the idea was that passing the second parameter tricks it into
                # using execvp instead of running a shell. Not really necessary since
                # there are no shell meta-characters, but it passes our tinderbox
                # test that way. :) http://bugzilla.mozilla.org/show_bug.cgi?id=21253
139 140 141 142 143 144 145 146 147
            } elsif ($! =~ /No more process/) {
                # recoverable fork error, try again in 5 seconds
                sleep 5;
                redo FORK;
            } else {
                # something weird went wrong
                die "Can't create background process to run syncshadowdb: $!";
            }
        }
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
# This is used to manipulate global state used by SendSQL(),
# MoreSQLData() and FetchSQLData().  It provides a way to do another
# SQL query without losing any as-yet-unfetched data from an existing
# query.  Just push the current global state, do your new query and fetch
# any data you need from it, then pop the current global state.
# 
@::SQLStateStack = ();

sub PushGlobalSQLState() {
    push @::SQLStateStack, $::currentquery;
    push @::SQLStateStack, [ @::fetchahead ]; 
}

sub PopGlobalSQLState() {
    die ("PopGlobalSQLState: stack underflow") if ( $#::SQLStateStack < 1 );
    @::fetchahead = @{pop @::SQLStateStack};
    $::currentquery = pop @::SQLStateStack;
}

sub SavedSQLStates() {
    return ($#::SqlStateStack + 1) / 2;
}


176 177 178 179 180 181 182
my $dosqllog = (-e "data/sqllog") && (-w "data/sqllog");

sub SqlLog {
    if ($dosqllog) {
        my ($str) = (@_);
        open(SQLLOGFID, ">>data/sqllog") || die "Can't write to data/sqllog";
        if (flock(SQLLOGFID,2)) { # 2 is magic 'exclusive lock' const.
183 184 185 186 187 188 189 190

            # if we're a subquery (ie there's pushed global state around)
            # indent to indicate the level of subquery-hood
            #
            for (my $i = SavedSQLStates() ; $i > 0 ; $i--) {
                print SQLLOGFID "\t";
            }

191 192 193 194 195 196
            print SQLLOGFID time2str("%D %H:%M:%S $$", time()) . ": $str\n";
        }
        flock(SQLLOGFID,8);     # '8' is magic 'unlock' const.
        close SQLLOGFID;
    }
}
197

198 199 200 201 202 203 204 205 206 207
# This is from the perlsec page, slightly modifed to remove a warning
# From that page:
#      This function makes use of the fact that the presence of
#      tainted data anywhere within an expression renders the
#      entire expression tainted.
# Don't ask me how it works...
sub is_tainted {
    return not eval { my $foo = join('',@_), kill 0; 1; };
}

208
sub SendSQL {
209
    my ($str, $dontshadow) = (@_);
210 211 212 213 214 215

    # Don't use DBI's taint stuff yet, because:
    # a) We don't want out vars to be tainted (yet)
    # b) We want to know who called SendSQL...
    # Is there a better way to do b?
    if (is_tainted($str)) {
216
        die "Attempted to send tainted string '$str' to the database";
217 218
    }

219 220 221 222
    my $iswrite =  ($str =~ /^(INSERT|REPLACE|UPDATE|DELETE)/i);
    if ($iswrite && !$::dbwritesallowed) {
        die "Evil code attempted to write stuff to the shadow database.";
    }
223
    if ($str =~ /^LOCK TABLES/i && $str !~ /shadowlog/ && $::dbwritesallowed) {
224
        $str =~ s/^LOCK TABLES/LOCK TABLES shadowlog WRITE, /i;
225
    }
226 227
    # If we are shutdown, we don't want to run queries except in special cases
    if (Param('shutdownhtml')) {
228
        if ($0 =~ m:[\\/]((do)?editparams.cgi|syncshadowdb)$:) {
229 230 231 232 233 234
            $::ignorequery = 0;
        } else {
            $::ignorequery = 1;
            return;
        }
    }
235
    SqlLog($str);
236
    $::currentquery = $::db->prepare($str);
237
    if (!$::currentquery->execute) {
238 239
        my $errstr = $::db->errstr;
        # Cut down the error string to a reasonable.size
240 241
        $errstr = substr($errstr, 0, 2000) . ' ... ' . substr($errstr, -2000)
                if length($errstr) > 4000;
242
        die "$str: " . $errstr;
243
    }
244
    SqlLog("Done");
245 246 247 248 249 250 251 252 253 254 255
    if (!$dontshadow && $iswrite && Param("shadowdb")) {
        my $q = SqlQuote($str);
        my $insertid;
        if ($str =~ /^(INSERT|REPLACE)/i) {
            SendSQL("SELECT LAST_INSERT_ID()");
            $insertid = FetchOneColumn();
        }
        SendSQL("INSERT INTO shadowlog (command) VALUES ($q)", 1);
        if ($insertid) {
            SendSQL("SET LAST_INSERT_ID = $insertid");
        }
256
        $shadowchanges++;
257
    }
258 259 260
}

sub MoreSQLData {
261 262 263 264
    # $::ignorequery is set in SendSQL
    if ($::ignorequery) {
        return 0;
    }
265
    if (defined @::fetchahead) {
266
        return 1;
267
    }
268
    if (@::fetchahead = $::currentquery->fetchrow_array) {
269
        return 1;
270 271 272 273 274
    }
    return 0;
}

sub FetchSQLData {
275 276 277 278
    # $::ignorequery is set in SendSQL
    if ($::ignorequery) {
        return;
    }
279
    if (defined @::fetchahead) {
280 281 282
        my @result = @::fetchahead;
        undef @::fetchahead;
        return @result;
283
    }
284
    return $::currentquery->fetchrow_array;
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
}


sub FetchOneColumn {
    my @row = FetchSQLData();
    return $row[0];
}

    

@::default_column_list = ("severity", "priority", "platform", "owner",
                          "status", "resolution", "summary");

sub AppendComment {
    my ($bugid,$who,$comment) = (@_);
300 301
    $comment =~ s/\r\n/\n/g;     # Get rid of windows-style line endings.
    $comment =~ s/\r/\n/g;       # Get rid of mac-style line endings.
302 303 304
    if ($comment =~ /^\s*$/) {  # Nothin' but whitespace.
        return;
    }
305 306 307 308 309

    my $whoid = DBNameToIdAndCheck($who);

    SendSQL("INSERT INTO longdescs (bug_id, who, bug_when, thetext) " .
            "VALUES($bugid, $whoid, now(), " . SqlQuote($comment) . ")");
310 311

    SendSQL("UPDATE bugs SET delta_ts = now() WHERE bug_id = $bugid");
312 313
}

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
sub GetFieldID {
    my ($f) = (@_);
    SendSQL("SELECT fieldid FROM fielddefs WHERE name = " . SqlQuote($f));
    my $fieldid = FetchOneColumn();
    if (!$fieldid) {
        my $q = SqlQuote($f);
        SendSQL("REPLACE INTO fielddefs (name, description) VALUES ($q, $q)");
        SendSQL("SELECT LAST_INSERT_ID()");
        $fieldid = FetchOneColumn();
    }
    return $fieldid;
}
        



330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
sub lsearch {
    my ($list,$item) = (@_);
    my $count = 0;
    foreach my $i (@$list) {
        if ($i eq $item) {
            return $count;
        }
        $count++;
    }
    return -1;
}

sub Product_element {
    my ($prod,$onchange) = (@_);
    return make_popup("product", keys %::versions, $prod, 1, $onchange);
}

sub Component_element {
    my ($comp,$prod,$onchange) = (@_);
    my $componentlist;
    if (! defined $::components{$prod}) {
        $componentlist = [];
    } else {
        $componentlist = $::components{$prod};
    }
    my $defcomponent;
    if ($comp ne "" && lsearch($componentlist, $comp) >= 0) {
        $defcomponent = $comp;
    } else {
        $defcomponent = $componentlist->[0];
    }
    return make_popup("component", $componentlist, $defcomponent, 1, "");
}

sub Version_element {
    my ($vers, $prod, $onchange) = (@_);
    my $versionlist;
    if (!defined $::versions{$prod}) {
        $versionlist = [];
    } else {
        $versionlist = $::versions{$prod};
    }
    my $defversion = $versionlist->[0];
    if (lsearch($versionlist,$vers) >= 0) {
        $defversion = $vers;
    }
    return make_popup("version", $versionlist, $defversion, 1, $onchange);
}
        
379 380 381 382 383 384 385 386
sub Milestone_element {
    my ($tm, $prod, $onchange) = (@_);
    my $tmlist;
    if (!defined $::target_milestone{$prod}) {
        $tmlist = [];
    } else {
        $tmlist = $::target_milestone{$prod};
    }
387

388 389 390 391 392 393 394 395
    my $deftm = $tmlist->[0];

    if (lsearch($tmlist, $tm) >= 0) {
        $deftm = $tm;
    }

    return make_popup("target_milestone", $tmlist, $deftm, 1, $onchange);
}
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439

# Generate a string which, when later interpreted by the Perl compiler, will
# be the same as the given string.

sub PerlQuote {
    my ($str) = (@_);
    return SqlQuote($str);
    
# The below was my first attempt, but I think just using SqlQuote makes more 
# sense...
#     $result = "'";
#     $length = length($str);
#     for (my $i=0 ; $i<$length ; $i++) {
#         my $c = substr($str, $i, 1);
#         if ($c eq "'" || $c eq '\\') {
#             $result .= '\\';
#         }
#         $result .= $c;
#     }
#     $result .= "'";
#     return $result;
}


# Given the name of a global variable, generate Perl code that, if later
# executed, would restore the variable to its current value.

sub GenerateCode {
    my ($name) = (@_);
    my $result = $name . " = ";
    if ($name =~ /^\$/) {
        my $value = eval($name);
        if (ref($value) eq "ARRAY") {
            $result .= "[" . GenerateArrayCode($value) . "]";
        } else {
            $result .= PerlQuote(eval($name));
        }
    } elsif ($name =~ /^@/) {
        my @value = eval($name);
        $result .= "(" . GenerateArrayCode(\@value) . ")";
    } elsif ($name =~ '%') {
        $result = "";
        foreach my $k (sort { uc($a) cmp uc($b)} eval("keys $name")) {
            $result .= GenerateCode("\$" . substr($name, 1) .
440
                                    "{" . PerlQuote($k) . "}");
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
        }
        return $result;
    } else {
        die "Can't do $name -- unacceptable variable type.";
    }
    $result .= ";\n";
    return $result;
}

sub GenerateArrayCode {
    my ($ref) = (@_);
    my @list;
    foreach my $i (@$ref) {
        push @list, PerlQuote($i);
    }
    return join(',', @list);
}



sub GenerateVersionTable {
    ConnectToDatabase();
    SendSQL("select value, program from versions order by value");
    my @line;
    my %varray;
    my %carray;
    while (@line = FetchSQLData()) {
        my ($v,$p1) = (@line);
        if (!defined $::versions{$p1}) {
            $::versions{$p1} = [];
        }
        push @{$::versions{$p1}}, $v;
        $varray{$v} = 1;
    }
475
    SendSQL("select value, program from components order by value");
476 477 478 479 480 481 482 483 484 485
    while (@line = FetchSQLData()) {
        my ($c,$p) = (@line);
        if (!defined $::components{$p}) {
            $::components{$p} = [];
        }
        my $ref = $::components{$p};
        push @$ref, $c;
        $carray{$c} = 1;
    }

486 487 488 489 490
    my $dotargetmilestone = 1;  # This used to check the param, but there's
                                # enough code that wants to pretend we're using
                                # target milestones, even if they don't get
                                # shown to the user.  So we cache all the data
                                # about them anyway.
491 492

    my $mpart = $dotargetmilestone ? ", milestoneurl" : "";
493
    SendSQL("select product, description, votesperuser, disallownew$mpart from products");
494
    $::anyvotesallowed = 0;
495
    while (@line = FetchSQLData()) {
496
        my ($p, $d, $votesperuser, $dis, $u) = (@line);
497
        $::proddesc{$p} = $d;
498 499 500 501 502 503
        if ($dis) {
            # Special hack.  Stomp on the description and make it "0" if we're
            # not supposed to allow new bugs against this product.  This is
            # checked for in enter_bug.cgi.
            $::proddesc{$p} = "0";
        }
504 505 506
        if ($dotargetmilestone) {
            $::milestoneurl{$p} = $u;
        }
507
        $::prodmaxvotes{$p} = $votesperuser;
508 509 510
        if ($votesperuser > 0) {
            $::anyvotesallowed = 1;
        }
511 512 513
    }
            

514 515 516
    my $cols = LearnAboutColumns("bugs");
    
    @::log_columns = @{$cols->{"-list-"}};
517
    foreach my $i ("bug_id", "creation_ts", "delta_ts", "lastdiffed") {
518 519 520 521 522
        my $w = lsearch(\@::log_columns, $i);
        if ($w >= 0) {
            splice(@::log_columns, $w, 1);
        }
    }
523
    @::log_columns = (sort(@::log_columns));
524 525 526 527

    @::legal_priority = SplitEnumType($cols->{"priority,type"});
    @::legal_severity = SplitEnumType($cols->{"bug_severity,type"});
    @::legal_platform = SplitEnumType($cols->{"rep_platform,type"});
528
    @::legal_opsys = SplitEnumType($cols->{"op_sys,type"});
529 530
    @::legal_bug_status = SplitEnumType($cols->{"bug_status,type"});
    @::legal_resolution = SplitEnumType($cols->{"resolution,type"});
531 532 533 534 535 536 537 538

    # 'settable_resolution' is the list of resolutions that may be set 
    # directly by hand in the bug form. Start with the list of legal 
    # resolutions and remove 'MOVED' and 'DUPLICATE' because setting 
    # bugs to those resolutions requires a special process.
    #
    @::settable_resolution = @::legal_resolution;
    my $w = lsearch(\@::settable_resolution, "DUPLICATE");
539
    if ($w >= 0) {
540 541 542 543 544
        splice(@::settable_resolution, $w, 1);
    }
    my $z = lsearch(\@::settable_resolution, "MOVED");
    if ($z >= 0) {
        splice(@::settable_resolution, $z, 1);
545 546 547 548 549 550 551 552 553
    }

    my @list = sort { uc($a) cmp uc($b)} keys(%::versions);
    @::legal_product = @list;
    mkdir("data", 0777);
    chmod 0777, "data";
    my $tmpname = "data/versioncache.$$";
    open(FID, ">$tmpname") || die "Can't create $tmpname";

554 555 556 557 558 559 560
    print FID "#\n";
    print FID "# DO NOT EDIT!\n";
    print FID "# This file is automatically generated at least once every\n";
    print FID "# hour by the GenerateVersionTable() sub in globals.pl.\n";
    print FID "# Any changes you make will be overwritten.\n";
    print FID "#\n";

561 562 563 564 565
    print FID GenerateCode('@::log_columns');
    print FID GenerateCode('%::versions');

    foreach my $i (@list) {
        if (!defined $::components{$i}) {
566
            $::components{$i} = [];
567 568 569 570 571 572 573
        }
    }
    @::legal_versions = sort {uc($a) cmp uc($b)} keys(%varray);
    print FID GenerateCode('@::legal_versions');
    print FID GenerateCode('%::components');
    @::legal_components = sort {uc($a) cmp uc($b)} keys(%carray);
    print FID GenerateCode('@::legal_components');
574
    foreach my $i('product', 'priority', 'severity', 'platform', 'opsys',
575
                  'bug_status', 'resolution') {
576 577
        print FID GenerateCode('@::legal_' . $i);
    }
578
    print FID GenerateCode('@::settable_resolution');
579
    print FID GenerateCode('%::proddesc');
580
    print FID GenerateCode('%::prodmaxvotes');
581
    print FID GenerateCode('$::anyvotesallowed');
582

583
    if ($dotargetmilestone) {
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
        # reading target milestones in from the database - matthew@zeroknowledge.com
        SendSQL("SELECT value, product FROM milestones ORDER BY sortkey, value");
        my @line;
        my %tmarray;
        @::legal_target_milestone = ();
        while(@line = FetchSQLData()) {
            my ($tm, $pr) = (@line);
            if (!defined $::target_milestone{$pr}) {
                $::target_milestone{$pr} = [];
            }
            push @{$::target_milestone{$pr}}, $tm;
            if (!exists $tmarray{$tm}) {
                $tmarray{$tm} = 1;
                push(@::legal_target_milestone, $tm);
            }
599
        }
600 601

        print FID GenerateCode('%::target_milestone');
602
        print FID GenerateCode('@::legal_target_milestone');
603
        print FID GenerateCode('%::milestoneurl');
604
    }
605 606 607 608

    SendSQL("SELECT id, name FROM keyworddefs ORDER BY name");
    while (MoreSQLData()) {
        my ($id, $name) = FetchSQLData();
609
        push(@::legal_keywords, $name);
610
        $name = lc($name);
611 612 613 614 615
        $::keywordsbyname{$name} = $id;
    }
    print FID GenerateCode('@::legal_keywords');
    print FID GenerateCode('%::keywordsbyname');

616 617 618 619 620 621 622
    print FID "1;\n";
    close FID;
    rename $tmpname, "data/versioncache" || die "Can't rename $tmpname to versioncache";
    chmod 0666, "data/versioncache";
}


623 624 625 626 627 628 629 630
sub GetKeywordIdFromName {
    my ($name) = (@_);
    $name = lc($name);
    return $::keywordsbyname{$name};
}



631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

# Returns the modification time of a file.

sub ModTime {
    my ($filename) = (@_);
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
        $atime,$mtime,$ctime,$blksize,$blocks)
        = stat($filename);
    return $mtime;
}



# This proc must be called before using legal_product or the versions array.

646
$::VersionTableLoaded = 0;
647
sub GetVersionTable {
648
    return if $::VersionTableLoaded;
649 650 651 652 653 654 655 656 657 658 659 660 661
    my $mtime = ModTime("data/versioncache");
    if (!defined $mtime || $mtime eq "") {
        $mtime = 0;
    }
    if (time() - $mtime > 3600) {
        GenerateVersionTable();
    }
    require 'data/versioncache';
    if (!defined %::versions) {
        GenerateVersionTable();
        do 'data/versioncache';

        if (!defined %::versions) {
662
            die "Can't generate file data/versioncache";
663 664
        }
    }
665
    $::VersionTableLoaded = 1;
666 667 668 669
}


sub InsertNewUser {
670
    my ($username, $realname) = (@_);
671

672 673 674 675 676 677
    # Generate a new random password for the user.
    my $password = GenerateRandomPassword();
    my $cryptpassword = Crypt($password);

    # Determine what groups the user should be in by default
    # and add them to those groups.
678
    PushGlobalSQLState();
679 680 681 682
    SendSQL("select bit, userregexp from groups where userregexp != ''");
    my $groupset = "0";
    while (MoreSQLData()) {
        my @row = FetchSQLData();
683 684 685
        # Modified -Joe Robins, 2/17/00
        # Making this case insensitive, since usernames are email addresses,
        # and could be any case.
686
        if ($username =~ m/$row[1]/i) {
687 688 689 690 691 692
            $groupset .= "+ $row[0]"; # Silly hack to let MySQL do the math,
                                      # not Perl, since we're dealing with 64
                                      # bit ints here, and I don't *think* Perl
                                      # does that.
        }
    }
693 694

    # Insert the new user record into the database.            
695 696
    $username = SqlQuote($username);
    $realname = SqlQuote($realname);
697 698 699
    $cryptpassword = SqlQuote($cryptpassword);
    SendSQL("INSERT INTO profiles (login_name, realname, cryptpassword, groupset) 
             VALUES ($username, $realname, $cryptpassword, $groupset)");
700
    PopGlobalSQLState();
701 702 703 704 705 706 707 708 709 710 711 712

    # Return the password to the calling code so it can be included 
    # in an email sent to the user.
    return $password;
}

sub GenerateRandomPassword {
    my ($size) = @_;

    # Generated passwords are eight characters long by default.
    $size ||= 8;

713 714 715
    # The list of characters that can appear in a randomly generated password.
    # Note that users can put any character into a password they choose themselves.
    my @pwchars = (0..9, 'A'..'Z', 'a'..'z', '-', '_', '!', '@', '#', '$', '%', '^', '&', '*');
716 717 718 719 720 721 722 723 724 725 726

    # The number of characters in the list.
    my $pwcharslen = scalar(@pwchars);

    # Generate the password.
    my $password = "";
    for ( my $i=0 ; $i<$size ; $i++ ) {
        $password .= $pwchars[rand($pwcharslen)];
    }

    # Return the password.
727 728 729
    return $password;
}

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 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 814 815 816 817 818 819 820 821
sub SelectVisible {
    my ($query, $userid, $usergroupset) = @_;

    # Run the SQL $query with the additional restriction that
    # the bugs can be seen by $userid. $usergroupset is provided
    # as an optimisation when this is already known, eg from CGI.pl
    # If not present, it will be obtained from the db.
    # Assumes that 'bugs' is mentioned as a table name. You should
    # also make sure that bug_id is qualified bugs.bug_id!
    # Your query must have a WHERE clause. This is unlikely to be a problem.

    # Also, note that mySQL requires aliases for tables to be locked, as well
    # This means that if you change the name from selectVisible_cc (or add
    # additional tables), you will need to update anywhere which does a
    # LOCK TABLE, and then calls routines which call this

    $usergroupset = 0 unless $userid;

    unless (defined($usergroupset)) {
        PushGlobalSQLState();
        SendSQL("SELECT groupset FROM profiles WHERE userid = $userid");
        $usergroupset = FetchOneColumn();
        PopGlobalSQLState();
    }

    # 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.

    # 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.

    # 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.

    my $replace = " ";

    if ($userid) {
        $replace .= "LEFT JOIN cc selectVisible_cc ON 
                     bugs.bug_id = selectVisible_cc.bug_id AND 
                     selectVisible_cc.who = $userid "
    }

    $replace .= "WHERE ((bugs.groupset & $usergroupset) = bugs.groupset ";

    if ($userid) {
        # There is a mysql bug affecting v3.22 and 3.23 (at least), where this will
        # cause all rows to be returned! We work arround this by adding an not isnull
        # test to the JOINed cc table. See http://lists.mysql.com/cgi-ez/ezmlm-cgi?9:mss:11417
        # Its needed, even though it shouldn't be
        $replace .= "OR (bugs.reporter_accessible = 1 AND bugs.reporter = $userid) 
                   OR (bugs.assignee_accessible = 1 AND bugs.assigned_to = $userid) 
                   OR (bugs.qacontact_accessible = 1 AND bugs.qa_contact = $userid) 
                   OR (bugs.cclist_accessible = 1 AND selectVisible_cc.who = $userid AND not isnull(selectVisible_cc.who))";
    }

    $replace .= ") AND ";

    $query =~ s/\sWHERE\s/$replace/i;

    return $query;
}

sub CanSeeBug {
    # Note that we pass in the usergroupset, since this is known
    # in most cases (ie viewing bugs). Maybe make this an optional
    # parameter?

    my ($id, $userid, $usergroupset) = @_;

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

    PushGlobalSQLState();
    SendSQL(SelectVisible("SELECT bugs.bug_id FROM bugs WHERE bugs.bug_id = $id",
                          $userid, $usergroupset));

    my $ret = defined(FetchSQLData());
    PopGlobalSQLState();

    return $ret;
}
822 823 824 825 826 827 828 829 830 831 832 833

sub ValidatePassword {
    # Determines whether or not a password is valid (i.e. meets Bugzilla's
    # requirements for length and content).  If the password is valid, the
    # function returns boolean false.  Otherwise it returns an error message
    # (synonymous with boolean true) that can be displayed to the user.
    
    # If a second password is passed in, this function also verifies that
    # the two passwords match.

    my ($password, $matchpassword) = @_;
    
834
    if ( length($password) < 3 ) {
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
        return "The password is less than three characters long.  It must be at least three characters.";
    } elsif ( length($password) > 16 ) {
        return "The password is more than 16 characters long.  It must be no more than 16 characters.";
    } elsif ( $matchpassword && $password ne $matchpassword ) { 
        return "The two passwords do not match.";
    }

    return 0;
}


sub Crypt {
    # Crypts a password, generating a random salt to do it.
    # Random salts are generated because the alternative is usually
    # to use the first two characters of the password itself, and since
    # the salt appears in plaintext at the beginning of the crypted
    # password string this has the effect of revealing the first two
    # characters of the password to anyone who views the crypted version.

    my ($password) = @_;

    # The list of characters that can appear in a salt.  Salts and hashes
    # are both encoded as a sequence of characters from a set containing
    # 64 characters, each one of which represents 6 bits of the salt/hash.
    # The encoding is similar to BASE64, the difference being that the
    # BASE64 plus sign (+) is replaced with a forward slash (/).
    my @saltchars = (0..9, 'A'..'Z', 'a'..'z', '.', '/');

    # Generate the salt.  We use an 8 character (48 bit) salt for maximum
    # security on systems whose crypt uses MD5.  Systems with older
    # versions of crypt will just use the first two characters of the salt.
    my $salt = '';
    for ( my $i=0 ; $i < 8 ; ++$i ) {
        $salt .= $saltchars[rand(64)];
    }

    # Crypt the password.
    my $cryptedpassword = crypt($password, $salt);

    # Return the crypted password.
    return $cryptedpassword;
}


879
sub DBID_to_real_or_loginname {
880
    my ($id) = (@_);
881
    PushGlobalSQLState();
882 883
    SendSQL("SELECT login_name,realname FROM profiles WHERE userid = $id");
    my ($l, $r) = FetchSQLData();
884
    PopGlobalSQLState();
885
    if (!defined $r || $r eq "") {
886
        return $l;
887
    } else {
888
        return "$l ($r)";
889 890
    }
}
891 892 893

sub DBID_to_name {
    my ($id) = (@_);
894 895 896 897 898 899
    # $id should always be a positive integer
    if ($id =~ m/^([1-9][0-9]*)$/) {
        $id = $1;
    } else {
        $::cachedNameArray{$id} = "__UNKNOWN__";
    }
900
    if (!defined $::cachedNameArray{$id}) {
901
        PushGlobalSQLState();
902 903
        SendSQL("select login_name from profiles where userid = $id");
        my $r = FetchOneColumn();
904
        PopGlobalSQLState();
905
        if (!defined $r || $r eq "") {
906 907 908 909 910 911 912 913 914
            $r = "__UNKNOWN__";
        }
        $::cachedNameArray{$id} = $r;
    }
    return $::cachedNameArray{$id};
}

sub DBname_to_id {
    my ($name) = (@_);
915
    PushGlobalSQLState();
916 917
    SendSQL("select userid from profiles where login_name = @{[SqlQuote($name)]}");
    my $r = FetchOneColumn();
918
    PopGlobalSQLState();
919 920 921 922
    # $r should be a positive integer, this makes Taint mode happy
    if (defined $r && $r =~ m/^([1-9][0-9]*)$/) {
        return $1;
    } else {
923 924 925 926 927 928 929
        return 0;
    }
}


sub DBNameToIdAndCheck {
    my ($name, $forceok) = (@_);
930
    $name = html_quote($name);
931 932 933 934 935
    my $result = DBname_to_id($name);
    if ($result > 0) {
        return $result;
    }
    if ($forceok) {
936
        InsertNewUser($name, "");
937 938 939 940 941 942 943
        $result = DBname_to_id($name);
        if ($result > 0) {
            return $result;
        }
        print "Yikes; couldn't create user $name.  Please report problem to " .
            Param("maintainer") ."\n";
    } else {
944
        print "\n";  # http://bugzilla.mozilla.org/show_bug.cgi?id=80045
945 946 947 948
        print "The name <TT>$name</TT> is not a valid username.  Either you\n";
        print "misspelled it, or the person has not registered for a\n";
        print "Bugzilla account.\n";
        print "<P>Please hit the <B>Back</B> button and try again.\n";
949 950 951 952
    }
    exit(0);
}

953
# Use trick_taint() when you know that there is no way that the data
954 955 956 957 958
# in a scalar can be tainted, but taint mode still bails on it.
# WARNING!! Using this routine on data that really could be tainted
#           defeats the purpose of taint mode.  It should only be
#           used on variables that cannot be touched by users.

959 960 961 962 963 964 965 966 967 968
sub trick_taint {
    $_[0] =~ /^(.*)$/s;
    $_[0] = $1;
    return (defined($_[0]));
}

sub detaint_natural {
    $_[0] =~ /^(\d+)$/;
    $_[0] = $1;
    return (defined($_[0]));
969 970
}

971 972 973 974 975 976 977 978
# This routine quoteUrls contains inspirations from the HTML::FromText CPAN
# module by Gareth Rees <garethr@cre.canon.co.uk>.  It has been heavily hacked,
# all that is really recognizable from the original is bits of the regular
# expressions.

sub quoteUrls {
    my ($knownattachments, $text) = (@_);
    return $text unless $text;
979
    
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    my $base = Param('urlbase');

    my $protocol = join '|',
    qw(afs cid ftp gopher http https mid news nntp prospero telnet wais);

    my %options = ( metachars => 1, @_ );

    my $count = 0;

    # Now, quote any "#" characters so they won't confuse stuff later
    $text =~ s/#/%#/g;

    # Next, find anything that looks like a URL or an email address and
    # pull them out the the text, replacing them with a "##<digits>##
    # marker, and writing them into an array.  All this confusion is
    # necessary so that we don't match on something we've already replaced,
    # which can happen if you do multiple s///g operations.

    my @things;
    while ($text =~ s%((mailto:)?([\w\.\-\+\=]+\@[\w\-]+(?:\.[\w\-]+)+)\b|
                    (\b((?:$protocol):[^ \t\n<>"]+[\w/])))%"##$count##"%exo) {
        my $item = $&;

        $item = value_quote($item);

        if ($item !~ m/^$protocol:/o && $item !~ /^mailto:/) {
            # We must have grabbed this one because it looks like an email
            # address.
            $item = qq{<A HREF="mailto:$item">$item</A>};
        } else {
            $item = qq{<A HREF="$item">$item</A>};
        }

        $things[$count++] = $item;
    }
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    # Either a comment string or no comma and a compulsory #.
    while ($text =~ s/\bbug(\s|%\#)*(\d+),?\s*comment\s*(\s|%\#)(\d+)/"##$count##"/ei) {
        my $item = $&;
        my $bugnum = $2;
        my $comnum = $4;
        $item = GetBugLink($bugnum, $item);
        $item =~ s/(id=\d+)/$1#c$comnum/;
        $things[$count++] = $item;
    }
    while ($text =~ s/\bcomment(\s|%\#)*(\d+)/"##$count##"/ei) {
        my $item = $&;
        my $num = $2;
        $item = value_quote($item);
        $item = qq{<A HREF="#c$num">$item</A>};
        $things[$count++] = $item;
    }
1031 1032 1033
    while ($text =~ s/\bbug(\s|%\#)*(\d+)/"##$count##"/ei) {
        my $item = $&;
        my $num = $2;
1034
        $item = GetBugLink($num, $item);
1035 1036
        $things[$count++] = $item;
    }
1037 1038 1039 1040 1041 1042 1043 1044
    while ($text =~ s/\battachment(\s|%\#)*(\d+)/"##$count##"/ei) {
        my $item = $&;
        my $num = $2;
        $item = value_quote($item); # Not really necessary, since we know
                                    # there's no special chars in it.
        $item = qq{<A HREF="showattachment.cgi?attach_id=$num">$item</A>};
        $things[$count++] = $item;
    }
1045 1046 1047
    while ($text =~ s/\*\*\* This bug has been marked as a duplicate of (\d+) \*\*\*/"##$count##"/ei) {
        my $item = $&;
        my $num = $1;
1048 1049 1050
        my $bug_link;
        $bug_link = GetBugLink($num, $num);
        $item =~ s@\d+@$bug_link@;
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        $things[$count++] = $item;
    }
    while ($text =~ s/Created an attachment \(id=(\d+)\)/"##$count##"/e) {
        my $item = $&;
        my $num = $1;
        if ($knownattachments->{$num}) {
            $item = qq{<A HREF="showattachment.cgi?attach_id=$num">$item</A>};
        }
        $things[$count++] = $item;
    }

    $text = value_quote($text);
1063
    $text =~ s/\&#013;/\n/g;
1064 1065 1066 1067 1068 1069 1070 1071 1072

    # Stuff everything back from the array.
    for (my $i=0 ; $i<$count ; $i++) {
        $text =~ s/##$i##/$things[$i]/e;
    }

    # And undo the quoting of "#" characters.
    $text =~ s/%#/#/g;

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    return $text;
}

# This is a new subroutine written 12/20/00 for the purpose of processing a
# link to a bug.  It can be called using "GetBugLink (<BugNumber>, <LinkText>);"
# Where <BugNumber> is the number of the bug and <LinkText> is what apprears
# between '<a>' and '</a>'.

sub GetBugLink {
    my ($bug_num, $link_text) = (@_);
1083 1084 1085 1086 1087 1088 1089 1090 1091
    detaint_natural($bug_num) || die "GetBugLink() called with non-integer bug number";

    # If we've run GetBugLink() for this bug number before, %::buglink
    # will contain an anonymous array ref of relevent values, if not
    # we need to get the information from the database.
    if (! defined $::buglink{$bug_num}) {
        # Make sure any unfetched data from a currently running query
        # is saved off rather than overwritten
        PushGlobalSQLState();
1092

1093 1094 1095 1096 1097 1098 1099 1100 1101
        SendSQL("SELECT bugs.bug_status, resolution, short_desc, groupset " .
                "FROM bugs WHERE bugs.bug_id = $bug_num");

        # If the bug exists, save its data off for use later in the sub
        if (MoreSQLData()) {
            my ($bug_state, $bug_res, $bug_desc, $bug_grp) = FetchSQLData();
            # Initialize these variables to be "" so that we don't get warnings
            # if we don't change them below (which is highly likely).
            my ($pre, $title, $post) = ("", "", "");
1102

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
            $title = $bug_state;
            if ($bug_state eq $::unconfirmedstate) {
                $pre = "<i>";
                $post = "</i>";
            }
            elsif (! IsOpenedState($bug_state)) {
                $pre = "<strike>";
                $title .= " $bug_res";
                $post = "</strike>";
            }
            if ($bug_grp == 0 || CanSeeBug($bug_num, $::userid, $::usergroupset)) {
                $title .= " - $bug_desc";
            }
            $::buglink{$bug_num} = [$pre, value_quote($title), $post];
        }
        else {
            # Even if there's nothing in the database, we want to save a blank
            # anonymous array in the %::buglink hash so the query doesn't get
            # run again next time we're called for this bug number.
            $::buglink{$bug_num} = [];
        }
        # All done with this sidetrip
        PopGlobalSQLState();
    }
1127

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    # Now that we know we've got all the information we're gonna get, let's
    # return the link (which is the whole reason we were called :)
    my ($pre, $title, $post) = @{$::buglink{$bug_num}};
    # $title will be undefined if the bug didn't exist in the database.
    if (defined $title) {
        return qq{$pre<a href="show_bug.cgi?id=$bug_num" title="$title">$link_text</a>$post};
    }
    else {
        return qq{$link_text};
    }
1138 1139 1140
}

sub GetLongDescriptionAsText {
1141
    my ($id, $start, $end) = (@_);
1142 1143
    my $result = "";
    my $count = 0;
1144 1145 1146 1147 1148 1149 1150 1151
    my ($query) = ("SELECT profiles.login_name, longdescs.bug_when, " .
                   "       longdescs.thetext " .
                   "FROM longdescs, profiles " .
                   "WHERE profiles.userid = longdescs.who " .
                   "      AND longdescs.bug_id = $id ");

    if ($start && $start =~ /[1-9]/) {
        # If the start is all zeros, then don't do this (because we want to
1152
        # not emit a leading "Additional Comments" line in that case.)
1153 1154 1155 1156 1157 1158 1159 1160 1161
        $query .= "AND longdescs.bug_when > '$start'";
        $count = 1;
    }
    if ($end) {
        $query .= "AND longdescs.bug_when <= '$end'";
    }

    $query .= "ORDER BY longdescs.bug_when";
    SendSQL($query);
1162 1163 1164
    while (MoreSQLData()) {
        my ($who, $when, $text) = (FetchSQLData());
        if ($count) {
1165
            $result .= "\n\n------- Additional Comments From $who".Param('emailsuffix')."  ".
1166 1167 1168 1169 1170 1171 1172
                time2str("%Y-%m-%d %H:%M", str2time($when)) . " -------\n";
        }
        $result .= $text;
        $count++;
    }

    return $result;
1173 1174 1175
}


1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
sub GetLongDescriptionAsHTML {
    my ($id, $start, $end) = (@_);
    my $result = "";
    my $count = 0;
    my %knownattachments;
    SendSQL("SELECT attach_id FROM attachments WHERE bug_id = $id");
    while (MoreSQLData()) {
        $knownattachments{FetchOneColumn()} = 1;
    }

1186
    my ($query) = ("SELECT profiles.realname, profiles.login_name, longdescs.bug_when, " .
1187 1188 1189 1190 1191 1192 1193
                   "       longdescs.thetext " .
                   "FROM longdescs, profiles " .
                   "WHERE profiles.userid = longdescs.who " .
                   "      AND longdescs.bug_id = $id ");

    if ($start && $start =~ /[1-9]/) {
        # If the start is all zeros, then don't do this (because we want to
1194
        # not emit a leading "Additional Comments" line in that case.)
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        $query .= "AND longdescs.bug_when > '$start'";
        $count = 1;
    }
    if ($end) {
        $query .= "AND longdescs.bug_when <= '$end'";
    }

    $query .= "ORDER BY longdescs.bug_when";
    SendSQL($query);
    while (MoreSQLData()) {
1205
        my ($who, $email, $when, $text) = (FetchSQLData());
1206
        $email .= Param('emailsuffix');
1207
        if ($count) {
1208 1209 1210 1211 1212 1213 1214 1215
            $result .= qq|<BR><BR><I>------- Additional Comment <a name="c$count" href="#c$count">#$count</a> From |;
            if ($who) {
                $result .= qq{<A HREF="mailto:$email">$who</A> };
            } else {
                $result .= qq{<A HREF="mailto:$email">$email</A> };
            }
              
            $result .= time2str("%Y-%m-%d %H:%M", str2time($when)) . " -------</I><BR>\n";
1216 1217 1218 1219 1220 1221 1222 1223
        }
        $result .= "<PRE>" . quoteUrls(\%knownattachments, $text) . "</PRE>\n";
        $count++;
    }

    return $result;
}

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
# Fills in a hashtable with info about the columns for the given table in the
# database.  The hashtable has the following entries:
#   -list-  the list of column names
#   <name>,type  the type for the given name

sub LearnAboutColumns {
    my ($table) = (@_);
    my %a;
    SendSQL("show columns from $table");
    my @list = ();
    my @row;
    while (@row = FetchSQLData()) {
        my ($name,$type) = (@row);
        $a{"$name,type"} = $type;
        push @list, $name;
    }
    $a{"-list-"} = \@list;
    return \%a;
}



# If the above returned a enum type, take that type and parse it into the
# list of values.  Assumes that enums don't ever contain an apostrophe!

sub SplitEnumType {
    my ($str) = (@_);
    my @result = ();
    if ($str =~ /^enum\((.*)\)$/) {
        my $guts = $1 . ",";
        while ($guts =~ /^\'([^\']*)\',(.*)$/) {
            push @result, $1;
            $guts = $2;
1257
        }
1258 1259 1260 1261 1262 1263 1264 1265 1266
    }
    return @result;
}


# This routine is largely copied from Mysql.pm.

sub SqlQuote {
    my ($str) = (@_);
1267 1268 1269
#     if (!defined $str) {
#         confess("Undefined passed to SqlQuote");
#     }
1270 1271
    $str =~ s/([\\\'])/\\$1/g;
    $str =~ s/\0/\\0/g;
1272
    # If it's been SqlQuote()ed, then it's safe, so we tell -T that.
1273
    trick_taint($str);
1274 1275 1276 1277 1278
    return "'$str'";
}



1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
sub UserInGroup {
    my ($groupname) = (@_);
    if ($::usergroupset eq "0") {
        return 0;
    }
    ConnectToDatabase();
    SendSQL("select (bit & $::usergroupset) != 0 from groups where name = " . SqlQuote($groupname));
    my $bit = FetchOneColumn();
    if ($bit) {
        return 1;
    }
    return 0;
}

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
sub BugInGroup {
    my ($bugid, $groupname) = (@_);
    my $groupbit = GroupNameToBit($groupname);
    PushGlobalSQLState();
    SendSQL("SELECT (bugs.groupset & $groupbit) != 0 FROM bugs WHERE bugs.bug_id = $bugid");
    my $bugingroup = FetchOneColumn();
    PopGlobalSQLState();
    return $bugingroup;
}

1303 1304 1305 1306 1307 1308 1309
sub GroupExists {
    my ($groupname) = (@_);
    ConnectToDatabase();
    SendSQL("select count(*) from groups where name=" . SqlQuote($groupname));
    my $count = FetchOneColumn();
    return $count;
}
1310

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
# Given the name of an existing group, returns the bit associated with it.
# If the group does not exist, returns 0.
# !!! Remove this function when the new group system is implemented!
sub GroupNameToBit {
    my ($groupname) = (@_);
    ConnectToDatabase();
    PushGlobalSQLState();
    SendSQL("SELECT bit FROM groups WHERE name = " . SqlQuote($groupname));
    my $bit = FetchOneColumn() || 0;
    PopGlobalSQLState();
    return $bit;
}

1324 1325 1326 1327 1328
# Determines whether or not a group is active by checking 
# the "isactive" column for the group in the "groups" table.
# Note: This function selects groups by bit rather than by name.
sub GroupIsActive {
    my ($groupbit) = (@_);
1329
    $groupbit ||= 0;
1330 1331 1332 1333 1334 1335
    ConnectToDatabase();
    SendSQL("select isactive from groups where bit=$groupbit");
    my $isactive = FetchOneColumn();
    return $isactive;
}

1336 1337 1338 1339 1340 1341
# Determines if the given bug_status string represents an "Opened" bug.  This
# routine ought to be paramaterizable somehow, as people tend to introduce
# new states into Bugzilla.

sub IsOpenedState {
    my ($state) = (@_);
1342
    if (grep($_ eq $state, OpenStates())) {
1343 1344 1345 1346 1347
        return 1;
    }
    return 0;
}

1348 1349 1350 1351 1352 1353 1354
# This sub will return an array containing any status that
# is considered an open bug.

sub OpenStates {
    return ('NEW', 'REOPENED', 'ASSIGNED', $::unconfirmedstate);
}

1355

1356
sub RemoveVotes {
1357
    my ($id, $who, $reason) = (@_);
1358
    ConnectToDatabase();
1359 1360 1361 1362
    my $whopart = "";
    if ($who) {
        $whopart = " AND votes.who = $who";
    }
1363 1364 1365 1366 1367 1368
    SendSQL("SELECT profiles.login_name, profiles.userid, votes.count, " .
            "products.votesperuser, products.maxvotesperbug " .
            "FROM profiles " . 
            "LEFT JOIN votes ON profiles.userid = votes.who " .
            "LEFT JOIN bugs USING(bug_id) " .
            "LEFT JOIN products USING(product)" .
1369 1370
            "WHERE votes.bug_id = $id " .
            $whopart);
1371 1372
    my @list;
    while (MoreSQLData()) {
1373 1374
        my ($name, $userid, $oldvotes, $votesperuser, $maxvotesperbug) = (FetchSQLData());
        push(@list, [$name, $userid, $oldvotes, $votesperuser, $maxvotesperbug]);
1375 1376
    }
    if (0 < @list) {
1377
        foreach my $ref (@list) {
1378 1379 1380 1381
            my ($name, $userid, $oldvotes, $votesperuser, $maxvotesperbug) = (@$ref);
            my $s;

            $maxvotesperbug = $votesperuser if ($votesperuser < $maxvotesperbug);
1382 1383 1384

            # If this product allows voting and the user's votes are in
            # the acceptable range, then don't do anything.
1385
            next if $votesperuser && $oldvotes <= $maxvotesperbug;
1386 1387 1388 1389

            # If the user has more votes on this bug than this product
            # allows, then reduce the number of votes so it fits
            my $newvotes = $votesperuser ? $maxvotesperbug : 0;
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399

            my $removedvotes = $oldvotes - $newvotes;

            $s = $oldvotes == 1 ? "" : "s";
            my $oldvotestext = "You had $oldvotes vote$s on this bug.";

            $s = $removedvotes == 1 ? "" : "s";
            my $removedvotestext = "You had $removedvotes vote$s removed from this bug.";

            my $newvotestext;
1400 1401 1402
            if ($newvotes) {
                SendSQL("UPDATE votes SET count = $newvotes " .
                        "WHERE bug_id = $id AND who = $userid");
1403 1404
                $s = $newvotes == 1 ? "" : "s";
                $newvotestext = "You still have $newvotes vote$s on this bug."
1405 1406
            } else {
                SendSQL("DELETE FROM votes WHERE bug_id = $id AND who = $userid");
1407
                $newvotestext = "You have no more votes remaining on this bug.";
1408 1409 1410
            }

            # Notice that we did not make sure that the user fit within the $votesperuser
1411
            # range.  This is considered to be an acceptable alternative to losing votes
1412 1413 1414 1415 1416
            # during product moves.  Then next time the user attempts to change their votes,
            # they will be forced to fit within the $votesperuser limit.

            # Now lets send the e-mail to alert the user to the fact that their votes have
            # been reduced or removed.
1417 1418 1419 1420 1421
            my $sendmailparm = '-ODeliveryMode=deferred';
            if (Param('sendmailnow')) {
               $sendmailparm = '';
            }
            if (open(SENDMAIL, "|/usr/lib/sendmail $sendmailparm -t")) {
1422
                my %substs;
1423

1424 1425 1426
                $substs{"to"} = $name;
                $substs{"bugid"} = $id;
                $substs{"reason"} = $reason;
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437

                $substs{"votesremoved"} = $removedvotes;
                $substs{"votesold"} = $oldvotes;
                $substs{"votesnew"} = $newvotes;

                $substs{"votesremovedtext"} = $removedvotestext;
                $substs{"votesoldtext"} = $oldvotestext;
                $substs{"votesnewtext"} = $newvotestext;

                $substs{"count"} = $removedvotes . "\n    " . $newvotestext;

1438 1439 1440
                my $msg = PerformSubsts(Param("voteremovedmail"),
                                        \%substs);
                print SENDMAIL $msg;
1441 1442
                close SENDMAIL;
            }
1443
        }
1444 1445 1446 1447 1448
        SendSQL("SELECT SUM(count) FROM votes WHERE bug_id = $id");
        my $v = FetchOneColumn();
        $v ||= 0;
        SendSQL("UPDATE bugs SET votes = $v, delta_ts = delta_ts " .
                "WHERE bug_id = $id");
1449 1450 1451 1452
    }
}


1453
sub Param ($) {
1454 1455 1456 1457
    my ($value) = (@_);
    if (defined $::param{$value}) {
        return $::param{$value};
    }
1458 1459 1460 1461 1462 1463 1464 1465

    # See if it is a dynamically-determined param (can't be changed by user).
    if ($value eq "commandmenu") {
        return GetCommandMenu();
    }
    if ($value eq "settingsmenu") {
        return GetSettingsMenu();
    }
1466 1467
    # Um, maybe we haven't sourced in the params at all yet.
    if (stat("data/params")) {
1468 1469 1470 1471 1472
        # Write down and restore the version # here.  That way, we get around
        # anyone who maliciously tries to tweak the version number by editing
        # the params file.  Not to mention that in 2.0, there was a bug that
        # wrote the version number out to the params file...
        my $v = $::param{'version'};
1473
        require "data/params";
1474
        $::param{'version'} = $v;
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    }
    if (defined $::param{$value}) {
        return $::param{$value};
    }
    # Well, that didn't help.  Maybe it's a new param, and the user
    # hasn't defined anything for it.  Try and load a default value
    # for it.
    require "defparams.pl";
    WriteParams();
    if (defined $::param{$value}) {
        return $::param{$value};
    }
    # We're pimped.
    die "Can't find param named $value";
}

1491 1492 1493 1494 1495
# Take two comma or space separated strings and return what
# values were removed from or added to the new one.
sub DiffStrings {
    my ($oldstr, $newstr) = @_;

1496 1497 1498 1499 1500 1501
    # Split the old and new strings into arrays containing their values.
    $oldstr =~ s/[\s,]+/ /g;
    $newstr =~ s/[\s,]+/ /g;
    my @old = split(" ", $oldstr);
    my @new = split(" ", $newstr);

1502 1503 1504
    my (@remove, @add) = ();

    # Find values that were removed
1505 1506
    foreach my $value (@old) {
        push (@remove, $value) if !grep($_ eq $value, @new);
1507 1508 1509
    }

    # Find values that were added
1510 1511
    foreach my $value (@new) {
        push (@add, $value) if !grep($_ eq $value, @old);
1512 1513 1514 1515 1516 1517 1518 1519
    }

    my $removed = join (", ", @remove);
    my $added = join (", ", @add);

    return ($removed, $added);
}

1520 1521 1522 1523 1524 1525
sub PerformSubsts {
    my ($str, $substs) = (@_);
    $str =~ s/%([a-z]*)%/(defined $substs->{$1} ? $substs->{$1} : Param($1))/eg;
    return $str;
}

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
# Min and max routines.
sub min {
    my $min = shift(@_);
    foreach my $val (@_) {
        $min = $val if $val < $min;
    }
    return $min;
}

sub max {
    my $max = shift(@_);
    foreach my $val (@_) {
        $max = $val if $val > $max;
    }
    return $max;
}
1542 1543 1544 1545

# Trim whitespace from front and back.

sub trim {
1546 1547 1548 1549
    my ($str) = @_;
    $str =~ s/^\s+//g;
    $str =~ s/\s+$//g;
    return $str;
1550 1551 1552
}

1;