--- loncom/interface/londocs.pm	2017/05/19 20:00:45	1.484.2.72
+++ loncom/interface/londocs.pm	2018/04/29 17:33:52	1.484.2.72.2.5
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # Documents
 #
-# $Id: londocs.pm,v 1.484.2.72 2017/05/19 20:00:45 raeburn Exp $
+# $Id: londocs.pm,v 1.484.2.72.2.5 2018/04/29 17:33:52 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -622,7 +622,7 @@ sub recurse_html {
 }
 
 sub group_import {
-    my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
+    my ($coursenum, $coursedom, $folder, $container, $caller, $ltitoolsref, @files) = @_;
     my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
         %removeparam,$importuploaded,$fixuperrors);
     $allmaps = {};
@@ -651,6 +651,112 @@ sub group_import {
             }
         }
 	if ($url) {
+            if ($url =~ m{^(/adm/$coursedom/$coursenum/(\d+)/ext\.tool)\:?(.*)$}) {
+                $url = $1;
+                my $marker = $2;
+                my $info = $3;
+                my ($toolid,%toolhash,%toolsettings);
+                my @extras = ('linktext','explanation','crslabel','crstitle'); 
+                my @toolinfo = split(/:/,$info);
+                if ($residx) {
+                    %toolsettings=&Apache::lonnet::dump('exttool_'.$marker,$coursedom,$coursenum);
+                    $toolid = $toolsettings{'id'};
+                } else {
+                    $toolid = shift(@toolinfo);
+                }
+                $toolid =~ s/\D//g;
+                ($toolhash{'target'},$toolhash{'width'},$toolhash{'height'},
+                 $toolhash{'linktext'},$toolhash{'explanation'},
+                 $toolhash{'crslabel'},$toolhash{'crstitle'}) = @toolinfo;
+                foreach my $item (@extras) {
+                    $toolhash{$item} = &unescape($toolhash{$item});
+                }
+                if (ref($ltitoolsref) eq 'HASH') {
+                    my @deleted;
+                    if (ref($ltitoolsref->{$toolid}) eq 'HASH') {
+                        $toolhash{'id'} = $toolid;
+                        if (($toolhash{'target'} eq 'iframe') || ($toolhash{'target'} eq 'tab') ||
+                            ($toolhash{'target'} eq 'window')) {
+                            if ($toolhash{'target'} eq 'window') {
+                                foreach my $item ('width','height') {
+                                    $toolhash{$item} =~ s/^\s+//;
+                                    $toolhash{$item} =~ s/\s+$//;
+                                    if ($toolhash{$item} =~ /\D/) {
+                                        delete($toolhash{$item});
+                                        if ($residx) {
+                                            if ($toolsettings{$item}) {
+                                                push(@deleted,$item);
+                                            }
+                                        }
+                                    }
+                                }
+                            }
+                        } elsif ($residx) {
+                            $toolhash{'target'} = $toolsettings{'target'};
+                            if ($toolhash{'target'} eq 'window') {
+                                foreach my $item ('width','height') {
+                                    $toolhash{$item} = $toolsettings{$item};
+                                }
+                            }
+                        } elsif (ref($ltitoolsref->{$toolid}->{'display'}) eq 'HASH') {
+                            $toolhash{'target'} = $ltitoolsref->{$toolid}->{'display'}->{'target'};
+                            if ($toolhash{'target'} eq 'window') {
+                                $toolhash{'width'} = $ltitoolsref->{$toolid}->{'display'}->{'width'};
+                                $toolhash{'height'} = $ltitoolsref->{$toolid}->{'display'}->{'height'};
+                            }
+                        }
+                        if ($toolhash{'target'} eq 'iframe') {
+                            foreach my $item ('width','height','linktext','explanation') {
+                                delete($toolhash{$item});
+                                if ($residx) {
+                                    if ($toolsettings{$item}) {
+                                        push(@deleted,$item);
+                                    }
+                                }
+                            }
+                        } elsif ($toolhash{'target'} eq 'tab') {
+                            foreach my $item ('width','height') {
+                                delete($toolhash{$item});
+                                if ($residx) {
+                                    if ($toolsettings{$item}) {
+                                        push(@deleted,$item);
+                                    }
+                                }
+                            }
+                        }
+                        if (ref($ltitoolsref->{$toolid}->{'crsconf'}) eq 'HASH') {
+                            foreach my $item ('label','title','linktext','explanation') {
+                                my $crsitem;
+                                if (($item eq 'label') || ($item eq 'title')) {
+                                    $crsitem = 'crs'.$item;
+                                } else {
+                                    $crsitem = $item;
+                                }
+                                if ($ltitoolsref->{$toolid}->{'crsconf'}->{$item}) {
+                                    $toolhash{$crsitem} =~ s/^\s+//;
+                                    $toolhash{$crsitem} =~ s/\s+$//;
+                                    if ($toolhash{$crsitem} eq '') {
+                                        delete($toolhash{$crsitem});
+                                    }
+                                } else {
+                                    delete($toolhash{$crsitem});
+                                }
+                                if (($residx) && (exists($toolsettings{$crsitem}))) {
+                                    unless (exists($toolhash{$crsitem})) {
+                                        push(@deleted,$crsitem);
+                                    }
+                                }
+                            }
+                        }
+                        my $putres = &Apache::lonnet::put('exttool_'.$marker,\%toolhash,$coursedom,$coursenum);
+                        if ($putres eq 'ok') {
+                            if (@deleted) {
+                                &Apache::lonnet::del('exttool_'.$marker,\@deleted,$coursedom,$coursenum);
+                            }
+                        }
+                    }
+                }
+            }
             if (($caller eq 'londocs') &&
                 ($folder =~ /^default/)) {
                 if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
@@ -662,8 +768,8 @@ sub group_import {
                     $donechk = 1;
                 }
                 if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
-                    &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
-                                         \%addedmaps,\%hierarchy,\%titles,$allmaps);
+                    &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
+                                         \%removeparam,\%addedmaps,\%hierarchy,\%titles,$allmaps);
                     $importuploaded = 1;
                 } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                     next if ($allmaps->{$url});
