# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
#                 Dave Miller <justdave@syndicomm.com>

use diagnostics;
use strict;

use RelationSet;

# Use the Attachment module to display attachments for the bug.
use Attachment;

# Prepare a hash for the section of the bug form showing information
# replicated from the Perforce source code management system by the
# P4DTI replicator.  Derived from code contributed by Matt Albrecht
# <matt.albrecht@zilliant.com>.

sub PreparePerforceSection {
    my ($bug_id) = (@_);
    my $jobname;
    my %p4dti;
    $p4dti{'hasp4dti'} = 0;
    if (Param("p4dti")) {
        $p4dti{'hasp4dti'} = 1;
        
        # First get the row from p4dti_bugs showing whether or not this bug is
        # replicated at all.
        SendSQL("SELECT rid, sid, jobname FROM p4dti_bugs " .
            "WHERE bug_id = $bug_id");
        if (!MoreSQLData()) {
            $p4dti{'isreplicated'} = 0;
        } else {
            $p4dti{'isreplicated'} = 1;
            
            ($p4dti{'rid'}, $p4dti{'sid'}, $jobname) =
                (FetchSQLData());

            # Replicating a bug more than once (i.e. to more than one
            # Perforce server or via more than one replicator) is
            # currently not supported by the replication system.
            if (MoreSQLData()) {
                my ($other_rid, $other_sid) = (FetchSQLData());
                die "bug $bug_id is replicated by (".$p4dti{'rid'}.", ".
                    $p4dti{'sid'}.") and ($other_rid, $other_sid).";
            }

            # Get P4DTI config for this rid/sid combination
            my %p4dti_config;
            SendSQL("SELECT config_key, config_value FROM p4dti_config " .
                "WHERE rid = " . SqlQuote($p4dti{'rid'}) . " AND sid = " .
                SqlQuote($p4dti{'sid'}));
            while(MoreSQLData()) {
                my ($p4dti_config_key, $p4dti_config_value) = FetchSQLData();
                $p4dti_config{$p4dti_config_key} = $p4dti_config_value;
            }
            if (!defined $p4dti_config{'p4_server_description'}) {
                $p4dti_config{'p4_server_description'} = "";
            }
            if (!defined $p4dti_config{'changelist_url'}) {
                $p4dti_config{'changelist_url'} = "";
            }
            if (!defined $p4dti_config{'job_url'}) {
                $p4dti_config{'job_url'} = "";
            }
            if (!defined $p4dti_config{'replicator_user'}) {
                $p4dti_config{'replicator_user'} = "";
            }
            $p4dti{'config'} = \%p4dti_config;
            
            $jobname = value_quote($jobname);
            if ($p4dti_config{"job_url"} ne "") {
                $p4dti{'jobname'} = sprintf("<a href=\"$p4dti_config{'job_url'}\">$jobname</a>", $jobname);
            } else { # no job URL pattern.
                $p4dti{'jobname'} = $jobname;
            }

            # Get actual fixes.
            # Every row in the p4dti_fixes table with the right bug_id
            # is a fix for this bug.  We have to match that up with a row
            # in the p4dti_changelist table, to get the fix description.
            # However, if there are multiple replicators running,
            # there may be more than one row in the p4dti_changelist
            # table with a given changelist number.  So we make
            # the SIDs (Perforce server IDs) match.
            #
            # We do a LEFT JOIN and get a not-NULL field (the rid)
            # from the p4dti_changelists table so we can distinguish
            # the cases in which there is not a p4dti_changelists row
            # for this changelist.  That indicates a failure in the
            # replicator, so we want to know about it.
            SendSQL("SELECT profiles.realname, profiles.login_name, " .
                    "    p4dti_fixes.changelist, " .
                    "    p4dti_fixes.status, p4dti_changelists.p4date, " .
                    "    p4dti_changelists.description, p4dti_changelists.rid, " .
                    "    p4dti_changelists.flags " .
                    "FROM p4dti_fixes, profiles " .
                    "LEFT JOIN p4dti_changelists " .
                    "       ON (p4dti_changelists.changelist=p4dti_fixes.changelist" .
                    "           AND p4dti_changelists.sid = p4dti_fixes.sid)" .
                    "WHERE p4dti_fixes.bug_id = $bug_id " .
                    "  AND profiles.userid = p4dti_changelists.user " .
                    "  AND p4dti_fixes.rid = ". SqlQuote($p4dti{'rid'}) .
                    "  AND p4dti_changelists.rid = ". SqlQuote($p4dti{'rid'}) .
                    "  AND p4dti_fixes.sid = ". SqlQuote($p4dti{'sid'}) .
                    "  AND p4dti_changelists.sid = ". SqlQuote($p4dti{'sid'}) .
                    " ORDER BY p4dti_fixes.changelist");
            if (MoreSQLData()) {
                $p4dti{'hasfixes'} = 1;
                my @fixlist;
                while (MoreSQLData()) {
                    my %myset;
                    my ($realname, $login_name, $changelist, $status, $p4date,
                    $description, $changelist_rid, $changelist_flags) =
                        (FetchSQLData());
                    if (!defined $changelist_rid || $changelist_rid eq "") {
                        die "p4dti_changelists has no row for changelist $changelist.";
                    }
                    $myset{'changelist_rid'} = $changelist_rid;
                    $myset{'description'} = $description || "(none)";
                    if ($changelist) {
                        my $changelist_html;
                        if ($p4dti_config{"changelist_url"} ne "") {
                            $myset{'changelist'} =
                                sprintf("<a href=\"$p4dti_config{'changelist_url'}\">$changelist</a>",
                                        $changelist);
                        } else { # no changelist URL pattern.
                            $myset{'changelist'} = $changelist;
                        }
                    } else {
                        $myset{'changelist'} = "";
                    }
                    if ($changelist_flags & 1) {
                        $myset{'changelist_note'} = "";
                    } else {
                        $myset{'changelist_note'} = "(pending)";
                    }
                    if ($login_name eq $p4dti_config{"replicator_user"}) {
                        $myset{'user_field'} = "(unknown)";
                    } else {
                        $myset{'user_field'} = ("<a href=\"mailto:$login_name\">" .
                                   value_quote($realname) . "</a>");
                    }
                    $myset{'status'} = $status || "";
                    $myset{'p4date'} = $p4date || "";
                    
                    push( @fixlist, \%myset );
                }
                $p4dti{'fixes'} = \@fixlist;
            } else {
                $p4dti{'hasfixes'} = 0;
            }
            # get filespecs.
            SendSQL("SELECT filespec " .
                "FROM p4dti_filespecs " .
                "WHERE bug_id = $bug_id");
            if (MoreSQLData()) {
                $p4dti{'hasfilespecs'} = 1;
                my @speclist;
                while (MoreSQLData()) {
                    my ($filespec) = (FetchSQLData());
                    push( @speclist, $filespec );
                }
                $p4dti{'filespecs'} = \@speclist;
            } else {
                $p4dti{'hasfilespecs'} = 0;
            }
        }
    }
    return \%p4dti;
}



