#!/usr/local/bin/perl -w
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# View/Edit/Delete customfields as described in Bugzilla bug no. 91037
#
# Contributor: Maciej Maczynski <macmac@xdsnet.pl>
#

use diagnostics;
use strict;

require "CGI.pl";

sub sillyness {
    my $zz;
    $zz = @::legal_product;
#    $zz = @::legal_customfields;
    $zz = @::legal_product;
    $zz = $::COOKIE{'Bugzilla_login'};
};

confirm_login();

print "Content-type: text/html\n\n";

ConnectToDatabase();
GetVersionTable();

my $action  = trim($::FORM{action}  || '');
my $field  = trim($::FORM{field}  || '');
my $name  =  trim($::FORM{name}  || '');
my $id  = trim($::FORM{id}  || '');
my $description  =  trim($::FORM{description}  || '');
my $type  =  $::FORM{type};
my $valid_exp  =  trim($::FORM{valid_exp}  || '');
my $default_value  =  trim($::FORM{default_value}  || '');
my $mandatory  =  trim($::FORM{mandatory}  || '');
my $product =  $::FORM{product};


#  Sub:     CheckField
#  Purpose: Check if all field parameters were set
#
sub   CheckField {
    my ($name, $description, $type, $product, $default, $val) = @_;
    my $params_ok = 1;

    #  Check if all necessary fields got filled
    unless ($name) {
        print "You must enter a name for the custom field. Please press\n";
        print "<b>Back</b> and try again.\n";
        $params_ok = 0;
    }
    if ($params_ok and $name !~ /^[a-zA-Z0-9_]+$/) {
        print "This is not a valid field name ($name). The only characters\n";
        print "allowed are a-z, 0-9 and underline. Please press\n";
        print "<b>Back</b> and try again.\n";
        $params_ok = 0;
    }
    if ($params_ok && !$description) {
        print "You must enter a description for the custom field. Please press\n";
        print "<b>Back</b> and try again.\n";
        $params_ok = 0;
    }
    if ($params_ok and $type eq 'any' and $default ne '' 
        and $val ne '' and $default !~ $val) {
        print "The default value is not a valid value. Please press\n";
        print "<b>Back</b> and try again.\n";
        $params_ok = 0;
    }

    if ($params_ok && !$type) {
        print "You must enter a type for the custom field. Please press\n";
        print "<b>Back</b> and try again.\n";
        $params_ok = 0;
    }

    if ($params_ok && !$product) {
        print "You must select at least one product for the custom field. Please press\n";
        print "<b>Back</b> and try again.\n";
        $params_ok = 0;
    }
    $params_ok;
}

######################### Default action - list custom fields

unless ($action) {
    PutHeader("Custom fields list", "Custom fields list", $::COOKIE{'Bugzilla_login'});
    print "<TABLE BORDER=1 CELLPADDING=4 CELLSPACING=0><TR BGCOLOR=\"#6666FF\">\n";
    print "  <TH ALIGN=\"left\">Id</TH>\n";
    print "  <TH ALIGN=\"left\">Name</TH>\n";
    print "  <TH ALIGN=\"left\">Description</TH>\n";
    print "  <TH ALIGN=\"left\">Type</TH>\n";
    print "  <TH ALIGN=\"left\">Value regexp</TH>\n";
    print "  <TH ALIGN=\"left\">Mandatory</TH>\n";
    print "  <TH ALIGN=\"left\">Default</TH>\n";
    print "  <TH ALIGN=\"left\">Action</TH>\n";
    print "  <TH ALIGN=\"left\">Action</TH>\n";
    print "</TR>";

    SendSQL("select id, c.name, f.description, type, valid_exp, mandatory, default_value from customfields c, fielddefs f  WHERE f.name = c.name ORDER BY id" );
    my @row;   
    while ( @row = FetchSQLData()) {
	my ($id, $name, $description, $type, $val, $mandatory, $default_value) = (@row);
	print "<TR>";
	print "<TD ALIGN=\"left\">$id</TD>\n";
	print "<TD ALIGN=\"left\">$name</TD>\n";
	print "<TD ALIGN=\"left\">$description</TD>\n";
	print "<TD ALIGN=\"left\">$type</TD>\n";
	print "<TD ALIGN=\"left\">", $val || '&nbsp;', "</TD>\n";
	print "<TD ALIGN=\"left\">", ($mandatory?'yes':'no'), "</TD>\n";
	print "<TD ALIGN=\"left\">", $default_value || '&nbsp;', "</TD>\n";
	print "<TD ALIGN=\"left\"><A HREF=\"editcustomfields.cgi?action=edit&id=$id", 
        "&field=$name&description=", html_quote($description), 
        "&valid_exp=", html_quote($val), "&type=$type", 
        "&mandatory=", $mandatory?'yes':'', "&default_value=", html_quote($default_value), 
        "\">Edit</A></TD>\n";
	print "<TD ALIGN=\"left\"><A HREF=\"editcustomfields.cgi?action=delete&field=$name&id=$id\">Delete</A></TD>\n";
	print "</TR>";
    };

    print "<TR>\n";
    print "<TD ALIGN=\"left\" COLSPAN=5>Add new field</TD>\n";
    print "<TD ALIGN=\"left\" COLSPAN=2><A HREF=\"editcustomfields.cgi?action=add\">Add</A></TD>\n";
    print "</TR>\n";

    print "</TABLE>\n";
    PutFooter();
    exit();
};