@@ -834,7 +940,7 @@ sub docs_change_log {
              '// <![CDATA['."\n".
              &Apache::loncommon::display_filter_js('docslog')."\n".
              &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag,
-                         $coursedom,$coursenum,$canedit,\$navmap)."\n".
+                         $coursedom,$coursenum,'',$canedit,\$navmap)."\n".
              &history_tab_js()."\n".
              &Apache::lonratedt::editscript('simple')."\n".
              '// ]]>'."\n".
@@ -1108,8 +1214,8 @@ sub update_paste_buffer {
                 $subdir = $prefix;
             }
             my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
-            &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
-                                 \%hierarchy,\%titles,\%allmaps);
+            &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
+                                 \%removeparam,\%addedmaps,\%hierarchy,\%titles,\%allmaps);
             if (ref($hierarchy{$url}) eq 'HASH') {
                 my ($nested,$nestednames);
                 &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
@@ -1182,10 +1288,12 @@ sub print_paste_buffer {
             ($url ne '')) {
             $clipboardcount ++;
             my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent,
-                $canpaste,$nopaste,$othercrs,$areachange);
+                $canpaste,$nopaste,$othercrs,$areachange,$is_exttool);
             my $extension = (split(/\./,$env{'docs.markedcopy_url_'.$suffix}))[-1];
             if ($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
                 $is_external = 1;
+            } elsif ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
+                $is_exttool = 1;
             }
             if ($folder =~ /^supplemental/) {
                 $canpaste = &supp_pasteable($env{'docs.markedcopy_url_'.$suffix});
@@ -1203,9 +1311,7 @@ sub print_paste_buffer {
                     if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
                         $othercourse = 1;
                         if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
-                            if ($canpaste) {
-                                $othercrs = '<br />'.&mt('(from another course)');
-                            }
+                            $othercrs = '<br />'.&mt('(from another course)');
                         } else {
                             $canpaste = 0;
                             $nopaste = &mt('Paste from another course unavailable.'); 
@@ -1219,16 +1325,35 @@ sub print_paste_buffer {
                         }
                         $is_uploaded_map = 1;
                     }
+                } elsif (($url =~ m{^/res/lib/templates/\w+\.problem$}) ||
+                         ($url =~ m{^/adm/($match_domain)/($match_username)/\d+/(bulletinboard|smppg|ext\.tool)$})) {
+                    if ($cid ne $env{'request.course.id'}) {
+                        my ($srcdom,$srcnum) = split(/_/,$cid);
+                        if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
+                            if (($is_exttool) && ($srcdom ne $coursedom)) {
+                                $canpaste = 0;
+                                $nopaste = &mt('Paste from another domain unavailable.');
+                            } else {
+                                $othercrs = '<br />'.&mt('(from another course)');
+                            }
+                        } else {
+                            $canpaste = 0;
+                            $nopaste = &mt('Paste from another course unavailable.');
+                        }
+                    }
                 }
             }
             if ($canpaste) {
                push(@pasteable,$suffix);
             }
             my $buffer;
