#!/util/perl/bin/perl



# The path to the config.pl file.  Default is 'config.pl', which
# tells this script that the file is in the same directory.

require( 'config.pl' );




# Check if the database is writable, and crash if it isn't.

&checkWritable;



# Open & read the data file.
open( hDataFile, "<$DATA_FILE" ) || die;
flock( hDataFile, LOCK_SH );
@dataFile = <hDataFile>;
flock( hDataFile, LOCK_UN );
close( hDataFile );


&parse;


# If the record and pwp fields are defined....
if ( defined $FORM{'record'} && defined $FORM{'pwp'} ) {


    # If the password isn't present, prompt for it.
    if ( $FORM{'pwp'} eq 0 ) {
        &promptForPassword( $FORM{'record'} );
    
    # If the commit flag is set, then attempt to commit to the database.
    } elsif ( $FORM{'commit'} eq 1 ) {
        &checkPassword( $FORM{'password'}, $FORM{'record'} );
        &commitDatabase( $FORM{'record'} );
    
    # Else, prompt the user with the edit form.
    } else {
        &checkPassword( $FORM{'password'}, $FORM{'record'} );
        &editDatabase( $FORM{'password'}, $FORM{'record'} );
    }
    
    
# ... the fields weren't defined, so crash & burn.
} else {

    print "Content-type: text/html\n\n";
    print "<html><br><br><br><br><center><b>Error:  essential fields are missing.</b></center></html>";
    
}



exit( 0 );




sub promptForPassword {


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

    print "<html><head><title>Authorization required</title></head><br><br><br><br>\n";
    print "<center>A password is required to edit this entry.</center>\n\n";

    print "<form action=\"$PROTOCOL$HOSTNAME$EDIT_SCRIPT\" method=\"POST\">\n";
    print "<center><input type=\"password\" name=\"password\"><input type=\"submit\" value=\"login!\"></center>\n\n";

    print "<input type=hidden name=\"record\" value=\"$_[ 0 ]\">\n";
    print "<input type=hidden name=\"pwp\" value=\"1\">\n";
    print "</form></html>";


}




sub checkPassword {



    $sentpw = $_[ 0 ];
    $cryptedSentpw = crypt( $sentpw, $SALT_CHARS );
    $record = $_[ 1 ];


    # Get the admin password, and strip off the trailing newline character.
    $adminpw = $dataFile[ 0 ];
    chomp( $adminpw );


    # Get the line in the database pointed to by the record variable.
    $dataLine = $dataFile[ $record ];
    @dataFields = split( /\|/, $dataLine );


    # If the sent password does not equal the user password for this record, or the
    # administrator password, then crash & burn.

    if ( !(( $cryptedSentpw eq $dataFields[ 11 ] ) || ( $cryptedSentpw eq $adminpw )) ) {
        print "Content-type: text/html\n\n";
        print "<html><br><br><br><br><center><b>Incorrect password.</b></center></html>";
        exit( 1 );
    }


}