######################### Edit field

if ( $action eq 'edit') {
    PutHeader("Edit field '$field'");

    print "<FORM METHOD=GET ACTION=editcustomfields.cgi>\n";
    print "<TABLE BORDER=0 CELLPADDING=4 CELLSPACING=0>\n";
    print " <TR>";
    print "  <TH ALIGN=\"left\">Name</TH>\n";
    print "  <TD>$field</TD>\n";
    print " </TR>";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Description</TH>\n";
    print "  <TD><INPUT SIZE=64 MAXLENGTH=64 NAME=\"description\" VALUE=\"$description\"></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Value expression</TH>\n";
    print "  <TD><INPUT SIZE=64 MAXLENGTH=255 NAME=\"valid_exp\" VALUE=", 
    html_quote($valid_exp), "></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Type</TH>\n";
    print "  <TD>";

    my @options = ("any", "single", "multi" );
    my $type_popup = make_popup( "type", \@options, $type, "", 0 );
    print $type_popup;
    print "  </TD>";
    print "</TR>";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Default</TH>\n";
    print "  <TD><INPUT SIZE=64 MAXLENGTH=255 NAME=\"default_value\" VALUE=", 
    html_quote($default_value), "></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Mandatory</TH>\n";
    print "  <TD><INPUT TYPE=CHECKBOX NAME=\"mandatory\" ", ($mandatory ? ' CHECKED' : ''), "></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Products</TH>\n";
    print "  <TD>";

    SendSQL( "select product from products_customfields where cf_id = $id" );
    my $product;
    my $default;
    while ( ($product) = FetchSQLData() )
    {
        if ( $default ) { $default .= "|"; };
        $default .= "$product";
    };

    my $product_popup = make_selection_widget( "product", \@::legal_product, $default, 1, 1, 5);
    print $product_popup;
    print "  </TD>";
 
    print "</TR>\n";


    print "</TABLE>\n";
    print "<INPUT TYPE=SUBMIT VALUE=\"Commit\">\n";
    print "<INPUT TYPE=HIDDEN NAME=\"action\" VALUE=\"update\">\n";
    print "<INPUT TYPE=HIDDEN NAME=\"id\" VALUE=\"$id\">\n";
    print "<INPUT TYPE=HIDDEN NAME=\"name\" VALUE=\"$field\">\n";
    print "</FORM>";


    PutFooter();
    exit();
}


######################### Update edited parameters

if ( $action eq 'update') {
    PutHeader("Changed parameters for '$name'");

    my %F;
    my %M;
    ParseUrlString($::buffer, \%F, \%M);


    if ( CheckField( $name, $description, $type, @{$M{'product'}}[0], 
                     $default_value, $valid_exp ) )
    {
#  Some better handling would be nice here: update only things which really changed
        SendSQL( "UPDATE customfields SET type=" . SqlQuote($type) . 
                 ", valid_exp=" . SqlQuote($valid_exp) . 
                 ", mandatory = " . ($mandatory ne ''?'1':'0') . ", default_value=" . 
                 SqlQuote($default_value) . " WHERE id = $id");
        SendSQL( "UPDATE fielddefs SET description='$description' WHERE name = '$name'");
        
#  Delete all product associations and insert new one
        SendSQL("DELETE from products_customfields WHERE cf_id = $id");

        my $i=0;
        while ( @{$M{'product'}}[$i] )
        {
            SendSQL( "INSERT INTO products_customfields (product, cf_id) VALUES ('".@{$M{'product'}}[$i]."', $id)" );
            $i++;
        }

        print "<br>Custom field '$name' changed <br>";
        print "Back to the <A HREF=\"editcustomfields.cgi\"> customfields page</A>";
        # Make versioncache flush (don't really know if this is safe)
        unlink "data/versioncache";        
    }


    PutFooter();
    exit();
}