-            if ($is_external) {
+            if ($is_external) { 
                 $buffer = &mt('External Resource').': '.
                     &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
                     &LONCAPA::map::qtescape($url).')';
+            } elsif ($is_exttool) {
+                $buffer = &mt('External Tool').': '.
+                    &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
             } else {
                 my $icon = &Apache::loncommon::icon($extension);
                 if ($extension eq 'sequence' &&
@@ -1284,7 +1409,7 @@ sub print_paste_buffer {
             }
             $buttons = '<input type="submit" name="pastemarked" value="'.$value.'" />'.('&nbsp;'x2);
         }
-        $buttons .= '<input type="submit" name="clearmarked" value="'.&mt('Clear selected').'" />'.('&nbsp;'x2);
+        $buttons .= '<input type="submit" name="clearmarked" value="'.&mt('Remove from clipboard').'" />'.('&nbsp;'x2);
         if ($clipboardcount > 1) {
             $buttons .=
                 '<span style="text-decoration:line-through">'.('&nbsp;'x20).'</span>'.('&nbsp;'x2).
@@ -1385,7 +1510,8 @@ sub supp_pasteable {
         (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
         ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
         ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
-        ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
+        ($url =~ m{^/public/$match_domain/$match_courseid/syllabus}) ||
+        ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$})) {
         return 1;
     }
     return;
@@ -1507,11 +1633,12 @@ sub do_paste_from_buffer {
         return();
     }
 
-    my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%duplicate,
+    my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%notindom,%duplicate,
         %prefixchg,%srcdom,%srcnum,%marktomove,$save_err,$lockerrors,$allresult);
 
     foreach my $suffix (@topaste) {
         my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
+        my $cid=&LONCAPA::map::qtescape($env{'docs.markedcopy_crs_'.$suffix});
 # Supplemental content may only include certain types of content
 # Early out if pasted content is not supported in Supplemental area
         if ($folder =~ /^supplemental/) {
@@ -1533,8 +1660,25 @@ sub do_paste_from_buffer {
             }
             $srcdom{$suffix} = $srcd;
             $srcnum{$suffix} = $srcn;
+        } elsif ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
+            my ($srcd,$srcn) = split(/_/,$cid);
+# When paste buffer was populated using an active role in a different course
+# check for mdc privilege in the course from which the resource was pasted
+            if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
+                unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
+                    $notincrs{$suffix} = 1;
+                    next;
+                }
+            }
+# When buffer was populated using an active role in a different course
+# disallow pasting of External Tool if course is in a different domain.
+            if ($srcd ne $coursedom) {
+                $notindom{$suffix} = 1;
+                next;
+            }
+            $srcdom{$suffix} = $srcd;
+            $srcnum{$suffix} = $srcn;
         }
-
         push(@dopaste,$suffix);
         if ($url=~/\.(page|sequence)$/) {
             $is_map{$suffix} = 1; 
@@ -1544,7 +1688,7 @@ sub do_paste_from_buffer {
             my $oldprefix = $1;
 # When pasting content from Main Content to Supplemental Content and vice versa 
 # URLs will contain different paths (which depend on whether pasted item is
-# a folder/page or a document.   
+# a folder/page or a document).   
             if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
                 $prefixchg{$suffix} = 'docstosupp';
             } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
@@ -1584,6 +1728,7 @@ sub do_paste_from_buffer {
     %msgs = &Apache::lonlocal::texthash (
                 notinsupp => 'Paste failed: content type is not supported within Supplemental Content',
                 notincrs  => 'Paste failed: Item is from a different course which you do not have rights to edit.',
+                notindom  => 'Paste failed: Item is an external tool from a course in a different donain.', 
                 duplicate => 'Paste failed: only one instance of a particular published sequence or page is allowed within each course.',
             );
 
@@ -1632,12 +1777,14 @@ sub do_paste_from_buffer {
         }
         my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
         my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
+        my $cid=&LONCAPA::map::qtescape($env{'docs.markedcopy_crs_'.$suffix});
         my $oldurl = $url;
         if ($is_map{$suffix}) {
 # If pasting a map, check if map contains other maps
             my (%hierarchy,%titles);
-            &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
-                                 \%addedmaps,\%hierarchy,\%titles,$allmaps);
+            &contained_map_check($url,$folder,$coursenum,$coursedom,
+                                 \%removefrommap,\%removeparam,\%addedmaps,
+                                 \%hierarchy,\%titles,$allmaps);
             if ($url=~ m{^/uploaded/}) {
                 my $newurl;
                 unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
@@ -1679,7 +1826,7 @@ sub do_paste_from_buffer {
                                       \%tomove,\%newsubdir,\%newurls); 
                 }
             } elsif ($url=~m {^/res/}) {
-# published map can only exists once, so remove from paste buffer when done
+# published map can only exist once, so remove from paste buffer when done
                 push(@toclear,$suffix);
 # if pasting published map (main content area only) check map not already in course
                 if ($folder =~ /^default/) {
@@ -1690,15 +1837,23 @@ sub do_paste_from_buffer {
                 }
             }
         }
-        if ($url=~ m{/(bulletinboard|smppg)$}) {
+        if ($url=~ m{/(ext\.tool)$}) {
             my $prefix = $1;
+            my $fromothercrs;
             #need to copy the db contents to a new one, unless this is a move.
             my %info = (
                          src  => $url,
                          cdom => $coursedom,
                          cnum => $coursenum,
             );
-            unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
+            if (($srcdom{$suffix} =~ /^$match_domain$/) && ($srcnum{$suffix} =~ /^$match_courseid$/)) {
+                unless (($srcdom{$suffix} eq $coursedom) && ($srcnum{$suffix} eq $coursenum)) {
+                    $fromothercrs = 1;
+                    $info{'cdom'} = $srcdom{$suffix};
+                    $info{'cnum'} = $srcnum{$suffix};
+                }
+            }
+            unless (($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') && (!$fromothercrs)) {
                 my (%lockerr,$msg); 
                 my ($newurl,$result,$errtext) =
                     &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
@@ -1706,10 +1861,8 @@ sub do_paste_from_buffer {
                     $url = $newurl;
                     $title=&mt('Copy of').' '.$title;
                 } else {
-                    if ($prefix eq 'smppg') {
-                        $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
-                    } elsif ($prefix eq 'bulletinboard') {
-                        $msg = &mt('Paste failed: An error occurred when copying the discussion board.').' '.$errtext;
+                    if ($prefix eq 'ext.tool') {
+                        $msg = &mt('Paste failed: An error occurred when copying the external tool.').' '.$errtext;
                     }
                     $results{$suffix} = $result;
                     $msgerrs{$suffix} = $msg;
@@ -1961,8 +2114,11 @@ sub dbcopy {
     my ($url,$result,$errtext);
     if (ref($dbref) eq 'HASH') {
         $url = $dbref->{'src'};
-        if ($url =~ m{/(smppg|bulletinboard)$}) {
+        if ($url =~ m{/(smppg|bulletinboard|ext\.tool)$}) {
             my $prefix = $1;
+            if ($prefix eq 'ext.tool') {
+                $prefix = 'exttool';
+            }
             if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
                 ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
                 my $db_name;
@@ -1973,6 +2129,8 @@ sub dbcopy {
                         &Apache::lonsimplepage::get_db_name($url,$marker,
                                                             $dbref->{'cdom'},
                                                             $dbref->{'cnum'});
+                } elsif ($dbref->{'src'} =~ m{/ext\.tool$}) {
+                    $db_name = 'exttool_'.$marker;
                 } else {
                     $db_name = 'bulletinpage_'.$marker;
                 }
@@ -1983,6 +2141,8 @@ sub dbcopy {
                 if (!$suffix) {
                     if ($prefix eq 'smppg') {
                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
+                    } elsif ($prefix eq 'exttool') {
+                        $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying an external tool [_1].',$url);
                     } else {
                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a discussion board [_1].',$url);
                     }
@@ -2016,7 +2176,7 @@ sub dbcopy {
                     $result=&Apache::lonnet::put($db_name,\%contents,
                                                  $coursedom,$coursenum);
                     if ($result eq 'ok') {
-                        $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
+                        $url =~ s{/(\d*)/(smppg|bulletinboard|ext\.tool)$}{/$suffix/$2}x;
                     }
                 }
                 if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
@@ -2026,6 +2186,9 @@ sub dbcopy {
                     if ($prefix eq 'smppg') {
                         $lockerrorsref->{$prefix} .=
                             ' '.&mt('This will prevent creation of additional simple pages in this course.');
+                    } elsif ($prefix eq 'exttool') {
+                        $lockerrorsref->{$prefix} .=
+                            ' '.&mt('This will prevent addition of more external tools to this course.');
                     } else {
                         $lockerrorsref->{$prefix} .= ' '.&mt('This will prevent creation of additional discussion boards in this course.');
                     }
@@ -2066,8 +2229,8 @@ sub uniqueness_check {
 }
 
 sub contained_map_check {
-    my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
-        $allmaps) = @_;
+    my ($url,$folder,$coursenum,$coursedom,$removefrommap,$removeparam,$addedmaps,
+        $hierarchy,$titles,$allmaps) = @_;
     my $content = &Apache::lonnet::getfile($url);
     unless ($content eq '-1') {
         my $parser = HTML::TokeParser->new(\$content);
@@ -2096,7 +2259,8 @@ sub contained_map_check {
                             $addedmaps->{$ressrc} = [$url];
                         }
                     }
-                    &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
+                    &contained_map_check($ressrc,$folder,$coursenum,$coursedom,
+                                         $removefrommap,$removeparam,
                                          $addedmaps,$hierarchy,$titles,$allmaps);
                 }
             } elsif ($token->[1] eq 'param') {
@@ -2434,7 +2598,8 @@ sub apply_fixups {
                     }
                 }
             }
-            for (my $i=0; $i<@LONCAPA::map::order; $i++) {
+            my $total = scalar(@LONCAPA::map::order) - 1;
+            for (my $i=$total; $i>=0; $i--) {
                 my $idx = $LONCAPA::map::order[$i];
                 if (defined($LONCAPA::map::resources[$idx])) {
                     my $changed;
@@ -2444,7 +2609,7 @@ sub apply_fixups {
                         splice(@LONCAPA::map::order,$i,1);
                         if (ref($currparam{$idx}) eq 'ARRAY') {
                             foreach my $name (@{$currparam{$idx}}) {
-                                &LONCAPA::map::delparameter($idx,'parameter_'.$name);
+                                &LONCAPA::map::delparameter($idx,$name);
                             }
                         }
                         next;
@@ -2486,7 +2651,7 @@ sub apply_fixups {
             foreach my $idx (keys(%remparam)) {
                 if (ref($remparam{$idx}) eq 'ARRAY') {
                     foreach my $name (@{$remparam{$idx}}) {   
-                        &LONCAPA::map::delparameter($idx,'parameter_'.$name);
+                        &LONCAPA::map::delparameter($idx,$name);
                     }
                 }
             }
@@ -2745,8 +2910,8 @@ sub handle_edit_cmd {
 
 sub editor {
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
-        $supplementalflag,$orderhash,$iconpath,$pathitem,$canedit,$navmapref,
-        $hiddentop)=@_;
+        $supplementalflag,$orderhash,$iconpath,$pathitem,$ltitoolsref,
+        $canedit,$navmapref,$hiddentop)=@_;
     my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
     if ($allowed) {
         (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
@@ -2957,6 +3122,17 @@ sub editor {
                         } else {
                             return $errortxt;
                         }
+                    } elsif ($url =~ m{^/adm/$coursedom/$coursenum/new/ext\.tool}) {
+                        my ($suffix,$errortxt,$locknotfreed) =
+                            &new_timebased_suffix($coursedom,$coursenum,'exttool');
+                        if ($locknotfreed) {
+                            $r->print($locknotfreed);
+                        }
+                        if ($suffix) {
+                            $url =~ s{^(/adm/$coursedom/$coursenum)/new}{$1/$suffix};
+                        } else {
+                            return $errortxt;
+                        }
                     } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
                         if ($supplementalflag) {
                             next unless ($1 eq 'supplemental');
@@ -2979,7 +3155,7 @@ sub editor {
 	    }
             ($errtext,$fatal,my $fixuperrors) =
                 &group_import($coursenum, $coursedom, $folder,$container,
-                              'londocs',@imports);
+                              'londocs',$ltitoolsref,@imports);
 	    return $errtext if ($fatal);
             if ($fixuperrors) {
                 $r->print($fixuperrors);
@@ -3065,7 +3241,7 @@ sub editor {
         $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
                               $coursenum,$coursedom,$crstype,
                               $pathitem,$supplementalflag,$container,
-                              \%filters,\%curr_groups,$canedit,
+                              \%filters,\%curr_groups,$ltitoolsref,$canedit,
                               $isencrypted,$navmapref);
         $idx++;
         $shown++;
@@ -3445,7 +3621,7 @@ sub is_supplemental_title {
 sub entryline {
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
         $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups,
-        $canedit,$isencrypted,$navmapref)=@_;
+        $ltitoolsref,$canedit,$isencrypted,$navmapref)=@_;
     my ($foldertitle,$renametitle,$oldtitle);
     if (&is_supplemental_title($title)) {
 	($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
@@ -3542,6 +3718,7 @@ END
 		'rn' => 'Rename',
 		'cp' => 'Copy',
                 'ex' => 'External Resource',
+                'et' => 'External Tool',
                 'ed' => 'Edit',
                 'pr' => 'Preview',
                 'sv' => 'Save',
@@ -3561,6 +3738,7 @@ END
 			    |/aboutme$
 			    |/navmaps$
 			    |/bulletinboard$
+                            |/ext\.tool$
 			    |\.html$)}x)
              || $isexternal) {
 	    $skip_confirm = 1;
@@ -3719,6 +3897,8 @@ END
                 if (($ENV{'SERVER_PORT'} == 443) && ($exturl !~ /^https:/)) {
                     $nomodal = 1;
                 }
+            } elsif ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
+                $url='/adm/wrapper'.$url;
             } elsif ($url eq "/public/$coursedom/$coursenum/syllabus") {
                 if (($ENV{'SERVER_PORT'} == 443) &&
                     ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
@@ -3746,7 +3926,7 @@ END
                     }
                 }
                 if ($url ne '') {
-                    $url.=(($url=~/\?/)?'&':'?').'symb='.&HTML::Entities::encode($shownsymb,'"<>&');
+                    $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($shownsymb);
                 }
             } elsif (!$env{'request.role.adv'}) {
                 my $checkencrypt;
@@ -3767,7 +3947,7 @@ END
                     my $shownsymb = &Apache::lonenc::encrypted($symb);
                     my $shownurl = &Apache::lonenc::encrypted($url);
                     if (&Apache::lonnet::symbverify($shownsymb,$shownurl)) {
-                        $url = $shownurl.(($shownurl=~/\?/)?'&':'?').'symb='.&HTML::Entities::encode($shownsymb,'"<>&');
+                        $url = $shownurl.(($shownurl=~/\?/)?'&':'?').'symb='.&escape($shownsymb);
                         if ($env{'request.enc'} ne '') {
                             delete($env{'request.enc'});
                         }
@@ -3883,12 +4063,17 @@ $form_common."\n".
 $form_end;
         }
     } elsif ($supplementalflag && !$allowed) {
+        my $isexttool;
+        if ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
+            $url='/adm/wrapper'.$url;
+            $isexttool = 1;
+        }
         $url .= ($url =~ /\?/) ? '&amp;':'?';
         $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
         if ($title) {
             $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
         }
-        if ($isexternal && $orderidx) {
+        if ((($isexternal) || ($isexttool)) && $orderidx) {
             $url .= '&amp;idx='.$orderidx;
         }
         if ($anchor ne '') {
@@ -3903,6 +4088,11 @@ $form_end;
             ($editlink,$extresform) = 
                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
                                                      undef,undef,undef,$disabled);
+        } elsif ($orig_url =~ m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
+            ($editlink,$extresform) =
+                &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
+                                                     undef,undef,undef,'tool',$coursedom,
+                                                     $coursenum,$ltitoolsref,$disabled);
         } elsif (!$isfolder && !$ispage) {
             my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
                 &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
@@ -4105,6 +4295,8 @@ sub new_timebased_suffix {
             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
         } elsif ($type eq 'smppg') {
             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
+        } elsif ($type eq 'exttool') {
+            $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new external tool.');
         } else {
             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new discussion board.');
         }
@@ -4133,6 +4325,9 @@ sub new_timebased_suffix {
         } elsif ($type eq 'smppg') {
             $locknotfreed .=
                 &mt('This will prevent creation of additional simple pages in this course.');
+        } elsif ($type eq 'exttool') {
+            $locknotfreed .=
+                &mt('This will prevent creation of additional external tools in this course.');
         } else {
             $locknotfreed .=
                 &mt('This will prevent creation of additional discussion boards in this course.');
@@ -4754,12 +4949,12 @@ sub handler {
 #
 # --------------------------------------------- Initialize help topics for this
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
-	               'Adding_External_Resource','Navigate_Content',
-	               'Adding_Folders','Docs_Overview', 'Load_Map',
-	               'Supplemental','Score_Upload_Form','Adding_Pages',
-	               'Importing_LON-CAPA_Resource','Importing_IMS_Course',
-                       'Uploading_From_Harddrive','Course_Roster','Web_Page',
-                       'Dropbox','Simple_Problem') {
+	               'Adding_External_Resource','Adding_External_Tool',
+                       'Navigate_Content','Adding_Folders','Docs_Overview',
+	               'Load_Map','Supplemental','Score_Upload_Form',
+                       'Adding_Pages','Importing_LON-CAPA_Resource',
+                       'Importing_IMS_Course','Uploading_From_Harddrive',
+                       'Course_Roster','Web_Page','Dropbox','Simple_Problem') {
 	$help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
     }
     # Composite help files
@@ -4791,6 +4986,11 @@ sub handler {
         $disabled = ' disabled="disabled"';
     }
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
+    if ($env{'form.inhibitmenu'}) {
+        unless ($env{'form.inhibitmenu'} eq 'yes') {
+            delete($env{'form.inhibitmenu'});
+        }
+    }
   if ($allowed && $env{'form.verify'}) {
       &init_breadcrumbs('verify','Verify Content','Docs_Verify_Content');
       &verifycontent($r);
@@ -4824,6 +5024,25 @@ sub handler {
                                              'forcesupplement','forcestandard',
                                              'tools','symb','command','supppath']);
 
+    foreach my $item ('forcesupplement','forcestandard','tools') {
+        next if ($env{'form.'.$item} eq '');
+        unless ($env{'form.'.$item} eq '1') {
+            delete($env{'form.'.$item});
+        }
+    }
+
+    if ($env{'form.command'}) {
+        unless ($env{'form.command'} =~ /^(direct|directnav|editdocs|editsupp|contents|home)$/) {
+            delete($env{'form.command'});
+        }
+    }
+
+    if ($env{'form.symb'}) {
+        my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
+        unless (($id =~ /^\d+$/) && (&Apache::lonnet::is_on_map($resurl))) {
+            delete($env{'form.symb'});
+        }
+    }
 # standard=1: this is a "new-style" course with an uploaded map as top level
 # standard=2: this is a "old-style" course, and there is nothing we can do
 
@@ -4846,12 +5065,45 @@ sub handler {
     my $toolsflag=0;
     if ($env{'form.tools'}) { $toolsflag=1; }
 
+    if ($env{'form.folderpath'} ne '') {
+        my @items = split(/\&/,$env{'form.folderpath'});
+        my $badpath;
+        for (my $i=0; $i<@items; $i++) {
+            my $odd = $i%2;
+            if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
+                $badpath = 1;
+            } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
+                $badpath = 1;
+            }
+            last if ($badpath);
+        }
+        if ($badpath) {
+            delete($env{'form.folderpath'});
+        }
+    }
+
+    if ($env{'form.supppath'} ne '') {
+        my @items = split(/\&/,$env{'form.supppath'});
+        my $badpath;
+        for (my $i=0; $i<@items; $i++) {
+            my $odd = $i%2;
+            if ((!$odd) && ($items[$i] !~ /^supplemental(|_\d+)$/)) {
+                $badpath = 1;
+            }
+            last if ($badpath);
+        }
+        if ($badpath) {
+            delete($env{'form.supppath'});
+        }
+    }
+
     my $script='';
     my $showdoc=0;
     my $addentries = {};
     my $container;
     my $containertag;
     my $pathitem;
+    my %ltitools;
     my $hiddentop;
     my $navmap;
     my $filterFunc = sub { my $res = shift; return (!$res->randomout() && !$res->is_map()) };
@@ -5029,12 +5281,14 @@ sub handler {
                 }
             }
             my $tabidstr = join("','",@tabids);
-	    $script .= &editing_js($udom,$uname,$supplementalflag,$coursedom,$coursenum,
+            %ltitools = &Apache::lonnet::get_domain_ltitools($coursedom);
+            my $posslti = keys(%ltitools);
+	    $script .= &editing_js($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
                                    $canedit,\$navmap).
                        &history_tab_js().
                        &inject_data_js().
                        &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr,$tid).
-                       &Apache::lonextresedit::extedit_javascript();
+                       &Apache::lonextresedit::extedit_javascript(\%ltitools);
             $addentries = {
                             onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
                           };
@@ -5112,6 +5366,7 @@ sub handler {
 	  undef($hadchanges);
           $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
                                               \%allfiles,\%codebase,$context,$crstype);
+          undef($navmap);
 	  if ($hadchanges) {
 	      &mark_hash_old();
 	  }
@@ -5168,6 +5423,8 @@ sub handler {
                 'impo' => 'Import',
 		'lnks' => 'Import from Stored Links',
                 'impm' => 'Import from Assembled Map',
+                'extr' => 'External Resource',
+                'extt' => 'External Tool',
                 'selm' => 'Select Map',
                 'load' => 'Load Map',
                 'newf' => 'New Folder',
@@ -5338,6 +5595,11 @@ SEDFFORM
             &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
                                                  $help{'Adding_External_Resource'},
                                                  undef,undef,$disabled);
+        my $exttoolform =
+            &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
+                                                 $help{'Adding_External_Tool'},undef,
+                                                 undef,'tool',$coursedom,$coursenum,
+                                                 \%ltitools,$disabled);
     if ($allowed) {
         my $folder = $env{'form.folder'};
         if ($folder eq '') {
@@ -5585,6 +5847,11 @@ NGFFORM
         my @importdoc = (
         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform}
         );
+        if (keys(%ltitools)) {
+            push(@importdoc,
+                {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="toggleUpload(\'tool\');" />'=>$exttoolform},
+        );
+        }
         unless ($container eq 'page') {
             push(@importdoc,
                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform}
@@ -5627,15 +5894,16 @@ unless ($container eq 'page') {
        unless (($supplementalflag || $toolsflag)) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,\%orderhash,$iconpath,$pathitem,
-                              $canedit,\$navmap,$hiddentop);
+                              \%ltitools,$canedit,\$navmap,$hiddentop);
           undef($navmap);
           if ($error) {
              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
           if ($hadchanges) {
-             &mark_hash_old();
+             unless (&is_hash_old()) {
+                 &mark_hash_old();
+             }
           }
-
           &changewarning($r,'');
         }
     }
@@ -5696,6 +5964,11 @@ SNFFORM
                                                  $help{'Adding_External_Resource'},
                                                  undef,undef,$disabled);
 
+        my $supexttoolform =
+            &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
+                                                 $help{'Adding_External_Tool'},
+                                                 undef,undef,'tool',$coursedom,
+                                                 $coursenum,\%ltitools,$disabled);
 	my $supnewsylform=(<<SNSFORM);
 	<form action="/adm/coursedocs" method="post" name="supnewsyl">
 	<input type="hidden" name="active" value="ff" />
@@ -5749,10 +6022,16 @@ my @specialdocs = (
 		);
 my @supimportdoc = (
 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:toggleUpload(\'suppext\')" />'
-            =>$supextform},
+            =>$supextform});
+        if (keys(%ltitools)) {
+            push(@supimportdoc,
+                {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="javascript:toggleUpload(\'supptool\')" />'
+            =>$supexttoolform});
+        }
+        push(@supimportdoc,
                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
             =>$supupdocform},
-                   );
+        );
 
 $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
 my %suporderhash = (
@@ -5763,7 +6042,7 @@ my %suporderhash = (
         if ($supplementalflag) {
            my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                $supplementalflag,\%suporderhash,$iconpath,$pathitem,
-                               $canedit);
+                               \%ltitools,$canedit);
            if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
            } else {
@@ -5817,6 +6096,7 @@ my %suporderhash = (
 sub embedded_form_elems {
     my ($phase,$primaryurl,$newidx) = @_;
     my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
+    $newidx =~s /\D+//g;
     return <<STATE;
     <input type="hidden" name="folderpath" value="$folderpath" />
     <input type="hidden" name="cmd" value="upload_embedded" />
@@ -5837,7 +6117,11 @@ sub embedded_destination {
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
         $destination .=  $2.'/';
     }
-    $destination .= $env{'form.newidx'};
+    my $newidx = $env{'form.newidx'};
+    $newidx =~s /\D+//g;
+    if ($newidx) {
+        $destination .= $newidx;
+    }
     my $dir_root = '/userfiles';
     return ($destination,$dir_root);
 }
@@ -5863,6 +6147,9 @@ sub decompression_info {
     }
     unshift(@hiddens,$pathitem);
     foreach my $item (@hiddens) {
+        if ($item eq 'newidx') {
+            next if ($env{'form.'.$item} =~ /\D/);
+        }
         if ($env{'form.'.$item}) {
             $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
                            &HTML::Entities::encode($env{'form.'.$item},'<>&"').'" />'."\n";
@@ -6155,7 +6442,7 @@ END
 }
 
 sub editing_js {
-    my ($udom,$uname,$supplementalflag,$coursedom,$coursenum,$canedit,$navmapref) = @_;
+    my ($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,$canedit,$navmapref) = @_;
     my %js_lt = &Apache::lonlocal::texthash(
                                           p_mnf => 'Name of New Folder',
                                           t_mnf => 'New Folder',
@@ -6227,8 +6514,13 @@ sub editing_js {
                 } else {
                     $url = $res;
                 }
-                $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($url),'<>&"').'?symb='.
-                             &HTML::Entities::encode($caller,'<>&"');
+                $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($url),'<>&"');
+                if ($backtourl =~ m{^\Q/uploaded/$coursedom/$coursenum/\Edefault_\d+\.sequence$}) {
+                    $backtourl .= '?navmap=1';
+                } else {
+                    $backtourl .= '?symb='.
+                                  &HTML::Entities::encode($caller,'<>&"');
+                }
                 if ($anchor ne '') {
                     $backtourl .= '#'.&HTML::Entities::encode($anchor,'<>&"');
                 }
@@ -6246,11 +6538,17 @@ sub editing_js {
     }
 
     my $fieldsets = "'ext','doc'";
+    if ($posslti) {
+        $fieldsets .= ",'tool'";
+    }
     unless ($main_container_page) {
         $fieldsets .=",'ims'";
     }
     if ($supplementalflag) {
         $fieldsets = "'suppext','suppdoc'";
+        if ($posslti) {
+            $fieldsets .= ",'supptool'";
+        }
     }
 
     my $jsmakefunctions;
@@ -6447,6 +6745,19 @@ function toggleUpload(caller) {
             }
         }
         document.getElementById('upload'+blocks[i]+'form').style.display=disp;
+        if ((caller == 'tool') || (caller == 'supptool')) {
+            if (disp == 'block') {
+                if (document.getElementById('LC_exttoolid')) {
+                    var toolselector = document.getElementById('LC_exttoolid');
+                    var suppflag = 0;
+                    if (caller == 'supptool') {
+                        suppflag = 1;
+                    }
+                    currForm = document.getElementById('new'+caller);
+                    updateExttool(toolselector,currForm,suppflag);
+                }
+            }
+        }
     }
     resize_scrollbox('contentscroll','1','1');
     return;
@@ -7424,7 +7735,9 @@ check on this
 
 Verify Content
 
-=item devalidateversioncache() & checkversions()
+=item devalidateversioncache() 
+
+=item checkversions()
 
 Check Versions