sub commitDatabase {




    $record = int( $_[ 0 ] );


    $dataLine = $dataFile[ $record ];
    @dataFields = split( /\|/, $dataLine );
    $storedUserpw = $dataFields[ 11 ];



    # Make sure that the user password is stored, not the admin password (if it was used).
    $thePassword = $storedUserpw;


    # If the new_password field isn't empty, then the user wants to change his/her password.
    if ( !( $FORM{'new_password'} eq '' ) ) {
        $thePassword = crypt( $FORM{'new_password'}, $SALT_CHARS );
    }

    

    # Construct the new entry in the database from scratch.

    $newEntry = $FORM{'full_name'} . '|' . $FORM{'language'} . '|' . $FORM{'email'} . '|';
    $newEntry .= $FORM{'office_number'} . '%' . $FORM{'office_building'} . '|';
    $newEntry .= $FORM{'public_phone'} . '|';


     ##############
    # Office hours


    # See which checkbox is checked, then add the hours and minutes selected.

    foreach( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ) {
        $day = $_;
        if ( $FORM{"checkBox$day"} eq 'yes' ) {
            $temp .= ( $day . '%' );
            $temp .= ( $FORM{"startHours$day"} . '%' );
            $temp .= ( $FORM{"startMinutes$day"} . '%' );
            $temp .= ( $FORM{"endHours$day"} . '%' );
            $temp .= ( $FORM{"endMinutes$day"} . '!' );
        }
    }

    $newEntry .= ( substr( $temp, 0, -1 ) . '|' );
    undef $temp;


     ######
    # URLs


    # See what URL box is not empty, and add a URL entry for those != ''.

    for ( $p = 0; $p < 4; $p++ ) {
        if ( !( $FORM{"courseSubject_$p"} eq '' ) ) {
            $temp .= ( $FORM{"courseSubject_$p"} . '%' );
            $temp .= ( $FORM{"courseNumber_$p"} . '%' );
            $temp .= ( $FORM{"courseURL_$p"} . '!' );
        }
    }


    $newEntry .= ( substr( $temp, 0, -1 ) . '|' );
    undef $temp;


    $newEntry .= $FORM{'translate'} . '%' . $FORM{'tutor'} . '%' . $FORM{'additionalInfo'} . '|';


    $newEntry .= $FORM{'private_street'} . '|';
    $newEntry .= $FORM{'private_city'} . '|';
    $newEntry .= $FORM{'private_phone'} . '|';

    $newEntry .= $thePassword . '|' . "\n";



    # Replace the existing line within the database with the new one.
    $dataFile[ $record ] = $newEntry;



    # Write to the database.
    open( hDataFile, ">$DATA_FILE" ) || die;
    flock( hDataFile, LOCK_EX );
    print hDataFile @dataFile;
    flock( hDataFile, LOCK_UN );
    close( hDataFile );


    # Construct some JavaScript to send back to the user.  This will use an
    # alert() box to notify that the update was successful, then it will call
    # the window.location method to automatically go to the view_script.cgi page.

    $javaScript =<< "END_JAVASCRIPT";
<script language="JavaScript" type="text/javascript">

function doIt() {
    alert( "Database was successfully updated!  You may need to click on your browser's 'Reload' button to see the changes." );
    window.location = "http://$HOSTNAME$VIEW_SCRIPT";
}

</script>
END_JAVASCRIPT


    print "Content-type: text/html\n\n";
    print "<html><head>" . $javaScript . "</head><body onLoad=\"doIt()\">";
    print "</body></html>";




}