sub show_bug {    
    # Shut up misguided -w warnings about "used only once".  For some reason,
    # "use vars" chokes on me when I try it here.
    sub bug_form_pl_sillyness {
        my $zz;
        $zz = %::FORM;
        $zz = %::proddesc;
        $zz = %::prodmaxvotes;
        $zz = @::enterable_products;                                            
        $zz = @::settable_resolution;
        $zz = $::unconfirmedstate;
        $zz = $::milestoneurl;
        $zz = $::template;
        $zz = $::vars;
        $zz = @::legal_priority;
        $zz = @::legal_platform;
        $zz = @::legal_severity;
        $zz = @::legal_bug_status;
        $zz = @::target_milestone;
        $zz = @::components;
        $zz = @::legal_keywords;
        $zz = @::versions;
        $zz = @::legal_opsys;
    }

    # Use templates
    my $template = $::template;
    my $vars = $::vars;
    
    $vars->{'GetBugLink'} = \&GetBugLink;
    $vars->{'quoteUrls'} = \&quoteUrls,
    $vars->{'lsearch'} = \&lsearch,
    $vars->{'header_done'} = (@_),

    quietly_check_login();

    my $id = $::FORM{'id'};
    
    if (!defined($id)) {
      $template->process("bug/choose.html.tmpl", $vars)
        || ThrowTemplateError($template->error());
      exit;
    }
    
    my %user = %{$vars->{'user'}};
    my %bug;

    # Populate the bug hash with the info we get directly from the DB.
    my $query = "
    SELECT bugs.bug_id, product, version, rep_platform, 
        op_sys, bug_status, resolution, priority, 
        bug_severity, component, assigned_to, reporter, 
        bug_file_loc, short_desc, target_milestone, 
        qa_contact, status_whiteboard, 
        date_format(creation_ts,'%Y-%m-%d %H:%i'),
        groupset, delta_ts, sum(votes.count)
    FROM bugs LEFT JOIN votes USING(bug_id)
    WHERE bugs.bug_id = $id
    GROUP BY bugs.bug_id";

    SendSQL($query);

    my $value;
    my @row = FetchSQLData();
    foreach my $field ("bug_id", "product", "version", "rep_platform",
                       "op_sys", "bug_status", "resolution", "priority",
                       "bug_severity", "component", "assigned_to", "reporter",
                       "bug_file_loc", "short_desc", "target_milestone",
                       "qa_contact", "status_whiteboard", "creation_ts",
                       "groupset", "delta_ts", "votes") 
    {
        $value = shift(@row);
        $bug{$field} = defined($value) ? $value : "";
    }

    # General arrays of info about the database state
    GetVersionTable();

    # Fiddle the product list.
    my $seen_curr_prod;
    my @prodlist;
    
    foreach my $product (@::enterable_products) {
        if ($product eq $bug{'product'}) {
            # if it's the product the bug is already in, it's ALWAYS in
            # the popup, period, whether the user can see it or not, and
            # regardless of the disallownew setting.
            $seen_curr_prod = 1;
            push(@prodlist, $product);
            next;
        }

        if (Param("usebuggroupsentry")
          && GroupExists($product)
          && !UserInGroup($product))
        {
            # If we're using bug groups to restrict entry on products, and
            # this product has a bug group, and the user is not in that
            # group, we don't want to include that product in this list.
            next;
        }

        push(@prodlist, $product);
    }

    # The current product is part of the popup, even if new bugs are no longer
    # allowed for that product
    if (!$seen_curr_prod) {
        push (@prodlist, $bug{'product'});
        @prodlist = sort @prodlist;
    }

    $vars->{'product'} = \@prodlist;
    $vars->{'rep_platform'} = \@::legal_platform;
    $vars->{'priority'} = \@::legal_priority;
    $vars->{'bug_severity'} = \@::legal_severity;
    $vars->{'op_sys'} = \@::legal_opsys;
    $vars->{'bug_status'} = \@::legal_bug_status;

    # Hack - this array contains "" for some reason. See bug 106589.
    shift @::settable_resolution; 
    $vars->{'resolution'} = \@::settable_resolution;

    $vars->{'component_'} = $::components{$bug{'product'}};
    $vars->{'version'} = $::versions{$bug{'product'}};
    $vars->{'target_milestone'} = $::target_milestone{$bug{'product'}};
    $bug{'milestoneurl'} = $::milestoneurl{$bug{'product'}} || 
                           "notargetmilestone.html";

    $vars->{'use_votes'} = Param('usevotes')
                           && $::prodmaxvotes{$bug{'product'}} > 0;

    # Add additional, calculated fields to the bug hash
    if (@::legal_keywords) {
        $vars->{'use_keywords'} = 1;

        SendSQL("SELECT keyworddefs.name 
                 FROM keyworddefs, keywords
                 WHERE keywords.bug_id = $id 
                 AND keyworddefs.id = keywords.keywordid
                 ORDER BY keyworddefs.name");
        my @keywords;
        while (MoreSQLData()) {
            push(@keywords, FetchOneColumn());
        }

        $bug{'keywords'} = \@keywords;
    }    

    # Attachments
    $bug{'attachments'} = Attachment::query($id);

    # Dependencies
    my @list;
    SendSQL("SELECT dependson FROM dependencies WHERE  
             blocked = $id ORDER BY dependson");
    while (MoreSQLData()) {
        my ($i) = FetchSQLData();
        push(@list, $i);
    }

    $bug{'dependson'} = \@list;

    my @list2;
    SendSQL("SELECT blocked FROM dependencies WHERE  
             dependson = $id ORDER BY blocked");
    while (MoreSQLData()) {
        my ($i) = FetchSQLData();
        push(@list2, $i);
    }

    $bug{'blocked'} = \@list2;

    # Groups
    my @groups;
    if ($::usergroupset ne '0' || $bug{'groupset'} ne '0') {      
        my $bug_groupset = $bug{'groupset'};

        SendSQL("SELECT bit, name, description, (bit & $bug_groupset != 0),
                 (bit & $::usergroupset != 0) FROM groups 
                 WHERE isbuggroup != 0 " .
                 # Include active groups as well as inactive groups to which
                 # the bug already belongs.  This way the bug can be removed
                 # from an inactive group but can only be added to active ones.
                "AND ((isactive = 1 AND (bit & $::usergroupset != 0)) OR
                 (bit & $bug_groupset != 0))");

        $user{'inallgroups'} = 1;

        while (MoreSQLData()) {
            my ($bit, $name, $description, $ison, $ingroup) = FetchSQLData();
            # For product groups, we only want to display the checkbox if either
            # (1) The bit is already set, or
            # (2) The user is in the group, but either:
            #     (a) The group is a product group for the current product, or
            #     (b) The group name isn't a product name
            # This means that all product groups will be skipped, but 
            # non-product bug groups will still be displayed.
            if($ison || 
               ($ingroup && (($name eq $bug{'product'}) ||
                             (!defined $::proddesc{$name}))))
            {
                $user{'inallgroups'} &= $ingroup;

                push (@groups, { "bit" => $bit,
                                 "ison" => $ison,
                                 "ingroup" => $ingroup,
                                 "description" => $description });            
            }
        }

        # If the bug is restricted to a group, display checkboxes that allow
        # the user to set whether or not the reporter 
        # and cc list can see the bug even if they are not members of all 
        # groups to which the bug is restricted.
        if ($bug{'groupset'} != 0) {
            $bug{'inagroup'} = 1;

            # Determine whether or not the bug is always accessible by the
            # reporter, QA contact, and/or users on the cc: list.
            SendSQL("SELECT reporter_accessible, cclist_accessible
                     FROM   bugs
                     WHERE  bug_id = $id
                    ");
            ($bug{'reporter_accessible'}, 
             $bug{'cclist_accessible'}) = FetchSQLData();        
        }
    }
    $vars->{'groups'} = \@groups;

    my $movers = Param("movers");
    $user{'canmove'} = Param("move-enabled") 
                       && (defined $::COOKIE{"Bugzilla_login"}) 
                       && ($::COOKIE{"Bugzilla_login"} =~ /\Q$movers\E/);

    # User permissions

    # In the below, if the person hasn't logged in ($::userid == 0), then
    # we treat them as if they can do anything.  That's because we don't
    # know why they haven't logged in; it may just be because they don't
    # use cookies.  Display everything as if they have all the permissions
    # in the world; their permissions will get checked when they log in
    # and actually try to make the change.
    $user{'canedit'} = $::userid == 0
                       || $::userid == $bug{'reporter'}
                       || $::userid == $bug{'qa_contact'}
                       || $::userid == $bug{'assigned_to'}
                       || UserInGroup("editbugs");
    $user{'canconfirm'} = ($::userid == 0)
                          || UserInGroup("canconfirm")
                          || UserInGroup("editbugs");

    # Bug states
    $bug{'isunconfirmed'} = ($bug{'bug_status'} eq $::unconfirmedstate);
    $bug{'isopened'} = IsOpenedState($bug{'bug_status'});

    # People involved with the bug
    $bug{'assigned_to_email'} = DBID_to_name($bug{'assigned_to'});
    $bug{'assigned_to'} = DBID_to_real_or_loginname($bug{'assigned_to'});
    $bug{'reporter'} = DBID_to_real_or_loginname($bug{'reporter'});
    $bug{'qa_contact'} = $bug{'qa_contact'} > 0 ? 
                                          DBID_to_name($bug{'qa_contact'}) : "";

    my $ccset = new RelationSet;
    $ccset->mergeFromDB("SELECT who FROM cc WHERE bug_id=$id");
    
    my @cc = $ccset->toArrayOfStrings();
    $bug{'cc'} = \@cc if $cc[0];

    # Next bug in list (if there is one)
    my @bug_list;
    if ($::COOKIE{"BUGLIST"} && $id) 
    {
        @bug_list = split(/:/, $::COOKIE{"BUGLIST"});
    }
    $vars->{'bug_list'} = \@bug_list;

    $bug{'comments'} = GetComments($bug{'bug_id'});

    # This is length in number of comments
    $bug{'longdesclength'} = scalar(@{$bug{'comments'}});

    # Add the bug and user hashes to the variables
    $vars->{'bug'} = \%bug;
    $vars->{'user'} = \%user;
    
    $vars->{'p4dti'} = PreparePerforceSection($bug{'bug_id'});

    # Create the <link> elements for browsing bug lists
    $vars->{'navigation_links'} = navigation_links(join(':',@bug_list));

    # Generate and return the UI (HTML page) from the appropriate template.
    $template->process("bug/edit.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
}
 
1;