######################### Delete field
if ( $action eq 'delete') {
    PutHeader("Delete field '$field'");

    print "<br>";
    SendSQL("select count(bug_id) from bugs_customfields where cf_id=$id" );
    my ($count) = FetchSQLData();
    if ( $count )
    {
        print "<B>$count ".($count==1 ? "bug uses" : "bugs use")." this keyword!</B><br>";
    }

    print "<FORM METHOD=GET ACTION=editcustomfields.cgi>\n";
    print "<B>Do you really want do delete '$field' customfield?</B><br><br>\n";

    print "<INPUT TYPE=SUBMIT VALUE=\"Delete\">\n";
    print "<INPUT TYPE=HIDDEN NAME=\"action\" VALUE=\"do_delete\">\n";
    print "<INPUT TYPE=HIDDEN NAME=\"name\" VALUE=\"$field\">\n";
    print "<INPUT TYPE=HIDDEN NAME=\"id\" VALUE=\"$id\">\n";
    print "</FORM>";    

    PutFooter();
    exit();
}


######################### Perform delete
if ( $action eq 'do_delete') {
    PutHeader("Deleting field '$name'");
    SendSQL("delete from fielddefs where name='$name'");
    SendSQL("delete from products_customfields where cf_id=$id");
    SendSQL("delete from customfields where name='$name'" );
    SendSQL("delete from bugs_customfields where cf_id=$id" );

    unlink "data/versioncache";

    print "<br>Custom field '$name' deleted <br>";
    print "Back to the <A HREF=\"editcustomfields.cgi\"> customfields page</A>";
    PutFooter();
    exit();
}


######################### Add field dialog
if ( $action eq 'add') {
    PutHeader("Add new custom field");
    my ($name, $valid_exp, $type, $description);

    print "<FORM METHOD=GET ACTION=editcustomfields.cgi>\n";
    print "<TABLE BORDER=0 CELLPADDING=4 CELLSPACING=0>\n";
    print " <TR>";
    print "  <TH ALIGN=\"left\">Name</TH>\n";
    print "  <TD><INPUT SIZE=64 MAXLENGTH=64 NAME=\"name\" VALUE=\"$name\"></TD>\n";
    print " </TR>";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Description</TH>\n";
    print "  <TD><INPUT SIZE=64 MAXLENGTH=64 NAME=\"description\" VALUE=\"$description\"></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Value expression</TH>\n";
    print "  <TD><INPUT SIZE=64 MAXLENGTH=255 NAME=\"valid_exp\" VALUE=\"$valid_exp\"></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Type</TH>\n";
    print "  <TD>";

    my @options = ("any", "single", "multi" );
    my $type_popup = make_popup( "type", \@options, "any", 0, 0 );
    print $type_popup;
    print "  </TD>";
    print "</TR>";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Default</TH>\n";
    print "  <TD><INPUT SIZE=64 MAXLENGTH=255 NAME=\"default_value\" VALUE=\"$default_value\"></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Mandatory</TH>\n";
    print "  <TD><INPUT TYPE=CHECKBOX NAME=\"mandatory\" ", ($mandatory ? ' checked' : ''), "></TD>";
    print "</TR>\n";

    print "<TR>";
    print "  <TH ALIGN=\"left\">Select products</TH>\n";
    print "  <TD>";

    my $product_popup = make_selection_widget( "product", \@::legal_product, "", 0, 1, 5);
    print $product_popup;
    print "  </TD>";
 
    print "</TR>\n";


    print "</TABLE>\n";
    print "<INPUT TYPE=SUBMIT VALUE=\"Add\">\n";
    print "<INPUT TYPE=HIDDEN NAME=\"action\" VALUE=\"new\">\n";
    print "</FORM>";

    PutFooter();
    exit();
}

######################### Add field action
if ( $action eq 'new') {
    PutHeader("Adding new custom field");

    my %F;
    my %M;
    ParseUrlString($::buffer, \%F, \%M);

    if ( CheckField( $name, $description, $type, @{$M{'product'}}[0],
                     $default_value, $valid_exp) )
    {
        my $i=0;
        SendSQL("INSERT into customfields (name, type, valid_exp, mandatory, default_value) VALUES ('$name', '$type', " . 
                SqlQuote($valid_exp) . ", " . (($mandatory ne '') ? '1' : '0') . ", " . 
                SqlQuote($default_value) . ")");

        $i=0;

        while ( @{$M{'product'}}[$i] )
        {
            SendSQL( "INSERT INTO products_customfields (product, cf_id) SELECT '".@{$M{'product'}}[$i]."' product, id cf_id from customfields where name = '$name'" );
            $i++;
        }

        my $sortkey=0;

        SendSQL( "SELECT max(sortkey) from fielddefs" );
        ($sortkey) = FetchSQLData();
#  Get next sortkey
        $sortkey++;
        SendSQL( "INSERT INTO fielddefs ( name, description, sortkey ) VALUES ('$name', " .
                 SqlQuote($description) . ", $sortkey)" );

        print "Custom field '$name' added <br>";
        print "Back to the <A HREF=\"editcustomfields.cgi\"> customfields page</A>";

        # Make versioncache flush (don't really know if this is safe)
        unlink "data/versioncache";
    }

    PutFooter();
    exit();
}