sub editDatabase {


    $sentpw = $_[ 0 ];
    $record = $_[ 1 ];


    # Make sure that 'record' is never 0, which is the line containing
    # the administrator password.
    if ( $record eq 0 ) {  $record = 1;  }
    $dataLine = $dataFile[ $record ];
    @dataFields = split( /\|/, $dataLine );


    # Open the edit template and save the contents.
    open( hTemplateEdit, "<$TEMPLATE_EDIT" );
    @templateEditContents = <hTemplateEdit>;
    close( hTemplateEdit );


    # Transform the array into a scalar so that the substitution
    # 'gauntlet' can be completed without a loop.
    for ( $p = 0; $p < scalar @templateEditContents; $p++ ) {
        $scalarTemplateEditContents = $scalarTemplateEditContents . $templateEditContents[ $p ];
    }
    undef( @templateEditContents );



    $scalarTemplateEditContents =~ s/\$HOST\$/$HOSTNAME/gi;
    $scalarTemplateEditContents =~ s/\$CGIPATH\$/$EDIT_SCRIPT/gi;




    $scalarTemplateEditContents =~ s/\$PASSWORD\$/$sentpw/gi;
    $scalarTemplateEditContents =~ s/\$RECORD\$/$record/gi;
    $scalarTemplateEditContents =~ s/\$PROTOCOL\$/$PROTOCOL/gi;


#    $scalarTemplateEditContents =~ s/\$EDIT_SCRIPT\$/$dataFields[ 0 ]/gi;
    $scalarTemplateEditContents =~ s/\$FULL_NAME\$/$dataFields[ 0 ]/gi;    
    $scalarTemplateEditContents =~ s/\$EMAIL\$/$dataFields[ 2 ]/gi;
    $scalarTemplateEditContents =~ s/\$PRIVATE_STREET\$/$dataFields[ 8 ]/gi;
    $scalarTemplateEditContents =~ s/\$PRIVATE_CITY\$/$dataFields[ 9 ]/gi;
    $scalarTemplateEditContents =~ s/\$PRIVATE_PHONE\$/$dataFields[ 10 ]/gi;    



# Select correct language for combo-box.
###########

    # Make a hash table using the keys within @DEPARTMENT_LANGUAGES.

    for( $p = 0; $p < scalar @DEPARTMENT_LANGUAGES; $p++ ) {
        $languageSelector{ $DEPARTMENT_LANGUAGES[ $p ] } = "";
    }
    $languageSelector{ $dataFields[ 1 ] } = " selected";


    @languages = keys %languageSelector;
    for ( $p = 0; $p < scalar @languages; $p++ ) {
        $scalarTemplateEditContents =~ s/\$LANGUAGE_$languages[ $p ]\$/$languageSelector{ $languages[ $p ] }/gi;
    }


    $languageSelector{ $dataFields[ 1 ] } = "";
###########



    # This fills in the building & office number...

    $publicAddress = $dataFields[ 3 ];
    @publicAddressFields = split( /\%/, $publicAddress );
    undef $publicAddress;


    $buildingSelector{'Clemens Hall'} = "";
    $buildingSelector{'Baldy Hall'} = "";
    $buildingSelector{'Baird Hall'} = "";


    $buildingSelector{ $publicAddressFields[ 1 ] } = " selected";


    @buildings = keys %buildingSelector;
    for ( $p = 0; $p < scalar @buildings; $p++ ) {
        $scalarTemplateEditContents =~ s/\$BUILDING_$buildings[ $p ]\$/$buildingSelector{ $buildings[ $p ] }/gi;
    }
   
    $scalarTemplateEditContents =~ s/\$OFFICE_NUMBER\$/$publicAddressFields[ 0 ]/gi;


    undef @publicAddressFields;
    undef %buildingSelector;
    undef @buildings;



###############



#     $publicPhone = $dataFields[ 4 ];
#     #@publicPhoneFields = split( /\%/, $publicPhone );
#     @publicPhoneFields = split( $publicPhone );
#     undef $publicPhone;
# 
# 
#     $scalarTemplateEditContents =~ s/\$PUBLIC_PHONE\$/$publicPhoneFields[ 0 ]/gi;
#     #$scalarTemplateEditContents =~ s/\$PUBLIC_PHONE_EXTENSION\$/$publicPhoneFields[ 1 ]/gi;
# 
# 
# 
#     undef @publicPhoneFields;

##mojo

    $publicPhone = $dataFields[ 4 ];
    $publicPhoneFields = $publicPhone;
    undef $publicPhone;


    $scalarTemplateEditContents =~ s/\$PUBLIC_PHONE\$/$publicPhoneFields/gi;
    #$scalarTemplateEditContents =~ s/\$PUBLIC_PHONE_EXTENSION\$/$publicPhoneFields[ 1 ]/gi;



    undef @publicPhoneFields;







#################



    # Schedule....
    $rawSchedule = $dataFields[ 5 ];
    @scheduleFields = split( /\!/, $rawSchedule );
#    undef $rawSchedule;



    for( $j = 0; $j < scalar @scheduleFields; $j++ ) {



        @subFields = split( /\%/, $scheduleFields[ $j ] );


        $stuff = $subFields[ 0 ];
        $rep = " checked";
        $scalarTemplateEditContents =~ s/\$CHECKED_$stuff\$/$rep/giex;
        $scalarTemplateEditContents =~ s/\$DEBUG\$/$rep/gi;



        $hourSelector{'8'} = "";
        $hourSelector{'9'} = "";
        $hourSelector{'10'} = "";
        $hourSelector{'11'} = "";
        $hourSelector{'12'} = "";
        $hourSelector{'1'} = "";
        $hourSelector{'2'} = "";
        $hourSelector{'3'} = "";
        $hourSelector{'4'} = "";
        $hourSelector{'5'} = "";
        $hourSelector{'6'} = "";


        $minuteSelector{'00'} = "";
        $minuteSelector{'15'} = "";
        $minuteSelector{'30'} = "";
        $minuteSelector{'45'} = "";



        # Starting hours...

        $hourSelector{ $subFields[ 1 ] } = " selected";
        @hours = keys %hourSelector;

        for ( $p = 0; $p < scalar @hours; $p++ ) {
            $stuff = $subFields[ 0 ] . '_' . $hours[ $p ];
            $scalarTemplateEditContents =~ s/\$START_$stuff\$/$hourSelector{ $hours[ $p ] }/gi;
        }
        $hourSelector{ $subFields[ 1 ] } = "";



        # Starting minutes...

        $minuteSelector{ $subFields[ 2 ] } = " selected";
        @minutes = keys %minuteSelector;

        for ( $p = 0; $p < scalar @minutes; $p++ ) {
            $stuff = $subFields[ 0 ] . '_' . $minutes[ $p ];
            $scalarTemplateEditContents =~ s/\$START_$stuff\$/$minuteSelector{ $minutes[ $p ] }/gi;
        }
        $minuteSelector{ $subFields[ 2 ] } = "";






        # Ending hours...

        $hourSelector{ $subFields[ 3 ] } = " selected";
        @hours = keys %hourSelector;

        for ( $p = 0; $p < scalar @hours; $p++ ) {
            $stuff = $subFields[ 0 ] . '_' . $hours[ $p ];
            $scalarTemplateEditContents =~ s/\$END_$stuff\$/$hourSelector{ $hours[ $p ] }/gi;
        }
        $hourSelector{ $subFields[ 3 ] } = "";



        # Ending minutes...

        $minuteSelector{ $subFields[ 4 ] } = " selected";
        @minutes = keys %minuteSelector;

        for ( $p = 0; $p < scalar @minutes; $p++ ) {
            $stuff = $subFields[ 0 ] . '_' . $minutes[ $p ];
            $scalarTemplateEditContents =~ s/\$END_$stuff\$/$minuteSelector{ $minutes[ $p ] }/gi;
        }
        $minuteSelector{ $subFields[ 4 ] } = "";









    }




    # Blank out the entries that are not in the database.


    @days = ( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' );
    @hours = ( '8', '9', '10', '11', '12', '1', '2', '3', '4', '5', '6' );
    @minutes = ( '00', '15', '30', '45' );


    for( $j = 0; $j < 5; $j++ ) {



        $day = $days[ $j ];
        $scalarTemplateEditContents =~ s/\$CHECKED_$day\$//gi;


        for ( $p = 0; $p < scalar @hours; $p++ ) {
            $stuff = $day . '_' . $hours[ $p ];
            $scalarTemplateEditContents =~ s/\$START_$stuff\$//gi;
        }


        for ( $p = 0; $p < scalar @minutes; $p++ ) {
            $stuff = $day . '_' . $minutes[ $p ];
            $scalarTemplateEditContents =~ s/\$START_$stuff\$//gi;
        }




        for ( $p = 0; $p < scalar @hours; $p++ ) {
            $stuff = $day . '_' . $hours[ $p ];
            $scalarTemplateEditContents =~ s/\$END_$stuff\$//gi;
        }


        for ( $p = 0; $p < scalar @minutes; $p++ ) {
            $stuff = $day . '_' . $minutes[ $p ];
            $scalarTemplateEditContents =~ s/\$END_$stuff\$//gi;
        }





    }









#################




    # URLs...
    $rawURLs = $dataFields[ 6 ];
    @urlFields = split( /\!/, $rawURLs );
    

    undef %languageSelector;


    # Make a hash table using the keys within @DEPARTMENT_LANGUAGES.

    for( $p = 0; $p < scalar @URL_CLASSTYPES; $p++ ) {
        $languageSelector{ $URL_CLASSTYPES[ $p ] } = "";
    }
    


    @languages = keys %languageSelector;
 

    $p = 0;
    for ( ; $p < scalar @urlFields; $p++ ) {

        @subURLFields = split( /\%/, $urlFields[ $p ] );
        $languageSelector{ $subURLFields[ 0 ] } = " selected";


        for ( $q = 0; $q < scalar @languages; $q++ ) {
            $stuff = $languages[ $q ] . '_' . $p;
            $scalarTemplateEditContents =~ s/\$URL_$stuff\$/$languageSelector{ $languages[ $q ] }/gi;
        }


        $languageSelector{ $subURLFields[ 0 ] } = "";


        $stuff = 'COURSE_NUMBER_' . $p;
        $scalarTemplateEditContents =~ s/\$$stuff\$/$subURLFields[ 1 ]/gi;


        $stuff = 'COURSE_URL_' . $p;
        $scalarTemplateEditContents =~ s/\$$stuff\$/$subURLFields[ 2 ]/gi;

        

    }

    
    for ( ; $p < 4; $p++ ) {

        for ( $q = 0; $q < scalar @languages; $q++ ) {
            $stuff = $languages[ $q ] . '_' . $p;
            $scalarTemplateEditContents =~ s/\$URL_$stuff\$//gi;
        }


        $stuff = 'COURSE_NUMBER_' . $p;
        $scalarTemplateEditContents =~ s/\$$stuff\$//gi;


        $stuff = 'COURSE_URL_' . $p;
        $scalarTemplateEditContents =~ s/\$$stuff\$//gi;

    }


#################








    $additionalInfo = $dataFields[ 7 ];

    @addInfoFields = split( /\%/, $additionalInfo );



    $yep = "";
    $nope = " checked";
    if ( $addInfoFields[ 0 ] eq '1' ) {
        $yep = " checked";
        $nope = "";
    }


    $scalarTemplateEditContents =~ s/\$TRANSLATE_YES_CHECKED\$/$yep/gi;
    $scalarTemplateEditContents =~ s/\$TRANSLATE_NO_CHECKED\$/$nope/gi;


    $yep = "";
    $nope = " checked";
    if ( $addInfoFields[ 1 ] eq '1' ) {
        $yep = " checked";
        $nope = "";
    }


    $scalarTemplateEditContents =~ s/\$TUTOR_YES_CHECKED\$/$yep/gi;
    $scalarTemplateEditContents =~ s/\$TUTOR_NO_CHECKED\$/$nope/gi;





   
    $scalarTemplateEditContents =~ s/\$ADDITIONAL_INFO\$/$addInfoFields[ 2 ]/gi;





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


}
