#!/bin/sh # (C) 2010 by Eugeniy Mikhailov, # vim:set ft=tcl: \ exec tclsh "$0" "$@" # internal version of this code set VERSION 1.0 package require sqlite3 package require ncgi package require md5 ::ncgi::parse # defaults set sortCol LastName set user guest set password guest set action defaultview # defaults end # read cookies set user [::ncgi::cookie user] set sortCol [::ncgi::cookie sortCol] set password [::ncgi::cookie password] set action [::ncgi::value action defaultview] # end of read cookies if { [catch {set script_name $env(SCRIPT_NAME)} errStat] } { set script_name unknown} # ########################## procs begin ################################# proc dbg {msg {level 1}} { if { $level <=2 } { set fid [open log a+] puts $fid $msg close $fid } } set dbfile "./testdb" #set url_base sqlite3 db $dbfile proc CreatePasswordsTable {db} { db eval {CREATE TABLE PasswordsTable(UserName text, PasswordHash text, GroupName text)} set eval_str [list INSERT INTO PasswordsTable VALUES('instructor', '[::md5::md5 -hex qwerty]', 'instructor')] db eval $eval_str set eval_str [list INSERT INTO PasswordsTable VALUES('ta', '[::md5::md5 -hex qwerty]', 'ta')] db eval $eval_str set eval_str [list INSERT INTO PasswordsTable VALUES('jhn', '[::md5::md5 -hex qwerty]', 'student')] db eval $eval_str set eval_str [list INSERT INTO PasswordsTable VALUES('ale', '[::md5::md5 -hex qwerty]', 'student')] db eval $eval_str set eval_str [list INSERT INTO PasswordsTable VALUES('dan', '[::md5::md5 -hex qwerty]', 'student')] db eval $eval_str } proc AddUserNonWeb { first_name last_name user_name password_hash {group_name {guest}} } { set eval_str [concat INSERT INTO GradesTable (FirstName, LastName, UserName, PassWordHash, GroupName) VALUES('$first_name', '$last_name', '$user_name', '$password_hash', '$group_name')] set err [catch {db eval $eval_str } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } } proc CreateGradesTable {db} { set err [catch {db eval {CREATE TABLE GradesTable(FirstName text, LastName text, UserName text, PassWordHash text, GroupName text)} } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 1 } # add special users aka special info rows AddUserNonWeb {} {} _Col_Category_ {} infocolumn AddUserNonWeb {} {} _Max_Points_ {} infocolumn # dummy users AddUserNonWeb Dan "Dandanovich" dan [::md5::md5 -hex qwerty] student AddUserNonWeb Ale "Alevna" ale [::md5::md5 -hex qwerty] student AddUserNonWeb Jon "Jonovich" jon [::md5::md5 -hex qwerty] student } proc CreateAccessRightsTable {db} { db eval {CREATE TABLE AccessRightsTable(actionname text, instructor integer, ta integer, student integer, guest integer)} # guest should have no rights make sure that 0 is evereywhere db eval {INSERT INTO AccessRightsTable VALUES('logon', 1, 1, 1, 1)} db eval {INSERT INTO AccessRightsTable VALUES('showgrades', 1, 1, 1, 0)} db eval {INSERT INTO AccessRightsTable VALUES('sort', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('addcolumnrequest', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('addcolumn', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('deletecolumn', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('showcontrols', 1, 1, 1, 0)} db eval {INSERT INTO AccessRightsTable VALUES('changegrades', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('updategrades', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('changecolumn', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('updatecolumn', 1, 1, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('logoff', 1, 1, 1, 0)} db eval {INSERT INTO AccessRightsTable VALUES('changefirstname', 1, 0, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('changelastname', 1, 0, 0, 0)} db eval {INSERT INTO AccessRightsTable VALUES('changeusername', 1, 0, 0, 0)} } proc htmlErrorMsg { msg } { puts "
error: $msg
" } proc htmlReplaceEmptyString { string } { # empty string replaced with "---" regsub {^$} $string "---" string # white spaces only string replaced with "---" regsub {^\s+$} $string "---" string set string } proc htmlDBout {db permission_list user {sort_col {}}} { array set permission $permission_list global script_name set defSortCol LastName if { $sort_col == {} } { set sort_col $defSortCol dbg "empty sort col changed to $sort_col" 4 } # testing for the existense of the sorting column set eval_str [list SELECT * FROM GradesTable ORDER BY $sort_col] set err [catch {db eval $eval_str } errStat] if { $err } { dbg $errStat 3 dbg "changing to default sorting column $defSortCol" 3 set sort_col $defSortCol } puts {
} set show_header 1 # show the table with grades set column_list [getColListFromTable GradesTable] switch $permission(GroupName) { instructor { set hidden_columns {} } ta { set hidden_columns [list UserName] } student { set hidden_columns [list FirstName LastName UserName] } guest { set hidden_columns $column_list } default { set hidden_columns $column_list } } # remove hidden columns from sql request foreach col $hidden_columns { set column_list [removeElementFromList $col $column_list] } set sql_column_str [colList2sqlColStr $column_list] # get all allowed columns set eval_str [concat SELECT $sql_column_str FROM GradesTable ORDER BY $sort_col] set err [catch { db eval $eval_str v { if { $show_header } { set show_header 0 puts {} puts "" foreach col $v(*) { puts -nonewline "" puts "" } puts "" puts "" } else { puts "" } foreach index $v(*) { if { $index != "*" } { set col_value [htmlReplaceEmptyString $v($index)] puts -nonewline "" } } puts "" } } errStat ] if { $err } { dbg "we should never be here if $sortCol exist in the table" 1 dbg $errStat 1 } puts "
$col" # below list has action and action_label pairs set action_list {} switch $col { FirstName { lappend action_list changefirstname "change first name" } LastName { lappend action_list changelastname "change last name" } UserName { lappend action_list changeusername "change user name" } default { lappend action_list changegrades "change grades" deletecolumn delete changecolumn "change column" } } set separator {
} foreach {act act_label} $action_list { if { [isActionGranted $act $permission_list $user] } { puts -nonewline "$separator$act_label" } } puts -nonewline "
$col_value
" puts {
} } proc htmlTop {permission_list} { array set permission $permission_list if { $permission(GroupName) == "guest" } { askToLogin } else { Greetings } } proc htmlFooter {permission_list} { array set permission $permission_list global VERSION puts "
" puts "GradeBook $VERSION code is written by Eugeniy Mikhailov" puts "
" } proc Greetings {} { global user password script_name set FirstName UnknownFirstName set LastName UnknownLastName # get First name info set eval_str "SELECT \"FirstName\" FROM GradesTable where UserName=\"$user\"" set err [catch { db eval $eval_str v { set FirstName $v(FirstName) } } errStat ] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } # get Last name info set eval_str "SELECT \"LastName\" FROM GradesTable where UserName=\"$user\"" set err [catch { db eval $eval_str v { set LastName $v(LastName) } } errStat ] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } puts "
" puts ", you are logged in as ." #puts "logoff" puts "
" } proc askToLogin {} { global script_name puts "
" puts "Either you are here first time or you password and user name does not match.
" puts "Please login
" puts "
" puts {Login:
} puts {Password:
} puts {} puts {} puts {
} puts "
" } #proc CheckAccessRights { user password} {} #proc IsUserknown {} {return 1} #proc SetLoginInfo {} { #global user password #set isAccessGranted [IsUserknown] #if { $isAccessGranted } { #dbg "access granted to user $user" #} #set access_rights [CheckAccessRights $user $password] #} proc LogMeOn {} { global user password set user [::ncgi::value user guest] set password [::ncgi::value password guest] dbg "Logging in and setting cookies" 4 ::ncgi::setCookie -name user -value $user ::ncgi::setCookie -name password -value $password } proc LogMeOff {} { dbg "Logging off" 4 global user password set user guest set password guest ::ncgi::setCookie -name user -value $user ::ncgi::setCookie -name password -value $password } proc SetSortColumn {} { global sortCol set sortCol [::ncgi::value sortCol LastName] ::ncgi::setCookie -name sortCol -value $sortCol } proc isActionGranted { action permission_list user } { array set permission $permission_list if { $action == "defaultview" } { # this one permitted to everyone dbg "requested action $action for user $user is granted" 4 return 1; } if { ![info exist permission($action) ] } { dbg "requested UNKNOWN action $action for user $user is not granted" 0 htmlErrorMsg "requested UNKNOWN action $action" return 0; } if {$permission($action) } { dbg "requested action $action for user $user is granted" 4 return 1; } else { dbg "requested action $action for user $user is not granted" 1 return 0; } } proc ChoseAction {action permission_list user} { array set permission $permission_list dbg "requested action: $action" 1 if { [isActionGranted $action $permission_list $user] } { switch $action { sort { SetSortColumn; ChoseAction defaultview $permission_list $user } addcolumn { AddColumn $permission_list $user; htmlDefaultView $permission_list $user } addcolumnrequest { AddColumnRequest $permission_list $user } deletecolumn { DeleteColumn $permission_list $user; htmlDefaultView $permission_list $user } changegrades { ChangeGrades $permission_list $user } updategrades { UpdateGrades $permission_list $user htmlDefaultView $permission_list $user } changecolumn { ChangeColumn $permission_list $user } updatecolumn { UpdateColumn $permission_list $user htmlDefaultView $permission_list $user } showcontrols { ShowControls $permission_list $user } showgrades { htmlGradesTable db $permission_list $user } defaultview { htmlDefaultView $permission_list $user } default { htmlErrorMsg "requested action $action is granted but not implemented yet" } } } else { # this action is permitted to everyone by default ChoseAction defaultview $permission_list $user } } proc ChangeColumn { permission_list user } { set columnname [::ncgi::value columnname {}] set category "none" set eval_str "SELECT \"$columnname\" FROM GradesTable where UserName=\"_Col_Category_\"" set err [catch { db eval $eval_str v { set category $v($columnname) } } errStat ] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } set eval_str "SELECT \"$columnname\" FROM GradesTable where UserName=\"_Max_Points_\"" set err [catch { db eval $eval_str v { set maxpoints $v($columnname) } } errStat ] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } puts {
} puts "
" set out_str {} append out_str {Column Name:
} puts $out_str set out_str {} append out_str {Category:
} set out_str {} append out_str {Max Point Possible:
} puts $out_str puts {} set out_str {} append out_str {} puts $out_str puts {} puts {
} puts {
} } proc UpdateColumn { permission_list user } { set oldcolumnname [::ncgi::value oldcolumnname {}] set newcolumnname [::ncgi::value newcolumnname {}] set column_category [::ncgi::value category {}] set maxpointpossible [::ncgi::value maxpointpossible {}] # first we update category and maxpointpossible values of the old columnname set sql_str [concat UPDATE GradesTable SET \"$oldcolumnname\"=\'$column_category\' where UserName=\"_Col_Category_\"] set err [catch {db eval $sql_str } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } set sql_str [concat UPDATE GradesTable SET \"$oldcolumnname\"=\'$maxpointpossible\' where UserName=\"_Max_Points_\"] set err [catch {db eval $sql_str } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } if { $newcolumnname eq $oldcolumnname } { # no need to mess with renaming return } if { $newcolumnname == "" } { htmlErrorMsg "empty column names are not permitted" return } set eval_str [concat SELECT * FROM GradesTable ] set err [catch {db eval $eval_str v {} } errStat] set old_column_list $v(*) # check if column with the suggested new name is already exist foreach cname $old_column_list { if { $cname eq $newcolumnname } { htmlErrorMsg "The column name $newcolumnname is already exist" return } } # sqlite does not allow rename columns # I will first create new column identical to the old one AddColumnNonWeb $newcolumnname $column_category $maxpointpossible set sql_str [concat UPDATE GradesTable SET \"$newcolumnname\"=\"$oldcolumnname\"] set err [catch {db eval $sql_str } errStat] # then delete the old one DeleteColumnNonWeb $oldcolumnname } proc UpdateGrades { permission_list user } { global script_name set subaction [::ncgi::value subaction {}] set columnname [::ncgi::value columnname {}] set nv [::ncgi::nvlist] array set colval $nv if { $subaction eq "Submit" } { set eval_str "SELECT UserName FROM GradesTable" set err [catch { db eval $eval_str v { if { [info exist colval($v(UserName))] } { set sql_str [concat UPDATE GradesTable SET \"$columnname\"=\'$colval($v(UserName))\' where UserName=\"$v(UserName)\"] set err2 [catch { db eval $sql_str } errStat2 ] if { $err2 } { htmlErrorMsg $errStat2 dbg "the following error happen: $errStat2" 3 } } } } errStat ] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } } } proc ChangeGrades { permission_list user } { global script_name set columnname [::ncgi::value columnname {}] if { $columnname != "" } { # output only selected columns set column_list {} lappend column_list FirstName LastName UserName lappend column_list \"$columnname\" set sql_column_list [join $column_list ","] puts "
" # output only selected columns set eval_str "SELECT $sql_column_list FROM GradesTable WHERE UserName<>'_Col_Category_' AND UserName<>'_Max_Points_' ORDER BY LastName" set show_header 1 set err [catch { db eval $eval_str v { if { $show_header } { set show_header 0 puts {} puts "" foreach col $v(*) { puts -nonewline "" } puts "" } else { puts "" } foreach index $v(*) { if { $index != "*" } { if { $index eq $columnname } { #column with grade puts "" } else { puts -nonewline "" } } } puts "" } } errStat ] puts "
$col
$v($index)
" if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } puts {} puts [concat ] puts {} puts {} puts {
} #puts "Cancel changes" } else { htmlErrorMsg "empty column names are not permitted" } } proc getColListFromTable { table } { set eval_str [concat SELECT * FROM \'$table\' ] set err [catch {db eval $eval_str v {} } errStat] set old_column_list $v(*) return $old_column_list } proc removeElementFromList { element2remove old_list } { set new_list {} foreach element $old_list { if { $element2remove ne $element } { lappend new_list $element } } return $new_list } proc colList2sqlColStr { col_list } { set sqlStr {} foreach col $col_list { if {$sqlStr ne ""} { set sqlStr $sqlStr,\"$col\" } else { set sqlStr \"$col\" } } return $sqlStr } proc DeleteColumnNonWeb { columnname } { if { $columnname != "" } { # removing the column name to be deleted from total list set old_column_list [getColListFromTable GradesTable] set new_column_list [removeElementFromList $columnname $old_column_list] set sql_new_column_str [colList2sqlColStr $new_column_list] set eval_str "BEGIN TRANSACTION; CREATE TEMPORARY TABLE GradesTable_backup($sql_new_column_str); INSERT INTO GradesTable_backup SELECT $sql_new_column_str FROM GradesTable; DROP TABLE GradesTable; CREATE TABLE GradesTable($sql_new_column_str); INSERT INTO GradesTable SELECT $sql_new_column_str FROM GradesTable_backup; DROP TABLE GradesTable_backup; COMMIT;" set err [catch {db eval $eval_str } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } } else { htmlErrorMsg "empty column names are not permitted" } } proc DeleteColumn { permission_list user } { global script_name set columnname [::ncgi::value columnname {}] DeleteColumnNonWeb $columnname } proc AddColumnNonWeb { columnname2add column_category maxpointpossible } { if { $columnname2add != "" } { set eval_str [concat ALTER TABLE GradesTable ADD \"$columnname2add\" text] set err [catch {db eval $eval_str } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } set sql_str [concat UPDATE GradesTable SET \"$columnname2add\"=\'$column_category\' where UserName=\"_Col_Category_\"] set err [catch {db eval $sql_str } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } set sql_str [concat UPDATE GradesTable SET \"$columnname2add\"=\'$maxpointpossible\' where UserName=\"_Max_Points_\"] set err [catch {db eval $sql_str } errStat] if { $err } { htmlErrorMsg $errStat dbg "the following error happen: $errStat" 3 } } else { htmlErrorMsg "empty column names are not permitted" } } proc AddColumn { permission_list user } { global script_name set columnname2add [::ncgi::value columnname2add {}] set column_category [::ncgi::value column_category {}] set maxpointpossible [::ncgi::value maxpointpossible {}] AddColumnNonWeb $columnname2add $column_category $maxpointpossible } proc AddColumnRequest { permission_list user } { global script_name puts {
} puts "
" puts {Column Name:
} puts {Category:
} puts {Max Point Possible:
} puts {} puts {} puts {
} puts {
} } proc ShowControls { permission_list user } { array set permission $permission_list global script_name dbg "outputing contol list" puts "
" set action_list [ list defaultview "Refresh" addcolumnrequest "Add Column" logoff "Logoff" ] set separator { } foreach {act act_label} $action_list { if { [isActionGranted $act $permission_list $user] } { puts -nonewline "$separator$act_label" } } puts "" puts "
" } proc AccessGroupRights {db user password } { dbg "access rights check for user: $user" set PasswordHash [::md5::md5 -hex $password] set eval_str [list SELECT GroupName FROM PasswordsTable WHERE UserName='$user' AND PasswordHash='$PasswordHash'] db eval $eval_str group_name_array {} if { [ info exist group_name_array(GroupName) ] } { set group $group_name_array(GroupName); } else { set group guest } dbg "Detected group is $group" set eval_str [list SELECT actionname,$group FROM AccessRightsTable ] set permission_list [list GroupName $group] db eval $eval_str permissions { lappend permission_list $permissions(actionname) $permissions($group) } dbg "permissions for user $user belonging to the group $group are: $permission_list" return $permission_list } proc htmlStudentGrades { db user } { set defSortCol LastName global script_name set sort_col $defSortCol puts {
} set show_header 1 set do_not_show_columns [list FirstName LastName UserName] set cols_to_show [getColListFromTable GradesTable] foreach col $do_not_show_columns { set cols_to_show [removeElementFromList $col $cols_to_show] } set sql_column_str [colList2sqlColStr $cols_to_show] # show the table with grades set eval_str [concat SELECT $sql_column_str FROM GradesTable WHERE UserName='$user' ORDER BY $sort_col] set err [catch { db eval $eval_str v { if { $show_header } { set show_header 0 puts {} puts "" foreach col $v(*) { puts -nonewline "" } puts "" puts "" } else { puts "" } foreach index $v(*) { if { $index != "*" } { set col_value [htmlReplaceEmptyString $v($index)] puts -nonewline "" } } puts "" } } errStat ] if { $err } { dbg "we should never be here if $sortCol and $user exist in the table" 1 dbg $errStat 1 } puts "
$col
$col_value
" puts {
} } proc htmlGradesTable {db permission_list user} { array set permission $permission_list global sortCol switch $permission(GroupName) { guest { } student { htmlStudentGrades db $user} ta { htmlDBout db $permission_list $user $sortCol} instructor { htmlDBout db $permission_list $user $sortCol} default { } } } proc htmlDefaultView { permission_list user } { ChoseAction showcontrols $permission_list $user ChoseAction showgrades $permission_list $user } proc htmlHeader {} { puts { Grade Book } } ##################### end of procs #################################### set timestamp [clock format [clock seconds] -format "%Y-%m-%dT%H:%M:%S"] #CreatePasswordsTable db #CreateGradesTable db #CreateAccessRightsTable db dbg [::ncgi::names] 4 # logon and logoff actions are granted to everyone if { $action == "logon" } { LogMeOn; set action defaultview } if { $action == "logoff" } { LogMeOff; set action defaultview } dbg "===== Connection at $timestamp for user $user =====" set permission_list [AccessGroupRights db $user $password] ::ncgi::header htmlHeader puts "" htmlTop $permission_list ChoseAction $action $permission_list $user #htmlDefaultView $permission_list $user #htmlGradesTable db $permission_list $user #htmlDBout db $sortCol htmlFooter $permission_list puts "" # vim: ts=2 sw=2 foldmethod=indent: