[LON-CAPA-cvs] cvs: loncom /interface courseprefs.pm domainprefs.pm lonconfigsettings.pm /lonnet/perl lonnet.pm

raeburn raeburn at source.lon-capa.org
Sun Mar 19 12:05:49 EDT 2023


raeburn		Sun Mar 19 16:05:49 2023 EDT

  Modified files:              
    /loncom/interface	courseprefs.pm domainprefs.pm 
                     	lonconfigsettings.pm 
    /loncom/lonnet/perl	lonnet.pm 
  Log:
  - Bug 6754
    - Support encryption of secrets set for External Tools in a domain.
    - Requires perl-Crypt-CBC
    - External Tools can be configured in a course via Course Settings by a user
      with 'opa' privilege in the course.
  
  
-------------- next part --------------
Index: loncom/interface/courseprefs.pm
diff -u loncom/interface/courseprefs.pm:1.117 loncom/interface/courseprefs.pm:1.118
--- loncom/interface/courseprefs.pm:1.117	Wed Oct 19 00:03:10 2022
+++ loncom/interface/courseprefs.pm	Sun Mar 19 16:05:48 2023
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Handler to set configuration settings for a course
 #
-# $Id: courseprefs.pm,v 1.117 2022/10/19 00:03:10 raeburn Exp $
+# $Id: courseprefs.pm,v 1.118 2023/03/19 16:05:48 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -225,6 +225,7 @@
 use Apache::lonlocal;
 use LONCAPA qw(:DEFAULT :match);
 use Crypt::CBC;
+use Time::HiRes qw( sleep );
 
 my $registered_cleanup;
 my $modified_courses;
@@ -372,6 +373,8 @@
     my %values=&Apache::lonnet::dump('environment',$cdom,$cnum);
     my %linkprot=&Apache::lonnet::dump('lti',$cdom,$cnum,undef,undef,undef,1);
     my %ltienc = &Apache::lonnet::dump('nohist_ltienc',$cdom,$cnum,undef,undef,undef,1);
+    my %ltitools = &Apache::lonnet::dump('ltitools',$cdom,$cnum,undef,undef,undef,1);
+    my %ltitoolsenc = &Apache::lonnet::dump('nohist_toolsenc',$cdom,$cnum,undef,undef,undef,1);
     foreach my $id (keys(%linkprot)) {
         if (ref($linkprot{$id}) eq 'HASH') {
             if (ref($ltienc{$id}) eq 'HASH') {
@@ -389,11 +392,27 @@
     if ($linkprot{'lock'}) {
         delete($linkprot{'lock'});
     }
+    foreach my $id (keys(%ltitools)) {
+        if (ref($ltitools{$id}) eq 'HASH') {
+            if (ref($ltitoolsenc{$id}) eq 'HASH') {
+                $values{'ltitools'}{$id} = { %{$ltitools{$id}}, %{$ltitoolsenc{$id}} };
+            } else {
+                $values{'ltitools'}{$id} = $ltitools{$id};
+            }
+        }
+        unless ($phase eq 'process') {
+            if (ref($values{'ltitools'}{$id}) eq 'HASH') {
+                delete($values{'ltitools'}{$id}{'secret'});
+            }
+        }
+    }
+    if ($ltitools{'lock'}) {
+        delete($ltitools{'lock'});
+    }
     my @prefs_order = ('courseinfo','localization','feedback','discussion',
                        'classlists','appearance','grading','printouts',
-                       'menuitems','linkprot','spreadsheet','bridgetasks',
-                       'lti','other');
-
+                       'menuitems','ltitools','linkprot','spreadsheet',
+                       'bridgetasks','lti','other');
     my %prefs = (
         'courseinfo' =>
                    { text => $lt{'gens'},
@@ -593,6 +612,14 @@
                                  col2 => 'Settings',
                                 }],
                    },
+        'ltitools' =>
+                   {
+                     text => 'External tools',
+                     help => 'Course_Prefs_ExternalTools',
+                     header => [{col1 => 'Item',
+                                 col2 => 'Settings',
+                                }],
+                   },
         'other' =>
                   { text => 'Other settings',
                     help => 'Course_Prefs_Other',
@@ -800,6 +827,12 @@
         $output .= &print_spreadsheet($cdom,$settings,$ordered,$itemtext,\$rowtotal,$crstype,$noedit);
     } elsif ($action eq 'bridgetasks') {
         $output .= &print_bridgetasks($cdom,$settings,$ordered,$itemtext,\$rowtotal,$crstype,$noedit);
+    } elsif ($action eq 'ltitools') {
+        my $currtools = {};
+        if ((ref($settings) eq 'HASH') && (ref($settings->{'ltitools'}))) {
+            $currtools = $settings->{'ltitools'};
+        }
+        $output .= &print_ltitools($cdom,$cnum,$currtools,\$rowtotal,$crstype,$noedit,'course');
     } elsif ($action eq 'lti') {
         $output .= &print_lti($cdom,$settings,$ordered,$itemtext,\$rowtotal,$crstype,$noedit);
     } elsif ($action eq 'menuitems') {
@@ -836,7 +869,7 @@
                         }
                     }
                 }
-            } elsif ($action eq 'linkprot') {
+            } elsif (($action eq 'linkprot') || ($action eq 'ltitools')) {
                 if (ref($values->{$action}) eq 'HASH') {
                     foreach my $id (keys(%{$values->{$action}})) {
                         if ($id =~ /^\d+$/) {
@@ -845,8 +878,8 @@
                     }
                 }
                 @ordered = sort { $a <=> $b } @ordered;
-                if (($env{'form.linkprot_add'}) && ($env{'form.linkprot_maxnum'} =~ /^\d+$/)) {
-                    push(@ordered,$env{'form.linkprot_maxnum'});
+                if (($env{'form.'.$action.'_add'}) && ($env{'form.'.$action.'_maxnum'} =~ /^\d+$/)) {
+                    push(@ordered,$env{'form.'.$action.'_maxnum'});
                 }
             } elsif (ref($item->{'ordered'}) eq 'ARRAY') {
                 if ($action eq 'courseinfo') {
@@ -989,6 +1022,12 @@
                     if (ref($values) eq 'HASH') {
                         $errors = &process_linkprot($cdom,$cnum,$values->{$action},$changes,'course',$lastactref);
                     }
+                } elsif ($action eq 'ltitools') {
+                    if (ref($values) eq 'HASH') {
+                        my $switchserver = &check_switchserver($cdom,$cnum,'course','/adm/courseprefs');
+                        $errors = &process_ltitools('',$cdom,$cnum,$values->{$action},$changes,'course',$lastactref,
+                                                    'ok','','ok');
+                    }
                 } else {
                     foreach my $entry (@ordered) {
                         if ($entry eq 'cloners') {
@@ -1528,7 +1567,7 @@
 
 sub process_linkprot {
     my ($cdom,$cnum,$values,$changes,$context,$lastactref) = @_;
-    my ($home,$dest,$ltiauth,$privkey,$privnum,$cipher,$errors,%linkprot);
+    my ($dest,$ltiauth,$privnum,$cipher,$errors,%linkprot);
     if (ref($values) eq 'HASH') {
         foreach my $id (keys(%{$values})) {
             if ($id =~ /^\d+$/) {
@@ -1538,31 +1577,7 @@
             }
         }
     }
-    my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
-    my @ids=&Apache::lonnet::current_machine_ids();
-    if ($context eq 'domain') {
-        $home = &Apache::lonnet::domain($cdom,'primary');
-    } else {
-        $home = &Apache::lonnet::homeserver($cnum,$cdom);
-    }
-    if ((($context eq 'domain') && ($domdefs{'linkprotenc_dom'})) ||
-        (($context eq 'course') && ($domdefs{'linkprotenc_crs'}))) {
-        unless (($home eq 'no_host') || ($home eq '')) {
-            if (grep(/^\Q$home\E$/, at ids)) {
-                if (ref($domdefs{'privhosts'}) eq 'ARRAY') {
-                    if (grep(/^\Q$home\E$/,@{$domdefs{'privhosts'}})) {
-                        my %privhash  = &Apache::lonnet::restore_dom('lti','private',$cdom,$home,1);
-                        $privkey = $privhash{'key'};
-                        $privnum = $privhash{'version'};
-                        if (($privnum) && ($privkey ne '')) {
-                            $cipher = Crypt::CBC->new({'key'     => $privkey,
-                                                       'cipher'  => 'DES'});
-                        }
-                    }
-                }
-            }
-        }
-    }
+    ($cipher,$privnum) = &get_credentials($cdom,$cnum,'lti',$context);
     if ($context eq 'domain') {
         $dest = '/adm/domainprefs';
         $ltiauth = 1;
@@ -1815,6 +1830,671 @@
     return ($id,$error);
 }
 
+sub get_credentials {
+    my ($cdom,$cnum,$type,$context) = @_;
+    my ($cipher,$privnum,$home);
+    my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
+    my @ids=&Apache::lonnet::current_machine_ids();
+    if ($context eq 'domain') {
+        $home = &Apache::lonnet::domain($cdom,'primary');
+    } else {
+        $home = &Apache::lonnet::homeserver($cnum,$cdom);
+    }
+    my ($hostskey,$domkey,$crskey);
+    if ($type eq 'ltitools') {
+        $hostskey = 'toolprivhosts';
+        $domkey = 'toolenc_dom';
+        $crskey = 'toolenc_crs';
+    } else {
+        $hostskey = 'ltiprivhosts';
+        $domkey = 'linkprotenc_dom';
+        $crskey = 'linkprotenc_crs';
+    }
+    if ((($context eq 'domain') && ($domdefs{$domkey})) ||
+        (($context eq 'course') && ($domdefs{$crskey}))) {
+        unless (($home eq 'no_host') || ($home eq '')) {
+            if (grep(/^\Q$home\E$/, at ids)) {
+                if (ref($domdefs{$hostskey}) eq 'ARRAY') {
+                    if (grep(/^\Q$home\E$/,@{$domdefs{$hostskey}})) {
+                        my %privhash  = &Apache::lonnet::restore_dom($type,'private',$cdom,$home,1);
+                        my $privkey = $privhash{'key'};
+                        $privnum = $privhash{'version'};
+                        if (($privnum) && ($privkey ne '')) {
+                            $cipher = Crypt::CBC->new({'key'     => $privkey,
+                                                       'cipher'  => 'DES'});
+                        }
+                    }
+                }
+            }
+        }
+    }
+    return ($cipher,$privnum);
+}
+
+sub process_ltitools {
+    my ($r,$cdom,$cnum,$values,$changes,$context,$lastactref,$configuserok,$lonhost,
+        $author_ok,$confname) = @_;
+    my (%currconfig,$newid, at allpos,%changes,%ltitools,$errors);
+
+    my (%posslti,%possfield);
+    my @courseroles = ('cc','in','ta','ep','st');
+    my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
+    map { $posslti{$_} = 1; } @ltiroles;
+    my @allfields = ('fullname','firstname','lastname','email','user','roles');
+    map { $possfield{$_} = 1; } @allfields;
+
+    my ($dest,$privnum,$cipher,$errors,%ltitools);
+
+    ($cipher,$privnum) = &get_credentials($cdom,$cnum,'ltitools',$context);
+    if ($context eq 'domain') {
+        $dest = '/adm/domainprefs';
+    } else {
+        $dest = '/adm/courseprefs';
+    }
+    my $switchserver = &check_switchserver($cdom,$cnum,$context,$dest);
+
+    my (@allpos, at items,%deletions,%itemids,%haschanges);
+    if ($env{'form.ltitools_add'}) {
+        my $title = $env{'form.ltitools_add_title'};
+        $title =~ s/(`)/'/g;
+        my ($newid,$error) = &get_ltitools_id($context,$cdom,$cnum,$title);
+        if ($newid) {
+            my $position = $env{'form.ltitools_add_pos'};
+            $position =~ s/\D+//g;
+            if ($position ne '') {
+                $allpos[$position] = $newid;
+            }
+            $haschanges{$newid} = 1;
+            foreach my $item ('title','url','lifetime') {
+                $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
+                if ($item eq 'lifetime') {
+                    $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
+                }
+                if ($env{'form.ltitools_add_'.$item}) {
+                    $ltitools{$newid}{$item} = $env{'form.ltitools_add_'.$item};
+                }
+            }
+            if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
+                $ltitools{$newid}{'version'} = $env{'form.ltitools_add_version'};
+            }
+            if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
+                $ltitools{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
+            }
+            if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
+                $ltitools{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
+            } else {
+                $ltitools{$newid}{'sigmethod'} = 'HMAC-SHA1';
+            }
+            foreach my $item ('width','height','linktext','explanation') {
+                $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
+                $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
+                if (($item eq 'width') || ($item eq 'height')) {
+                    if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
+                        $ltitools{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
+                    }
+                } else {
+                    if ($env{'form.ltitools_add_'.$item} ne '') {
+                        $ltitools{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
+                    }
+                }
+            }
+            if ($env{'form.ltitools_add_target'} eq 'window') {
+                $ltitools{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
+            } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
+                $ltitools{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
+            } else {
+                $ltitools{$newid}{'display'}{'target'} = 'iframe';
+            }
+            foreach my $item ('passback','roster') {
+                if ($env{'form.ltitools_'.$item.'_add'}) {
+                    $ltitools{$newid}{$item} = 1;
+                    if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
+                        my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
+                        $lifetime =~ s/^\s+|\s+$//g;
+                        if ($lifetime =~ /^\d+\.?\d*$/) {
+                            $ltitools{$newid}{$item.'valid'} = $lifetime;
+                        }
+                    }
+                }
+            }
+            if ($env{'form.ltitools_add_image.filename'} ne '') {
+                my ($imageurl,$error) =
+                    &process_ltitools_image($r,$context,$cdom,$cnum,$confname,'ltitools_add_image',
+                                            $newid,$configuserok,$lonhost,$author_ok);
+                if ($imageurl) {
+                    $ltitools{$newid}{'image'} = $imageurl;
+                }
+                if ($error) {
+                    &Apache::lonnet::logthis($error);
+                    $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
+                }
+            }
+            my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
+            foreach my $field (@fields) {
+                if ($possfield{$field}) {
+                    if ($field eq 'roles') {
+                        foreach my $role (@courseroles) {
+                            my $choice = $env{'form.ltitools_add_roles_'.$role};
+                            if (($choice ne '') && ($posslti{$choice})) {
+                                $ltitools{$newid}{'roles'}{$role} = $choice;
+                                if ($role eq 'cc') {
+                                    $ltitools{$newid}{'roles'}{'co'} = $choice;
+                                }
+                            }
+                        }
+                    } else {
+                        $ltitools{$newid}{'fields'}{$field} = 1;
+                    }
+                }
+            }
+            if (ref($ltitools{$newid}{'fields'}) eq 'HASH') {
+                if ($ltitools{$newid}{'fields'}{'user'}) {
+                    if ($env{'form.ltitools_add_userincdom'}) {
+                        $ltitools{$newid}{'incdom'} = 1;
+                    }
+                }
+            }
+            my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_add_courseconfig');
+            foreach my $item (@courseconfig) {
+                $ltitools{$newid}{'crsconf'}{$item} = 1;
+            }
+            if ($env{'form.ltitools_add_custom'}) {
+                my $name = $env{'form.ltitools_add_custom_name'};
+                my $value = $env{'form.ltitools_add_custom_value'};
+                $value =~ s/(`)/'/g;
+                $name =~ s/(`)/'/g;
+                $ltitools{$newid}{'custom'}{$name} = $value;
+            }
+            unless ($switchserver) {
+                my $keyitem = 'form.ltitools_add_key';
+                $env{$keyitem} =~ s/(`)/'/g;
+                if ($env{$keyitem} ne '') {
+                    $ltitools{$newid}{'key'} = $env{$keyitem};
+                }
+                my $secretitem = 'form.ltitools_add_secret';
+                $env{$secretitem} =~ s/(`)/'/g;
+                if ($env{$secretitem} ne '') {
+                    if ($privnum && $cipher) {
+                        $ltitools{$newid}{'secret'} = $cipher->encrypt_hex($env{$secretitem});
+                        $ltitools{$newid}{'cipher'} = $privnum;
+                    } else {
+                        $ltitools{$newid}{'secret'} = $env{$secretitem};
+                    }
+                }
+            }
+        } else {
+            $errors .= '<li><span class="LC_error">'.
+                       &mt('Failed to acquire unique ID for new external tool').
+                       '</span></li>';
+        }
+    }
+    if (ref($values) eq 'HASH') {
+        my %deletions;
+        my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
+        if (@todelete) {
+            map { $deletions{$_} = 1; } @todelete;
+        }
+        my %customadds;
+        my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
+        if (@newcustom) {
+            map { $customadds{$_} = 1; } @newcustom;
+        }
+        my %imgdeletions;
+        my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
+        if (@todeleteimages) {
+            map { $imgdeletions{$_} = 1; } @todeleteimages;
+        }
+        my $maxnum = $env{'form.ltitools_maxnum'};
+        for (my $i=0; $i<=$maxnum; $i++) {
+            my $itemid = $env{'form.ltitools_id_'.$i};
+            $itemid =~ s/\D+//g;
+            if (ref($values->{$itemid}) eq 'HASH') {
+                if ($deletions{$itemid}) {
+                    if ($values->{$itemid}{'image'}) {
+                        #FIXME need to obsolete item in RES space
+                    }
+                    $haschanges{$itemid} = $values->{$itemid}{'title'};
+                    next;
+                } else {
+                    my $newpos = $env{'form.ltitools_'.$itemid};
+                    $newpos =~ s/\D+//g;
+                    foreach my $item ('title','url','lifetime') {
+                        $ltitools{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
+                        if ($values->{$itemid}{$item} ne $ltitools{$itemid}{$item}) {
+                            $haschanges{$itemid} = 1;
+                        }
+                    }
+                    if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
+                        $ltitools{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
+                    }
+                    if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
+                        $ltitools{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
+                    }
+                    if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
+                        $ltitools{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
+                    } else {
+                        $ltitools{$itemid}{'sigmethod'} = 'HMAC-SHA1';
+                    }
+                    if ($values->{$itemid}{'sigmethod'} eq '') {
+                        if ($ltitools{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
+                            $haschanges{$itemid} = 1;
+                        }
+                    } elsif ($values->{$itemid}{'sigmethod'} ne $ltitools{$itemid}{'sigmethod'}) {
+                        $haschanges{$itemid} = 1;
+                    }
+                    foreach my $size ('width','height') {
+                        $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
+                        $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
+                        if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
+                            $ltitools{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
+                            if (ref($values->{$itemid}{'display'}) eq 'HASH') {
+                                if ($values->{$itemid}{'display'}{$size} ne $ltitools{$itemid}{'display'}{$size}) {
+                                    $haschanges{$itemid} = 1;
+                                }
+                            } else {
+                                $haschanges{$itemid} = 1;
+                            }
+                        } elsif (ref($values->{$itemid}{'display'}) eq 'HASH') {
+                            if ($values->{$itemid}{'display'}{$size} ne '') {
+                                $haschanges{$itemid} = 1;
+                            }
+                        }
+                    }
+                    foreach my $item ('linktext','explanation') {
+                        $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
+                        $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
+                        if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
+                            $ltitools{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
+                            if (ref($values->{$itemid}{'display'}) eq 'HASH') {
+                                if ($values->{$itemid}{'display'}{$item} ne $ltitools{$itemid}{'display'}{$item}) {
+                                    $haschanges{$itemid} = 1;
+                                }
+                            } else {
+                                $haschanges{$itemid} = 1;
+                            }
+                        } elsif (ref($values->{$itemid}{'display'}) eq 'HASH') {
+                            if ($values->{$itemid}{'display'}{$item} ne '') {
+                                $haschanges{$itemid} = 1;
+                            }
+                        }
+                    }
+                    if ($env{'form.ltitools_target_'.$i} eq 'window') {
+                        $ltitools{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
+                    } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
+                        $ltitools{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
+                    } else {
+                        $ltitools{$itemid}{'display'}{'target'} = 'iframe';
+                    }
+                    if (ref($values->{$itemid}{'display'}) eq 'HASH') {
+                        if ($values->{$itemid}{'display'}{'target'} ne $ltitools{$itemid}{'display'}{'target'}) {
+                            $haschanges{$itemid} = 1;
+                        }
+                    } else {
+                        $haschanges{$itemid} = 1;
+                    }
+                    foreach my $extra ('passback','roster') {
+                        if ($env{'form.ltitools_'.$extra.'_'.$i}) {
+                            $ltitools{$itemid}{$extra} = 1;
+                            if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
+                                my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
+                                $lifetime =~ s/^\s+|\s+$//g;
+                                if ($lifetime =~ /^\d+\.?\d*$/) {
+                                    $ltitools{$itemid}{$extra.'valid'} = $lifetime;
+                                }
+                            }
+                        }
+                        if ($values->{$itemid}{$extra} ne $ltitools{$itemid}{$extra}) {
+                            $haschanges{$itemid} = 1;
+                        }
+                        if ($values->{$itemid}{$extra.'valid'} ne $ltitools{$itemid}{$extra.'valid'}) {
+                            $haschanges{$itemid} = 1;
+                        }
+                    }
+                    my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
+                    foreach my $item ('label','title','target','linktext','explanation','append') {
+                        if (grep(/^\Q$item\E$/, at courseconfig)) {
+                            $ltitools{$itemid}{'crsconf'}{$item} = 1;
+                            if (ref($values->{$itemid}{'crsconf'}) eq 'HASH') {
+                                if ($values->{$itemid}{'crsconf'}{$item} ne $ltitools{$itemid}{'crsconf'}{$item}) {
+                                    $haschanges{$itemid} = 1;
+                                }
+                            } else {
+                                $haschanges{$itemid} = 1;
+                            }
+                        }
+                    }
+                    my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
+                    foreach my $field (@fields) {
+                        if ($possfield{$field}) {
+                            if ($field eq 'roles') {
+                                foreach my $role (@courseroles) {
+                                    my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
+                                    if (($choice ne '') && ($posslti{$choice})) {
+                                        $ltitools{$itemid}{'roles'}{$role} = $choice;
+                                        if ($role eq 'cc') {
+                                            $ltitools{$itemid}{'roles'}{'co'} = $choice;
+                                        }
+                                    }
+                                    if (ref($values->{$itemid}{'roles'}) eq 'HASH') {
+                                        if ($values->{$itemid}{'roles'}{$role} ne $ltitools{$itemid}{'roles'}{$role}) {
+                                            $haschanges{$itemid} = 1;
+                                        }
+                                    } elsif ($ltitools{$itemid}{'roles'}{$role}) {
+                                        $haschanges{$itemid} = 1;
+                                    }
+                                }
+                            } else {
+                                $ltitools{$itemid}{'fields'}{$field} = 1;
+                                if (ref($values->{$itemid}{'fields'}) eq 'HASH') {
+                                    if ($values->{$itemid}{'fields'}{$field} ne $ltitools{$itemid}{'fields'}{$field}) {
+                                        $haschanges{$itemid} = 1;
+                                    }
+                                } else {
+                                    $haschanges{$itemid} = 1;
+                                }
+                            }
+                        }
+                    }
+                    if (ref($ltitools{$itemid}{'fields'}) eq 'HASH') {
+                        if ($ltitools{$itemid}{'fields'}{'user'}) {
+                            if ($env{'form.ltitools_userincdom_'.$i}) {
+                                $ltitools{$itemid}{'incdom'} = 1;
+                            }
+                            if ($values->{$itemid}{'incdom'} ne $ltitools{$itemid}{'incdom'}) {
+                                $haschanges{$itemid} = 1;
+                            }
+                        }
+                    }
+                    $allpos[$newpos] = $itemid;
+                }
+                if ($imgdeletions{$itemid}) {
+                    $haschanges{$itemid} = 1;
+                    if ($context eq 'course') {
+                        my $currimgurl = $values->{$itemid}{'image'};
+                        if ($currimgurl =~ m{^(\Q/uploaded/$cdom/$cnum/toollogo/$itemid\E)/([^/]+)$}) {
+                            my ($path,$imagefile) = ($1,$2);
+                            if ($imagefile =~ /^tn\-(.+)$/) {
+                                my $origimg = $1;
+                                &Apache::lonnet::removeuploadedurl("$path/$origimg");
+                            }
+                            &Apache::lonnet::removeuploadedurl($currimgurl);
+                        }
+                    }
+                    #FIXME need to obsolete item in RES space
+                } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
+                    my $currimgurl = $values->{$itemid}{'image'};
+                    my ($imgurl,$error) = &process_ltitools_image($r,$context,$cdom,$cnum,$confname,'ltitools_image_'.$i,
+                                                                 $itemid,$configuserok,$lonhost,$author_ok,$currimgurl);
+                    if ($imgurl) {
+                        $ltitools{$itemid}{'image'} = $imgurl;
+                        $haschanges{$itemid} = 1;
+                    }
+                    if ($error) {
+                        &Apache::lonnet::logthis($error);
+                        $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
+                    }
+                } elsif ($values->{$itemid}{'image'}) {
+                    $ltitools{$itemid}{'image'} = $values->{$itemid}{'image'};
+                }
+                if ($customadds{$i}) {
+                    my $name = $env{'form.ltitools_custom_name_'.$i};
+                    $name =~ s/(`)/'/g;
+                    $name =~ s/^\s+//;
+                    $name =~ s/\s+$//;
+                    my $value = $env{'form.ltitools_custom_value_'.$i};
+                    $value =~ s/(`)/'/g;
+                    $value =~ s/^\s+//;
+                    $value =~ s/\s+$//;
+                    if ($name ne '') {
+                        $ltitools{$itemid}{'custom'}{$name} = $value;
+                        $haschanges{$itemid} = 1;
+                    }
+                }
+                my %customdels;
+                my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i);
+                if (@customdeletions) {
+                    $haschanges{$itemid} = 1;
+                }
+                map { $customdels{$_} = 1; } @customdeletions;
+                if (ref($values->{$itemid}{'custom'}) eq 'HASH') {
+                    foreach my $key (keys(%{$values->{$itemid}{'custom'}})) {
+                        unless ($customdels{$key}) {
+                            if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
+                                $ltitools{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i};
+                            }
+                            if ($values->{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
+                                $haschanges{$itemid} = 1;
+                            }
+                        }
+                    }
+                }
+                unless ($switchserver) {
+                    my $keyitem = 'form.ltitools_key_'.$i;
+                    $env{$keyitem} =~ s/(`)/'/g;
+                    if ($values->{$itemid}{'key'} ne $env{$keyitem}) {
+                        $haschanges{$itemid} = 1;
+                    }
+                    if ($env{$keyitem} ne '') {
+                        $ltitools{$itemid}{'key'} = $env{$keyitem};
+                    }
+                    my $secretitem = 'form.ltitools_secret_'.$i;
+                    $env{$secretitem} =~ s/(`)/'/g;
+                    if ($values->{$itemid}{'usable'}) {
+                        if ($env{'form.ltitools_changesecret_'.$i}) {
+                            if ($env{$secretitem} ne '') {
+                                if ($privnum && $cipher) {
+                                    $ltitools{$itemid}{'secret'} = $cipher->encrypt_hex($env{$secretitem});
+                                    $ltitools{$itemid}{'cipher'} = $privnum;
+                                } else {
+                                    $ltitools{$itemid}{'secret'} = $env{$secretitem};
+                                }
+                                $haschanges{$itemid} = 1;
+                            }
+                        } else {
+                            $ltitools{$itemid}{'secret'} = $values->{$itemid}{'secret'};
+                            $ltitools{$itemid}{'cipher'} = $values->{$itemid}{'cipher'};
+                        }
+                    } elsif ($env{$secretitem} ne '') {
+                        if ($privnum && $cipher) {
+                            $ltitools{$itemid}{'secret'} = $cipher->encrypt_hex($env{$secretitem});
+                            $ltitools{$itemid}{'cipher'} = $privnum;
+                        } else {
+                            $ltitools{$itemid}{'secret'} = $env{$secretitem};
+                        }
+                        $haschanges{$itemid} = 1;
+                    }
+                }
+                unless ($haschanges{$itemid}) {
+                    foreach my $key (keys(%{$values->{$itemid}})) {
+                        if (ref($values->{$itemid}{$key}) eq 'HASH') {
+                            if (ref($ltitools{$itemid}{$key}) eq 'HASH') {
+                                foreach my $innerkey (keys(%{$values->{$itemid}{$key}})) {
+                                    unless (exists($ltitools{$itemid}{$key}{$innerkey})) {
+                                        $haschanges{$itemid} = 1;
+                                        last;
+                                    }
+                                }
+                            } elsif (keys(%{$values->{$itemid}{$key}}) > 0) {
+                                $haschanges{$itemid} = 1;
+                            }
+                        }
+                        last if ($haschanges{$itemid});
+                    }
+                }
+            }
+        }
+    }
+    if (@allpos > 0) {
+        my $idx = 0;
+        foreach my $itemid (@allpos) {
+            if ($itemid ne '') {
+                $ltitools{$itemid}{'order'} = $idx;
+                if (ref($values) eq 'HASH') {
+                    if (ref($values->{$itemid}) eq 'HASH') {
+                        if ($values->{$itemid}{'order'} ne $idx) {
+                            $haschanges{$itemid} = 1;
+                        }
+                    }
+                }
+                $idx ++;
+            }
+        }
+    }
+    if (keys(%haschanges)) {
+        foreach my $entry (keys(%haschanges)) {
+            $changes->{$entry} = $ltitools{$entry};
+        }
+        if (ref($lastactref) eq 'HASH') {
+            $lastactref->{'courseltitools'} = 1;
+        }
+    }
+    return $errors;
+}
+
+sub get_ltitools_id {
+    my ($context,$cdom,$cnum,$title) = @_;
+    my ($lockhash,$tries,$gotlock,$id,$error);
+
+    # get lock on ltitools db
+    $lockhash = {
+                   lock => $env{'user.name'}.
+                           ':'.$env{'user.domain'},
+                };
+    $tries = 0;
+    if ($context eq 'domain') {
+        $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
+    } else {
+        $gotlock = &Apache::lonnet::newput('ltitools',$lockhash,$cdom,$cnum);
+    }
+    while (($gotlock ne 'ok') && ($tries<10)) {
+        $tries ++;
+        sleep (0.1);
+        if ($context eq 'domain') {
+            $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
+        } else {
+            $gotlock = &Apache::lonnet::newput('ltitools',$lockhash,$cdom,$cnum);
+        }
+    }
+    if ($gotlock eq 'ok') {
+        my %currids;
+        if ($context eq 'domain') {
+            %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
+        } else {
+            %currids = &Apache::lonnet::dump('ltitools',$cdom,$cnum);
+        }
+        if ($currids{'lock'}) {
+            delete($currids{'lock'});
+            if (keys(%currids)) {
+                my @curr = sort { $a <=> $b } keys(%currids);
+                if ($curr[-1] =~ /^\d+$/) {
+                    $id = 1 + $curr[-1];
+                }
+            } else {
+                $id = 1;
+            }
+            if ($id) {
+                if ($context eq 'domain') {
+                    unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
+                        $error = 'nostore';
+                    }
+                } else {
+                    unless (&Apache::lonnet::newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
+                        $error = 'nostore';
+                    }
+                }
+            } else {
+                $error = 'nonumber';
+            }
+        }
+        my $dellockoutcome;
+        if ($context eq 'domain') {
+            $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
+        } else {
+            $dellockoutcome = &Apache::lonnet::del('ltitools',['lock'],$cdom,$cnum);
+        }
+    } else {
+        $error = 'nolock';
+    }
+    return ($id,$error);
+}
+
+sub process_ltitools_image {
+    my ($r,$context,$dom,$cnum,$confname,$caller,$itemid,$configuserok,$switch,$author_ok,$currimg) = @_;
+    my $filename = $env{'form.'.$caller.'.filename'};
+    my ($error,$url);
+    my ($width,$height) = (21,21);
+    if ($configuserok eq 'ok') {
+        if ($switch) {
+            $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
+                         $switch);
+        } elsif ($author_ok eq 'ok') {
+            my ($result,$imageurl,$madethumb);
+            if ($context eq 'domain') {
+                ($result,$imageurl,$madethumb) =
+                    &Apache::lonconfigsettings::publishlogo($r,'upload',$caller,$dom,$confname,
+                                                            "ltitools/$itemid/icon",$width,$height);
+            } else {
+                ($result,$imageurl,$madethumb) = &processlogo($dom,$cnum,$caller,$currimg,$itemid,$width,$height);
+            }
+            if ($result eq 'ok') {
+                if ($madethumb) {
+                    my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
+                    my $imagethumb = "$path/tn-".$imagefile;
+                    $url = $imagethumb;
+                } else {
+                    $url = $imageurl;
+                }
+            } else {
+                if ($context eq 'domain') {
+                    $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
+                } else {
+                    $error = &mt("Upload of [_1] failed because an error occurred. Error was: [_2].",$filename,$result);
+                }
+            }
+        } else {
+            $error = &mt("Upload of [_1] failed because an author role could not be assigned to a Domain Configuration user ([_2]) in domain: [_3].  Error was: [_4].",$filename,$confname,$dom,$author_ok);
+        }
+    } else {
+        $error = &mt("Upload of [_1] failed because a Domain Configuration user ([_2]) could not be created in domain: [_3].  Error was: [_4].",$filename,$confname,$dom,$configuserok);
+    }
+    return ($url,$error);
+}
+
+sub processlogo {
+    my ($dom,$cnum,$caller,$currimg,$itemid,$width,$height) = @_;
+    my ($result,$imageurl,$madethumb);
+    if ($env{"form.$caller.filename"} ne '') {
+        unless ($caller eq 'ltitools_add_image') {
+            if ($currimg =~ m{^(\Q/uploaded/$dom/$cnum/toollogo/$itemid\E)/([^/]+)$}) {
+                my ($path,$imagefile) = ($1,$2);
+                if ($imagefile =~ /^tn\-(.+)$/) {
+                     my $origimg = $1;
+                     &Apache::lonnet::removeuploadedurl("$path/$origimg");
+                }
+                &Apache::lonnet::removeuploadedurl($currimg);
+            }
+        }
+        $imageurl = &Apache::lonnet::userfileupload($caller,'toollogo',"toollogo/$itemid",
+                                                    '','','',$cnum,$dom,$width,$height);
+        if ($imageurl =~ m{^(\Q/uploaded/$dom/$cnum/toollogo/$itemid\E)/([^/]+)$}) {
+            my ($path,$imagefile) = ($1,$2);
+            $result = 'ok';
+            my $thumburl = "$path/tn-".$imagefile;
+            my ($rtncode,$info);
+            my $res = &Apache::lonnet::getuploaded('HEAD',$thumburl,$dom,$cnum,\$info,\$rtncode);
+            if ($res eq 'ok') {
+                $madethumb = 1;
+            }
+        } elsif ($imageurl eq '/adm/notfound.html') {
+            undef($imageurl);
+            $result = 'store failed';
+        } elsif ($imageurl =~ /^error: (.+)$/) {
+            $result = $1;
+        }
+    }
+    return ($result,$imageurl,$madethumb);
+}
+
 sub get_sec_str {
     my ($entry,$num) = @_;
     my @secs = &Apache::loncommon::get_env_multiple('form.'.$entry.'_sections_'.$num);
@@ -1857,12 +2537,15 @@
 sub store_changes {
     my ($cdom,$cnum,$prefs_order,$actions,$prefs,$values,$changes,$crstype) = @_;
     my ($chome,$output);
-    my (%storehash, at delkeys, at need_env_update, at oldcloner,%oldlinkprot);
+    my (%storehash, at delkeys, at need_env_update, at oldcloner,%oldlinkprot,%oldltitools);
     if ((ref($values) eq 'HASH') && (ref($changes) eq 'HASH')) {
         if (ref($values->{'linkprot'}) eq 'HASH') {
             %oldlinkprot = %{$values->{'linkprot'}};
         }
         delete($values->{'linkprot'});
+        if (ref($values->{'ltitools'}) eq 'HASH') {
+            %oldltitools = %{$values->{'ltitools'}};
+        }
         %storehash = %{$values};
     } else {
         if ($crstype eq 'Community') {
@@ -1877,6 +2560,8 @@
         $numchanges = scalar(keys(%{$changes}));
         if (($numchanges == 1) && (exists($changes->{'linkprot'}))) {
             $skipstore = 1;
+        } elsif (($numchanges == 1) && (exists($changes->{'ltitools'}))) {
+            $skipstore = 1;
         } elsif (!$numchanges) {
             if ($crstype eq 'Community') {
                 $output = &mt('No changes made to community settings.');
@@ -1913,6 +2598,8 @@
                         }
                     } elsif ($item eq 'linkprot') {
                         $output .= &store_linkprot($cdom,$cnum,'course',$changes->{$item},\%oldlinkprot);
+                    } elsif ($item eq 'ltitools') {
+                        $output .= &store_ltitools($cdom,$cnum,'course',$changes->{$item},\%oldltitools);
                     } else {
                         if (ref($prefs->{$item}->{'ordered'}) eq 'ARRAY') {
                             my @settings = @{$prefs->{$item}->{'ordered'}};
@@ -2477,6 +3164,214 @@
     return $output;
 }
 
+sub store_ltitools {
+    my ($cdom,$cnum,$context,$changes,$oldltitools) = @_;
+    my ($home,$ltitools_save_error,$output,$error,%toolsenc, at deletions);
+    my %lt = &ltitools_names();
+    my @courseroles = ('cc','in','ta','ep','st');
+    my @allfields = ('fullname','firstname','lastname','email','user','roles');
+    if ($context eq 'domain') {
+        $home = &Apache::lonnet::domain($cdom,'primary');
+    } else {
+        $home = &Apache::lonnet::homeserver($cnum,$cdom);
+    }
+    if (ref($changes) eq 'HASH') {
+        foreach my $id (sort { $a <=> $b } keys(%{$changes})) {
+            if (ref($changes->{$id}) eq 'HASH') {
+                if (exists($changes->{$id}->{'key'})) {
+                    $toolsenc{$id}{'key'} = $changes->{$id}->{'key'};
+                    delete($changes->{$id}->{'key'});
+                }
+                if (exists($changes->{$id}->{'secret'})) {
+                    $toolsenc{$id}{'secret'} = $changes->{$id}->{'secret'};
+                    delete($changes->{$id}->{'secret'});
+                } elsif (ref($oldltitools->{$id}) eq 'HASH') {
+                    if (exists($oldltitools->{$id}{'usable'})) {
+                        $changes->{$id}->{'usable'} = 1;
+                    }
+                    if (exists($oldltitools->{$id}{'cipher'})) {
+                        $changes->{$id}->{'cipher'} = $oldltitools->{$id}{'cipher'};
+                    }
+                }
+            }
+        }
+    }
+    my @ids=&Apache::lonnet::current_machine_ids();
+    if (keys(%toolsenc) > 0) {
+        unless (($home eq 'no_host') || ($home eq '')) {
+            my $allowed;
+            foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
+            if ($allowed) {
+                if (($context eq 'domain') ||
+                    (($context eq 'course') &&
+                     (&Apache::lonnet::put('nohist_toolsenc',\%toolsenc,$cdom,$cnum,1) eq 'ok'))) {
+                    foreach my $id (keys(%toolsenc)) {
+                        if (exists($toolsenc{$id}{'secret'})) {
+                            $changes->{$id}->{'usable'} = 1;
+                        }
+                    }
+                } else {
+                    $ltitools_save_error = 1;
+                }
+            }
+        }
+    }
+    unless ($ltitools_save_error) {
+        if ($context eq 'course') {
+            if (&Apache::lonnet::put('ltitools',$changes,$cdom,$cnum,1) eq 'ok') {
+                my $hashid=$cdom.'_'.$cnum;
+                &Apache::lonnet::devalidate_cache_new('courseltitools',$hashid);
+                unless (($home eq 'no_host') || ($home eq '')) {
+                    if (grep(/^\Q$home\E$/, at ids)) {
+                        &Apache::lonnet::devalidate_cache_new('courseltitoolsenc',$hashid);
+                    }
+                }
+            } else {
+                $ltitools_save_error = 1;
+            }
+        }
+        unless ($ltitools_save_error) {
+            my %bynum;
+            foreach my $itemid (sort(keys(%{$changes}))) {
+                my $position = $changes->{$itemid}{'order'};
+                $bynum{$position} = $itemid;
+            }
+            foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
+                my $itemid = $bynum{$pos};
+                if (ref($changes->{$itemid}) ne 'HASH') {
+                    $output .= '<li>'.&mt('Deleted: [_1]',$changes->{$itemid}).'</li>';
+                } else {
+                    $output .= '<li><b>'.$changes->{$itemid}{'title'}.'</b>';
+                    if ($changes->{$itemid}{'image'}) {
+                        $output .= ' '.
+                                   '<img src="'.$changes->{$itemid}{'image'}.'"'.
+                                   ' alt="'.&mt('Tool Provider icon').'" />';
+                    }
+                    $output .= '</li><ul>';
+                    my $position = $pos + 1;
+                    $output .= '<li>'.&mt('Order: [_1]',$position).'</li>';
+                    foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
+                        if ($changes->{$itemid}{$item} ne '') {
+                            $output .= '<li>'.$lt{$item}.': '.$changes->{$itemid}{$item}.'</li>';
+                        }
+                    }
+                    if (ref($toolsenc{$itemid}) eq 'HASH') {
+                        foreach my $item ('key','secret') {
+                            if (exists($toolsenc{$itemid}{$item})) {
+                                if ($item eq 'secret') {
+                                    $output .= '<li>'.$lt{$item}.': ['.&mt('not shown').']</li>';
+                                } else {
+                                    $output .= '<li>'.$lt{$item}.': '.$toolsenc{$itemid}{$item}.'</li>';
+                                }
+                            }
+                        }
+                    }
+                    $output .= '<li>'.&mt('Configurable in course:');
+                    my @possconfig = ('label','title','target','linktext','explanation','append');
+                    my $numconfig = 0;
+                    if (ref($changes->{$itemid}{'crsconf'}) eq 'HASH') {
+                        foreach my $item (@possconfig) {
+                            if ($changes->{$itemid}{'crsconf'}{$item}) {
+                                $numconfig ++;
+                                $output .= ' "'.$lt{'crs'.$item}.'"';
+                            }
+                        }
+                    }
+                    if (!$numconfig) {
+                        $output .= ' '.&mt('None');
+                    }
+                    $output .= '</li>';
+                    foreach my $item ('passback','roster') {
+                        $output .= '<li>'.$lt{$item}.' ';
+                        if ($changes->{$itemid}{$item}) {
+                            $output .= &mt('Yes');
+                            if ($changes->{$itemid}{$item.'valid'}) {
+                                if ($item eq 'passback') {
+                                    $output .= ' '.&mt('valid for at least [quant,_1,day] after launch',
+                                                       $changes->{$itemid}{$item.'valid'});
+                                } else {
+                                    $output .= ' '.&mt('valid for at least [quant,_1,second] after launch',
+                                                       $changes->{$itemid}{$item.'valid'});
+                                }
+                            }
+                        } else {
+                            $output .= &mt('No');
+                        }
+                        $output .= '</li>';
+                    }
+                    if (ref($changes->{$itemid}{'display'}) eq 'HASH') {
+                        my $displaylist;
+                        if ($changes->{$itemid}{'display'}{'target'}) {
+                            $displaylist = &mt('Display target').': '.
+                                           $changes->{$itemid}{'display'}{'target'}.',';
+                        }
+                        foreach my $size ('width','height') {
+                            if ($changes->{$itemid}{'display'}{$size}) {
+                                $displaylist .= (' 'x2).$lt{$size}.': '.
+                                                $changes->{$itemid}{'display'}{$size}.',';
+                            }
+                        }
+                        if ($displaylist) {
+                            $displaylist =~ s/,$//;
+                            $output .= '<li>'.$displaylist.'</li>';
+                        }
+                        foreach my $item ('linktext','explanation') {
+                            if ($changes->{$itemid}{'display'}{$item}) {
+                                $output .= '<li>'.$lt{$item}.': '.$changes->{$itemid}{'display'}{$item}.'</li>';
+                            }
+                        }
+                    }
+                    if (ref($changes->{$itemid}{'fields'}) eq 'HASH') {
+                        my $fieldlist;
+                        foreach my $field (@allfields) {
+                            if ($changes->{$itemid}{'fields'}{$field}) {
+                                $fieldlist .= (' 'x2).$lt{$field}.',';
+                            }
+                        }
+                        if ($fieldlist) {
+                            $fieldlist =~ s/,$//;
+                            if ($changes->{$itemid}{'fields'}{'user'}) {
+                                if ($changes->{$itemid}{'incdom'}) {
+                                    $fieldlist .= ' ('.&mt('username:domain').')';
+                                } else {
+                                    $fieldlist .= ' ('.&mt('username').')';
+                                }
+                            }
+                            $output .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
+                        }
+                    }
+                    if (ref($changes->{$itemid}{'roles'}) eq 'HASH') {
+                        my $rolemaps;
+                        foreach my $role (@courseroles) {
+                            if ($changes->{$itemid}{'roles'}{$role}) {
+                                $rolemaps .= (' 'x2).&Apache::lonnet::plaintext($role,'Course').'='.
+                                             $changes->{$itemid}{'roles'}{$role}.',';
+                            }
+                        }
+                        if ($rolemaps) {
+                            $rolemaps =~ s/,$//;
+                            $output .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
+                        }
+                    }
+                    if (ref($changes->{$itemid}{'custom'}) eq 'HASH') {
+                        my $customlist;
+                        if (keys(%{$changes->{$itemid}{'custom'}})) {
+                            foreach my $key (sort(keys(%{$changes->{$itemid}{'custom'}}))) {
+                                $customlist .= $key.':'.$changes->{$itemid}{'custom'}{$key}.(' 'x2);
+                            }
+                        }
+                        if ($customlist) {
+                            $output .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
+                        }
+                    }
+                    $output .= '</ul></li>';
+                }
+            }
+        }
+    }
+    return $output;
+}
+
 sub update_env {
     my ($cnum,$cdom,$chome,$need_env_update,$storehash)  = @_;
     my $count = 0;
@@ -2613,6 +3508,11 @@
     my $stubrowse_js = &Apache::loncommon::studentbrowser_javascript();
     my $browse_js = &Apache::loncommon::browser_and_searcher_javascript('parmset');
     my $cloners_js = &cloners_javascript($phase);
+    my $currltitools;
+    if (ref($settings) eq 'HASH') {
+        $currltitools = $settings->{'ltitools'};
+    }
+    my $ltitools_js = &Apache::lonconfigsettings::ltitools_javascript($currltitools);
     my @code_order;
     if ($crstype ne 'Community') {
         if (ref($settings) eq 'HASH') {
@@ -2864,7 +3764,7 @@
                $cloners_js."\n".$instcode_js."\n".$localization_js."\n".
                $syllabus_js."\n".$menuitems_js."\n".$extresource_js."\n".
                &linkprot_javascript()."\n".'//]]>'."\n".
-               '</script>'."\n".$stubrowse_js."\n";
+               '</script>'."\n".$stubrowse_js."\n".$ltitools_js."\n";
     return $jscript;
 }
 
@@ -2951,38 +3851,6 @@
 
 sub linkprot_javascript {
     return <<"ENDSCRIPT";
-function toggleLinkProt(form,num,item) {
-    var radioname = '';
-    var currdivid = '';
-    var newdivid = '';
-    if ((document.getElementById('linkprot_divcurr'+item+'_'+num)) &&
-        (document.getElementById('linkprot_divchg'+item+'_'+num))) {
-        currdivid = document.getElementById('linkprot_divcurr'+item+'_'+num);
-        newdivid = document.getElementById('linkprot_divchg'+item+'_'+num);
-        radioname = form.elements['linkprot_change'+item+'_'+num];
-        if (radioname) {
-            if (radioname.length > 0) {
-                var setvis;
-                for (var i=0; i<radioname.length; i++) {
-                    if (radioname[i].checked == true) {
-                        if (radioname[i].value == 1) {
-                            newdivid.style.display = 'inline-block';
-                            currdivid.style.display = 'none';
-                            setvis = 1;
-                        }
-                        break;
-                    }
-                }
-                if (!setvis) {
-                    newdivid.style.display = 'none';
-                    currdivid.style.display = 'inline-block';
-                }
-            }
-        }
-    }
-    return;
-}
-
 function toggleLinkProtExtra(form,item,extra,valon,styleon,num) {
     if (document.getElementById('linkprot_'+extra+'_'+num)) {
         var extraid = document.getElementById('linkprot_'+extra+'_'+num);
@@ -3008,20 +3876,10 @@
     return;
 }
 
-function uncheckLinkProtMakeVis(item,num) {
-    if (document.getElementById('linkprot_'+item+'_'+num)) {
-        var currtype = document.getElementById('linkprot_'+item+'_'+num).type;
-        if (currtype.toLowerCase() == 'checkbox') {
-            document.getElementById('linkprot_'+item+'_'+num).checked = false;
-        }
-    }
-    return;
-}
 ENDSCRIPT
 
 }
 
-
 sub print_courseinfo {
     my ($cdom,$settings,$ordered,$itemtext,$rowtotal,$crstype,$noedit) = @_;
     unless ((ref($settings) eq 'HASH') && (ref($ordered) eq 'ARRAY') && (ref($itemtext) eq 'HASH')) {
@@ -5449,6 +6307,523 @@
     return &make_item_rows($cdom,\%items,$ordered,$settings,$rowtotal,$crstype,'bridgetasks',$noedit);
 }
 
+sub print_ltitools {
+    my ($cdom,$cnum,$settings,$rowtotal,$crstype,$noedit,$context) = @_;
+    my ($datatable,$disabled,$css_class,$dest);
+    my %lt = &ltitools_names();
+    my $itemcount = 1;
+    my $maxnum = 0;
+    my %ordered;
+    if (ref($settings) eq 'HASH') {
+        foreach my $item (keys(%{$settings})) {
+            if (ref($settings->{$item}) eq 'HASH') {
+                my $num = $settings->{$item}{'order'};
+                $ordered{$num} = $item;
+            }
+        }
+    }
+
+    if ($context eq 'domain') {
+        $dest = '/adm/domainprefs';
+    } else {
+        $dest = '/adm/courseprefs';
+    }
+    my ($switchserver,$switchmessage);
+    $switchserver = &check_switchserver($cdom,$cnum,$context,$dest);
+    if ($switchserver) {
+        if ($context eq 'domain') {
+            $switchmessage = &mt("submit from domain's primary library server: [_1].",$switchserver);
+        } elsif ($crstype eq 'Community') {
+            $switchmessage = &mt("submit from community's home server: [_1].",$switchserver);
+        } else {
+            $switchmessage = &mt("submit from course's home server: [_1].",$switchserver);
+        }
+    }
+    my $maxnum = scalar(keys(%ordered));
+    my @courseroles = ('cc','in','ta','ep','st');
+    my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
+    my @fields = ('fullname','firstname','lastname','email','roles','user');
+    if (keys(%ordered)) {
+        my @items = sort { $a <=> $b } keys(%ordered);
+        for (my $i=0; $i<@items; $i++) {
+            $css_class = $itemcount%2?' class="LC_odd_row"':'';
+            my $item = $ordered{$items[$i]};
+            my ($title,$key,$url,$usable,$lifetime,$imgsrc,%sigsel);
+            if (ref($settings->{$item}) eq 'HASH') {
+                $title = $settings->{$item}->{'title'};
+                $url = $settings->{$item}->{'url'};
+                $key = $settings->{$item}->{'key'};
+                $usable = $settings->{$item}->{'usable'};
+                $lifetime = $settings->{$item}->{'lifetime'};
+                my $image = $settings->{$item}->{'image'};
+                if ($image ne '') {
+                    $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
+                }
+                if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
+                    $sigsel{'HMAC-256'} = ' selected="selected"';
+                } else {
+                    $sigsel{'HMAC-SHA1'} = ' selected="selected"';
+                }
+            }
+            my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
+            $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
+                         .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
+            for (my $k=0; $k<=$maxnum; $k++) {
+                my $vpos = $k+1;
+                my $selstr;
+                if ($k == $i) {
+                    $selstr = ' selected="selected" ';
+                }
+                $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
+            }
+            $datatable .= '</select>'.(' 'x2).
+                '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
+                &mt('Delete?').'</label></span></td>'.
+                '<td colspan="2">'.
+                '<fieldset><legend>'.&mt('Required settings').'</legend>'.
+                '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
+                (' 'x2).
+                '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
+                '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
+                (' 'x2).
+                '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
+                '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
+                (' 'x2).
+                '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
+                '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
+                '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
+                '<br /><br />'.
+                '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
+                ' value="'.$url.'" /></span>'.
+                (' 'x2).
+                '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
+                '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span><br /><br />';
+            if ($key ne '') {
+                $datatable .= '<span class="LC_nobreak">'.$lt{'key'};
+                if ($noedit) {
+                    $datatable .= ': ['.&mt('not shown').']';
+                } elsif ($switchserver) {
+                    $datatable .= ': ['.&mt('[_1] to view/edit',$switchserver).']';
+                } else {
+                    $datatable .= ':<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" autocomplete="off"'.$disabled.' />';
+                }
+                $datatable .= '</span> '.(' 'x2);
+            } elsif (!$switchserver) {
+                $datatable .= '<span class="LC_nobreak">'.$lt{'key'}.':'.
+                              '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" autocomplete="off"'.$disabled.' />'.
+                              '</span> '.(' 'x2);
+            }
+            if ($switchserver) {
+                if ($usable ne '') {
+                    $datatable .= '<div id="ltitools_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
+                                  $lt{'secret'}.': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
+                                  '<span class="LC_nobreak">'.&mt('Change secret?').
+                                  '<label><input type="radio" value="0" name="ltitools_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','ltitools'".');" checked="checked"'.$disabled.' />'.&mt('No').'</label>'.
+                                  (' 'x2).
+                                  '<label><input type="radio" value="1" name="ltitools_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','ltitools'".');" '.$disabled.' />'.&mt('Yes').'</label>'.(' 'x2).
+                                  '</span><div id="ltitools_divchgsecret_'.$i.'" style="display:none" />'.
+                                  '<span class="LC_nobreak"> - '.$switchmessage.'</span>'.
+                                  '</div>';
+                } elsif ($key eq '') {
+                    $datatable .= '<span class="LC_nobreak">'.&mt('Key and Secret are required').' - '.$switchmessage.'</span>'."\n";
+                } else {
+                    $datatable .= '<span class="LC_nobreak">'.&mt('Secret required').' - '.$switchmessage.'</span>'."\n";
+                }
+                $datatable .= '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" />';
+            } else {
+                if ($usable ne '') {
+                    $datatable .= '<div id="ltitools_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
+                                  $lt{'secret'}.': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
+                                  '<span class="LC_nobreak">'.&mt('Change?').
+                                  '<label><input type="radio" value="0" name="ltitools_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','ltitools'".');" checked="checked"'.$disabled.' />'.&mt('No').'</label>'.
+                                  (' 'x2).
+                                  '<label><input type="radio" value="1" name="ltitools_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','ltitools'".');"'.$disabled.' />'.&mt('Yes').
+                                  '</label>  </span><div id="ltitools_divchgsecret_'.$i.'" style="display:none" />'.
+                                  '<span class="LC_nobreak">'.&mt('New Secret').':'.
+                                  '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="" autocomplete="new-password"'.$disabled.' />'.
+                                  '<label><input type="checkbox" name="ltitools_visible_'.$i.'" id="ltitools_visible_'.$i.'" onclick="if (this.checked) { this.form.ltitools_secret_'.$i.'.type='."'text'".' } else { this.form.ltitools_secret_'.$i.'.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>'.
+                                  '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span></div>';
+                } else {
+                    $datatable .=
+                        '<span class="LC_nobreak">'.$lt{'secret'}.':'.
+                        '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="" autocomplete="new-password"'.$disabled.' />'.
+                        '<label><input type="checkbox" name="ltitools_visible_'.$i.'" id="ltitools_visible_'.$i.'" onclick="if (this.checked) { this.form.ltitools_secret_'.$i.'.type='."'text'".' } else { this.form.ltitools_secret_'.$i.'.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>'.
+                        '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>';
+                }
+            }
+            $datatable .= '</fieldset>'.
+                          '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
+                          '<span class="LC_nobreak">'.&mt('Display target:');
+            my %currdisp;
+            if (ref($settings->{$item}->{'display'}) eq 'HASH') {
+                if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
+                    $currdisp{'window'} = ' checked="checked"';
+                } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
+                    $currdisp{'tab'} = ' checked="checked"';
+                } else {
+                    $currdisp{'iframe'} = ' checked="checked"';
+                }
+                if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
+                    $currdisp{'width'} = $1;
+                }
+                if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
+                    $currdisp{'height'} = $1;
+                }
+                $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
+                $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
+            } else {
+                $currdisp{'iframe'} = ' checked="checked"';
+            }
+            foreach my $disp ('iframe','tab','window') {
+                $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
+                              $lt{$disp}.'</label>'.(' 'x2);
+            }
+            $datatable .= (' 'x4);
+            foreach my $dimen ('width','height') {
+                $datatable .= '<label>'.$lt{$dimen}.' '.
+                              '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
+                              (' 'x2);
+            }
+            $datatable .= '</span><br />'.
+                          '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
+                          '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
+                          '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
+                          '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
+                          '</textarea></div><div style=""></div><br />';
+            my %units = (
+                          'passback' => 'days',
+                          'roster'   => 'seconds',
+                        );
+            foreach my $extra ('passback','roster') {
+                my $validsty = 'none';
+                my $currvalid;
+                my $checkedon = '';
+                my $checkedoff = ' checked="checked"';
+                if ($settings->{$item}->{$extra}) {
+                    $checkedon = $checkedoff;
+                    $checkedoff = '';
+                    $validsty = 'inline-block';
+                    if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
+                        $currvalid = $settings->{$item}->{$extra.'valid'};
+                    }
+                }
+                my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
+                $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.' '.
+                              '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
+                              &mt('No').'</label>'.(' 'x2).
+                              '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
+                              &mt('Yes').'</label></span></div>'.
+                              '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
+                              '<span class="LC_nobreak">'.
+                              &mt("until at least [_1] $units{$extra} after launch",
+                                  '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
+                              '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
+            }
+            $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.': ';
+            if ($imgsrc) {
+                $datatable .= $imgsrc.
+                              '<label><input type="checkbox" name="ltitools_image_del"'.
+                              ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
+                              '<span class="LC_nobreak"> '.&mt('Replace:').' ';
+            } else {
+                $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').') ';
+            }
+            if ($switchserver) {
+                $datatable .= &mt('Upload to library server: [_1]',$switchserver);
+            } else {
+                $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
+            }
+            $datatable .= '</span></fieldset>';
+            my (%checkedfields,%rolemaps,$userincdom);
+            if (ref($settings->{$item}) eq 'HASH') {
+                if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
+                    %checkedfields = %{$settings->{$item}->{'fields'}};
+                }
+                $userincdom = $settings->{$item}->{'incdom'};
+                if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
+                    %rolemaps = %{$settings->{$item}->{'roles'}};
+                    $checkedfields{'roles'} = 1;
+                }
+            }
+            $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
+                          '<span class="LC_nobreak">';
+            my $userfieldstyle = 'display:none;';
+            my $seluserdom = '';
+            my $unseluserdom = ' selected="selected"';
+            foreach my $field (@fields) {
+                my ($checked,$onclick,$id,$spacer);
+                if ($checkedfields{$field}) {
+                    $checked = ' checked="checked"';
+                }
+                if ($field eq 'user') {
+                    $id = ' id="ltitools_user_field_'.$i.'"';
+                    $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
+                    if ($checked) {
+                        $userfieldstyle = 'display:inline-block';
+                        if ($userincdom) {
+                            $seluserdom = $unseluserdom;
+                            $unseluserdom = '';
+                        }
+                    }
+                } else {
+                    $spacer = (' ' x2);
+                }
+                $datatable .= '<label>'.
+                              '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
+                              $lt{$field}.'</label>'.$spacer;
+            }
+            $datatable .= '</span>';
+            $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
+                          '<span class="LC_nobreak"> : '.
+                          '<select name="ltitools_userincdom_'.$i.'">'.
+                          '<option value="">'.&mt('Select').'</option>'.
+                          '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
+                          '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
+                          '</select></span></div>';
+            $datatable .= '</fieldset>'.
+                          '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
+            foreach my $role (@courseroles) {
+                my ($selected,$selectnone);
+                if (!$rolemaps{$role}) {
+                    $selectnone = ' selected="selected"';
+                }
+                $datatable .= '<td style="text-align: center">'.
+                              &Apache::lonnet::plaintext($role,'Course').'<br />'.
+                              '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
+                              '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
+                foreach my $ltirole (@ltiroles) {
+                    unless ($selectnone) {
+                        if ($rolemaps{$role} eq $ltirole) {
+                            $selected = ' selected="selected"';
+                        } else {
+                            $selected = '';
+                        }
+                    }
+                    $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
+                }
+                $datatable .= '</select></td>';
+            }
+            $datatable .= '</tr></table></fieldset>';
+            my %courseconfig;
+            if (ref($settings->{$item}) eq 'HASH') {
+                if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
+                    %courseconfig = %{$settings->{$item}->{'crsconf'}};
+                }
+            }
+            $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
+            foreach my $item ('label','title','target','linktext','explanation','append') {
+                my $checked;
+                if ($courseconfig{$item}) {
+                    $checked = ' checked="checked"';
+                }
+                $datatable .= '<label>'.
+                       '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
+                       $lt{'crs'.$item}.'</label>  '."\n";
+            }
+            $datatable .= '</span></fieldset>'.
+                          '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
+                          '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
+            if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
+                my %custom = %{$settings->{$item}->{'custom'}};
+                if (keys(%custom) > 0) {
+                    foreach my $key (sort(keys(%custom))) {
+                        $datatable .= '<tr><td><span class="LC_nobreak">'.
+                                      '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
+                                      $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
+                                      '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
+                                      ' value="'.$custom{$key}.'" /></td></tr>';
+                    }
+                }
+            }
+            $datatable .= '<tr><td><span class="LC_nobreak">'.
+                          '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
+                          &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
+                          '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
+            $datatable .= '</table></fieldset></td></tr>'."\n";
+            $itemcount ++;
+        }
+    }
+    $css_class = $itemcount%2?' class="LC_odd_row"':'';
+    my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
+    $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
+                  '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
+                  '<select name="ltitools_add_pos"'.$chgstr.'>';
+    for (my $k=0; $k<$maxnum+1; $k++) {
+        my $vpos = $k+1;
+        my $selstr;
+        if ($k == $maxnum) {
+            $selstr = ' selected="selected" ';
+        }
+        $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
+    }
+    $datatable .= '</select> '."\n".
+                  '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
+                  '<td colspan="2">'.
+                  '<fieldset><legend>'.&mt('Required settings').'</legend>'.
+                  '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
+                  (' 'x2).
+                  '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
+                  '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
+                  (' 'x2).
+                  '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
+                  '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
+                  '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
+                  '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
+                  '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
+                  '<br />'.
+                  '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
+                  (' 'x2).
+                  '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span><br />';
+    if ($switchserver) {
+        $datatable .= '<span class="LC_nobreak">'.&mt('Key and Secret are required').' - '.$switchmessage.'</span>'."\n";
+    } else {
+        $datatable .= '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" autocomplete="off"'.$disabled.' /></span> '."\n".
+                      (' 'x2).
+                      '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" autocomplete="new-password"'.$disabled.' />'.
+                      '<label><input type="checkbox" name="ltitools_add_visible" id="ltitools_add_visible" onclick="if (this.checked) { this.form.ltitools_add_secret.type='."'text'".' } else { this.form.ltitools_add_secret.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label></span> '."\n";
+    }
+    $datatable .= '<br /><br />'.
+                  '</fieldset>'.
+                  '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
+                  '<span class="LC_nobreak">'.&mt('Display target:');
+    my %defaultdisp;
+    $defaultdisp{'iframe'} = ' checked="checked"';
+    foreach my $disp ('iframe','tab','window') {
+        $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
+                      $lt{$disp}.'</label>'.(' 'x2);
+    }
+    $datatable .= (' 'x4);
+    foreach my $dimen ('width','height') {
+        $datatable .= '<label>'.$lt{$dimen}.' '.
+                      '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
+                      (' 'x2);
+    }
+    $datatable .= '</span><br />'.
+                  '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
+                  '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
+                  '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
+                  '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
+                  '</div><div style=""></div><br />';
+    my %units = (
+                  'passback' => 'days',
+                  'roster'   => 'seconds',
+                );
+    my %defaulttimes = (
+                     'passback' => '7',
+                     'roster'   => '300',
+                   );
+    foreach my $extra ('passback','roster') {
+        my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
+        $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.' '.
+                      '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
+                      &mt('No').'</label></span>'.(' 'x2).'<span class="LC_nobreak">'.
+                      '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
+                      &mt('Yes').'</label></span></div>'.
+                      '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
+                      '<span class="LC_nobreak">'.
+                      &mt("until at least [_1] $units{$extra} after launch",
+                          '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
+                      '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
+    }
+    $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.': '.
+                  '('.&mt('if larger than 21x21 pixels, image will be scaled').') ';
+    if ($switchserver) {
+        $datatable .= &mt('Upload to library server: [_1]',$switchserver);
+    } else {
+        $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
+    }
+    $datatable .= '</span></fieldset>'.
+                  '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
+                  '<span class="LC_nobreak">';
+    foreach my $field (@fields) {
+        my ($id,$onclick,$spacer);
+        if ($field eq 'user') {
+            $id = ' id="ltitools_user_field_add"';
+            $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
+        } else {
+            $spacer = (' ' x2);
+        }
+        $datatable .= '<label>'.
+                      '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
+                      $lt{$field}.'</label>'.$spacer;
+    }
+    $datatable .= '</span>'.
+                  '<div style="display:none;" id="ltitools_user_div_add">'.
+                  '<span class="LC_nobreak"> : '.
+                  '<select name="ltitools_add_userincdom">'.
+                  '<option value="" selected="selected">'.&mt('Select').'</option>'.
+                  '<option value="0">'.&mt('username').'</option>'.
+                  '<option value="1">'.&mt('username:domain').'</option>'.
+                  '</select></span></div></fieldset>';
+    $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
+    foreach my $role (@courseroles) {
+        my ($checked,$checkednone);
+        $datatable .= '<td style="text-align: center">'.
+                      &Apache::lonnet::plaintext($role,'Course').'<br />'.
+                      '<select name="ltitools_add_roles_'.$role.'">'.
+                      '<option value="" selected="selected">'.&mt('Select').'</option>';
+        foreach my $ltirole (@ltiroles) {
+            $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
+        }
+        $datatable .= '</select></td>';
+    }
+    $datatable .= '</tr></table></fieldset>'.
+                  '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
+    foreach my $item ('label','title','target','linktext','explanation','append') {
+        $datatable .= '<label>'.
+                      '<input type="checkbox" name="ltitools_add_courseconfig" value="'.$item.'" checked="checked" />'.
+                      $lt{'crs'.$item}.'</label>'.(' ' x2)."\n";
+    }
+    $datatable .= '</span></fieldset>'.
+                  '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
+                  '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
+                  '<tr><td><span class="LC_nobreak">'.
+                  '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
+                  &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
+                  '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
+                  '</table></fieldset>'."\n".
+                  '</td>'."\n".
+                  '</tr>'."\n";
+    $itemcount ++;
+    return $datatable;
+}
+
+sub ltitools_names {
+    my %lt = &Apache::lonlocal::texthash(
+                                          'title'          => 'Title',
+                                          'version'        => 'Version',
+                                          'msgtype'        => 'Message Type',
+                                          'sigmethod'      => 'Signature Method',
+                                          'url'            => 'URL',
+                                          'key'            => 'Key',
+                                          'lifetime'       => 'Nonce lifetime (s)',
+                                          'secret'         => 'Secret',
+                                          'icon'           => 'Icon',
+                                          'user'           => 'User',
+                                          'fullname'       => 'Full Name',
+                                          'firstname'      => 'First Name',
+                                          'lastname'       => 'Last Name',
+                                          'email'          => 'E-mail',
+                                          'roles'          => 'Role',
+                                          'window'         => 'Window',
+                                          'tab'            => 'Tab',
+                                          'iframe'         => 'iFrame',
+                                          'height'         => 'Height',
+                                          'width'          => 'Width',
+                                          'linktext'       => 'Default Link Text',
+                                          'explanation'    => 'Default Explanation',
+                                          'passback'       => 'Tool can return grades:',
+                                          'roster'         => 'Tool can retrieve roster:',
+                                          'crstarget'      => 'Display target',
+                                          'crslabel'       => 'Course label',
+                                          'crstitle'       => 'Course title',
+                                          'crslinktext'    => 'Link Text',
+                                          'crsexplanation' => 'Explanation',
+                                          'crsappend'      => 'Provider URL',
+                                        );
+    return %lt;
+}
+
 sub print_lti {
     my ($cdom,$settings,$ordered,$itemtext,$rowtotal,$crstype,$noedit) = @_;
     unless ((ref($settings) eq 'HASH') && (ref($ordered) eq 'ARRAY') && (ref($itemtext) eq 'HASH')) {
@@ -5966,9 +7341,9 @@
                         $datatable .= '<div id="linkprot_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
                                       $desc{'secret'}.': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
                                       '<span class="LC_nobreak">'.&mt('Change secret?').
-                                      '<label><input type="radio" value="0" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleLinkProt(this.form,'."'$i','secret'".');" checked="checked"'.$disabled.' />'.&mt('No').'</label>'.
+                                      '<label><input type="radio" value="0" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','linkprot'".');" checked="checked"'.$disabled.' />'.&mt('No').'</label>'.
                                       (' 'x2).
-                                      '<label><input type="radio" value="1" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleLinkProt(this.form,'."'$i','secret'".');" '.$disabled.' />'.&mt('Yes').'</label>'.(' 'x2).
+                                      '<label><input type="radio" value="1" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','linkprot'".');" '.$disabled.' />'.&mt('Yes').'</label>'.(' 'x2).
                                       '</span><div id="linkprot_divchgsecret_'.$i.'" style="display:none" />'.
                                       '<span class="LC_nobreak"> - '.$switchmessage.'</span>'.
                                       '</div>';
@@ -5983,9 +7358,9 @@
                         $datatable .= '<div id="linkprot_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
                                       $desc{'secret'}.': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
                                       '<span class="LC_nobreak">'.&mt('Change?').
-                                      '<label><input type="radio" value="0" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleLinkProt(this.form,'."'$i','secret'".');" checked="checked"'.$disabled.' />'.&mt('No').'</label>'.
+                                      '<label><input type="radio" value="0" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','linkprot'".');" checked="checked"'.$disabled.' />'.&mt('No').'</label>'.
                                       (' 'x2).
-                                      '<label><input type="radio" value="1" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleLinkProt(this.form,'."'$i','secret'".');"'.$disabled.' />'.&mt('Yes').
+                                      '<label><input type="radio" value="1" name="linkprot_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','linkprot'".');"'.$disabled.' />'.&mt('Yes').
                                       '</label>  </span><div id="linkprot_divchgsecret_'.$i.'" style="display:none" />'.
                                       '<span class="LC_nobreak">'.&mt('New Secret').':'.
                                       '<input type="password" size="20" name="linkprot_secret_'.$i.'" value="" autocomplete="new-password"'.$disabled.' />'.
Index: loncom/interface/domainprefs.pm
diff -u loncom/interface/domainprefs.pm:1.420 loncom/interface/domainprefs.pm:1.421
--- loncom/interface/domainprefs.pm:1.420	Wed Mar  8 15:06:45 2023
+++ loncom/interface/domainprefs.pm	Sun Mar 19 16:05:48 2023
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Handler to set domain-wide configuration settings
 #
-# $Id: domainprefs.pm,v 1.420 2023/03/08 15:06:45 raeburn Exp $
+# $Id: domainprefs.pm,v 1.421 2023/03/19 16:05:48 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -221,8 +221,8 @@
                 'serverstatuses','requestcourses','helpsettings',
                 'coursedefaults','usersessions','loadbalancing',
                 'requestauthor','selfenrollment','inststatus',
-                'ltitools','ssl','trust','lti','ltisec','privacy','passwords',
-                'proctoring','wafproxy','ipaccess'],$dom);
+                'ltitools','toolsec','ssl','trust','lti','ltisec',
+                'privacy','passwords','proctoring','wafproxy','ipaccess'],$dom);
     my %encconfig =
         &Apache::lonnet::get_dom('encconfig',['ltitools','lti','proctoring','linkprot'],$dom,undef,1);
     if (ref($domconfig{'ltitools'}) eq 'HASH') {
@@ -230,9 +230,7 @@
             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
-                    foreach my $item ('key','secret') {
-                        $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
-                    }
+                    $domconfig{'ltitools'}{$id}{'key'} = $encconfig{'ltitools'}{$id}{'key'};
                 }
             }
         }
@@ -585,8 +583,12 @@
         'ltitools' => 
                  {text => 'External Tools (LTI)',
                   help => 'Domain_Configuration_LTI_Tools',
-                  header => [{col1 => 'Setting',
-                              col2 => 'Value',}],
+                  header => [{col1 => 'Encryption of shared secrets',
+                              col2 => 'Settings'},
+                             {col1 => 'Rules for shared secrets',
+                              col2 => 'Settings'},
+                             {col1 => 'Providers',
+                              col2 => 'Settings',}],
                   print => \&print_ltitools,
                   modify => \&modify_ltitools,
                  },
@@ -894,9 +896,9 @@
             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
                                                       \@templateroles);
     } elsif ($action eq 'ltitools') {
-        $output .= &ltitools_javascript($settings);
+        $output .= &Apache::lonconfigsettings::ltitools_javascript($settings);
     } elsif ($action eq 'lti') {
-        $output .= &passwords_javascript('secrets')."\n".
+        $output .= &passwords_javascript('ltisecrets')."\n".
                    &lti_javascript($dom,$settings);
     } elsif ($action eq 'proctoring') {
         $output .= &proctoring_javascript($settings);
@@ -951,7 +953,8 @@
             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
-            ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') || ($action eq 'lti')) {
+            ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') ||
+            ($action eq 'lti') || ($action eq 'ltitools')) {
             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
         } elsif ($action eq 'passwords') {
             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
@@ -987,7 +990,8 @@
             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
             ($action eq 'trust') || ($action eq 'contacts') || ($action eq 'defaults') ||
-            ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti')) {
+            ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti') ||
+            ($action eq 'ltitools')) {
             if ($action eq 'coursecategories') {
                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
                 $colspan = ' colspan="2"';
@@ -1278,8 +1282,7 @@
             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
-                 ($action eq 'ltitools') || ($action eq 'proctoring') ||
-                 ($action eq 'ipaccess')) {
+                 ($action eq 'proctoring') || ($action eq 'ipaccess')) {
             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
         }
     }
@@ -3730,124 +3733,6 @@
     return;
 }
 
-function toggleLTIEncKey(form) {
-    var shownhosts = new Array();
-    var hiddenhosts = new Array();
-    var forcourse = new Array($course_servers);
-    var fromdomain = '$primary';
-    var crsradio = form.elements['ltisec_crslinkprot'];
-    if (crsradio.length) {
-        for (var i=0; i<crsradio.length; i++) {
-            if (crsradio[i].checked) {
-                if (crsradio[i].value == 1) {
-                    if (forcourse.length > 0) {
-                        for (var j=0; j<forcourse.length; j++) {
-                            if (!shownhosts.includes(forcourse[j])) {
-                                shownhosts.push(forcourse[j]);
-                            }
-                        }
-                    }
-                } else {
-                    if (forcourse.length > 0) {
-                        for (var j=0; j<forcourse.length; j++) {
-                            if (!hiddenhosts.includes(forcourse[j])) { 
-                                hiddenhosts.push(forcourse[j]);
-                            }
-                        }
-                    } 
-                }
-            }
-        }
-    }
-    var domradio = form.elements['ltisec_domlinkprot'];
-    if (domradio.length) {
-        for (var i=0; i<domradio.length; i++) {
-            if (domradio[i].checked) {
-                if (domradio[i].value == 1) {
-                    if (!shownhosts.includes(fromdomain)) { 
-                        shownhosts.push(fromdomain);
-                    }
-                } else {
-                    if (!hiddenhosts.includes(fromdomain)) {
-                        hiddenhosts.push(fromdomain);
-                    }
-                }
-            }
-        }
-    }
-    var consumersradio = form.elements['ltisec_consumers'];
-    if (consumersradio.length) {
-        for (var i=0; i<consumersradio.length; i++) {
-            if (consumersradio[i].checked) {
-                if (consumersradio[i].value == 1) {
-                    if (!shownhosts.includes(fromdomain)) {     
-                        shownhosts.push(fromdomain);
-                    }
-                } else {
-                    if (!hiddenhosts.includes(fromdomain)) {
-                        hiddenhosts.push(fromdomain);
-                    }
-                }
-            }
-        }
-    }
-    if (shownhosts.length > 0) {
-        for (var i=0; i<shownhosts.length; i++) {
-            if (document.getElementById('ltisec_info_'+shownhosts[i])) {
-                document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';                 
-            }
-        }
-        if (document.getElementById('ltisec_noprivkey')) {
-            document.getElementById('ltisec_noprivkey').style.display = 'none';
-        }
-    } else {
-        if (document.getElementById('ltisec_noprivkey')) {
-            document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
-        }
-    }
-    if (hiddenhosts.length > 0) {
-        for (var i=0; i<hiddenhosts.length; i++) {
-            if (!shownhosts.includes(hiddenhosts[i])) {
-                if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
-                    document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
-                }
-            }
-        }
-    }
-    return;
-}
-
-function togglePrivKey(form,hostid) {
-    var radioname = '';
-    var currdivid = '';
-    var newdivid = '';
-    if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
-        (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
-        currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
-        newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
-        radioname = form.elements['ltisec_changeprivkey_'+hostid];
-        if (radioname) {
-            if (radioname.length > 0) {
-                var setvis;
-                for (var i=0; i<radioname.length; i++) {
-                    if (radioname[i].checked == true) {
-                        if (radioname[i].value == 1) {
-                            newdivid.style.display = 'inline-block';
-                            currdivid.style.display = 'none';
-                            setvis = 1;
-                        }
-                        break;
-                    }
-                }
-                if (!setvis) {
-                    newdivid.style.display = 'none';
-                    currdivid.style.display = 'inline-block';
-                }
-            }
-        }
-    }
-}
-
 // ]]>
 </script>
 
@@ -5399,421 +5284,50 @@
 }
 
 sub print_ltitools {
-    my ($dom,$settings,$rowtotal) = @_;
-    my $rownum = 0;
-    my $css_class;
-    my $itemcount = 1;
-    my $maxnum = 0;
-    my %ordered;
+    my ($position,$dom,$settings,$rowtotal) = @_;
+    my (%rules,%encrypt,%privkeys,%linkprot);
     if (ref($settings) eq 'HASH') {
-        foreach my $item (keys(%{$settings})) {
-            if (ref($settings->{$item}) eq 'HASH') {
-                my $num = $settings->{$item}{'order'};
-                $ordered{$num} = $item;
-            }
-        }
-    }
-    my $confname = $dom.'-domainconfig';
-    my $switchserver = &check_switchserver($dom,$confname);
-    my $maxnum = scalar(keys(%ordered));
-    my $datatable;
-    my %lt = &ltitools_names();
-    my @courseroles = ('cc','in','ta','ep','st');
-    my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
-    my @fields = ('fullname','firstname','lastname','email','roles','user');
-    if (keys(%ordered)) {
-        my @items = sort { $a <=> $b } keys(%ordered);
-        for (my $i=0; $i<@items; $i++) {
-            $css_class = $itemcount%2?' class="LC_odd_row"':'';
-            my $item = $ordered{$items[$i]};
-            my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
-            if (ref($settings->{$item}) eq 'HASH') {
-                $title = $settings->{$item}->{'title'};
-                $url = $settings->{$item}->{'url'};
-                $key = $settings->{$item}->{'key'};
-                $secret = $settings->{$item}->{'secret'};
-                $lifetime = $settings->{$item}->{'lifetime'};
-                my $image = $settings->{$item}->{'image'};
-                if ($image ne '') {
-                    $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
-                }
-                if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
-                    $sigsel{'HMAC-256'} = ' selected="selected"';
-                } else {
-                    $sigsel{'HMAC-SHA1'} = ' selected="selected"';
-                }
-            }
-            my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
-            $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
-                         .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
-            for (my $k=0; $k<=$maxnum; $k++) {
-                my $vpos = $k+1;
-                my $selstr;
-                if ($k == $i) {
-                    $selstr = ' selected="selected" ';
-                }
-                $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
-            }
-            $datatable .= '</select>'.(' 'x2).
-                '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
-                &mt('Delete?').'</label></span></td>'.
-                '<td colspan="2">'.
-                '<fieldset><legend>'.&mt('Required settings').'</legend>'.
-                '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
-                (' 'x2).
-                '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
-                '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
-                (' 'x2).
-                '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
-                '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
-                (' 'x2).
-                '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
-                '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
-                '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
-                '<br /><br />'.
-                '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
-                ' value="'.$url.'" /></span>'.
-                (' 'x2).
-                '<span class="LC_nobreak">'.$lt{'key'}.':'.
-                '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
-                (' 'x2).
-                '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
-                '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
-                (' 'x2).
-                '<span class="LC_nobreak">'.$lt{'secret'}.':'.
-                '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
-                '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_secret_'.$i.'.type='."'text'".' } else { this.form.ltitools_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
-                '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
-                '</fieldset>'.
-                '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
-                '<span class="LC_nobreak">'.&mt('Display target:');
-            my %currdisp;
-            if (ref($settings->{$item}->{'display'}) eq 'HASH') {
-                if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
-                    $currdisp{'window'} = ' checked="checked"';
-                } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
-                    $currdisp{'tab'} = ' checked="checked"';
-                } else {
-                    $currdisp{'iframe'} = ' checked="checked"';
-                }
-                if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
-                    $currdisp{'width'} = $1;
-                }
-                if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
-                     $currdisp{'height'} = $1;
-                }
-                $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
-                $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
-            } else {
-                $currdisp{'iframe'} = ' checked="checked"';
-            }
-            foreach my $disp ('iframe','tab','window') {
-                $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
-                              $lt{$disp}.'</label>'.(' 'x2);
-            }
-            $datatable .= (' 'x4);
-            foreach my $dimen ('width','height') {
-                $datatable .= '<label>'.$lt{$dimen}.' '.
-                              '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
-                              (' 'x2);
-            }
-            $datatable .= '</span><br />'.
-                          '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
-                          '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
-                          '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
-                          '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
-                          '</textarea></div><div style=""></div><br />';
-            my %units = (
-                          'passback' => 'days',
-                          'roster'   => 'seconds',
-                        );
-            foreach my $extra ('passback','roster') {
-                my $validsty = 'none';
-                my $currvalid;
-                my $checkedon = '';
-                my $checkedoff = ' checked="checked"';
-                if ($settings->{$item}->{$extra}) {
-                    $checkedon = $checkedoff;
-                    $checkedoff = '';
-                    $validsty = 'inline-block';
-                    if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
-                        $currvalid = $settings->{$item}->{$extra.'valid'};
-                    }
-                }
-                my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
-                $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.' '.
-                              '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
-                              &mt('No').'</label>'.(' 'x2).
-                              '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
-                              &mt('Yes').'</label></span></div>'.
-                              '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
-                              '<span class="LC_nobreak">'.
-                              &mt("at least [_1] $units{$extra} after launch",
-                                  '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
-                              '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
-            }
-            $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.': ';
-            if ($imgsrc) {
-                $datatable .= $imgsrc.
-                              '<label><input type="checkbox" name="ltitools_image_del"'.
-                              ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
-                              '<span class="LC_nobreak"> '.&mt('Replace:').' ';
-            } else {
-                $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').') ';
-            }
-            if ($switchserver) {
-                $datatable .= &mt('Upload to library server: [_1]',$switchserver);
-            } else {
-                $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
-            }
-            $datatable .= '</span></fieldset>';
-            my (%checkedfields,%rolemaps,$userincdom);
-            if (ref($settings->{$item}) eq 'HASH') {
-                if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
-                    %checkedfields = %{$settings->{$item}->{'fields'}};
-                }
-                $userincdom = $settings->{$item}->{'incdom'};
-                if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
-                    %rolemaps = %{$settings->{$item}->{'roles'}};
-                    $checkedfields{'roles'} = 1;
-                }
-            }
-            $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
-                          '<span class="LC_nobreak">';
-            my $userfieldstyle = 'display:none;';
-            my $seluserdom = '';
-            my $unseluserdom = ' selected="selected"';
-            foreach my $field (@fields) {
-                my ($checked,$onclick,$id,$spacer);
-                if ($checkedfields{$field}) {
-                    $checked = ' checked="checked"';
-                }
-                if ($field eq 'user') {
-                    $id = ' id="ltitools_user_field_'.$i.'"';
-                    $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
-                    if ($checked) {
-                        $userfieldstyle = 'display:inline-block';
-                        if ($userincdom) {
-                            $seluserdom = $unseluserdom;
-                            $unseluserdom = '';
-                        }
+        if ($position eq 'top') {
+            if (exists($settings->{'encrypt'})) {
+                if (ref($settings->{'encrypt'}) eq 'HASH') {
+                    foreach my $key (keys(%{$settings->{'encrypt'}})) {
+                        $encrypt{'toolsec_'.$key} = $settings->{'encrypt'}{$key};
                     }
-                } else {
-                    $spacer = (' ' x2);
                 }
-                $datatable .= '<label>'.
-                              '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
-                              $lt{$field}.'</label>'.$spacer;
             }
-            $datatable .= '</span>';
-            $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
-                          '<span class="LC_nobreak"> : '.
-                          '<select name="ltitools_userincdom_'.$i.'">'.
-                          '<option value="">'.&mt('Select').'</option>'.
-                          '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
-                          '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
-                          '</select></span></div>';
-            $datatable .= '</fieldset>'.
-                          '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
-            foreach my $role (@courseroles) {
-                my ($selected,$selectnone);
-                if (!$rolemaps{$role}) {
-                    $selectnone = ' selected="selected"';
-                }
-                $datatable .= '<td style="text-align: center">'. 
-                              &Apache::lonnet::plaintext($role,'Course').'<br />'.
-                              '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
-                              '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
-                foreach my $ltirole (@ltiroles) {
-                    unless ($selectnone) {
-                        if ($rolemaps{$role} eq $ltirole) {
-                            $selected = ' selected="selected"';
-                        } else {
-                            $selected = '';
+            if (exists($settings->{'private'})) {
+                if (ref($settings->{'private'}) eq 'HASH') {
+                    if (ref($settings->{'private'}) eq 'HASH') {
+                        if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
+                            map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
                         }
                     }
-                    $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
                 }
-                $datatable .= '</select></td>';
             }
-            $datatable .= '</tr></table></fieldset>';
-            my %courseconfig;
-            if (ref($settings->{$item}) eq 'HASH') {
-                if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
-                    %courseconfig = %{$settings->{$item}->{'crsconf'}};
-                }
-            }
-            $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
-            foreach my $item ('label','title','target','linktext','explanation','append') {
-                my $checked;
-                if ($courseconfig{$item}) {
-                    $checked = ' checked="checked"';
+        } elsif ($position eq 'middle') {
+            if (exists($settings->{'rules'})) {
+                if (ref($settings->{'rules'}) eq 'HASH') {
+                    %rules = %{$settings->{'rules'}};
                 }
-                $datatable .= '<label>'.
-                       '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
-                       $lt{'crs'.$item}.'</label>  '."\n";
             }
-            $datatable .= '</span></fieldset>'.
-                          '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
-                          '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
-            if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
-                my %custom = %{$settings->{$item}->{'custom'}};
-                if (keys(%custom) > 0) {
-                    foreach my $key (sort(keys(%custom))) {
-                        $datatable .= '<tr><td><span class="LC_nobreak">'.
-                                      '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
-                                      $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
-                                      '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
-                                      ' value="'.$custom{$key}.'" /></td></tr>';
-                    }
+        } else {
+            foreach my $key ('encrypt','private','rules') {
+                if (exists($settings->{$key})) {
+                    delete($settings->{$key});
                 }
             }
-            $datatable .= '<tr><td><span class="LC_nobreak">'.
-                          '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
-                          &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
-                          '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
-            $datatable .= '</table></fieldset></td></tr>'."\n";
-            $itemcount ++;
         }
     }
-    $css_class = $itemcount%2?' class="LC_odd_row"':'';
-    my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
-    $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
-                  '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
-                  '<select name="ltitools_add_pos"'.$chgstr.'>';
-    for (my $k=0; $k<$maxnum+1; $k++) {
-        my $vpos = $k+1;
-        my $selstr;
-        if ($k == $maxnum) {
-            $selstr = ' selected="selected" ';
-        }
-        $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
+    my $datatable;
+    my $itemcount = 1;
+    if ($position eq 'top') {
+        $datatable = &secrets_form($dom,'toolsec',\%encrypt,\%privkeys,$rowtotal);
+    } elsif ($position eq 'middle') {
+        $datatable = &password_rules('toolsecrets',\$itemcount,\%rules);
+        $$rowtotal += $itemcount;
+    } else {
+        $datatable = &Apache::courseprefs::print_ltitools($dom,'',$settings,\$rowtotal,'','','domain');
     }
-    $datatable .= '</select> '."\n".
-                  '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
-                  '<td colspan="2">'.
-                  '<fieldset><legend>'.&mt('Required settings').'</legend>'.
-                  '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
-                  (' 'x2).
-                  '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
-                  '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
-                  (' 'x2).
-                  '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
-                  '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
-                  '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
-                  '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
-                  '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
-                  '<br />'.
-                  '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
-                  (' 'x2).
-                  '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
-                  (' 'x2).
-                  '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
-                  (' 'x2).
-                  '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
-                  '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_add_secret.type='."'text'".' } else { this.form.ltitools_add_secret.type='."'password'".' }" />'.&mt('Visible input').'</label></span> '."\n".
-                  '</fieldset>'.
-                  '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
-                  '<span class="LC_nobreak">'.&mt('Display target:');
-    my %defaultdisp;
-    $defaultdisp{'iframe'} = ' checked="checked"';
-    foreach my $disp ('iframe','tab','window') {
-        $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
-                      $lt{$disp}.'</label>'.(' 'x2);
-    }
-    $datatable .= (' 'x4);
-    foreach my $dimen ('width','height') {
-        $datatable .= '<label>'.$lt{$dimen}.' '.
-                      '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
-                      (' 'x2);
-    }
-    $datatable .= '</span><br />'.
-                  '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
-                  '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
-                  '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
-                  '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
-                  '</div><div style=""></div><br />';
-    my %units = (
-                  'passback' => 'days',
-                  'roster'   => 'seconds',
-                );
-    my %defaulttimes = (
-                     'passback' => '7',
-                     'roster'   => '300',
-                   );
-    foreach my $extra ('passback','roster') {
-        my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
-        $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.' '.
-                      '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
-                      &mt('No').'</label></span>'.(' 'x2).'<span class="LC_nobreak">'.
-                      '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
-                      &mt('Yes').'</label></span></div>'.
-                      '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
-                      '<span class="LC_nobreak">'.
-                      &mt("at least [_1] $units{$extra} after launch",
-                          '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
-                      '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
-    }
-    $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.': '.
-                  '('.&mt('if larger than 21x21 pixels, image will be scaled').') ';
-    if ($switchserver) {
-        $datatable .= &mt('Upload to library server: [_1]',$switchserver);
-    } else {
-        $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
-    }
-    $datatable .= '</span></fieldset>'.
-                  '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
-                  '<span class="LC_nobreak">';
-    foreach my $field (@fields) {
-        my ($id,$onclick,$spacer);
-        if ($field eq 'user') {
-            $id = ' id="ltitools_user_field_add"';
-            $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
-        } else {
-            $spacer = (' ' x2);
-        }
-        $datatable .= '<label>'.
-                      '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
-                      $lt{$field}.'</label>'.$spacer;
-    }
-    $datatable .= '</span>'.
-                  '<div style="display:none;" id="ltitools_user_div_add">'.
-                  '<span class="LC_nobreak"> : '.
-                  '<select name="ltitools_userincdom_add">'.
-                  '<option value="" selected="selected">'.&mt('Select').'</option>'.
-                  '<option value="0">'.&mt('username').'</option>'.
-                  '<option value="1">'.&mt('username:domain').'</option>'.
-                  '</select></span></div></fieldset>';
-    $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
-    foreach my $role (@courseroles) {
-        my ($checked,$checkednone);
-        $datatable .= '<td style="text-align: center">'.
-                      &Apache::lonnet::plaintext($role,'Course').'<br />'.
-                      '<select name="ltitools_add_roles_'.$role.'">'.
-                      '<option value="" selected="selected">'.&mt('Select').'</option>';
-        foreach my $ltirole (@ltiroles) {
-            $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
-        }
-        $datatable .= '</select></td>';
-    }
-    $datatable .= '</tr></table></fieldset>'.
-                  '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
-    foreach my $item ('label','title','target','linktext','explanation','append') {
-        $datatable .= '<label>'.
-                      '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
-                      $lt{'crs'.$item}.'</label>'.(' ' x2)."\n";
-    }
-    $datatable .= '</span></fieldset>'.
-                  '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
-                  '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
-                  '<tr><td><span class="LC_nobreak">'.
-                  '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
-                  &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
-                  '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
-                  '</table></fieldset>'."\n".
-                  '</td>'."\n".
-                  '</tr>'."\n";
-    $itemcount ++;
     return $datatable;
 }
 
@@ -5853,6 +5367,123 @@
     return %lt;
 }
 
+sub secrets_form {
+    my ($dom,$context,$encrypt,$privkeys,$rowtotal) = @_;
+    my @ids=&Apache::lonnet::current_machine_ids();
+    my %servers = &Apache::lonnet::get_servers($dom,'library');
+    my $primary = &Apache::lonnet::domain($dom,'primary');
+    my ($css_class,$extra,$numshown,$itemcount,$output);
+    $itemcount = 0;
+    foreach my $hostid (sort(keys(%servers))) {
+        my ($showextra,$divsty,$switch);
+        if ($hostid eq $primary) {
+            if ($context eq 'ltisec') {
+                if (($encrypt->{'ltisec_consumers'}) || ($encrypt->{'ltisec_domlinkprot'})) {
+                    $showextra = 1;
+                }
+                if ($encrypt->{'ltisec_crslinkprot'}) {
+                    $showextra = 1;
+                }
+            } else {
+                if (($encrypt->{'toolsec_crs'}) || ($encrypt->{'toolsec_dom'})) {
+                    $showextra = 1;
+                }
+            }
+            unless (grep(/^\Q$hostid\E$/, at ids)) {
+                $switch = 1;
+            }
+            if ($showextra) {
+                $numshown ++;
+                $divsty = 'display:inline-block';
+            } else {
+                $divsty = 'display:none';
+            }
+            $extra .= '<fieldset id="'.$context.'_info_'.$hostid.'" style="'.$divsty.'">'.
+                      '<legend>'.$hostid.'</legend>';
+            if ($switch) {
+                my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&role='.
+                                   &HTML::Entities::encode($env{'request.role'},'\'<>"&').
+                                   '&destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
+                if (exists($privkeys->{$hostid})) {
+                    $extra .= '<div id="'.$context.'_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
+                              '<span class="LC_nobreak">'.
+                              &mt('Encryption Key').': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
+                              '<span class="LC_nobreak">'.&mt('Change?').
+                              '<label><input type="radio" value="0" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
+                              (' 'x2).
+                              '<label><input type="radio" value="1" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" />'.&mt('Yes').
+                              '</label>  </span><div id="'.$context.'_divchgprivkey_'.$hostid.'" style="display:none" />'.
+                              '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
+                              '</span></div>';
+                } else {
+                    $extra .= '<span class="LC_nobreak">'.
+                              &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
+                              '</span>'."\n";
+                }
+            } elsif (exists($privkeys->{$hostid})) {
+                $extra .= '<div id="'.$context.'_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
+                          &mt('Encryption Key').': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
+                          '<span class="LC_nobreak">'.&mt('Change?').
+                          '<label><input type="radio" value="0" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
+                          (' 'x2).
+                          '<label><input type="radio" value="1" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" />'.&mt('Yes').
+                          '</label>  </span><div id="'.$context.'_divchgprivkey_'.$hostid.'" style="display:none" />'.
+                          '<span class="LC_nobreak">'.&mt('New Key').':'.
+                          '<input type="password" size="20" name="'.$context.'_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
+                          '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.'.$context.'_privkey_'.$hostid.'.type='."'text'".' } else { this.form.'.$context.'_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
+                          '</span></div>';
+            } else {
+                $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
+                          '<input type="password" size="20" name="'.$context.'_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
+                          '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.'.$context.'_privkey_'.$hostid.'.type='."'text'".' } else { this.form.'.$context.'_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
+            }
+            $extra .= '</fieldset>';
+        }
+    }
+    my (%choices, at toggles,%defaultchecked);
+    if ($context eq 'ltisec') {
+        %choices = &Apache::lonlocal::texthash (
+                                                  ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
+                                                  ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
+                                                  ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
+                                               );
+        @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
+        %defaultchecked = (
+                           'ltisec_crslinkprot' => 'off',
+                           'ltisec_domlinkprot' => 'off',
+                           'ltisec_consumers'   => 'off',
+                          );
+    } else {
+        %choices = &Apache::lonlocal::texthash (
+                                                  toolsec_crs => 'Encrypt stored external tool secrets defined in courses',
+                                                  toolsec_dom => 'Encrypt stored external tool secrets defined in domain',
+                                               );
+        @toggles = qw(toolsec_crs toolsec_dom);
+        %defaultchecked = (
+                           'toolsec_crs' => 'off',
+                           'toolsec_dom' => 'off',
+                          );
+    }
+    my ($onclick,$itemcount);
+    $onclick = 'javascript:toggleLTIEncKey(this.form,'."'$context'".');';
+    ($output,$itemcount) = &radiobutton_prefs($encrypt,\@toggles,\%defaultchecked,
+                                              \%choices,$itemcount,$onclick,'','left','no');
+
+    $css_class = $itemcount%2?' class="LC_odd_row"':'';
+    my $noprivkeysty = 'display:inline-block';
+    if ($numshown) {
+        $noprivkeysty = 'display:none';
+    }
+    $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
+               '<td><div id="'.$context.'_noprivkey" style="'.$noprivkeysty.'" >'.
+               '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
+               $extra.
+               '</td></tr>';
+    $itemcount ++;
+    $$rowtotal += $itemcount;
+    return $output;
+}
+
 sub print_proctoring {
     my ($dom,$settings,$rowtotal) = @_;
     my $itemcount = 1;
@@ -6538,100 +6169,9 @@
         }
     }
     if ($position eq 'top') {
-        my @ids=&Apache::lonnet::current_machine_ids();
-        my %servers = &Apache::lonnet::get_servers($dom,'library');
-        my $primary = &Apache::lonnet::domain($dom,'primary');
-        my ($extra,$numshown);
-        foreach my $hostid (sort(keys(%servers))) {
-            my ($showextra,$divsty,$switch);
-            if ($hostid eq $primary) {
-                if (($encrypt{'ltisec_consumers'}) || ($encrypt{'ltisec_domlinkprot'})) {
-                    $showextra = 1;
-                }
-            }
-            if ($encrypt{'ltisec_crslinkprot'}) {
-                $showextra = 1;
-            }
-            unless (grep(/^\Q$hostid\E$/, at ids)) {
-                $switch = 1;
-            }
-            if ($showextra) {
-                $numshown ++;
-                $divsty = 'display:inline-block'; 
-            } else {
-                $divsty = 'display:none';
-            } 
-            $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
-                      '<legend>'.$hostid.'</legend>';
-            if ($switch) {
-                my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&role='.
-                                   &HTML::Entities::encode($env{'request.role'},'\'<>"&').
-                                   '&destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
-                if (exists($privkeys{$hostid})) {
-                    $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
-                              '<span class="LC_nobreak">'.
-                              &mt('Encryption Key').': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
-                              '<span class="LC_nobreak">'.&mt('Change?').
-                              '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
-                              (' 'x2).
-                              '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
-                              '</label>  </span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
-                              '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
-                              '</span></div>';
-                } else {
-                    $extra .= '<span class="LC_nobreak">'.
-                              &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
-                              '</span>'."\n";
-                }
-            } elsif (exists($privkeys{$hostid})) {
-                $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
-                          &mt('Encryption Key').': ['.&mt('not shown').'] '.(' 'x2).'</span></div>'.
-                          '<span class="LC_nobreak">'.&mt('Change?').
-                          '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
-                          (' 'x2).
-                          '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
-                          '</label>  </span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
-                          '<span class="LC_nobreak">'.&mt('New Key').':'.
-                          '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
-                          '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
-                          '</span></div>';
-            } else {
-                $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
-                          '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
-                          '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
-            }
-            $extra .= '</fieldset>';
-        }
-        my %choices = &Apache::lonlocal::texthash (
-                                                      ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
-                                                      ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
-                                                      ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
-                                                  );
-        my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
-        my %defaultchecked = (
-                               'ltisec_crslinkprot' => 'off',
-                               'ltisec_domlinkprot' => 'off',
-                               'ltisec_consumers'   => 'off',
-                             );
-        my ($onclick,$itemcount);
-        $onclick = 'javascript:toggleLTIEncKey(this.form);';
-        ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
-                                                     \%choices,$itemcount,$onclick,'','left','no');
-
-        $css_class = $itemcount%2?' class="LC_odd_row"':'';
-        my $noprivkeysty = 'display:inline-block';
-        if ($numshown) {
-            $noprivkeysty = 'display:none'; 
-        }
-        $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
-                      '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
-                      '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
-                      $extra.
-                      '</td></tr>';
-        $itemcount ++;                
-        $$rowtotal += $itemcount;
+        $datatable = &secrets_form($dom,'ltisec',\%encrypt,\%privkeys,$rowtotal);
     } elsif ($position eq 'middle') {
-        $datatable = &password_rules('secrets',\$itemcount,\%rules);
+        $datatable = &password_rules('ltisecrets',\$itemcount,\%rules);
         $$rowtotal += $itemcount;
     } elsif ($position eq 'lower') {
          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
@@ -8237,7 +7777,7 @@
             max            => 'Maximum password length',
             chars          => 'Required characters',
         );
-    } elsif ($prefix eq 'secrets') {
+    } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
         %titles = &Apache::lonlocal::texthash (
             min            => 'Minimum secret length',
             max            => 'Maximum secret length',
@@ -11061,10 +10601,13 @@
     my ($url,$error);
     my @statinfo = &Apache::lonnet::stat_file($newurl);
     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
+        my $modified = [];
         (my $result,$url) =
-            &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
-                         '','',$newfile);
-        if ($result ne 'ok') {
+            &Apache::lonconfigsettings::publishlogo($r,'copy',$legacyfile,$dom,$confname,
+                                                    'scantron','','',$newfile,$modified);
+        if ($result eq 'ok') {
+            &update_modify_urls($r,$modified);
+        } else {
             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
         }
     }
@@ -11644,7 +11187,7 @@
             passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
         );
-    } elsif ($prefix eq 'secrets') {
+    } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
         %intalert = &Apache::lonlocal::texthash (
             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
@@ -12518,13 +12061,16 @@
                 if ($addedfile ne '') {
                     push(@allnew,$addedfile);
                 }
+                my $modified = [];
                 foreach my $lang (@allnew) {
                     my $formelem = 'loginhelpurl_'.$lang;
                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
                         $formelem = 'loginhelpurl_add_file';
                     }
-                    (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
-                                                               "help/$lang",'','',$newfile{$lang});
+                    (my $result,$newurl{$lang}) = 
+                        &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
+                                                                "help/$lang",'','',$newfile{$lang},
+                                                                $modified);
                     if ($result eq 'ok') {
                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
                         $changes{'helpurl'}{$lang} = 1;
@@ -12537,6 +12083,7 @@
                         }
                     }
                 }
+                &update_modify_urls($r,$modified);
             } else {
                 $error = &mt("Upload of custom log-in help file(s) failed because an author role could not be assigned to a Domain Configuration user ([_1]) in domain: [_2].  Error was: [_3].",$confname,$dom,$author_ok);
             }
@@ -12594,11 +12141,14 @@
             if ($switchserver) {
                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
             } elsif ($author_ok eq 'ok') {
+                my $modified = [];
                 foreach my $lonhost (@newhosts) {
                     my $formelem = 'loginheadtag_'.$lonhost;
-                    (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
-                                                                          "login/headtag/$lonhost",'','',
-                                                                          $env{'form.loginheadtag_'.$lonhost.'.filename'});
+                    (my $result,$newheadtagurls{$lonhost}) = 
+                        &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
+                                                                "login/headtag/$lonhost",'','',
+                                                                $env{'form.loginheadtag_'.$lonhost.'.filename'},
+                                                                $modified);
                     if ($result eq 'ok') {
                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
                         $changes{'headtag'}{$lonhost} = 1;
@@ -12615,6 +12165,7 @@
                         }
                     }
                 }
+                &update_modify_urls($r,$modified);
             } else {
                 $error = &mt("Upload of custom markup file(s) failed because an author role could not be assigned to a Domain Configuration user ([_1]) in domain: [_2].  Error was: [_3].",$confname,$dom,$author_ok);
             }
@@ -12689,11 +12240,14 @@
             if ($switchserver) {
                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
             } elsif ($author_ok eq 'ok') {
+                my $modified = [];
                 foreach my $lonhost (@newsamlimgs) {
                     my $formelem = 'saml_img_'.$lonhost;
-                    my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
-                                                        "login/saml/$lonhost",'','',
-                                                        $env{'form.saml_img_'.$lonhost.'.filename'});
+                    my ($result,$imgurl) = 
+                        &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
+                                                                "login/saml/$lonhost",'','',
+                                                                $env{'form.saml_img_'.$lonhost.'.filename'},
+                                                                $modified);
                     if ($result eq 'ok') {
                         $currsaml{$lonhost}{'img'} = $imgurl;
                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
@@ -12704,6 +12258,7 @@
                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
                     }
                 }
+                &update_modify_urls($r,$modified);
             } else {
                 $error = &mt("Upload of SSO button image file(s) failed because an author role could not be assigned to a Domain Configuration user ([_1]) in domain: [_2].  Error was: [_3].",$confname,$dom,$author_ok);
             }
@@ -13408,12 +12963,15 @@
                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
                     } else {
                         if ($author_ok eq 'ok') {
+                            my $modified = [];
                             my ($result,$logourl) = 
-                                &publishlogo($r,'upload',$role.'_'.$img,
-                                           $dom,$confname,$img,$width,$height);
+                                &Apache::lonconfigsettings::publishlogo($r,'upload',$role.'_'.$img,
+                                                                        $dom,$confname,$img,$width,$height,
+                                                                        '',$modified);
                             if ($result eq 'ok') {
                                 $confhash->{$role}{$img} = $logourl;
                                 $changes{$role}{'images'}{$img} = 1;
+                                &update_modify_urls($r,$modified);
                             } else {
                                 $error = &mt("Upload of [_1] image for $role page(s) failed because an error occurred publishing the file in RES space. Error was: [_2].",$choices{img},$result);
                             }
@@ -13435,12 +12993,15 @@
 # is confname an author?
                         if ($switchserver eq '') {
                             if ($author_ok eq 'ok') {
+                                my $modified = [];
                                 my ($result,$logourl) = 
-                               &publishlogo($r,'copy',$domconfig->{$role}{$img},
-                                            $dom,$confname,$img,$width,$height);
+                                    &Apache::lonconfigsettings::publishlogo($r,'copy',$domconfig->{$role}{$img},
+                                                                            $dom,$confname,$img,$width,$height,
+                                                                            '',$modified);
                                 if ($result eq 'ok') {
                                     $confhash->{$role}{$img} = $logourl;
 				    $changes{$role}{'images'}{$img} = 1;
+                                    &update_modify_urls($r,$modified);
                                 }
                             }
                         }
@@ -13734,229 +13295,16 @@
     return $author_ok;
 }
 
-sub publishlogo {
-    my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
-    my ($output,$fname,$logourl,$madethumb);
-    if ($action eq 'upload') {
-        $fname=$env{'form.'.$formname.'.filename'};
-        chop($env{'form.'.$formname});
-    } else {
-        ($fname) = ($formname =~ /([^\/]+)$/);
-    }
-    if ($savefileas ne '') {
-        $fname = $savefileas;
-    }
-    $fname=&Apache::lonnet::clean_filename($fname);
-# See if there is anything left
-    unless ($fname) { return ('error: no uploaded file'); }
-    $fname="$subdir/$fname";
-    my $docroot=$r->dir_config('lonDocRoot');
-    my $filepath="$docroot/priv";
-    my $relpath = "$dom/$confname";
-    my ($fnamepath,$file,$fetchthumb);
-    $file=$fname;
-    if ($fname=~m|/|) {
-        ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
-    }
-    my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
-    my $count;
-    for ($count=5;$count<=$#parts;$count++) {
-        $filepath.="/$parts[$count]";
-        if ((-e $filepath)!=1) {
-            mkdir($filepath,02770);
-        }
-    }
-    # Check for bad extension and disallow upload
-    if ($file=~/\.(\w+)$/ &&
-        (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
-        $output = 
-            &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
-    } elsif ($file=~/\.(\w+)$/ &&
-        !defined(&Apache::loncommon::fileembstyle($1))) {
-        $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
-    } elsif ($file=~/\.(\d+)\.(\w+)$/) {
-        $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
-    } elsif (-d "$filepath/$file") {
-        $output = &mt('Filename is a directory name - rename the file and re-upload');
-    } else {
-        my $source = $filepath.'/'.$file;
-        my $logfile;
-        if (!open($logfile,">>",$source.'.log')) {
-            return (&mt('No write permission to Authoring Space'));
-        }
-        print $logfile
-"\n================= Publish ".localtime()." ================\n".
-$env{'user.name'}.':'.$env{'user.domain'}."\n";
-# Save the file
-        if (!open(FH,">",$source)) {
-            &Apache::lonnet::logthis('Failed to create '.$source);
-            return (&mt('Failed to create file'));
-        }
-        if ($action eq 'upload') {
-            if (!print FH ($env{'form.'.$formname})) {
-                &Apache::lonnet::logthis('Failed to write to '.$source);
-                return (&mt('Failed to write file'));
-            }
-        } else {
-            my $original = &Apache::lonnet::filelocation('',$formname);
-            if(!copy($original,$source)) {
-                &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
-                return (&mt('Failed to write file'));
-            }
-        }
-        close(FH);
-        chmod(0660, $source); # Permissions to rw-rw---.
-
-        my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
-        my $copyfile=$targetdir.'/'.$file;
-
-        my @parts=split(/\//,$targetdir);
-        my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
-        for (my $count=5;$count<=$#parts;$count++) {
-            $path.="/$parts[$count]";
-            if (!-e $path) {
-                print $logfile "\nCreating directory ".$path;
-                mkdir($path,02770);
-            }
-        }
-        my $versionresult;
-        if (-e $copyfile) {
-            $versionresult = &logo_versioning($targetdir,$file,$logfile);
-        } else {
-            $versionresult = 'ok';
-        }
-        if ($versionresult eq 'ok') {
-            if (copy($source,$copyfile)) {
-                print $logfile "\nCopied original source to ".$copyfile."\n";
-                $output = 'ok';
-                $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
-                push(@{$modified_urls},[$copyfile,$source]);
-                my $metaoutput = 
-                    &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
-                unless ($registered_cleanup) {
-                    my $handlers = $r->get_handlers('PerlCleanupHandler');
-                    $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
-                    $registered_cleanup=1;
-                }
-            } else {
-                print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
-                $output = &mt('Failed to copy file to RES space').", $!";
-            }
-            if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
-                my $inputfile = $filepath.'/'.$file;
-                my $outfile = $filepath.'/'.'tn-'.$file;
-                my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
-                if ($fullwidth ne '' && $fullheight ne '') { 
-                    if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
-                        my $thumbsize = $thumbwidth.'x'.$thumbheight;
-                        my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
-                        system({$args[0]} @args);
-                        chmod(0660, $filepath.'/tn-'.$file);
-                        if (-e $outfile) {
-                            my $copyfile=$targetdir.'/tn-'.$file;
-                            if (copy($outfile,$copyfile)) {
-                                print $logfile "\nCopied source to ".$copyfile."\n";
-                                my $thumb_metaoutput = 
-                                    &write_metadata($dom,$confname,$formname,
-                                                    $targetdir,'tn-'.$file,$logfile);
-                                push(@{$modified_urls},[$copyfile,$outfile]);
-                                unless ($registered_cleanup) {
-                                    my $handlers = $r->get_handlers('PerlCleanupHandler');
-                                    $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
-                                    $registered_cleanup=1;
-                                }
-                                $madethumb = 1;
-                            } else {
-                                print $logfile "\nUnable to write ".$copyfile.
-                                               ':'.$!."\n";
-                            }
-                        }
-                    }
-                }
-            }
-        } else {
-            $output = $versionresult;
-        }
-    }
-    return ($output,$logourl,$madethumb);
-}
-
-sub logo_versioning {
-    my ($targetdir,$file,$logfile) = @_;
-    my $target = $targetdir.'/'.$file;
-    my ($maxversion,$fn,$extn,$output);
-    $maxversion = 0;
-    if ($file =~ /^(.+)\.(\w+)$/) {
-        $fn=$1;
-        $extn=$2;
-    }
-    opendir(DIR,$targetdir);
-    while (my $filename=readdir(DIR)) {
-        if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
-            $maxversion=($1>$maxversion)?$1:$maxversion;
-        }
-    }
-    $maxversion++;
-    print $logfile "\nCreating old version ".$maxversion."\n";
-    my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
-    if (copy($target,$copyfile)) {
-        print $logfile "Copied old target to ".$copyfile."\n";
-        $copyfile=$copyfile.'.meta';
-        if (copy($target.'.meta',$copyfile)) {
-            print $logfile "Copied old target metadata to ".$copyfile."\n";
-            $output = 'ok';
-        } else {
-            print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
-            $output = &mt('Failed to copy old meta').", $!, ";
-        }
-    } else {
-        print $logfile "Unable to write ".$copyfile.':'.$!."\n";
-        $output = &mt('Failed to copy old target').", $!, ";
-    }
-    return $output;
-}
-
-sub write_metadata {
-    my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
-    my (%metadatafields,%metadatakeys,$output);
-    $metadatafields{'title'}=$formname;
-    $metadatafields{'creationdate'}=time;
-    $metadatafields{'lastrevisiondate'}=time;
-    $metadatafields{'copyright'}='public';
-    $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
-                                         $env{'user.domain'};
-    $metadatafields{'authorspace'}=$confname.':'.$dom;
-    $metadatafields{'domain'}=$dom;
-    {
-        print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
-        my $mfh;
-        if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
-            foreach (sort(keys(%metadatafields))) {
-                unless ($_=~/\./) {
-                    my $unikey=$_;
-                    $unikey=~/^([A-Za-z]+)/;
-                    my $tag=$1;
-                    $tag=~tr/A-Z/a-z/;
-                    print $mfh "\n\<$tag";
-                    foreach (split(/\,/,$metadatakeys{$unikey})) {
-                        my $value=$metadatafields{$unikey.'.'.$_};
-                        $value=~s/\"/\'\'/g;
-                        print $mfh ' '.$_.'="'.$value.'"';
-                    }
-                    print $mfh '>'.
-                        &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
-                            .'</'.$tag.'>';
-                }
-            }
-            $output = 'ok';
-            print $logfile "\nWrote metadata";
-            close($mfh);
-        } else {
-            print $logfile "\nFailed to open metadata file";
-            $output = &mt('Could not write metadata');
+sub update_modify_urls {
+    my ($r,$modified) = @_;
+    if ((ref($modified) eq 'ARRAY') && (@{$modified})) {
+        push(@{$modified_urls},$modified);
+        unless ($registered_cleanup) {
+            my $handlers = $r->get_handlers('PerlCleanupHandler');
+            $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
+            $registered_cleanup=1;
         }
     }
-    return $output;
 }
 
 sub notifysubscribed {
@@ -14738,11 +14086,14 @@
             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
                          $switchserver);
         } elsif ($author_ok eq 'ok') {
+            my $modified = [];
             my ($result,$imageurl) =
-                &publishlogo($r,'upload',$caller,$dom,$confname,
-                             "$type/$cdom/$cnum/cover",$width,$height);
+                &Apache::lonconfigsettings::publishlogo($r,'upload',$caller,$dom,$confname,
+                                                        "$type/$cdom/$cnum/cover",$width,$height,
+                                                        '',$modified);
             if ($result eq 'ok') {
                 $url = $imageurl;
+                &update_modify_urls($r,$modified);
             } else {
                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
             }
@@ -14757,692 +14108,355 @@
 
 sub modify_ltitools {
     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
-    my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
-    my ($newid, at allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
+    my (%currtoolsec,%secchanges,%newtoolsec,%newkeyset);
+    &fetch_secrets($dom,'toolsec',\%domconfig,\%currtoolsec,\%secchanges,\%newtoolsec,\%newkeyset);
+
     my $confname = $dom.'-domainconfig';
     my $servadm = $r->dir_config('lonAdmEMail');
     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
-    my (%posslti,%possfield);
-    my @courseroles = ('cc','in','ta','ep','st');
-    my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
-    map { $posslti{$_} = 1; } @ltiroles;
-    my @allfields = ('fullname','firstname','lastname','email','user','roles');
-    map { $possfield{$_} = 1; } @allfields;
-    my %lt = &ltitools_names(); 
-    if ($env{'form.ltitools_add'}) {
-        my $title = $env{'form.ltitools_add_title'};
-        $title =~ s/(`)/'/g;
-        ($newid,my $error) = &get_ltitools_id($dom,$title);
-        if ($newid) {
-            my $position = $env{'form.ltitools_add_pos'};
-            $position =~ s/\D+//g;
-            if ($position ne '') {
-                $allpos[$position] = $newid;
-            }
-            $changes{$newid} = 1;
-            foreach my $item ('title','url','key','secret','lifetime') {
-                $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
-                if ($item eq 'lifetime') {
-                    $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
+
+    my ($resulttext,$ltitoolsoutput,$is_home,$errors,%ltitoolschg,%newtoolsenc,%newltitools);
+    my $toolserror =
+        &Apache::courseprefs::process_ltitools($r,$dom,$confname,$domconfig{'ltitools'},\%ltitoolschg,'domain',
+                                               $lastactref,$configuserok,$switchserver,$author_ok);
+
+    my $home = &Apache::lonnet::domain($dom,'primary');
+    unless (($home eq 'no_host') || ($home eq '')) {
+        my @ids=&Apache::lonnet::current_machine_ids();
+        foreach my $id (@ids) { if ($id eq $home) { $is_home=1; last; } }
+    }
+
+    if (keys(%ltitoolschg)) {
+        foreach my $id (keys(%ltitoolschg)) {
+            if (ref($ltitoolschg{$id}) eq 'HASH') {
+                foreach my $inner (keys(%{$ltitoolschg{$id}})) {
+                    if (($inner eq 'secret') || ($inner eq 'key')) {
+                        if ($is_home) {
+                            $newtoolsenc{$id}{$inner} = $ltitoolschg{$id}{$inner};
+                        }
+                    }
                 }
-                if ($env{'form.ltitools_add_'.$item}) {
-                    if (($item eq 'key') || ($item eq 'secret')) {
-                        $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
-                    } else {
-                        $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
+            }
+        }
+        $ltitoolsoutput = &Apache::courseprefs::store_ltitools($dom,'','domain',\%ltitoolschg,$domconfig{'ltitools'});
+        if (keys(%ltitoolschg)) {
+            %newltitools = %ltitoolschg;
+        }
+    }
+    if (ref($domconfig{'ltitools'}) eq 'HASH') {
+        foreach my $id (%{$domconfig{'ltitools'}}) {
+            next if ($id !~ /^\d+$/);
+            unless (exists($ltitoolschg{$id})) {
+                if (ref($domconfig{'ltitools'}{$id}) eq 'HASH') {
+                    foreach my $inner (keys(%{$domconfig{'ltitools'}{$id}})) {
+                        if (($inner eq 'secret') || ($inner eq 'key')) {
+                            if ($is_home) {
+                                $newtoolsenc{$id}{$inner} = $domconfig{'ltitools'}{$id}{$inner};
+                            }
+                        } else {
+                            $newltitools{$id}{$inner} = $domconfig{'ltitools'}{$id}{$inner};
+                        }
                     }
+                } else {
+                    $newltitools{$id} = $domconfig{'ltitools'}{$id};
                 }
             }
-            if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
-                $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
+        }
+    }
+    if ($toolserror) {
+        $errors = '<li>'.$toolserror.'</li>';
+    }
+    if ((keys(%ltitoolschg) == 0) && (keys(%secchanges) == 0)) {
+        $resulttext = &mt('No changes made.');
+        if ($errors) {
+            $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
+                                 $errors.'</ul>';
+        }
+        return $resulttext;
+    }
+    my %ltitoolshash = (
+                          $action => { %newltitools }
+                       );
+    if (keys(%secchanges)) {
+        $ltitoolshash{'toolsec'} = \%newtoolsec;
+    }
+    my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,$dom);
+    if ($putresult eq 'ok') {
+        my %keystore;
+        if ($is_home) {
+            my %toolsenchash = (
+                                   $action => { %newtoolsenc }
+                               );
+            &Apache::lonnet::put_dom('encconfig',\%toolsenchash,$dom,undef,1);
+            &store_security($dom,'ltitools',\%secchanges,\%newkeyset,\%keystore,$lastactref);
+        }
+        $resulttext = &mt('Changes made:').'<ul>';
+        if (keys(%secchanges) > 0) {
+            $resulttext .= &lti_security_results('ltitools',\%secchanges,\%newtoolsec,\%newkeyset,\%keystore);
+        }
+        if (keys(%ltitoolschg) > 0) {
+            $resulttext .= $ltitoolsoutput;
+        }
+    } else {
+        $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
+    }
+    if ($errors) {
+        $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
+                       $errors.'</ul></p>';
+    }
+    return $resulttext;
+}
+
+sub fetch_secrets {
+    my ($dom,$context,$domconfig,$currsec,$secchanges,$newsec,$newkeyset) = @_;
+    my %keyset;
+    %{$currsec} = ();
+    $newsec->{'private'}{'keys'} = [];
+    $newsec->{'encrypt'} = {};
+    $newsec->{'rules'} = {};
+    if ($context eq 'ltisec') {
+        $newsec->{'linkprot'} = {};
+    }
+    if (ref($domconfig->{$context}) eq 'HASH') {
+        %{$currsec} = %{$domconfig->{$context}};
+        if ($context eq 'ltisec') {
+            if (ref($currsec->{'linkprot'}) eq 'HASH') {
+                foreach my $id (keys(%{$currsec->{'linkprot'}})) {
+                    unless ($id =~ /^\d+$/) {
+                        delete($currsec->{'linkprot'}{$id});
+                    }
+                }
             }
-            if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
-                $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
+        }
+        if (ref($currsec->{'private'}) eq 'HASH') {
+            if (ref($currsec->{'private'}{'keys'}) eq 'ARRAY') {
+                $newsec->{'private'}{'keys'} = $currsec->{'private'}{'keys'};
+                map { $keyset{$_} = 1; } @{$currsec->{'private'}{'keys'}};
             }
-            if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
-                $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
+        }
+    }
+    my @items= ('crs','dom');
+    if ($context eq 'ltisec') {
+        push(@items,'consumers');
+    }
+    foreach my $item (@items) {
+        my $formelement;
+        if (($context eq 'toolsec') || ($item eq 'consumers')) {
+            $formelement = 'form.'.$context.'_'.$item;
+        } else {
+            $formelement = 'form.'.$context.'_'.$item.'linkprot';
+        }
+        if ($env{$formelement}) {
+            $newsec->{'encrypt'}{$item} = 1;
+            if (ref($currsec->{'encrypt'}) eq 'HASH') {
+                unless ($currsec->{'encrypt'}{$item}) {
+                    $secchanges->{'encrypt'} = 1;
+                }
             } else {
-                $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
+                $secchanges->{'encrypt'} = 1;
             }
-            foreach my $item ('width','height','linktext','explanation') {
-                $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
-                $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
-                if (($item eq 'width') || ($item eq 'height')) {
-                    if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
-                        $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
+        } elsif (ref($currsec->{'encrypt'}) eq 'HASH') {
+            if ($currsec->{'encrypt'}{$item}) {
+                $secchanges->{'encrypt'} = 1;
+            }
+        }
+    }
+    my $secrets;
+    if ($context eq 'ltisec') {
+        $secrets = 'ltisecrets';
+    } else {
+        $secrets = 'toolsecrets';
+    }
+    unless (exists($currsec->{'rules'})) {
+        $currsec->{'rules'} = {};
+    }
+    &password_rule_changes($secrets,$newsec->{'rules'},$currsec->{'rules'},$secchanges);
+
+    my @ids=&Apache::lonnet::current_machine_ids();
+    my %servers = &Apache::lonnet::get_servers($dom,'library');
+
+    foreach my $hostid (keys(%servers)) {
+        if (($hostid ne '') && (grep(/^\Q$hostid\E$/, at ids))) {
+            my $newkey;
+            my $keyitem = 'form.'.$context.'_privkey_'.$hostid;
+            if (exists($env{$keyitem})) {
+                $env{$keyitem} =~ s/(`)/'/g;
+                if ($keyset{$hostid}) {
+                    if ($env{'form.'.$context.'_changeprivkey_'.$hostid}) {
+                        if ($env{$keyitem} ne '') {
+                            $secchanges->{'private'} = 1;
+                            $newkeyset->{$hostid} = $env{$keyitem};
+                        }
                     }
-                } else {
-                    if ($env{'form.ltitools_add_'.$item} ne '') {
-                        $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
+                } elsif ($env{$keyitem} ne '') {
+                    unless (grep(/^\Q$hostid\E$/,@{$newsec->{'private'}{'keys'}})) {
+                        push(@{$newsec->{'private'}{'keys'}},$hostid);
                     }
+                    $secchanges->{'private'} = 1;
+                    $newkeyset->{$hostid} = $env{$keyitem};
                 }
             }
-            if ($env{'form.ltitools_add_target'} eq 'window') {
-                $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
-            } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
-                $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
+        }
+    }
+}
+
+sub store_security {
+    my ($dom,$context,$secchanges,$newkeyset,$keystore,$lastactref) = @_;
+    return unless ((ref($secchanges) eq 'HASH') && (ref($newkeyset) eq 'HASH') &&
+                   (ref($keystore) eq 'HASH'));
+    if (keys(%{$secchanges})) {
+        if ($secchanges->{'private'}) {
+            my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
+            foreach my $hostid (keys(%{$newkeyset})) {
+                my $storehash = {
+                                   key => $newkeyset->{$hostid},
+                                   who => $env{'user.name'}.':'.$env{'user.domain'},
+                                };
+                $keystore->{$hostid} = &Apache::lonnet::store_dom($storehash,$context,'private',
+                                                                  $dom,$hostid);
+            }
+        }
+        if (ref($lastactref) eq 'HASH') {
+            if (($secchanges->{'encrypt'}) || ($secchanges->{'private'})) {
+                $lastactref->{'domdefaults'} = 1;
+            }
+        }
+    }
+}
+
+sub lti_security_results {
+    my ($context,$secchanges,$newsec,$newkeyset,$keystore) = @_;
+    my $output;
+    foreach my $item (keys(%{$secchanges})) {
+        if ($item eq 'encrypt') {
+            my %encrypted;
+            if ($context eq 'lti') {
+                %encrypted = (
+                              crs  => {
+                                        on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
+                                        off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
+                                      },
+                              dom => {
+                                       on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
+                                       off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
+                                     },
+                              consumers => {
+                                             on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
+                                             off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
+                                           },
+                             );
             } else {
-                $confhash{$newid}{'display'}{'target'} = 'iframe';
+                %encrypted = (
+                              crs  => {
+                                        on => &mt('Encryption of stored external tool secrets defined in courses enabled'),
+                                        off => &mt('Encryption of stored external tool secrets defined in courses disabled'),
+                                      },
+                              dom => {
+                                       on => &mt('Encryption of stored external tool secrets defined in domain enabled'),
+                                       off => &mt('Encryption of stored external tool secrets defined in domain disabled'),
+                                     },
+                             );
+
             }
-            foreach my $item ('passback','roster') {
-                if ($env{'form.ltitools_'.$item.'_add'}) {
-                    $confhash{$newid}{$item} = 1;
-                    if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
-                        my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
-                        $lifetime =~ s/^\s+|\s+$//g;
-                        if ($lifetime =~ /^\d+\.?\d*$/) {
-                            $confhash{$newid}{$item.'valid'} = $lifetime;
-                        }
-                    }
-                }
+            my @types= ('crs','dom');
+            if ($context eq 'lti') {
+                push(@types,'consumers');
             }
-            if ($env{'form.ltitools_add_image.filename'} ne '') {
-                my ($imageurl,$error) =
-                    &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
-                                            $configuserok,$switchserver,$author_ok);
-                if ($imageurl) {
-                    $confhash{$newid}{'image'} = $imageurl;
-                }
-                if ($error) {
-                    &Apache::lonnet::logthis($error);
-                    $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
+            foreach my $type (@types) {
+                my $shown = $encrypted{$type}{'off'};
+                if (ref($newsec->{$item}) eq 'HASH') {
+                    if ($newsec->{$item}{$type}) {
+                        $shown = $encrypted{$type}{'on'};
+                    }
                 }
+                $output .= '<li>'.$shown.'</li>';
             }
-            my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
-            foreach my $field (@fields) {
-                if ($possfield{$field}) {
-                    if ($field eq 'roles') {
-                        foreach my $role (@courseroles) {
-                            my $choice = $env{'form.ltitools_add_roles_'.$role};
-                            if (($choice ne '') && ($posslti{$choice})) {
-                                $confhash{$newid}{'roles'}{$role} = $choice;
-                                if ($role eq 'cc') {
-                                    $confhash{$newid}{'roles'}{'co'} = $choice; 
-                                }
-                            }
-                        }
-                    } else {
-                        $confhash{$newid}{'fields'}{$field} = 1;
-                    }
+        } elsif ($item eq 'rules') {
+            my %titles = &Apache::lonlocal::texthash(
+                                      min   => 'Minimum password length',
+                                      max   => 'Maximum password length',
+                                      chars => 'Required characters',
+                         );
+            foreach my $rule ('min','max') {
+                if ($newsec->{rules}{$rule} eq '') {
+                    if ($rule eq 'min') {
+                        $output .= '<li>'.&mt('[_1] not set.',$titles{$rule});
+                                   ' '.&mt('Default of [_1] will be used',
+                                           $Apache::lonnet::passwdmin).'</li>';
+                    } else {
+                        $output .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
+                    }
+                } else {
+                    $output .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newsec->{rules}{$rule}).'</li>';
+                }
+            }
+            if (ref($newsec->{'rules'}{'chars'}) eq 'ARRAY') {
+                if (@{$newsec->{'rules'}{'chars'}} > 0) {
+                    my %rulenames = &Apache::lonlocal::texthash(
+                                             uc => 'At least one upper case letter',
+                                             lc => 'At least one lower case letter',
+                                             num => 'At least one number',
+                                             spec => 'At least one non-alphanumeric',
+                                    );
+                    my $needed = '<ul><li>'.
+                                 join('</li><li>',map {$rulenames{$_} } @{$newsec->{'rules'}{'chars'}}).
+                                 '</li></ul>';
+                    $output .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
+                } else {
+                    $output .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
                 }
+            } else {
+                $output .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
             }
-            if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
-                if ($confhash{$newid}{'fields'}{'user'}) {
-                    if ($env{'form.ltitools_userincdom_add'}) {
-                        $confhash{$newid}{'incdom'} = 1;
+        } elsif ($item eq 'private') {
+            if (keys(%{$newkeyset})) {
+                foreach my $hostid (sort(keys(%{$newkeyset}))) {
+                    if ($keystore->{$hostid} eq 'ok') {
+                        $output .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
                     }
                 }
             }
-            my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
-            foreach my $item (@courseconfig) {
-                $confhash{$newid}{'crsconf'}{$item} = 1;
-            }
-            if ($env{'form.ltitools_add_custom'}) {
-                my $name = $env{'form.ltitools_add_custom_name'};
-                my $value = $env{'form.ltitools_add_custom_value'};
-                $value =~ s/(`)/'/g;
-                $name =~ s/(`)/'/g;
-                $confhash{$newid}{'custom'}{$name} = $value;
-            }
-        } else {
-            my $error = &mt('Failed to acquire unique ID for new external tool');   
-            $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
+        } elsif ($item eq 'linkprot') {
+            next;
         }
     }
-    if (ref($domconfig{$action}) eq 'HASH') {
-        my %deletions;
-        my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
-        if (@todelete) {
-            map { $deletions{$_} = 1; } @todelete;
-        }
-        my %customadds;
-        my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
-        if (@newcustom) {
-            map { $customadds{$_} = 1; } @newcustom;
-        } 
-        my %imgdeletions;
-        my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
-        if (@todeleteimages) {
-            map { $imgdeletions{$_} = 1; } @todeleteimages;
-        }
-        my $maxnum = $env{'form.ltitools_maxnum'};
-        for (my $i=0; $i<=$maxnum; $i++) {
-            my $itemid = $env{'form.ltitools_id_'.$i};
-            $itemid =~ s/\D+//g;
-            if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
-                if ($deletions{$itemid}) {
-                    if ($domconfig{$action}{$itemid}{'image'}) {
-                        #FIXME need to obsolete item in RES space
-                    }
-                    $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
-                    next;
-                } else {
-                    my $newpos = $env{'form.ltitools_'.$itemid};
-                    $newpos =~ s/\D+//g;
-                    foreach my $item ('title','url','lifetime') {
-                        $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
-                        if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
-                            $changes{$itemid} = 1;
-                        }
-                    }
-                    foreach my $item ('key','secret') {
-                        $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
-                        if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
-                            $changes{$itemid} = 1;
-                        }
-                    }
-                    if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
-                        $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
-                    }
-                    if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
-                        $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
-                    }
-                    if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
-                        $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
-                    } else {
-                        $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
-                    }
-                    if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
-                        if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
-                            $changes{$itemid} = 1;
-                        }
-                    } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
-                        $changes{$itemid} = 1;
-                    }
-                    foreach my $size ('width','height') {
-                        $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
-                        $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
-                        if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
-                            $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
-                            if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
-                                if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
-                                    $changes{$itemid} = 1;
-                                }
-                            } else {
-                                $changes{$itemid} = 1;
-                            }
-                        } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
-                            if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
-                                $changes{$itemid} = 1;
-                            }
-                        }
-                    }
-                    foreach my $item ('linktext','explanation') {
-                        $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
-                        $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
-                        if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
-                            $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
-                            if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
-                                if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
-                                    $changes{$itemid} = 1;
-                                }
-                            } else {
-                                $changes{$itemid} = 1;
-                            }
-                        } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
-                            if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
-                                $changes{$itemid} = 1;
-                            }
-                        }
-                    }
-                    if ($env{'form.ltitools_target_'.$i} eq 'window') {
-                        $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
-                    } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
-                        $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
-                    } else {
-                        $confhash{$itemid}{'display'}{'target'} = 'iframe';
-                    }
-                    if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
-                        if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
-                            $changes{$itemid} = 1;
-                        }
-                    } else {
-                        $changes{$itemid} = 1;
-                    }
-                    foreach my $extra ('passback','roster') {
-                        if ($env{'form.ltitools_'.$extra.'_'.$i}) {
-                            $confhash{$itemid}{$extra} = 1;
-                            if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
-                                my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
-                                $lifetime =~ s/^\s+|\s+$//g;
-                                if ($lifetime =~ /^\d+\.?\d*$/) {
-                                    $confhash{$itemid}{$extra.'valid'} = $lifetime;
-                                }
-                            }
-                        }
-                        if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
-                            $changes{$itemid} = 1;
-                        }
-                        if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
-                            $changes{$itemid} = 1;
-                        }
-                    }
-                    my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
-                    foreach my $item ('label','title','target','linktext','explanation','append') {
-                        if (grep(/^\Q$item\E$/, at courseconfig)) {
-                            $confhash{$itemid}{'crsconf'}{$item} = 1;
-                            if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
-                                if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
-                                    $changes{$itemid} = 1;
-                                }
-                            } else {
-                                $changes{$itemid} = 1;
-                            }
-                        }
-                    }
-                    my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
-                    foreach my $field (@fields) {
-                        if ($possfield{$field}) {
-                            if ($field eq 'roles') {
-                                foreach my $role (@courseroles) {
-                                    my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
-                                    if (($choice ne '') && ($posslti{$choice})) {
-                                        $confhash{$itemid}{'roles'}{$role} = $choice;
-                                        if ($role eq 'cc') {
-                                            $confhash{$itemid}{'roles'}{'co'} = $choice;
-                                        }
-                                    }
-                                    if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
-                                        if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
-                                            $changes{$itemid} = 1;
-                                        }
-                                    } elsif ($confhash{$itemid}{'roles'}{$role}) {
-                                        $changes{$itemid} = 1;
-                                    }
-                                }
-                            } else {
-                                $confhash{$itemid}{'fields'}{$field} = 1;
-                                if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
-                                    if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
-                                        $changes{$itemid} = 1;
-                                    }
-                                } else {
-                                    $changes{$itemid} = 1;
-                                }
-                            }
-                        }
-                    }
-                    if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
-                        if ($confhash{$itemid}{'fields'}{'user'}) {
-                            if ($env{'form.ltitools_userincdom_'.$i}) {
-                                $confhash{$itemid}{'incdom'} = 1;
-                            }
-                            if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
-                                $changes{$itemid} = 1;
-                            }
-                        }
-                    }
-                    $allpos[$newpos] = $itemid;
-                }
-                if ($imgdeletions{$itemid}) {
-                    $changes{$itemid} = 1;
-                    #FIXME need to obsolete item in RES space
-                } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
-                    my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
-                                                                 $itemid,$configuserok,$switchserver,
-                                                                 $author_ok);
-                    if ($imgurl) {
-                        $confhash{$itemid}{'image'} = $imgurl;
-                        $changes{$itemid} = 1;
-                    }
-                    if ($error) {
-                        &Apache::lonnet::logthis($error);
-                        $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
-                    }
-                } elsif ($domconfig{$action}{$itemid}{'image'}) {
-                    $confhash{$itemid}{'image'} =
-                       $domconfig{$action}{$itemid}{'image'};
-                }
-                if ($customadds{$i}) {
-                    my $name = $env{'form.ltitools_custom_name_'.$i};
-                    $name =~ s/(`)/'/g;
-                    $name =~ s/^\s+//;
-                    $name =~ s/\s+$//;
-                    my $value = $env{'form.ltitools_custom_value_'.$i};
-                    $value =~ s/(`)/'/g;
-                    $value =~ s/^\s+//;
-                    $value =~ s/\s+$//;
-                    if ($name ne '') {
-                        $confhash{$itemid}{'custom'}{$name} = $value;
-                        $changes{$itemid} = 1;
-                    }
-                }
-                my %customdels;
-                my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
-                if (@customdeletions) {
-                    $changes{$itemid} = 1;
-                }
-                map { $customdels{$_} = 1; } @customdeletions;
-                if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
-                    foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
-                        unless ($customdels{$key}) {
-                            if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
-                                $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
-                            }
-                            if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
-                                $changes{$itemid} = 1;
-                            }
-                        }
-                    }
-                }
-                unless ($changes{$itemid}) {
-                    foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
-                        if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
-                            if (ref($confhash{$itemid}{$key}) eq 'HASH') {
-                                foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
-                                    unless (exists($confhash{$itemid}{$key}{$innerkey})) {
-                                        $changes{$itemid} = 1;
-                                        last;
-                                    }
-                                }
-                            } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
-                                $changes{$itemid} = 1;
-                            }
-                        }
-                        last if ($changes{$itemid});
-                    }
-                }
-            }
-        }
-    }
-    if (@allpos > 0) {
-        my $idx = 0;
-        foreach my $itemid (@allpos) {
-            if ($itemid ne '') {
-                $confhash{$itemid}{'order'} = $idx;
-                if (ref($domconfig{$action}) eq 'HASH') {
-                    if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
-                        if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
-                            $changes{$itemid} = 1;
-                        }
-                    }
-                }
-                $idx ++;
-            }
-        }
-    }
-    my %ltitoolshash = (
-                          $action => { %confhash }
-                       );
-    my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
-                                             $dom);
-    if ($putresult eq 'ok') {
-        my %ltienchash = (
-                             $action => { %encconfig }
-                         );
-        &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
-        if (keys(%changes) > 0) {
-            my $cachetime = 24*60*60;
-            my %ltiall = %confhash;
-            foreach my $id (keys(%ltiall)) {
-                if (ref($encconfig{$id}) eq 'HASH') {
-                    foreach my $item ('key','secret') {
-                        $ltiall{$id}{$item} = $encconfig{$id}{$item};
-                    }
-                }
-            }
-            &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
-            if (ref($lastactref) eq 'HASH') {
-                $lastactref->{'ltitools'} = 1;
-            }
-            $resulttext = &mt('Changes made:').'<ul>';
-            my %bynum;
-            foreach my $itemid (sort(keys(%changes))) {
-                my $position = $confhash{$itemid}{'order'};
-                $bynum{$position} = $itemid;
-            }
-            foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
-                my $itemid = $bynum{$pos}; 
-                if (ref($confhash{$itemid}) ne 'HASH') {
-                    $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
-                } else {
-                    $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
-                    if ($confhash{$itemid}{'image'}) {
-                        $resulttext .= ' '.
-                                       '<img src="'.$confhash{$itemid}{'image'}.'"'.
-                                       ' alt="'.&mt('Tool Provider icon').'" />';
-                    }
-                    $resulttext .= '</li><ul>';
-                    my $position = $pos + 1;
-                    $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
-                    foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
-                        if ($confhash{$itemid}{$item} ne '') {
-                            $resulttext .= '<li>'.$lt{$item}.': '.$confhash{$itemid}{$item}.'</li>';
-                        }
-                    }
-                    if ($encconfig{$itemid}{'key'} ne '') {
-                        $resulttext .= '<li>'.$lt{'key'}.': '.$encconfig{$itemid}{'key'}.'</li>';
-                    }
-                    if ($encconfig{$itemid}{'secret'} ne '') {
-                        $resulttext .= '<li>'.$lt{'secret'}.': ';
-                        my $num = length($encconfig{$itemid}{'secret'});
-                        $resulttext .= ('*'x$num).'</li>';
-                    }
-                    $resulttext .= '<li>'.&mt('Configurable in course:');
-                    my @possconfig = ('label','title','target','linktext','explanation','append');
-                    my $numconfig = 0; 
-                    if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
-                        foreach my $item (@possconfig) {
-                            if ($confhash{$itemid}{'crsconf'}{$item}) {
-                                $numconfig ++;
-                                $resulttext .= ' "'.$lt{'crs'.$item}.'"';
-                            }
-                        }
-                    }
-                    if (!$numconfig) {
-                        $resulttext .= ' '.&mt('None');
-                    }
-                    $resulttext .= '</li>';
-                    foreach my $item ('passback','roster') {
-                        $resulttext .= '<li>'.$lt{$item}.' ';
-                        if ($confhash{$itemid}{$item}) {
-                            $resulttext .= &mt('Yes');
-                            if ($confhash{$itemid}{$item.'valid'}) {
-                                if ($item eq 'passback') {
-                                    $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
-                                                           $confhash{$itemid}{$item.'valid'});
-                                } else {
-                                    $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
-                                                           $confhash{$itemid}{$item.'valid'});
-                                }
-                            }
-                        } else {
-                            $resulttext .= &mt('No');
-                        }
-                        $resulttext .= '</li>';
-                    }
-                    if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
-                        my $displaylist;
-                        if ($confhash{$itemid}{'display'}{'target'}) {
-                            $displaylist = &mt('Display target').': '.
-                                           $confhash{$itemid}{'display'}{'target'}.',';
-                        }
-                        foreach my $size ('width','height') { 
-                            if ($confhash{$itemid}{'display'}{$size}) {
-                                $displaylist .= (' 'x2).$lt{$size}.': '.
-                                                $confhash{$itemid}{'display'}{$size}.',';
-                            }
-                        }
-                        if ($displaylist) {
-                            $displaylist =~ s/,$//;
-                            $resulttext .= '<li>'.$displaylist.'</li>';
-                        }
-                        foreach my $item ('linktext','explanation') {
-                            if ($confhash{$itemid}{'display'}{$item}) {
-                                $resulttext .= '<li>'.$lt{$item}.': '.$confhash{$itemid}{'display'}{$item}.'</li>';
-                            }
-                        }
-                    }
-                    if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
-                        my $fieldlist;
-                        foreach my $field (@allfields) {
-                            if ($confhash{$itemid}{'fields'}{$field}) {
-                                $fieldlist .= (' 'x2).$lt{$field}.',';
-                            }
-                        }
-                        if ($fieldlist) {
-                            $fieldlist =~ s/,$//;
-                            if ($confhash{$itemid}{'fields'}{'user'}) {
-                                if ($confhash{$itemid}{'incdom'}) {
-                                    $fieldlist .= ' ('.&mt('username:domain').')';
-                                } else {
-                                    $fieldlist .= ' ('.&mt('username').')';
-                                }
-                            }
-                            $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
-                        }
-                    }
-                    if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
-                        my $rolemaps;
-                        foreach my $role (@courseroles) {
-                            if ($confhash{$itemid}{'roles'}{$role}) {
-                                $rolemaps .= (' 'x2).&Apache::lonnet::plaintext($role,'Course').'='.
-                                             $confhash{$itemid}{'roles'}{$role}.',';
-                            }
-                        }
-                        if ($rolemaps) {
-                            $rolemaps =~ s/,$//; 
-                            $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
-                        }
-                    }
-                    if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
-                        my $customlist;
-                        if (keys(%{$confhash{$itemid}{'custom'}})) {
-                            foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
-                                $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.(' 'x2);
-                            } 
-                        }
-                        if ($customlist) {
-                            $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
-                        }
-                    } 
-                    $resulttext .= '</ul></li>';
-                }
-            }
-            $resulttext .= '</ul>';
-        } else {
-            $resulttext = &mt('No changes made.');
-        }
-    } else {
-        $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
-    }
-    if ($errors) {
-        $resulttext .= &mt('The following errors occurred: ').'<ul>'.
-                       $errors.'</ul>';
-    }
-    return $resulttext;
-}
-
-sub process_ltitools_image {
-    my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
-    my $filename = $env{'form.'.$caller.'.filename'};
-    my ($error,$url);
-    my ($width,$height) = (21,21);
-    if ($configuserok eq 'ok') {
-        if ($switchserver) {
-            $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
-                         $switchserver);
-        } elsif ($author_ok eq 'ok') {
-            my ($result,$imageurl,$madethumb) =
-                &publishlogo($r,'upload',$caller,$dom,$confname,
-                             "ltitools/$itemid/icon",$width,$height);
-            if ($result eq 'ok') {
-                if ($madethumb) {
-                    my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
-                    my $imagethumb = "$path/tn-".$imagefile;
-                    $url = $imagethumb;
-                } else {
-                    $url = $imageurl;
-                }
-            } else {
-                $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
-            }
-        } else {
-            $error = &mt("Upload of [_1] failed because an author role could not be assigned to a Domain Configuration user ([_2]) in domain: [_3].  Error was: [_4].",$filename,$confname,$dom,$author_ok);
-        }
-    } else {
-        $error = &mt("Upload of [_1] failed because a Domain Configuration user ([_2]) could not be created in domain: [_3].  Error was: [_4].",$filename,$confname,$dom,$configuserok);
-    }
-    return ($url,$error);
-}
-
-sub get_ltitools_id {
-    my ($cdom,$title) = @_;
-    # get lock on ltitools db
-    my $lockhash = {
-                      lock => $env{'user.name'}.
-                              ':'.$env{'user.domain'},
-                   };
-    my $tries = 0;
-    my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
-    my ($id,$error);
- 
-    while (($gotlock ne 'ok') && ($tries<10)) {
-        $tries ++;
-        sleep (0.1);
-        $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
-    }
-    if ($gotlock eq 'ok') {
-        my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
-        if ($currids{'lock'}) {
-            delete($currids{'lock'});
-            if (keys(%currids)) {
-                my @curr = sort { $a <=> $b } keys(%currids);
-                if ($curr[-1] =~ /^\d+$/) {
-                    $id = 1 + $curr[-1];
-                }
-            } else {
-                $id = 1;
-            }
-            if ($id) {
-                unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
-                    $error = 'nostore';
-                }
-            } else {
-                $error = 'nonumber';
-            }
-        }
-        my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
-    } else {
-        $error = 'nolock';
-    }
-    return ($id,$error);
-}
-
-sub modify_proctoring {
-    my ($r,$dom,$action,$lastactref,%domconfig) = @_;
-    my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
-    my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
-    my $confname = $dom.'-domainconfig';
-    my $servadm = $r->dir_config('lonAdmEMail');
-    my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
-    my %providernames = &proctoring_providernames();
-    my $maxnum = scalar(keys(%providernames));
-
-    my (%requserfields,%optuserfields,%defaults,%extended,%crsconf, at courseroles, at ltiroles);
-    my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
-    if (ref($requref) eq 'HASH') {
-        %requserfields = %{$requref};
-    }
-    if (ref($opturef) eq 'HASH') {
-        %optuserfields = %{$opturef};
-    }
-    if (ref($defref) eq 'HASH') {
-        %defaults = %{$defref};
-    }
-    if (ref($extref) eq 'HASH') {
-        %extended = %{$extref};
-    }
-    if (ref($crsref) eq 'HASH') {
-        %crsconf = %{$crsref};
-    }
-    if (ref($rolesref) eq 'ARRAY') {
-        @courseroles = @{$rolesref};
-    }
-    if (ref($ltiref) eq 'ARRAY') {
-        @ltiroles = @{$ltiref};
-    }
-
+    return $output;
+}
+
+sub modify_proctoring {
+    my ($r,$dom,$action,$lastactref,%domconfig) = @_;
+    my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
+    my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
+    my $confname = $dom.'-domainconfig';
+    my $servadm = $r->dir_config('lonAdmEMail');
+    my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
+    my %providernames = &proctoring_providernames();
+    my $maxnum = scalar(keys(%providernames));
+
+    my (%requserfields,%optuserfields,%defaults,%extended,%crsconf, at courseroles, at ltiroles);
+    my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
+    if (ref($requref) eq 'HASH') {
+        %requserfields = %{$requref};
+    }
+    if (ref($opturef) eq 'HASH') {
+        %optuserfields = %{$opturef};
+    }
+    if (ref($defref) eq 'HASH') {
+        %defaults = %{$defref};
+    }
+    if (ref($extref) eq 'HASH') {
+        %extended = %{$extref};
+    }
+    if (ref($crsref) eq 'HASH') {
+        %crsconf = %{$crsref};
+    }
+    if (ref($rolesref) eq 'ARRAY') {
+        @courseroles = @{$rolesref};
+    }
+    if (ref($ltiref) eq 'ARRAY') {
+        @ltiroles = @{$ltiref};
+    }
+
     if (ref($domconfig{$action}) eq 'HASH') {
         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
         if (@todeleteimages) {
@@ -15916,9 +14930,11 @@
             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
                          $switchserver);
         } elsif ($author_ok eq 'ok') {
+            my $modified = [];
             my ($result,$imageurl,$madethumb) =
-                &publishlogo($r,'upload',$caller,$dom,$confname,
-                             "proctoring/$provider/icon",$width,$height);
+                &Apache::lonconfigsettings::publishlogo($r,'upload',$caller,$dom,$confname,
+                                                        "proctoring/$provider/icon",$width,$height,
+                                                        '',$modified);
             if ($result eq 'ok') {
                 if ($madethumb) {
                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
@@ -15927,6 +14943,7 @@
                 } else {
                     $url = $imageurl;
                 }
+                &update_modify_urls($r,$modified);
             } else {
                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
             }
@@ -15963,81 +14980,9 @@
     map { $posscrstype{$_} = 1; } @coursetypes;
 
     my %menutitles = &ltimenu_titles();
+    my (%currltisec,%secchanges,%newltisec,%newltienc,%newkeyset);
 
-    my (%currltisec,%secchanges,%newltisec,%newltienc,%keyset,%newkeyset);
-    $newltisec{'private'}{'keys'} = [];
-    $newltisec{'encrypt'} = {};
-    $newltisec{'rules'} = {};
-    $newltisec{'linkprot'} = {};
-    if (ref($domconfig{'ltisec'}) eq 'HASH') {
-        %currltisec = %{$domconfig{'ltisec'}};
-        if (ref($currltisec{'linkprot'}) eq 'HASH') {
-            foreach my $id (keys(%{$currltisec{'linkprot'}})) {
-                unless ($id =~ /^\d+$/) {
-                    delete($currltisec{'linkprot'}{$id});
-                }
-            }
-        }
-        if (ref($currltisec{'private'}) eq 'HASH') {
-            if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
-                $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
-                map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
-            }
-        }
-    }
-    foreach my $item ('crs','dom','consumers') {
-        my $formelement;
-        if ($item eq 'consumers') { 
-            $formelement = 'form.ltisec_'.$item;
-        } else {
-            $formelement = 'form.ltisec_'.$item.'linkprot';
-        }
-        if ($env{$formelement}) {
-            $newltisec{'encrypt'}{$item} = 1;
-            if (ref($currltisec{'encrypt'}) eq 'HASH') {
-                unless ($currltisec{'encrypt'}{$item}) {
-                    $secchanges{'encrypt'} = 1;
-                }
-            } else {
-                $secchanges{'encrypt'} = 1;
-            }
-        } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
-            if ($currltisec{'encrypt'}{$item}) {
-                $secchanges{'encrypt'} = 1;
-            }
-        }
-    }
-    unless (exists($currltisec{'rules'})) {
-        $currltisec{'rules'} = {};
-    }
-    &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
-
-    my @ids=&Apache::lonnet::current_machine_ids();
-    my %servers = &Apache::lonnet::get_servers($dom,'library');
-   
-    foreach my $hostid (keys(%servers)) {
-        if (($hostid ne '') && (grep(/^\Q$hostid\E$/, at ids))) {
-            my $newkey;
-            my $keyitem = 'form.ltisec_privkey_'.$hostid;
-            if (exists($env{$keyitem})) {
-                $env{$keyitem} =~ s/(`)/'/g;
-                if ($keyset{$hostid}) {
-                    if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
-                        if ($env{$keyitem} ne '') {
-                            $secchanges{'private'} = 1;
-                            $newkeyset{$hostid} = $env{$keyitem};
-                        }
-                    }
-                } elsif ($env{$keyitem} ne '') {
-                    unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) { 
-                        push(@{$newltisec{'private'}{'keys'}},$hostid);
-                    }
-                    $secchanges{'private'} = 1;
-                    $newkeyset{$hostid} = $env{$keyitem};
-                }
-            }
-        }
-    }
+    &fetch_secrets($dom,'ltisec',\%domconfig,\%currltisec,\%secchanges,\%newltisec,\%newkeyset);
 
     my (%linkprotchg,$linkprotoutput,$is_home);
     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
@@ -16414,103 +15359,16 @@
     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
     if ($putresult eq 'ok') {
         my %keystore;
-        if (keys(%secchanges)) {
-            if ($secchanges{'private'}) {
-                my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
-                foreach my $hostid (keys(%newkeyset)) {
-                    my $storehash = {
-                                       key => $newkeyset{$hostid},
-                                       who => $env{'user.name'}.':'.$env{'user.domain'},
-                                    };
-                    $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
-                                                                    $dom,$hostid);
-                }
-            }
-            if (ref($lastactref) eq 'HASH') {
-                if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
-                    $lastactref->{'domdefaults'} = 1;
-                }
-            }
-        }
+        &store_security($dom,'lti',\%secchanges,\%newkeyset,\%keystore,$lastactref);
         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
         if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
             return &mt('No changes made.');
         }
         $resulttext = &mt('Changes made:').'<ul>';
         if (keys(%secchanges) > 0) {
-            foreach my $item (keys(%secchanges)) {
-                if ($item eq 'encrypt') {
-                    my %encrypted = (
-                              crs  => {
-                                        on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
-                                        off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
-                                      },
-                              dom => {
-                                       on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
-                                       off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
-                                     },
-                              consumers => {
-                                             on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
-                                             off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
-                                           },
-                            );
-                    foreach my $type ('crs','dom','consumers') {
-                        my $shown = $encrypted{$type}{'off'};
-                        if (ref($newltisec{$item}) eq 'HASH') {
-                            if ($newltisec{$item}{$type}) {
-                                $shown = $encrypted{$type}{'on'}; 
-                            }
-                        }
-                        $resulttext .= '<li>'.$shown.'</li>';
-                    } 
-                } elsif ($item eq 'rules') {
-                     my %titles = &Apache::lonlocal::texthash(
-                                      min   => 'Minimum password length',
-                                      max   => 'Maximum password length',
-                                      chars => 'Required characters',
-                     );
-                     foreach my $rule ('min','max') {
-                         if ($newltisec{rules}{$rule} eq '') {
-                             if ($rule eq 'min') {
-                                 $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
-                                                ' '.&mt('Default of [_1] will be used',
-                                                            $Apache::lonnet::passwdmin).'</li>';
-                             } else {
-                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
-                             }
-                         } else {
-                             $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
-                         }
-                     }
-                     if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
-                         if (@{$newltisec{'rules'}{'chars'}} > 0) {
-                             my %rulenames = &Apache::lonlocal::texthash(
-                                                 uc => 'At least one upper case letter',
-                                                 lc => 'At least one lower case letter',
-                                                 num => 'At least one number',
-                                                 spec => 'At least one non-alphanumeric',
-                                             );
-                             my $needed = '<ul><li>'.
-                                          join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
-                                          '</li></ul>';
-                             $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
-                         } else {
-                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
-                         }
-                     } else {
-                         $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
-                     }
-                } elsif ($item eq 'private') {
-                    if (keys(%newkeyset)) {
-                        foreach my $hostid (sort(keys(%newkeyset))) {
-                            if ($keystore{$hostid} eq 'ok') {
-                                $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
-                            }
-                        }
-                    }
-                } elsif ($item eq 'linkprot') {
-                    $resulttext .= $linkprotoutput;
-                }
+            $resulttext .= &lti_security_results('lti',\%secchanges,\%newltisec,\%newkeyset,\%keystore);
+            if (exists($secchanges{'linkprot'})) {
+                $resulttext .= $linkprotoutput;
             }
         }
         if (keys(%changes) > 0) {
@@ -18208,7 +17066,7 @@
                     $resulttext .= '</ul></li>';
                 }
             }
-            $resulttext .= '</ul>'; 
+            $resulttext .= '</ul>';
         } else {
             $resulttext = &mt('No changes made to user information settings');
         }
@@ -18395,12 +17253,15 @@
                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
             } else {
                 if ($author_ok eq 'ok') {
+                    my $modified = [];
                     my ($result,$customurl) =
-                        &publishlogo($r,'upload','passwords_customfile',$dom,
-                                     $confname,'customtext/resetpw','','',$customfn);
+                        &Apache::lonconfigsettings::publishlogo($r,'upload','passwords_customfile',$dom,
+                                                                $confname,'customtext/resetpw','','',$customfn,
+                                                                $modified);
                     if ($result eq 'ok') {
                         $newvalues{'resetcustom'} = $customurl;
                         $changes{'reset'} = 1;
+                        &update_modify_urls($r,$modified);
                     } else {
                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
                     }
@@ -18721,7 +17582,7 @@
     my (@rules,%staticdefaults);
     if ($prefix eq 'passwords') {
         @rules = ('min','max','expire','numsaved');
-    } elsif ($prefix eq 'secrets') {
+    } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
         @rules = ('min','max');
     }
     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
@@ -19656,7 +18517,7 @@
                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
                                             } else {
                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
-                                                                                              $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
+                                                                                              $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
                                             }
                                         }
                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
@@ -19674,7 +18535,7 @@
                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
                                             } else {
                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
-                                                                                                $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
+                                                                                                $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
                                             }
                                         }
                                     }
@@ -20415,12 +19276,15 @@
                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
             } else {
                 if ($author_ok eq 'ok') {
+                    my $modified = [];
                     my ($result,$scantronurl) =
-                        &publishlogo($r,'upload','scantronformat',$dom,
-                                     $confname,'scantron','','',$custom);
+                        &Apache::lonconfigsettings::publishlogo($r,'upload','scantronformat',$dom,
+                                                                $confname,'scantron','','',$custom,
+                                                                $modified);
                     if ($result eq 'ok') {
                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
                         $changes{'scantronformat'} = 1;
+                        &update_modify_urls($r,$modified);
                     } else {
                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
                     }
Index: loncom/interface/lonconfigsettings.pm
diff -u loncom/interface/lonconfigsettings.pm:1.67 loncom/interface/lonconfigsettings.pm:1.68
--- loncom/interface/lonconfigsettings.pm:1.67	Thu Sep  8 01:41:13 2022
+++ loncom/interface/lonconfigsettings.pm	Sun Mar 19 16:05:48 2023
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Handler to set domain-wide configuration settings
 #
-# $Id: lonconfigsettings.pm,v 1.67 2022/09/08 01:41:13 raeburn Exp $
+# $Id: lonconfigsettings.pm,v 1.68 2023/03/19 16:05:48 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -37,12 +37,13 @@
 use Apache::lonlocal;
 use Apache::lonparmset();
 use Apache::courseclassifier();
-use LONCAPA qw(:DEFAULT :match); 
+use LONCAPA qw(:DEFAULT :match);
+use File::Copy;
 
 sub print_header {
     my ($r,$phase,$context,$jscript,$container,$instcode,$dom,$confname,$values) = @_;
     my ($pagetitle,$brcrumtitle,$action,$call_category_check,$instcode_check,
-        $linkprot_check,$crstype, at actions, at code_order);
+        $linkprot_check,$ltitools_check,$crstype, at actions, at code_order);
     if ($phase eq 'display') {
         @actions = &Apache::loncommon::get_env_multiple('form.actions');
     }
@@ -116,8 +117,8 @@
 ENDSCRIPT
                 }
             }
-            if (($context eq 'course') && ($phase eq 'display') &&
-                (grep(/^linkprot$/, at actions))) {
+            if (($context eq 'course') && ((grep(/^linkprot$/, at actions)) ||
+                (grep(/^ltitools$/, at actions)))) {
                 my $allowed;
                 my $home = &Apache::lonnet::homeserver($confname,$dom);
                 unless ($home eq 'no_host') {
@@ -125,102 +126,12 @@
                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
                 }
                 if ($allowed) {
-                    my (@changeable, at settable);
-                    if (ref($values->{'linkprot'}) eq 'HASH') {
-                        if (keys(%{$values->{'linkprot'}})) {
-                            my @current = sort { $a <=> $b } keys(%{$values->{'linkprot'}});
-                            if (@current) {
-                                for (my $i=0; $i<@current; $i++) {
-                                    my $num = $current[$i];
-                                    if (ref($values->{'linkprot'}->{$num}) eq 'HASH') {
-                                        if ($values->{'linkprot'}->{$num}->{'usable'}) {
-                                            push(@changeable,$i);
-                                        } else {
-                                            push(@settable,$i);
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    }
-                    my ($numrules,$intargjs);
-$linkprot_check .= <<ENDJS;
-
-var linkprotradio = '';
-var secretinput = ''; 
-var posscheck = '';
-
-ENDJS
-                    if (@changeable) {
-                        foreach my $num (@changeable) {
-                            ($numrules,$intargjs) =
-                                &Apache::loncommon::passwd_validation_js('secretinput',$dom,'linkprot',$num);
-                            $linkprot_check .= <<ENDJS;
-posscheck = '';
-linkprotradio = document.display.elements['linkprot_changesecret_$num'];
-if (linkprotradio.length) {
-    for (var i=0; i<linkprotradio.length; i++) {
-        if (linkprotradio[i].checked) {
-            if (linkprotradio[i].value == 1) {
-                posscheck = 1;
-            }
-        }
-    }
-}
-
-ENDJS
-                            if ($numrules) {
-                                $linkprot_check .= <<ENDJS;
-if (posscheck) {
-    secretinput = document.display.elements['linkprot_secret_$num'].value;
-    $intargjs
-}
-
-ENDJS
-                            }
-                            $linkprot_check .= <<ENDJS;
-if (posscheck) {
-    uncheckLinkProtMakeVis('visible','$num');
-    document.display.elements['linkprot_secret_$num'].type = 'password';
-}
-
-ENDJS
-                        }
-                    }
-                    if (@settable) {
-                        foreach my $num (@settable) {
-                            ($numrules,$intargjs) =
-                                &Apache::loncommon::passwd_validation_js('secretinput',$dom,'linkprot',$num);
-                            if ($numrules) {
-                                $linkprot_check .= <<ENDJS;
-secretinput = document.display.elements['linkprot_secret_$num'].value;
-$intargjs
-
-ENDJS
-                            }
-                            $linkprot_check .= <<ENDJS;
-uncheckLinkProtMakeVis('visible','$num');
-document.display.elements['linkprot_secret_$num'].type = 'password';
-
-ENDJS
-                        }
+                    if (grep((/^linkprot$/, at actions))) {
+                        $linkprot_check = &ltisecret_js('linkprot',$dom,$values);
                     }
-                    ($numrules,$intargjs) =
-                        &Apache::loncommon::passwd_validation_js('secretinput',$dom,'linkprot','add');
-                    if ($numrules) {
-                        $linkprot_check .= <<ENDJS
-secretinput = document.display.elements['linkprot_secret_add'].value;
-if (document.display.elements['linkprot_add'].checked) {
-    $intargjs
-}
-
-ENDJS
+                    if (grep((/^ltitools$/, at actions))) {
+                        $ltitools_check = &ltisecret_js('ltitools',$dom,$values);
                     }
-                    $linkprot_check .= <<ENDJS;
-uncheckLinkProtMakeVis('visible','add');
-document.display.elements['linkprot_secret_add'].type = 'password';
-
-ENDJS
                 }
             }
         }
@@ -253,7 +164,7 @@
             return;
         }
     }
-    '.$instcode_check.$call_category_check.$linkprot_check.'
+    '.$instcode_check.$call_category_check.$linkprot_check.$ltitools_check.'
     formname.submit();
 }'."\n";
     if ($phase eq 'pickactions') {
@@ -263,6 +174,11 @@
     } elsif ($phase eq 'display') {
 	$js .= &Apache::lonhtmlcommon::color_picker();
         $js .= &color_pick_js()."\n";
+        if ($context eq 'domain') {
+            if (grep(/^(lti|ltitools)$/, at actions)) {
+                 $js .= &ltisec_javascript($dom)."\n";
+            }
+        }
     }
     $js .= &Apache::loncommon::viewport_size_js().'
 
@@ -346,9 +262,9 @@
                 }
                 my %servers = &Apache::lonnet::get_servers($dom,'library');
                 foreach my $server (keys(%servers)) {
-                    $onload .= "togglePrivKey(document.display,'$server');";
+                    $onload .= "togglePrivKey(document.display,'ltisec','$server');";
                 }
-                $onload .= "toggleLTIEncKey(document.display);";
+                $onload .= "toggleLTIEncKey(document.display,'ltisec');";
             }
             if (grep(/^ltitools$/, at actions)) {
                 $onload .= "toggleLTITools(document.display,'passback','add');".
@@ -364,6 +280,11 @@
                         }
                     }
                 }
+                my %servers = &Apache::lonnet::get_servers($dom,'library');
+                foreach my $server (keys(%servers)) {
+                    $onload .= "togglePrivKey(document.display,'toolsec','$server');";
+                }
+                $onload .= "toggleLTIEncKey(document.display,'toolsec');";
             }
             if (grep(/^wafproxy$/, at actions)) {
                 $onload .= "toggleWAF();checkWAF();updateWAF();";
@@ -394,7 +315,7 @@
                 $additem = {'add_entries' => \%loaditems,};
             }
         } elsif ($context eq 'course') {
-            my $onload;
+            my ($onload,$ishome,$crshome_checked);
             if (grep(/^courseinfo$/, at actions)) {
                 if (@code_order) {
                     $onload = "courseSet('','load');toggleCloners(document.display.cloners_instcode);";
@@ -410,11 +331,9 @@
                             my %domdefs = &Apache::lonnet::get_domain_defaults($dom);
                             $ltiauth = $domdefs{'crsltiauth'};
                         }
-                        my $ishome;
-                        my $chome = $env{'course.'.$env{'request.course.id'}.'.home'};
-                        unless (($chome eq 'no_host') || ($chome eq '')) {
-                            my @ids=&Apache::lonnet::current_machine_ids();
-                            foreach my $id (@ids) { if ($id eq $chome) { $ishome=1; } }
+                        unless ($crshome_checked) {
+                            $ishome = &is_home();
+                            $crshome_checked = 1;
                         }
                         my $posslti = scalar(keys(%{$values->{'linkprot'}}));
                         for (my $i=0; $i<=$posslti; $i++) {
@@ -424,7 +343,7 @@
                             }
                             if (ref($values->{'linkprot'}->{$i}) eq 'HASH') {
                                 if ($values->{'linkprot'}->{$i}->{'usable'}) {
-                                    $onload .= "toggleLinkProt(document.display,'$num','secret');";
+                                    $onload .= "toggleChgSecret(document.display,'$num','secret','linkprot');";
                                 }
                             }
                             $onload .= "toggleLinkProtExtra(document.display,'returnurl','divurlparam','1','inline-block','$num');";
@@ -433,7 +352,32 @@
                                            "toggleLinkProtExtra(document.display,'mapuser','userfield','other','inline-block','$num');";
                             }
                             if ($ishome) {
-                                $onload .= "uncheckLinkProtMakeVis('visible','$num');";
+                                $onload .= "uncheckLinkProtMakeVis('linkprot','visible','$num');";
+                            }
+                        }
+                    }
+                }
+            }
+            if (grep(/^ltitools$/, at actions)) {
+                if (ref($values) eq 'HASH') {
+                    if (ref($values->{'ltitools'}) eq 'HASH') {
+                        unless ($crshome_checked) {
+                            $ishome = &is_home();
+                            $crshome_checked = 1;
+                        }
+                        my $possltitools = scalar(keys(%{$values->{'ltitools'}}));
+                        for (my $i=0; $i<=$possltitools; $i++) {
+                            my $num = $i;
+                            if ($i == $possltitools) {
+                                $num = 'add';
+                            }
+                            if (ref($values->{'ltitools'}->{$i}) eq 'HASH') {
+                                if ($values->{'ltitools'}->{$i}->{'usable'}) {
+                                    $onload .= "toggleChgSecret(document.display,'$num','secret','ltitools');";
+                                }
+                            }
+                            if ($ishome) {
+                                $onload .= "uncheckLinkProtMakeVis('ltitools','visible','$num');";
                             }
                         }
                     }
@@ -470,6 +414,126 @@
     return;
 }
 
+sub ltisecret_js {
+    my ($name,$dom,$values) = @_;
+    return unless (ref($values) eq 'HASH');
+    my $js;
+    if (($name eq 'linkprot') || ($name eq 'ltitools')) {
+        my (@changeable, at settable);
+        if (ref($values->{$name}) eq 'HASH') {
+            if (keys(%{$values->{$name}})) {
+                my @current = sort { $a <=> $b } keys(%{$values->{$name}});
+                if (@current) {
+                    for (my $i=0; $i<@current; $i++) {
+                        my $num = $current[$i];
+                        if (ref($values->{$name}->{$num}) eq 'HASH') {
+                            if ($values->{$name}->{$num}->{'usable'}) {
+                                push(@changeable,$i);
+                            } else {
+                                push(@settable,$i);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        my ($numrules,$intargjs);
+$js .= <<ENDJS;
+
+var ${name}radio = '';
+var ${name}secretinput = '';
+var ${name}posscheck = '';
+
+ENDJS
+        if (@changeable) {
+            foreach my $num (@changeable) {
+                ($numrules,$intargjs) =
+                    &Apache::loncommon::passwd_validation_js($name.'secretinput',$dom,$name,$num);
+                $js .= <<"ENDJS";
+${name}posscheck = '';
+${name}radio = document.display.elements['${name}_changesecret_$num'];
+if (${name}radio.length) {
+    for (var i=0; i<${name}radio.length; i++) {
+        if (${name}radio[i].checked) {
+            if (${name}radio[i].value == 1) {
+                ${name}posscheck = 1;
+            }
+        }
+    }
+}
+
+ENDJS
+                if ($numrules) {
+                    $js .= <<"ENDJS";
+if (${name}posscheck) {
+    ${name}secretinput = document.display.elements['${name}_secret_$num'].value;
+    $intargjs
+}
+
+ENDJS
+                }
+                $js .= <<"ENDJS";
+if (${name}posscheck) {
+    uncheckLinkProtMakeVis('$name','visible','$num');
+    document.display.elements['${name}_secret_$num'].type = 'password';
+}
+
+ENDJS
+            }
+        }
+        if (@settable) {
+            foreach my $num (@settable) {
+                ($numrules,$intargjs) =
+                    &Apache::loncommon::passwd_validation_js($name.'secretinput',$dom,$name,$num);
+                if ($numrules) {
+                    $js .= <<ENDJS;
+${name}secretinput = document.display.elements['${name}_secret_$num'].value;
+$intargjs
+
+ENDJS
+                }
+                $js .= <<ENDJS;
+uncheckLinkProtMakeVis('$name','visible','$num');
+document.display.elements['${name}_secret_$num'].type = 'password';
+
+ENDJS
+            }
+        }
+        ($numrules,$intargjs) =
+            &Apache::loncommon::passwd_validation_js($name.'secretinput',$dom,$name,'add');
+        if ($numrules) {
+            $js .= <<ENDJS
+${name}secretinput = document.display.elements['${name}_add_secret'].value;
+if (document.display.elements['${name}_add'].checked) {
+    $intargjs
+}
+
+ENDJS
+        }
+        $js .= <<ENDJS;
+uncheckLinkProtMakeVis('$name','visible','add');
+document.display.elements['${name}_add_secret'].type = 'password';
+
+ENDJS
+    }
+    return $js;
+}
+
+sub is_home {
+    my $ishome;
+    my $chome = $env{'course.'.$env{'request.course.id'}.'.home'};
+    unless (($chome eq 'no_host') || ($chome eq '')) {
+        my @ids=&Apache::lonnet::current_machine_ids();
+        foreach my $id (@ids) {
+            if ($id eq $chome) {
+                $ishome=1;
+                last;
+            }
+        }
+    }
+    return $ishome;
+}
+
 sub print_footer {
     my ($r,$phase,$newphase,$button_text,$actions,$container,$parm_permission) = @_;
     $button_text = &mt($button_text);
@@ -610,7 +674,7 @@
     if ((ref($prefs_order) eq 'ARRAY') && (ref($prefs) eq 'HASH') && (ref($values) eq 'HASH')) { 
         if (@actions > 0) {
             my $rowsum = 0;
-            my (%output,%rowtotal, at items,$got_check_uncheck);
+            my (%output,%rowtotal, at items,$got_check_uncheck,$got_change_secret);
             foreach my $item (@{$prefs_order}) {
                 if (grep(/^\Q$item\E$/, at actions)) {
                     push(@items,$item);
@@ -652,21 +716,47 @@
                                     $settings = $inststatus;
                                 }
                             }
-                        } elsif ($item eq 'lti') {
-                            if (ref($values->{'ltisec'}) eq 'HASH') {
-                                if (ref($values->{'lti'}) eq 'HASH') {
-                                    $settings = {%{$values->{'lti'}},%{$values->{'ltisec'}}};
-                                } else {
-                                    $settings = $values->{'ltisec'};
+                        } elsif (($item eq 'lti') || ($item eq 'ltitools')) {
+                            unless ($got_change_secret) {
+                                $r->print('<script type="text/javascript">'."\n".
+                                          '// <![CDATA['."\n".
+                                          &change_secret_js()."\n".
+                                          '// ]]>'."\n".
+                                          '</script>'."\n");
+                                $got_change_secret = 1;
+                            }
+                            if ($item eq 'lti') {
+                                if (ref($values->{'ltisec'}) eq 'HASH') {
+                                    if (ref($values->{'lti'}) eq 'HASH') {
+                                        $settings = {%{$values->{'lti'}},%{$values->{'ltisec'}}};
+                                    } else {
+                                        $settings = $values->{'ltisec'};
+                                    }
+                                } elsif (ref($values->{'lti'}) eq 'HASH') {
+                                    $settings = $values->{'lti'};
+                                }
+                            } elsif ($item eq 'ltitools') {
+                                if (ref($values->{'toolsec'}) eq 'HASH') {
+                                    if (ref($values->{'ltitools'}) eq 'HASH') {
+                                        $settings = {%{$values->{'ltitools'}},%{$values->{'toolsec'}}};
+                                    } else {
+                                        $settings = $values->{'toolsec'};
+                                    }
                                 }
-                            } elsif (ref($values->{'lti'}) eq 'HASH') {
-                                $settings = $values->{'lti'};
                             }
                         }
                         ($output{$item},$rowtotal{$item}) =
                             &Apache::domainprefs::print_config_box($r,$dom,$confname,
                                 $phase,$item,$prefs->{$item},$settings);
                     } else {
+                        unless ($got_change_secret) {
+                            $r->print('<script type="text/javascript">'."\n".
+                                      '// <![CDATA['."\n".
+                                      &change_secret_js()."\n".
+                                      '// ]]>'."\n".
+                                      '</script>'."\n");
+                            $got_change_secret = 1;
+                        }
                         ($output{$item},$rowtotal{$item}) =
                             &Apache::courseprefs::print_config_box($r,$dom,$confname,$phase,
                                 $item,$prefs->{$item},$values,$allitems,$crstype,$parm_permission);
@@ -801,6 +891,274 @@
     return $output;
 }
 
+sub ltisec_javascript {
+    my ($dom) = @_;
+    my %servers = &Apache::lonnet::get_servers($dom,'library');
+    my $primary = &Apache::lonnet::domain($dom,'primary');
+    my $course_servers = "'".join("','",keys(%servers))."'";
+    my $output = <<"ENDJS";
+
+function toggleLTIEncKey(form,context) {
+    var shownhosts = new Array();
+    var hiddenhosts = new Array();
+    var forcourse = new Array($course_servers);
+    var fromdomain = '$primary';
+    var crsradio;
+    if (context == 'ltisec') {
+        crsradio = form.elements['ltisec_crslinkprot'];
+    } else {
+        crsradio = form.elements['toolsec_crs'];
+    }
+    if (crsradio.length) {
+        for (var i=0; i<crsradio.length; i++) {
+            if (crsradio[i].checked) {
+                if (crsradio[i].value == 1) {
+                    if (forcourse.length > 0) {
+                        for (var j=0; j<forcourse.length; j++) {
+                            if (!shownhosts.includes(forcourse[j])) {
+                                shownhosts.push(forcourse[j]);
+                            }
+                        }
+                    }
+                } else {
+                    if (forcourse.length > 0) {
+                        for (var j=0; j<forcourse.length; j++) {
+                            if (!hiddenhosts.includes(forcourse[j])) {
+                                hiddenhosts.push(forcourse[j]);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+    var domradio;
+    if (context == 'ltisec') {
+        domradio = form.elements['ltisec_domlinkprot'];
+    } else {
+        domradio = form.elements['toolsec_dom'];
+    }
+    if (domradio.length) {
+        for (var i=0; i<domradio.length; i++) {
+            if (domradio[i].checked) {
+                if (domradio[i].value == 1) {
+                    if (!shownhosts.includes(fromdomain)) {
+                        shownhosts.push(fromdomain);
+                    }
+                } else {
+                    if (!hiddenhosts.includes(fromdomain)) {
+                        hiddenhosts.push(fromdomain);
+                    }
+                }
+            }
+        }
+    }
+    if (context == 'ltisec') {
+        var consumersradio = form.elements['ltisec_consumers'];
+        if (consumersradio.length) {
+            for (var i=0; i<consumersradio.length; i++) {
+                if (consumersradio[i].checked) {
+                    if (consumersradio[i].value == 1) {
+                        if (!shownhosts.includes(fromdomain)) {
+                            shownhosts.push(fromdomain);
+                        }
+                    } else {
+                        if (!hiddenhosts.includes(fromdomain)) {
+                            hiddenhosts.push(fromdomain);
+                        }
+                    }
+                }
+            }
+        }
+    }
+    if (shownhosts.length > 0) {
+        for (var i=0; i<shownhosts.length; i++) {
+            if (document.getElementById(context+'_info_'+shownhosts[i])) {
+                document.getElementById(context+'_info_'+shownhosts[i]).style.display = 'block';
+            }
+        }
+        if (document.getElementById(context+'_noprivkey')) {
+            document.getElementById(context+'_noprivkey').style.display = 'none';
+        }
+    } else {
+        if (document.getElementById(context+'_noprivkey')) {
+            document.getElementById(context+'_noprivkey').style.display = 'inline-block';
+        }
+    }
+    if (hiddenhosts.length > 0) {
+        for (var i=0; i<hiddenhosts.length; i++) {
+            if (!shownhosts.includes(hiddenhosts[i])) {
+                if (document.getElementById(context+'_info_'+hiddenhosts[i])) {
+                    document.getElementById(context+'_info_'+hiddenhosts[i]).style.display = 'none';
+                }
+            }
+        }
+    }
+    return;
+}
+
+function togglePrivKey(form,context,hostid) {
+    var radioname = '';
+    var currdivid = '';
+    var newdivid = '';
+    if ((document.getElementById(context+'_divcurrprivkey_'+hostid)) &&
+        (document.getElementById(context+'_divchgprivkey_'+hostid))) {
+        currdivid = document.getElementById(context+'_divcurrprivkey_'+hostid);
+        newdivid = document.getElementById(context+'_divchgprivkey_'+hostid);
+        radioname = form.elements[context+'_changeprivkey_'+hostid];
+        if (radioname) {
+            if (radioname.length > 0) {
+                var setvis;
+                for (var i=0; i<radioname.length; i++) {
+                    if (radioname[i].checked == true) {
+                        if (radioname[i].value == 1) {
+                            newdivid.style.display = 'inline-block';
+                            currdivid.style.display = 'none';
+                            setvis = 1;
+                        }
+                        break;
+                    }
+                }
+                if (!setvis) {
+                    newdivid.style.display = 'none';
+                    currdivid.style.display = 'inline-block';
+                }
+            }
+        }
+    }
+    return;
+}
+
+ENDJS
+
+}
+
+sub ltitools_javascript {
+    my ($settings) = @_;
+    my $togglejs = &ltitools_toggle_js();
+    unless (ref($settings) eq 'HASH') {
+        return $togglejs;
+    }
+    my (%ordered,$total,%jstext);
+    $total = 0;
+    foreach my $item (keys(%{$settings})) {
+        if (ref($settings->{$item}) eq 'HASH') {
+            my $num = $settings->{$item}{'order'};
+            $ordered{$num} = $item;
+        }
+    }
+    $total = scalar(keys(%{$settings}));
+    my @jsarray = ();
+    foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
+        push(@jsarray,$ordered{$item});
+    }
+    my $jstext = '    var ltitools = Array('."'".join("','", at jsarray)."'".');'."\n";
+    return <<"ENDSCRIPT";
+<script type="text/javascript">
+// <![CDATA[
+function reorderLTITools(form,item) {
+    var changedVal;
+$jstext
+    var newpos = 'ltitools_add_pos';
+    var maxh = 1 + $total;
+    var current = new Array;
+    var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
+    if (item == newpos) {
+        changedVal = newitemVal;
+    } else {
+        changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
+        current[newitemVal] = newpos;
+    }
+    for (var i=0; i<ltitools.length; i++) {
+        var elementName = 'ltitools_'+ltitools[i];
+        if (elementName != item) {
+            if (form.elements[elementName]) {
+                var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
+                current[currVal] = elementName;
+            }
+        }
+    }
+    var oldVal;
+    for (var j=0; j<maxh; j++) {
+        if (current[j] == undefined) {
+            oldVal = j;
+        }
+    }
+    if (oldVal < changedVal) {
+        for (var k=oldVal+1; k<=changedVal ; k++) {
+           var elementName = current[k];
+           form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
+        }
+    } else {
+        for (var k=changedVal; k<oldVal; k++) {
+            var elementName = current[k];
+            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
+        }
+    }
+    return;
+}
+
+// ]]>
+</script>
+
+$togglejs
+
+ENDSCRIPT
+}
+
+sub ltitools_toggle_js {
+    return <<"ENDSCRIPT";
+<script type="text/javascript">
+// <![CDATA[
+
+function toggleLTITools(form,setting,item) {
+    var radioname = '';
+    var divid = '';
+    if ((setting == 'passback') || (setting == 'roster')) {
+        radioname = 'ltitools_'+setting+'_'+item;
+        divid = 'ltitools_'+setting+'time_'+item;
+        var num = form.elements[radioname].length;
+        if (num) {
+            var setvis = '';
+            for (var i=0; i<num; i++) {
+                if (form.elements[radioname][i].checked) {
+                    if (form.elements[radioname][i].value == '1') {
+                        if (document.getElementById(divid)) {
+                            document.getElementById(divid).style.display = 'inline-block';
+                        }
+                        setvis = 1;
+                    }
+                    break;
+                }
+            }
+        }
+        if (!setvis) {
+            if (document.getElementById(divid)) {
+                document.getElementById(divid).style.display = 'none';
+            }
+        }
+    }
+    if (setting == 'user') {
+        divid = 'ltitools_'+setting+'_div_'+item;
+        var checkid = 'ltitools_'+setting+'_field_'+item;
+        if (document.getElementById(divid)) {
+            if (document.getElementById(checkid)) {
+                if (document.getElementById(checkid).checked) {
+                    document.getElementById(divid).style.display = 'inline-block';
+                } else {
+                    document.getElementById(divid).style.display = 'none';
+                }
+            }
+        }
+    }
+    return;
+}
+// ]]>
+</script>
+
+ENDSCRIPT
+}
+
 sub get_crumb_text {
     my %brcrumbtext = (
                        domain => 'Domain Settings',
@@ -809,4 +1167,271 @@
     return %brcrumbtext;
 }
 
+sub publishlogo {
+    my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,
+        $savefileas,$modified) = @_;
+    my ($output,$fname,$logourl,$madethumb);
+    if ($action eq 'upload') {
+        $fname=$env{'form.'.$formname.'.filename'};
+        chop($env{'form.'.$formname});
+    } else {
+        ($fname) = ($formname =~ /([^\/]+)$/);
+    }
+    if ($savefileas ne '') {
+        $fname = $savefileas;
+    }
+    $fname=&Apache::lonnet::clean_filename($fname);
+# See if there is anything left
+    unless ($fname) { return ('error: no uploaded file'); }
+    $fname="$subdir/$fname";
+    my $docroot=$r->dir_config('lonDocRoot');
+    my $filepath="$docroot/priv";
+    my $relpath = "$dom/$confname";
+    my ($fnamepath,$file,$fetchthumb);
+    $file=$fname;
+    if ($fname=~m|/|) {
+        ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
+    }
+    my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
+    my $count;
+    for ($count=5;$count<=$#parts;$count++) {
+        $filepath.="/$parts[$count]";
+        if ((-e $filepath)!=1) {
+            mkdir($filepath,02770);
+        }
+    }
+    # Check for bad extension and disallow upload
+    if ($file=~/\.(\w+)$/ &&
+        (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
+        $output =
+            &mt('Invalid file extension ([_1]) - reserved for internal use.',$1);
+    } elsif ($file=~/\.(\w+)$/ &&
+        !defined(&Apache::loncommon::fileembstyle($1))) {
+        $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
+    } elsif ($file=~/\.(\d+)\.(\w+)$/) {
+        $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
+    } elsif (-d "$filepath/$file") {
+        $output = &mt('Filename is a directory name - rename the file and re-upload');
+    } else {
+        my $source = $filepath.'/'.$file;
+        my $logfile;
+        if (!open($logfile,">>",$source.'.log')) {
+            return (&mt('No write permission to Authoring Space'));
+        }
+        print $logfile
+"\n================= Publish ".localtime()." ================\n".
+$env{'user.name'}.':'.$env{'user.domain'}."\n";
+# Save the file
+        if (!open(FH,">",$source)) {
+            &Apache::lonnet::logthis('Failed to create '.$source);
+            return (&mt('Failed to create file'));
+        }
+        if ($action eq 'upload') {
+            if (!print FH ($env{'form.'.$formname})) {
+                &Apache::lonnet::logthis('Failed to write to '.$source);
+                return (&mt('Failed to write file'));
+            }
+        } else {
+            my $original = &Apache::lonnet::filelocation('',$formname);
+            if(!copy($original,$source)) {
+                &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
+                return (&mt('Failed to write file'));
+            }
+        }
+        close(FH);
+        chmod(0660, $source); # Permissions to rw-rw---.
+
+        my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
+        my $copyfile=$targetdir.'/'.$file;
+
+        my @parts=split(/\//,$targetdir);
+        my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
+        for (my $count=5;$count<=$#parts;$count++) {
+            $path.="/$parts[$count]";
+            if (!-e $path) {
+                print $logfile "\nCreating directory ".$path;
+                mkdir($path,02770);
+            }
+        }
+        my $versionresult;
+        if (-e $copyfile) {
+            $versionresult = &logo_versioning($targetdir,$file,$logfile);
+        } else {
+            $versionresult = 'ok';
+        }
+        if ($versionresult eq 'ok') {
+            if (copy($source,$copyfile)) {
+                print $logfile "\nCopied original source to ".$copyfile."\n";
+                $output = 'ok';
+                $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
+                if (ref($modified) eq 'ARRAY') {
+                    push(@{$modified},[$copyfile,$source]);
+                }
+                my $metaoutput =
+                    &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
+            } else {
+                print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
+                $output = &mt('Failed to copy file to RES space').", $!";
+            }
+            if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
+                my $inputfile = $filepath.'/'.$file;
+                my $outfile = $filepath.'/'.'tn-'.$file;
+                my ($fullwidth,$fullheight) = &Apache::lonnet::check_dimensions($inputfile);
+                if ($fullwidth ne '' && $fullheight ne '') {
+                    if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
+                        my $thumbsize = $thumbwidth.'x'.$thumbheight;
+                        my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
+                        system({$args[0]} @args);
+                        chmod(0660, $filepath.'/tn-'.$file);
+                        if (-e $outfile) {
+                            my $copyfile=$targetdir.'/tn-'.$file;
+                            if (copy($outfile,$copyfile)) {
+                                print $logfile "\nCopied source to ".$copyfile."\n";
+                                my $thumb_metaoutput =
+                                    &write_metadata($dom,$confname,$formname,
+                                                    $targetdir,'tn-'.$file,$logfile);
+                                if (ref($modified) eq 'ARRAY') {
+                                    push(@{$modified},[$copyfile,$outfile]);
+                                }
+                                $madethumb = 1;
+                            } else {
+                                print $logfile "\nUnable to write ".$copyfile.
+                                               ':'.$!."\n";
+                            }
+                        }
+                    }
+                }
+            }
+        } else {
+            $output = $versionresult;
+        }
+    }
+    return ($output,$logourl,$madethumb);
+}
+
+sub logo_versioning {
+    my ($targetdir,$file,$logfile) = @_;
+    my $target = $targetdir.'/'.$file;
+    my ($maxversion,$fn,$extn,$output);
+    $maxversion = 0;
+    if ($file =~ /^(.+)\.(\w+)$/) {
+        $fn=$1;
+        $extn=$2;
+    }
+    opendir(DIR,$targetdir);
+    while (my $filename=readdir(DIR)) {
+        if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
+            $maxversion=($1>$maxversion)?$1:$maxversion;
+        }
+    }
+    $maxversion++;
+    print $logfile "\nCreating old version ".$maxversion."\n";
+    my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
+    if (copy($target,$copyfile)) {
+        print $logfile "Copied old target to ".$copyfile."\n";
+        $copyfile=$copyfile.'.meta';
+        if (copy($target.'.meta',$copyfile)) {
+            print $logfile "Copied old target metadata to ".$copyfile."\n";
+            $output = 'ok';
+        } else {
+            print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
+            $output = &mt('Failed to copy old meta').", $!, ";
+        }
+    } else {
+        print $logfile "Unable to write ".$copyfile.':'.$!."\n";
+        $output = &mt('Failed to copy old target').", $!, ";
+    }
+    return $output;
+}
+
+sub write_metadata {
+    my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
+    my (%metadatafields,%metadatakeys,$output);
+    $metadatafields{'title'}=$formname;
+    $metadatafields{'creationdate'}=time;
+    $metadatafields{'lastrevisiondate'}=time;
+    $metadatafields{'copyright'}='public';
+    $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
+                                         $env{'user.domain'};
+    $metadatafields{'authorspace'}=$confname.':'.$dom;
+    $metadatafields{'domain'}=$dom;
+    {
+        print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
+        my $mfh;
+        if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
+            foreach (sort(keys(%metadatafields))) {
+                unless ($_=~/\./) {
+                    my $unikey=$_;
+                    $unikey=~/^([A-Za-z]+)/;
+                    my $tag=$1;
+                    $tag=~tr/A-Z/a-z/;
+                    print $mfh "\n\<$tag";
+                    foreach (split(/\,/,$metadatakeys{$unikey})) {
+                        my $value=$metadatafields{$unikey.'.'.$_};
+                        $value=~s/\"/\'\'/g;
+                        print $mfh ' '.$_.'="'.$value.'"';
+                    }
+                    print $mfh '>'.
+                        &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
+                            .'</'.$tag.'>';
+                }
+            }
+            $output = 'ok';
+            print $logfile "\nWrote metadata";
+            close($mfh);
+        } else {
+            print $logfile "\nFailed to open metadata file";
+            $output = &mt('Could not write metadata');
+        }
+    }
+    return $output;
+}
+
+sub change_secret_js {
+    return <<"ENDSCRIPT";
+function toggleChgSecret(form,num,item,name) {
+    var radioname = '';
+    var currdivid = '';
+    var newdivid = '';
+    if ((document.getElementById(name+'_divcurr'+item+'_'+num)) &&
+        (document.getElementById(name+'_divchg'+item+'_'+num))) {
+        currdivid = document.getElementById(name+'_divcurr'+item+'_'+num);
+        newdivid = document.getElementById(name+'_divchg'+item+'_'+num);
+        radioname = form.elements[name+'_change'+item+'_'+num];
+        if (radioname) {
+            if (radioname.length > 0) {
+                var setvis;
+                for (var i=0; i<radioname.length; i++) {
+                    if (radioname[i].checked == true) {
+                        if (radioname[i].value == 1) {
+                            newdivid.style.display = 'inline-block';
+                            currdivid.style.display = 'none';
+                            setvis = 1;
+                        }
+                        break;
+                    }
+                }
+                if (!setvis) {
+                    newdivid.style.display = 'none';
+                    currdivid.style.display = 'inline-block';
+                }
+            }
+        }
+    }
+    return;
+}
+
+function uncheckLinkProtMakeVis(name,item,num) {
+    if (document.getElementById(name+'_'+item+'_'+num)) {
+        var currtype = document.getElementById(name+'_'+item+'_'+num).type;
+        if (currtype.toLowerCase() == 'checkbox') {
+            document.getElementById(name+'_'+item+'_'+num).checked = false;
+        }
+    }
+    return;
+}
+ENDSCRIPT
+
+}
+
 1;
Index: loncom/lonnet/perl/lonnet.pm
diff -u loncom/lonnet/perl/lonnet.pm:1.1503 loncom/lonnet/perl/lonnet.pm:1.1504
--- loncom/lonnet/perl/lonnet.pm:1.1503	Sat Dec 31 14:09:00 2022
+++ loncom/lonnet/perl/lonnet.pm	Sun Mar 19 16:05:48 2023
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # TCP networking package
 #
-# $Id: lonnet.pm,v 1.1503 2022/12/31 14:09:00 raeburn Exp $
+# $Id: lonnet.pm,v 1.1504 2023/03/19 16:05:48 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -2698,7 +2698,8 @@
                                   'coursedefaults','usersessions',
                                   'requestauthor','selfenrollment',
                                   'coursecategories','ssl','autoenroll',
-                                  'trust','helpsettings','wafproxy','ltisec'],$domain);
+                                  'trust','helpsettings','wafproxy',
+                                  'ltisec','toolsec'],$domain);
     my @coursetypes = ('official','unofficial','community','textbook','placement');
     if (ref($domconfig{'defaults'}) eq 'HASH') {
         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
@@ -2884,7 +2885,18 @@
         }
         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
-                $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
+                $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
+            }
+        }
+    }
+    if (ref($domconfig{'toolsec'}) eq 'HASH') {
+        if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
+            $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
+            $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
+        }
+        if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
+            if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
+                $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
             }
         }
     }
@@ -4269,7 +4281,7 @@
 # input: $formname - the contents of the file are in $env{"form.$formname"}
 #                    the desired filename is in $env{"form.$formname.filename"}
 #        $context - possible values: coursedoc, existingfile, overwrite, 
-#                                    canceloverwrite, scantron or ''.
+#                                    canceloverwrite, scantron, toollogo  or ''.
 #                   if 'coursedoc': upload to the current course
 #                   if 'existingfile': write file to tmp/overwrites directory 
 #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
@@ -4281,8 +4293,8 @@
 #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 #        $allfiles - reference to hash for embedded objects
 #        $codebase - reference to hash for codebase of java objects
-#        $desuname - username for permanent storage of uploaded file
-#        $dsetudom - domain for permanaent storage of uploaded file
+#        $destuname - username for permanent storage of uploaded file
+#        $destudom - domain for permanaent storage of uploaded file
 #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 #        $resizewidth - width (pixels) to which to resize uploaded image
@@ -4492,11 +4504,24 @@
     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
         my $input = $filepath.'/'.$file;
         my $output = $filepath.'/'.'tn-'.$file;
+        my $makethumb; 
         my $thumbsize = $thumbwidth.'x'.$thumbheight;
-        my @args = ('convert','-sample',$thumbsize,$input,$output);
-        system({$args[0]} @args);
-        if (-e $filepath.'/'.'tn-'.$file) {
-            $fetchthumb  = 1; 
+        if ($context eq 'toollogo') {
+            my ($fullwidth,$fullheight) = &check_dimensions($input);
+            if ($fullwidth ne '' && $fullheight ne '') {
+                if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
+                    $makethumb = 1;
+                }
+            }
+        } else {
+            $makethumb = 1;
+        }
+        if ($makethumb) {
+            my @args = ('convert','-sample',$thumbsize,$input,$output);
+            system({$args[0]} @args);
+            if (-e $filepath.'/'.'tn-'.$file) {
+                $fetchthumb  = 1; 
+            }
         }
     }
  
@@ -4728,6 +4753,30 @@
     return;
 }
 
+sub check_dimensions {
+    my ($inputfile) = @_;
+    my ($fullwidth,$fullheight);
+    if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
+        my $mm = new File::MMagic;
+        my $mime_type = $mm->checktype_filename($inputfile);
+        if ($mime_type =~ m{^image/}) {
+            if (open(PIPE,"identify $inputfile 2>&1 |")) {
+                my $imageinfo = <PIPE>;
+                if (!close(PIPE)) {
+                    &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
+                }
+                chomp($imageinfo);
+                my ($fullsize) =
+                    ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
+                if ($fullsize) {
+                    ($fullwidth,$fullheight) = split(/x/,$fullsize);
+                }
+            }
+        }
+    }
+    return ($fullwidth,$fullheight);
+}
+
 sub bubblesheet_converter {
     my ($cdom,$fullpath,$config,$format) = @_;
     if ((&domain($cdom) ne '') &&
@@ -7955,6 +8004,17 @@
     return;
 }
 
+sub is_coursetool_logo {
+    my ($uri) = @_;
+    if ($env{'request.course.id'}) {
+        my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
+        if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
+            return 1;
+        }
+    }
+    return;
+}
+
 sub usertools_access {
     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
     my ($access,%tools);
@@ -8583,6 +8643,12 @@
 
     if ($env{'request.course.id'}) {
 
+        if ($priv eq 'bre') {
+            if (&is_coursetool_logo($uri)) {
+                return 'F';
+            }
+        }
+
 # If this is modifying password (internal auth) domains must match for user and user's role.
 
         if ($priv eq 'mip') {


More information about the LON-CAPA-cvs mailing list