--- loncom/interface/londocs.pm	2014/12/21 19:20:41	1.484.2.57
+++ loncom/interface/londocs.pm	2016/06/06 17:40:48	1.604
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # Documents
 #
-# $Id: londocs.pm,v 1.484.2.57 2014/12/21 19:20:41 raeburn Exp $
+# $Id: londocs.pm,v 1.604 2016/06/06 17:40:48 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -196,7 +196,7 @@ ENDJS
         } else {
             &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                                                                    'dumpdocs',$cdom,$cnum);
-        }
+	}
         my @todump = &Apache::loncommon::get_env_multiple('form.archive');
         my (%tocopy,%replacehash,%lookup,%deps,%display,%result,%depresult,%simpleproblems,%simplepages,
             %newcontent,%has_simpleprobs);
@@ -207,7 +207,7 @@ ENDJS
                 if ($res =~ m{^uploaded/$cdom/$cnum/\E((?:docs|supplemental)/.+)$}) {
                     $tocopy{$1} = $name;
                     $display{$item} = $1;
-                    $lookup{$1} = $item;
+                    $lookup{$1} = $item; 
                 } elsif ($res eq 'lib/templates/simpleproblem.problem') {
                     $simpleproblems{$item} = {
                                                 symb => $resources{$item},
@@ -307,7 +307,7 @@ $contents{content}.'
 </div>';
                 }
                 if ($contents{webreferences}) {
-                    $content .= '
+                    $content .= ' 
 <div class="LC_Box">
 <h4 class="LC_hcell">'.&mt('Web References').'</h4>'.
 $contents{webreferences}.'
@@ -317,10 +317,10 @@ $contents{webreferences}.'
 </body>
 </html>
 ';
-                $newcontent{'/'.$simplepages{$item}{res}} = $content;
+                $newcontent{'/'.$simplepages{$item}{res}} = $content; 
             }
         }
-        foreach my $item (keys(%tocopy)) {
+	foreach my $item (keys(%tocopy)) {
             unless ($item=~/\.(sequence|page)$/) {
                 my $currurlpath = $prefix.$item;
                 my $currdirpath = &Apache::lonnet::filelocation('',$currurlpath);
@@ -351,39 +351,39 @@ $contents{webreferences}.'
                 if ($simpleproblems{$num}) {
                     $newfilename=$title.'/'.$simpleproblems{$num}{'name'};
                 } else {
-                    $newfilename=$title.'/'.$replacehash{$item};
+	            $newfilename=$title.'/'.$replacehash{$item};
                 }
-                $newfilename=~s/\.(\w+)$//;
-               my $ext=$1;
-                $newfilename=&clean($newfilename);
-                $newfilename.='.'.$ext;
-                my ($newrelpath) = ($newfilename =~ m{^\Q$title/\E(.+)$});
+	        $newfilename=~s/\.(\w+)$//;
+	        my $ext=$1;
+	        $newfilename=&clean($newfilename);
+	        $newfilename.='.'.$ext;
+                my ($newrelpath) = ($newfilename =~ m{^\Q$title/\E(.+)$}); 
                 if ($newrelpath ne $replacehash{$item}) {
                     $replacehash{$item} = $newrelpath;
                 }
-                my @dirs=split(/\//,$newfilename);
-                my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
-                my $makepath=$path;
-                my $fail;
+	        my @dirs=split(/\//,$newfilename);
+	        my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
+	        my $makepath=$path;
+	        my $fail;
                 my $origin;
-                for (my $i=0;$i<$#dirs;$i++) {
-                    $makepath.='/'.$dirs[$i];
-                    unless (-e $makepath) {
-                        unless(mkdir($makepath,0755)) {
+	        for (my $i=0;$i<$#dirs;$i++) {
+		    $makepath.='/'.$dirs[$i];
+		    unless (-e $makepath) {
+		        unless(mkdir($makepath,0755)) { 
                             $fail = &mt('Directory creation failed.');
                         }
-                    }
-                }
+		    }
+	        }
                 if ($i == 0) {
-                    $result = '<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ';
+	            $result = '<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ';
                 } else {
                     $depresult .= '<li><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt> '.
                                   '<span class="LC_fontsize_small" style="font-weight: bold;">'.
                                   &mt('(dependency)').'</span>: ';
                 }
                 if (-e $path.'/'.$newfilename) {
-                    $fail = &mt('Destination already exists -- not overwriting.');
-                } else {
+                    $fail = &mt('Destination already exists -- not overwriting.'); 
+	        } else {
                     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
                         if (($item =~ m{^/adm/$match_domain/$match_username/\d+/smppg}) ||
                             ($item =~ /^simpleproblem_/)) {
@@ -405,18 +405,18 @@ $contents{webreferences}.'
                                         while (my $token = $parser->get_token) {
                                             if ($token->[0] eq 'S') {
                                                 if (($token->[1] eq 'resource') &&
-                                                    ($token->[2]->{'src'} eq '/res/lib/templates/simpleproblem.problem') &&
+                                                    ($token->[2]->{'src'} eq '/res/lib/templates/simpleproblem.problem') && 
                                                     ($changes{$token->[2]->{'id'}})) {
                                                     my $id = $token->[2]->{'id'};
                                                     $updatedcontent .= '<'.$token->[1];
                                                     foreach my $attrib (@{$token->[3]}) {
-                                                       next unless ($attrib =~ /^(src|type|title|id)$/);
+                                                        next unless ($attrib =~ /^(src|type|title|id)$/);
                                                         if ($attrib eq 'src') {
-                                                            my ($file) = ($display{$changes{$id}} =~ /^\Qsimpleproblem_\E(.+)$/);
+                                                            my ($file) = ($display{$changes{$id}} =~ /^\Qsimpleproblem_\E(.+)$/); 
                                                             if ($file) {
                                                                 $updatedcontent .= ' '.$attrib.'="'.$file.'"';
                                                             } else {
-                                                                $updatedcontent .= ' '.$attrib.'="'.$token->[2]->{$attrib}.'"';
+                                                                $updatedcontent .= ' '.$attrib.'="'.$token->[2]->{$attrib}.'"'; 
                                                             }
                                                         } else {
                                                             $updatedcontent .= ' '.$attrib.'="'.$token->[2]->{$attrib}.'"';
@@ -431,36 +431,36 @@ $contents{webreferences}.'
                                              }
                                          }
                                          print $fh $updatedcontent;
-                                    } else {
-                                        print $fh &Apache::lonclonecourse::rewritefile(
+                                    } else {  
+		                        print $fh &Apache::lonclonecourse::rewritefile(
                      &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
-                                                      (%replacehash,$crs => '')
-                                                                                      );
+		                                      (%replacehash,$crs => '')
+							                              );
                                     }
                                 } else {
-                                    print $fh
+		                    print $fh
                                         &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
-                                }
+		                }
                             } else {
-                                $fail = &mt('Source does not exist.');
+                                $fail = &mt('Source does not exist.');  
                             }
                         }
                         $fh->close();
-                    } else {
-                        $fail = &mt('Could not write to destination.');
+	            } else {
+		        $fail = &mt('Could not write to destination.');
                     }
-                }
+	        }
                 my $text;
-                if ($fail) {
+	        if ($fail) {
                     $text = '<span class="LC_error">'.&mt('fail').('&nbsp;'x3).$fail.'</span>';
-                } else {
+	        } else {
                     $text = '<span class="LC_success">'.&mt('ok').'</span>';
                 }
                 if ($i == 0) {
                     $result .= $text;
                 } else {
                     $depresult .= $text.'</li>';
-                }
+	        }
             }
             $r->print($result);
             if ($depresult) {
@@ -477,63 +477,63 @@ $contents{webreferences}.'
             $r->rflush();
             my ($preamble,$formname);
             $formname = 'dumpdoc';
-            unless ($home==1) {
-                $preamble = '<div class="LC_left_float">'.
-                            '<fieldset><legend>'.
+	    unless ($home==1) {
+	        $preamble = '<div class="LC_left_float">'.
+		            '<fieldset><legend>'.
                             &mt('Select the Authoring Space').
                             '</legend><select name="authorspace">';
-            }
+	    }
             my @orderspaces = ();
-            foreach my $key (sort(keys(%outhash))) {
+	    foreach my $key (sort(keys(%outhash))) {
                 if ($key=~/^home_(.+)$/) {
                     if ($1 eq $env{'user.name'}.':'.$env{'user.domain'}) {
                         unshift(@orderspaces,$1);
                     } else {
                         push(@orderspaces,$1);
                     }
-                }
+                } 
             }
             if ($home>1) {
                 $preamble .= '<option value="" selected="selected">'.&mt('Select').'</option>';
             }
             foreach my $user (@orderspaces) {
-                if ($home==1) {
-                    $preamble .= '<input type="hidden" name="authorspace" value="'.$user.'" />';
-                } else {
-                    $preamble .= '<option value="'.$user.'">'.$user.' - '.
-                                 &Apache::loncommon::plainname(split(/\:/,$user)).'</option>';
-                }
-            }
-            unless ($home==1) {
-                $preamble .= '</select></fieldset></div>'."\n";
-            }
-            my $title=$origcrsdata{'description'};
-            $title=~s/[\/\s]+/\_/gs;
-            $title=&clean($title);
-            $preamble .= '<div class="LC_left_float">'.
+		if ($home==1) {
+		    $preamble .= '<input type="hidden" name="authorspace" value="'.$user.'" />';
+		} else {
+		    $preamble .= '<option value="'.$user.'">'.$user.' - '.
+			         &Apache::loncommon::plainname(split(/\:/,$user)).'</option>';
+	        }
+	    }
+	    unless ($home==1) {
+	        $preamble .= '</select></fieldset></div>'."\n";
+	    }
+	    my $title=$origcrsdata{'description'};
+	    $title=~s/[\/\s]+/\_/gs;
+	    $title=&clean($title);
+	    $preamble .= '<div class="LC_left_float">'.
                          '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
                          '<input type="text" size="50" name="authorfolder" value="'.
                          $title.'" />'.
                          '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>'."\n";
             my %uploadedfiles;
-            &tiehash();
-            foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
-                my ($ext)=($file=~/\.(\w+)$/);
+	    &tiehash();
+	    foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
+	        my ($ext)=($file=~/\.(\w+)$/);
 # FIXME Check supplemental here
-                my $title=$hash{'title_'.$hash{
-                                'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
-                if (!$title) {
-                    $title=$file;
-                } else {
-                    $title=~s|/|_|g;
-                }
-                $title=~s/\.(\w+)$//;
-                $title=&clean($title);
-                $title.='.'.$ext;
-#           $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
+	        my $title=$hash{'title_'.$hash{
+		                'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
+	        if (!$title) {
+		    $title=$file;
+	        } else {
+		    $title=~s|/|_|g;
+	        }
+	        $title=~s/\.(\w+)$//;
+	        $title=&clean($title);
+	        $title.='.'.$ext;
+#	    $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
                 $uploadedfiles{$file} = $title;
-            }
-            &untiehash();
+	    }
+	    &untiehash();
             $r->print(&Apache::loncourserespicker::create_picker($navmap,'dumpdocs',$formname,$crstype,undef,
                                                                  undef,undef,$preamble,$home,\%uploadedfiles));
         }
@@ -564,16 +564,16 @@ sub recurse_html {
                 } else {
                     $relfile = $dependency;
                     $depurl = $currurlpath;
-                    $depurl =~ s{[^/]+$}{}; 
+                    $depurl =~ s{[^/]+$}{};  
                     $depurl .= $dependency;
-                    ($newcontainer) = ($depurl =~ m{^\Q$prefix\E(.+)$});
+                    ($newcontainer) = ($depurl =~ m{^\Q$prefix\E(.+)$}); 
                 }
                 next if ($relfile eq '');
                 my $newname = $replacehash->{$container};
                 $newname =~ s{[^/]+$}{};
                 $replacehash->{$newcontainer} = $newname.$relfile;
                 $deps->{$item}{$newcontainer} = 1;
-                my ($newurlpath) = ($depurl =~ m{^(.*)/[^/]+$});
+                my ($newurlpath) = ($depurl =~ m{^(.*)/[^/]+$});  
                 my $depfile = &Apache::lonnet::filelocation('',$depurl);
                 my $type = $mm->checktype_filename($depfile);
                 if ($type eq 'text/html') {
@@ -586,7 +586,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 = {};
@@ -615,6 +615,89 @@ sub group_import {
             }
         }
 	if ($url) {
+            if ($url =~ m{^(/adm/$coursedom/$coursenum/(\d+)/exttool)s?\:?(.*)$}) {
+                $url = $1;
+                my $marker = $2;
+                my $info = $3;
+                my ($toolid,%toolhash,%toolsettings);
+                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{'crslabel'},$toolhash{'crstitle'}) = @toolinfo;
+                $toolhash{'crslabel'} = &unescape($toolhash{'crslabel'});
+                $toolhash{'crstitle'} = &unescape($toolhash{'crstitle'});
+                if (ref($ltitoolsref) eq 'HASH') {
+                    my @deleted;
+                    if (ref($ltitoolsref->{$toolid}) eq 'HASH') {
+                        if ($ltitoolsref->{$toolid}->{'url'} =~ m{^https://}) {
+                            $url =~ s/exttool$/exttools/;
+                        }
+                        $toolhash{'id'} = $toolid;
+                        if (($toolhash{'target'} eq 'iframe') || ($toolhash{'target'} eq 'window')) {
+                            if ($toolhash{'target'} eq 'window') {
+                                foreach my $item ('width','height') {
+                                    $toolhash{$item} =~ s/^\s+//;
+                                    $toolhash{$item} =~ s/\s+$//;
+                                }
+                            }
+                        } elsif ($residx) {
+                            $toolhash{'target'} = $toolsettings{'target'};
+                            if ($toolhash{'target'} eq 'window') {
+                                $toolhash{'width'} = $toolsettings{'width'};
+                                $toolhash{'height'} = $toolsettings{'height'};  
+                            }
+                        } 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') {
+                            delete($toolhash{'width'});
+                            delete($toolhash{'height'});
+                            if ($residx) {
+                                if ($toolsettings{'width'}) {
+                                    push(@deleted,'width');
+                                }
+                                if ($toolsettings{'height'}) {
+                                    push(@deleted,'height');
+                                }
+                            }
+                        }
+                        if (ref($ltitoolsref->{$toolid}->{'crsconf'}) eq 'HASH') {
+                            foreach my $item ('label','title') { 
+                                if ($ltitoolsref->{$toolid}->{'crsconf'}->{$item}) {
+                                    $toolhash{'crs'.$item} =~ s/^\s+//;
+                                    $toolhash{'crs'.$item} =~ s/\s+$//;
+                                    if ($toolhash{'crs'.$item} eq '') {
+                                        delete($toolhash{'crs'.$item});
+                                    }
+                                } else {
+                                    delete($toolhash{'crs'.$item});
+                                }
+                                if (($residx) && (exists($toolsettings{'crs'.$item}))) {
+                                    unless (exists($toolhash{'crs'.$item})) {
+                                        push(@deleted,'crs'.$item);
+                                    }
+                                }
+                            }
+                        }
+                        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)) {
@@ -652,7 +735,7 @@ sub group_import {
                 } else {
                     $fname =~ s/\W/_/g;
                 }
-                if (length($fname > 15)) {
+                if (length($fname) > 15) {
                     $fname = substr($fname,0,14);
                 }
                 my $initialtext = &mt('Replace with your own content.');
@@ -667,7 +750,7 @@ $initialtext
 </html>
 END
                 $env{'form.output'}=$newhtml;
-                my $result =
+                my $result = 
                     &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
                                                           'output',
                                                           "$filepath/$residx/$fname.html");
@@ -692,7 +775,7 @@ END
                           removefrommap => \%removefrommap,
                           removeparam   => \%removeparam,
                       );
-        my ($result,$msgsarray,$lockerror) =
+        my ($result,$msgsarray,$lockerror) = 
             &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
         if (keys(%import_errors) > 0) {
             $fixuperrors =
@@ -1022,27 +1105,33 @@ sub update_paste_buffer {
         foreach my $suffix (@currpaste) {
              my $cid = $env{'docs.markedcopy_crs_'.$suffix};
              my $url = $env{'docs.markedcopy_url_'.$suffix};
+             my $mapidx = $env{'docs.markedcopy_map_'.$suffix};           
              if (($cid =~ /^$match_domain(?:_)$match_courseid$/) &&
                  ($url ne '')) {
-                 $pasteurls{$cid.'_'.$url} = 1;
+                 $pasteurls{$cid.'_'.$url.'_'.$mapidx} = 1;
              }
         }
     }
 
 # Mark items for copying (skip any items already in user's paste buffer)
     my %addtoenv;
-                  
+
+    my @pathitems = split(/\&/,$env{'form.folderpath'});
+    my @folderconf = split(/\:/,$pathitems[-1]);
+    my $ispage = $folderconf[4];
+
     foreach my $item (@possibles) {
         my ($orderidx,$cmd) = split(/:/,$item);
         next if ($orderidx =~ /\D/);
         next unless (($cmd eq 'cut') || ($cmd eq 'copy') || ($cmd eq 'remove'));
+        my $mapidx = $folder.':'.$orderidx.':'.$ispage;
         my ($title,$url)=split(':',$LONCAPA::map::resources[$orderidx]);
         my %denied = &action_restrictions($coursenum,$coursedom,
                                           &LONCAPA::map::qtescape($url),
                                           $env{'form.folderpath'},\%curr_groups);
         next if ($denied{'copy'});
         $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
-        next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$url}));
+        next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$mapidx}));
         my ($suffix,$errortxt,$locknotfreed) =
             &new_timebased_suffix($env{'user.domain'},$env{'user.name'},'paste');
         if ($suffix ne '') {
@@ -1061,7 +1150,7 @@ sub update_paste_buffer {
         $addtoenv{'docs.markedcopy_url_'.$suffix}   = $url,
         $addtoenv{'docs.markedcopy_cmd_'.$suffix}   = $cmd,
         $addtoenv{'docs.markedcopy_crs_'.$suffix}   = $env{'request.course.id'};
- 
+        $addtoenv{'docs.markedcopy_map_'.$suffix}   = $mapidx;
         if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
             my $prefix = $1;
             my $subdir =$2;
@@ -1139,14 +1228,17 @@ sub print_paste_buffer {
         next if ($suffix =~ /\D/);
         my $cid = $env{'docs.markedcopy_crs_'.$suffix};
         my $url = $env{'docs.markedcopy_url_'.$suffix};
+        my $mapidx = $env{'docs.markedcopy_map_'.$suffix};
         if (($cid =~ /^$match_domain\_$match_courseid$/) &&
             ($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+/exttools?$}) {
+                $is_exttool = 1;
             }
             if ($folder =~ /^supplemental/) {
                 $canpaste = &supp_pasteable($env{'docs.markedcopy_url_'.$suffix});
@@ -1164,9 +1256,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.'); 
@@ -1180,13 +1270,24 @@ 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)$})) {
+                    if ($cid ne $env{'request.course.id'}) {
+                        my ($srcdom,$srcnum) = split(/_/,$cid);
+                        if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
+                            $othercrs = '<br />'.&mt('(from another course)');
+                        } else {
+                            $canpaste = 0;
+                            $nopaste = &mt('Paste from another course unavailable.');
+                        }       
+                    }
                 }
-            }
-            if ($canpaste) {
-               push(@pasteable,$suffix);
+                if ($canpaste) {
+                    push(@pasteable,$suffix);
+                }  
             }
             my $buffer;
-            if ($is_external) {
+            if (($is_external) || ($is_exttool)) {
                 $buffer = &mt('External Resource').': '.
                     &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
                     &LONCAPA::map::qtescape($url).')';
@@ -1242,10 +1343,10 @@ sub print_paste_buffer {
             my $value = &mt('Paste to current folder');
             if ($container eq 'page') {
                 $value = &mt('Paste to current page');
-            }
+            } 
             $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).
@@ -1346,36 +1447,42 @@ 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+/exttools?$})) {
         return 1;
     }
     return;
 }
 
 sub paste_popup_js {
-    my %lt = &Apache::lonlocal::texthash(
+    my %html_js_lt = &Apache::lonlocal::texthash(
                                           show => 'Show Options',
                                           hide => 'Hide Options',
+                                        );
+    my %js_lt = &Apache::lonlocal::texthash(
                                           none => 'No items selected from clipboard.',
                                         );
+    &html_escape(\%html_js_lt);
+    &js_escape(\%html_js_lt);
+    &js_escape(\%js_lt);
     return <<"END";
 
 function showPasteOptions(suffix) {
     document.getElementById('pasteoptions_'+suffix).style.display='block';
-    document.getElementById('pasteoptionstext_'+suffix).innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:hidePasteOptions(\\''+suffix+'\\');" class="LC_menubuttons_link">$lt{'hide'}</a>';
+    document.getElementById('pasteoptionstext_'+suffix).innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:hidePasteOptions(\\''+suffix+'\\');" class="LC_menubuttons_link">$html_js_lt{'hide'}</a>';
     return;
 }
 
 function hidePasteOptions(suffix) {
     document.getElementById('pasteoptions_'+suffix).style.display='none';
-    document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
+    document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$html_js_lt{'show'}</a>';
     return;
 }
 
 function showOptions(caller,suffix) {
     if (document.getElementById('pasteoptionstext_'+suffix)) {
         if (caller.checked) {
-            document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
+            document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$html_js_lt{'show'}</a>';
         } else {
             document.getElementById('pasteoptionstext_'+suffix).innerHTML ='';
         }
@@ -1404,7 +1511,7 @@ function validateClipboard() {
     if (numchk > 0) { 
         return true;
     } else {
-        alert("$lt{'none'}");
+        alert("$js_lt{'none'}");
         return false;
     }
 }
@@ -1413,7 +1520,7 @@ function checkClipboard() {
     if (document.pasteform.pasting.length > 1) {
         for (var i=0; i<document.pasteform.pasting.length; i++) {
             document.pasteform.pasting[i].checked = true;
-        }
+        } 
     }
     return;
 }
@@ -1464,10 +1571,12 @@ sub do_paste_from_buffer {
     }
 
     my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%duplicate,
-        %prefixchg,%srcdom,%srcnum,%marktomove,$save_err,$lockerrors,$allresult);
+        %prefixchg,%srcdom,%srcnum,%srcmapidx,%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});
+        my $mapidx=&LONCAPA::map::qtescape($env{'docs.markedcopy_map_'.$suffix}); 
 # Supplemental content may only include certain types of content
 # Early out if pasted content is not supported in Supplemental area
         if ($folder =~ /^supplemental/) {
@@ -1489,8 +1598,21 @@ sub do_paste_from_buffer {
             }
             $srcdom{$suffix} = $srcd;
             $srcnum{$suffix} = $srcn;
+        } elsif (($url =~ m{^/res/lib/templates/\w+\.problem$}) ||
+                 ($url =~ m{^/adm/$match_domain/$match_username/\d+/(bulletinboard|smppg)$})) {
+            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;
+                }
+            }
+            $srcdom{$suffix} = $srcd;
+            $srcnum{$suffix} = $srcn;
         }
-
+        $srcmapidx{$suffix} = $mapidx;
         push(@dopaste,$suffix);
         if ($url=~/\.(page|sequence)$/) {
             $is_map{$suffix} = 1; 
@@ -1500,7 +1622,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/)) {
@@ -1582,12 +1704,13 @@ sub do_paste_from_buffer {
 # Maps need to be copied first
         my (%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
             %dbcopies,%zombies,%params,%docmoves,%mapmoves,%mapchanges,%newsubdir,
-            %newurls,%tomove);
+            %newurls,%tomove,%resdatacopy);
         if (ref($marktomove{$suffix}) eq 'ARRAY') {
             map { $tomove{$_} = 1; } @{$marktomove{$suffix}};
         }
         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
@@ -1623,7 +1746,7 @@ sub do_paste_from_buffer {
                                               \%retitles,\%copies,\%dbcopies,
                                               \%zombies,\%params,\%mapmoves,
                                               \%mapchanges,\%tomove,\%newsubdir,
-                                              \%newurls)) {
+                                              \%newurls,\%resdatacopy)) {
                         $mapmoves{$url} = 1;
                     }
                     $url = $newurl;
@@ -1632,10 +1755,10 @@ sub do_paste_from_buffer {
                                       $coursenum,$srcdom{$suffix},$srcnum{$suffix},
                                       $allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
                                       \%zombies,\%params,\%mapmoves,\%mapchanges,
-                                      \%tomove,\%newsubdir,\%newurls); 
+                                      \%tomove,\%newsubdir,\%newurls,\%resdatacopy);
                 }
             } 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/) {
@@ -1648,13 +1771,21 @@ sub do_paste_from_buffer {
         }
         if ($url=~ m{/(bulletinboard|smppg)$}) {
             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);
@@ -1673,7 +1804,7 @@ sub do_paste_from_buffer {
                     next;
 	        }
                 if ($lockerr{$prefix}) {
-                    $lockerrs{$suffix} = $lockerr{$prefix};
+                    $lockerrs{$suffix} = $lockerr{$prefix};  
                 }
             }
         }
@@ -1712,7 +1843,7 @@ sub do_paste_from_buffer {
                     if ($newdocsdir eq '') {
                         $newdocsdir = 'default';
                     }
-                    if (($prefixchg{$suffix}) ||
+                    if (($prefixchg{$suffix}) || 
                         ($srcdom{$suffix} ne $coursedom) || 
                         ($srcnum{$suffix} ne $coursenum) ||
                         ($env{'form.docs.markedcopy_options_'.$suffix} ne 'move')) {
@@ -1730,6 +1861,12 @@ sub do_paste_from_buffer {
                         }
                     }
                 }
+            } elsif ($url =~ m{^/res/lib/templates/(\w+)\.problem$}) {
+                my $template = $1;
+                if ($newidx) {
+                    &copy_templated_files($url,$srcdom{$suffix},$srcnum{$suffix},$srcmapidx{$suffix},
+                                          $coursedom,$coursenum,$template,$newidx,"$folder.$container");
+                }
             }
             $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
                                               ':'.$ext.':normal:res';
@@ -1743,7 +1880,8 @@ sub do_paste_from_buffer {
             }
         }
 
-# Apply any changes to maps, or copy dependencies for uploaded HTML pages 
+# Apply any changes to maps, or copy dependencies for uploaded HTML pages, or update
+# resourcedata for simpleproblems copied from another course 
         unless ($allresult eq 'fail') {
             my %updated = (
                             rewrites      => \%rewrites,
@@ -1751,6 +1889,7 @@ sub do_paste_from_buffer {
                             removefrommap => \%removefrommap,
                             removeparam   => \%removeparam,
                             dbcopies      => \%dbcopies,
+                            resdatacopy   => \%resdatacopy,
                             retitles      => \%retitles,
                           );
             my %info = (
@@ -1915,11 +2054,11 @@ sub get_newmap_url {
 sub dbcopy {
     my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
     my ($url,$result,$errtext);
-    $url = $dbref->{'src'};
     if (ref($dbref) eq 'HASH') {
+        $url = $dbref->{'src'};
         if ($url =~ m{/(smppg|bulletinboard)$}) {
             my $prefix = $1;
-            if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
+            if (($dbref->{'cdom'} =~ /^$match_domain$/) && 
                 ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
                 my $db_name;
                 my $marker = (split(m{/},$url))[4];
@@ -1959,7 +2098,7 @@ sub dbcopy {
                             my $content = &Apache::lonnet::getfile($photo);
                             unless ($content eq '-1') {
                                 $env{'form.'.$suffix.'.photourl'} = $content;
-                                $newphoto =
+                                $newphoto = 
                                     &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
                                 delete($env{'form.'.$suffix.'.photourl'});
                             }
@@ -2007,6 +2146,95 @@ sub dbcopy {
     return ($url,$result,$errtext);
 }
 
+sub copy_templated_files {
+    my ($srcurl,$srcdom,$srcnum,$srcmapinfo,$coursedom,$coursenum,$template,$newidx,$newmapname) = @_;
+    my ($srcfolder,$srcid,$srcwaspage) = split(/:/,$srcmapinfo);
+    my $srccontainer = 'sequence';
+    if ($srcwaspage) {
+        $srccontainer = 'page';
+    }
+    my $srcsymb = "uploaded/$srcdom/$srcnum/$srcfolder.$srccontainer".
+                  '___'.$srcid.'___'.&Apache::lonnet::declutter($srcurl);
+    my $srcprefix = $srcdom.'_'.$srcnum.'.'.$srcsymb;
+    my %srcparms=&Apache::lonnet::dump('resourcedata',$srcdom,$srcnum,$srcprefix);
+    my $newsymb = "uploaded/$coursedom/$coursenum/$newmapname".'___'.$newidx.'___lib/templates/'.
+                  $template.'.problem';
+    my $newprefix = $coursedom.'_'.$coursenum.'.'.$newsymb;
+    if ($template eq 'simpleproblem') {
+        $srcprefix .= '.0.';
+        my $weightprefix = $newprefix;
+        $newprefix .= '.0.';
+        my @simpleprobqtypes = qw(radio option string essay numerical);
+        my $qtype=$srcparms{$srcprefix.'questiontype'};
+        if (grep(/^\Q$qtype\E$/,@simpleprobqtypes)) {
+            my %newdata;
+            foreach my $type (@simpleprobqtypes) {
+                if ($type eq $qtype) {
+                    $newdata{"$weightprefix.$type.weight"}=1;
+                } else {
+                    $newdata{"$weightprefix.$type.weight"}=0;
+                }
+            }
+            $newdata{$newprefix.'hiddenparts'} = '!'.$qtype;
+            $newdata{$newprefix.'questiontext'} = $srcparms{$srcprefix.'questiontext'};
+            $newdata{$newprefix.'hinttext'} = $srcparms{$srcprefix.'hinttext'};
+            if ($qtype eq 'numerical') {
+                $newdata{$newprefix.'numericalscript'} = $srcparms{$srcprefix.'numericalscript'};
+                $newdata{$newprefix.'numericalanswer'} = $srcparms{$srcprefix.'numericalanswer'};
+                $newdata{$newprefix.'numericaltolerance'} = $srcparms{$srcprefix.'numericaltolerance'};
+                $newdata{$newprefix.'numericalsigfigs'} = $srcparms{$srcprefix.'numericalsigfigs'};
+            } elsif (($qtype eq 'option') || ($qtype eq 'radio')) {
+                my $maxfoils=$srcparms{$srcprefix.'maxfoils'};
+                unless (defined($maxfoils)) { $maxfoils=10; }
+                    unless ($maxfoils=~/^\d+$/) { $maxfoils=10; }
+                        if ($maxfoils<=0) { $maxfoils=10; }
+                            my $randomize=$srcparms{$srcprefix.'randomize'};
+                            unless (defined($randomize)) { $randomize='yes'; }
+                            unless ($randomize eq 'no') { $randomize='yes'; }
+                            $newdata{$newprefix.'maxfoils'} = $maxfoils;
+                            $newdata{$newprefix.'randomize'} = $randomize;
+                            if ($qtype eq 'option') {
+                                $newdata{$newprefix.'options'} = $srcparms{$srcprefix.'options'};
+                            }
+                            for (my $i=1; $i<=10; $i++) {
+                                $newdata{$newprefix.'value'.$i} = $srcparms{$srcprefix.'value'.$i};
+                                $newdata{$newprefix.'position'.$i} = $srcparms{$srcprefix.'position'.$i};
+                                $newdata{$newprefix.'text'.$i} = $srcparms{$srcprefix.'text'.$i};
+                            }
+
+            } elsif (($qtype eq 'option') || ($qtype eq 'radio')) {
+                my $maxfoils=$srcparms{$srcprefix.'maxfoils'};
+                unless (defined($maxfoils)) { $maxfoils=10; }
+                unless ($maxfoils=~/^\d+$/) { $maxfoils=10; }
+                if ($maxfoils<=0) { $maxfoils=10; }
+                my $randomize=$srcparms{$srcprefix.'randomize'};
+                unless (defined($randomize)) { $randomize='yes'; }
+                unless ($randomize eq 'no') { $randomize='yes'; }
+                $newdata{$newprefix.'maxfoils'} = $maxfoils;
+                $newdata{$newprefix.'randomize'} = $randomize;
+                if ($qtype eq 'option') {
+                    $newdata{$newprefix.'options'} = $srcparms{$srcprefix.'options'};
+                }
+                for (my $i=1; $i<=10; $i++) {
+                    $newdata{$newprefix.'value'.$i} = $srcparms{$srcprefix.'value'.$i};
+                    $newdata{$newprefix.'position'.$i} = $srcparms{$srcprefix.'position'.$i};
+                    $newdata{$newprefix.'text'.$i} = $srcparms{$srcprefix.'text'.$i};
+                }
+            } elsif ($qtype eq 'string') {
+                $newdata{$newprefix.'stringanswer'} = $srcparms{$srcprefix.'stringanswer'};
+                $newdata{$newprefix.'stringtype'} = $srcparms{$srcprefix.'stringtype'};
+            }
+            if (keys(%newdata)) {
+                my $putres = &Apache::lonnet::cput('resourcedata',\%newdata,$coursedom,
+                                                   $coursenum);
+                if ($putres eq 'ok') {
+                    &Apache::lonnet::devalidatecourseresdata($coursenum,$coursedom);
+                }
+            }
+        }
+    }
+}
+
 sub uniqueness_check {
     my ($newurl) = @_;
     my $unique = 1;
@@ -2072,7 +2300,7 @@ sub contained_map_check {
 sub url_paste_fixups {
     my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
         $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
-        $mapchanges,$tomove,$newsubdir,$newurls) = @_;
+        $mapchanges,$tomove,$newsubdir,$newurls,$resdatacopy) = @_;
     my $checktitle;
     if (($prefixchg) &&
         ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
@@ -2104,7 +2332,7 @@ sub url_paste_fixups {
             }
             next if ($token->[2]->{'type'} eq 'external');
             if ($token->[2]->{'type'} eq 'zombie') {
-                next if ($skip);
+                next if ($skip);  
                 $zombies->{$oldurl}{$id} = $ressrc;
                 $changed = 1;
             } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
@@ -2121,7 +2349,7 @@ sub url_paste_fixups {
                                           $srcdom,$srcnum,$allmaps,$rewrites,
                                           $retitles,$copies,$dbcopies,$zombies,
                                           $params,$mapmoves,$mapchanges,$tomove,
-                                          $newsubdir,$newurls);
+                                          $newsubdir,$newurls,$resdatacopy);
                         next;
                     } else {
                         ($newurl,my $error) =
@@ -2145,7 +2373,7 @@ sub url_paste_fixups {
                                                   $cnum,$srcdom,$srcnum,$allmaps,
                                                   $rewrites,$retitles,$copies,$dbcopies,
                                                   $zombies,$params,$mapmoves,$mapchanges,
-                                                  $tomove,$newsubdir,$newurls)) {
+                                                  $tomove,$newsubdir,$newurls,$resdatacopy)) {
                             $mapmoves->{$ressrc} = 1;
                         }
                         $changed = 1;
@@ -2174,6 +2402,12 @@ sub url_paste_fixups {
                     $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
                     $changed = 1;
                 }
+            } elsif ($ressrc eq '/res/lib/templates/simpleproblem.problem') {
+                if (($fromcdom ne $cdom) || ($fromcnum ne $cnum)) {
+                    $resdatacopy->{$oldurl}{$id}{'src'} = $ressrc;
+                    $resdatacopy->{$oldurl}{$id}{'cdom'} = $fromcdom;
+                    $resdatacopy->{$oldurl}{$id}{'cnum'} = $fromcnum;
+                }
             } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
                 next if ($skip);
                 my $srcdom = $1;
@@ -2205,7 +2439,7 @@ sub apply_fixups {
         $oldurl,$url,$caller) = @_;
     my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
         %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
-        %lockerrors,$lockmsg);
+        %resdatacopy,%lockerrors,$lockmsg);
     if (ref($updated) eq 'HASH') {
         if (ref($updated->{'rewrites'}) eq 'HASH') {
             %rewrites = %{$updated->{'rewrites'}};
@@ -2225,6 +2459,9 @@ sub apply_fixups {
         if (ref($updated->{'retitles'}) eq 'HASH') {
             %retitles = %{$updated->{'retitles'}};
         }
+        if (ref($updated->{'resdatacopy'}) eq 'HASH') {
+            %resdatacopy = %{$updated->{'resdatacopy'}};
+        }
     }
     if (ref($info) eq 'HASH') {
         if (ref($info->{'newsubdir'}) eq 'HASH') {
@@ -2375,6 +2612,35 @@ sub apply_fixups {
                     }
                 }
             }
+            if (ref($resdatacopy{$key}) eq 'HASH') {
+                if ($newsubdir{$key}) {
+
+                }
+                foreach my $idx (keys(%{$resdatacopy{$key}})) {
+                    if (ref($resdatacopy{$key}{$idx}) eq 'HASH') {
+                        my $srcurl = $resdatacopy{$key}{$idx}{'src'};
+                        if ($srcurl =~ m{^/res/lib/templates/(\w+)\.problem$}) {
+                            my $template = $1;
+                            if (($resdatacopy{$key}{$idx}{'cdom'} =~ /^$match_domain$/) &&
+                                ($resdatacopy{$key}{$idx}{'cnum'} =~ /^$match_courseid$/)) {
+                                my $srcdom = $resdatacopy{$key}{$idx}{'cdom'};
+                                my $srcnum = $resdatacopy{$key}{$idx}{'cnum'};
+                                my ($newmapname) = ($key =~ m{/([^/]+)$});
+                                my ($srcfolder,$srccontainer) = split(/\./,$newmapname);
+                                my $srcmapinfo = $srcfolder.':'.$idx;
+                                if ($srccontainer eq 'page') {
+                                    $srcmapinfo .= ':1';
+                                }
+                                if ($newsubdir{$key}) {
+                                    $newmapname =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
+                                }
+                                &copy_templated_files($srcurl,$srcdom,$srcnum,$srcmapinfo,$cdom,
+                                                      $cnum,$template,$idx,$newmapname);
+                            }
+                        }
+                    }
+                }
+            }
             if (ref($params{$key}) eq 'HASH') {
                 %currparam = %{$params{$key}};
             }
@@ -2550,7 +2816,7 @@ sub update_parameter {
                          'randomorder'    => {},
                       );
         foreach my $which (keys(%allchecked)) {
-            $env{'form.all'.$which} =~ s/,$//;
+            $env{'form.all'.$which} =~ s/,$//;   
             if ($which eq 'randompick') {
                 foreach my $item (split(/,/,$env{'form.all'.$which})) {
                     my ($res,$value) = split(/:/,$item);
@@ -2577,7 +2843,7 @@ sub update_parameter {
             foreach my $which (keys(%allchecked)) {
                 if (($which eq 'randompick' || $which eq 'randomorder')) {
                     next if (!$is_map);
-                }
+                } 
                 my $oldvalue = 0;
                 my $newvalue = 0;
                 if ($allchecked{$which}{$res}) {
@@ -2613,26 +2879,44 @@ sub update_parameter {
         }
         return $haschanges;
     } else {
-        return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
+        my $haschanges = 0;
+        return $haschanges if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
 
         my $which = $env{'form.changeparms'};
         my $idx = $env{'form.setparms'};
+        my $oldvalue = 0;
+        my $newvalue = 0;
+        my $current = (&LONCAPA::map::getparameter($idx,'parameter_'.$which))[0];
+        if ($which eq 'randompick') {
+            if ($current =~ /^(\d+)$/) {
+                $oldvalue = $1;
+            }
+        } elsif ($current =~ /^yes$/i) {
+            $oldvalue = 1;
+        }
         if ($env{'form.'.$which.'_'.$idx}) {
-	    my $value = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
-	                                         : 'yes';
-	    &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
-				          $parameter_type{$which});
-	    &remember_parms($idx,$which,'set',$value);
-        } else {
-	    &LONCAPA::map::delparameter($idx,'parameter_'.$which);
-
-	    &remember_parms($idx,$which,'del');
+	    $newvalue = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
+	                                         : 1;
         }
-        return 1;
+        if ($oldvalue ne $newvalue) {
+            $haschanges = 1;
+            if ($newvalue) {
+                my $storeval = 'yes';
+                if ($which eq 'randompick') {
+                    $storeval = $newvalue;
+                }
+	        &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $storeval,
+				              $parameter_type{$which});
+	        &remember_parms($idx,$which,'set',$storeval);
+            } else {
+	        &LONCAPA::map::delparameter($idx,'parameter_'.$which);
+	        &remember_parms($idx,$which,'del');
+            }
+        }
+        return $haschanges;
     }
 }
 
-
 sub handle_edit_cmd {
     my ($coursenum,$coursedom) =@_;
     if ($env{'form.cmd'} eq '') {
@@ -2682,7 +2966,7 @@ sub handle_edit_cmd {
 
 sub editor {
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
-        $supplementalflag,$orderhash,$iconpath,$pathitem)=@_;
+        $supplementalflag,$orderhash,$iconpath,$pathitem,$ltitoolsref)=@_;
     my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
     if ($allowed) {
         (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
@@ -2724,7 +3008,7 @@ sub editor {
 	&snapshotbefore();
 
 	if (&update_parameter()) {
-	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
+	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 	    return $errtext if ($fatal);
 	}
 
@@ -2786,9 +3070,9 @@ sub editor {
 	$r->print($upload_output);
 
 # Rename, cut, copy or remove a single resource
-	if (&handle_edit_cmd()) {
+	if (&handle_edit_cmd($coursenum,$coursedom)) {
             my $contentchg;
-            if ($env{'form.cmd'} =~ m{^(del|cut)_}) {
+            if ($env{'form.cmd'} =~ m{^(remove|cut)_}) {
                 $contentchg = 1;
             }
 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
@@ -2881,6 +3165,17 @@ sub editor {
                         } else {
                             return $errortxt;
                         }
+                    } elsif ($url =~ m{^/adm/$coursedom/$coursenum/new/exttool}) {
+                        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');
@@ -2903,7 +3198,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);
@@ -2988,7 +3283,7 @@ sub editor {
         $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
                               $coursenum,$coursedom,$crstype,
                               $pathitem,$supplementalflag,$container,
-                              \%filters,\%curr_groups);
+                              \%filters,\%curr_groups,$ltitoolsref);
         $idx++;
         $shown++;
     }
@@ -3036,11 +3331,11 @@ sub editor {
                     if (@allidx > 0) {
                         my $path;
                         if ($env{'form.folderpath'}) {
-                            $path =
+                            $path = 
                                 &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
                         }
                         if (@allidx > 1) {
-                            $to_show .=
+                            $to_show .= 
                                 &Apache::loncommon::continue_data_table_row().
                                 '<td colspan="2">&nbsp;</td>'.
                                 '<td>'.
@@ -3185,6 +3480,8 @@ sub process_file_upload {
     my $quotatype = 'unofficial';
     if ($crstype eq 'Community') {
         $quotatype = 'community';
+    } elsif ($crstype eq 'Placement') {
+        $quotatype = 'placement';
     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.coursecode'}) {
         $quotatype = 'official';
     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.textbook'}) {
@@ -3354,7 +3651,8 @@ sub is_supplemental_title {
 
 sub entryline {
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
-        $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups)=@_;
+        $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups,
+        $ltitoolsref)=@_;
     my ($foldertitle,$renametitle,$oldtitle);
     if (&is_supplemental_title($title)) {
 	($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
@@ -3371,7 +3669,7 @@ sub entryline {
     $renametitle=~s/"/%22/g;
     $renametitle=~s/ /%20/g;
     $oldtitle = $renametitle;
-    $renametitle=~s/\&#39\;/\\\'/g;
+    $renametitle=~s/\&#39;/\\\'/g;
     my $line=&Apache::loncommon::start_data_table_row();
     my ($form_start,$form_end,$form_common,$form_param);
 # Edit commands
@@ -3445,6 +3743,7 @@ END
 		'rn' => 'Rename',
 		'cp' => 'Copy',
                 'ex' => 'External Resource',
+                'et' => 'External Tool',
                 'ed' => 'Edit',
                 'pr' => 'Preview',
                 'sv' => 'Save',
@@ -3456,16 +3755,22 @@ END
                                           $currgroups);
         my ($copylink,$cutlink,$removelink);
 	my $skip_confirm = 0;
+        my $confirm_removal = 0;
 	if ( $folder =~ /^supplemental/
 	     || ($url =~ m{( /smppg$
 			    |/syllabus$
 			    |/aboutme$
 			    |/navmaps$
 			    |/bulletinboard$
+                            |/exttools?$
 			    |\.html$)}x)
              || $isexternal) {
 	    $skip_confirm = 1;
 	}
+        if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
+            ($url!~/$LONCAPA::assess_page_seq_re/)) {
+            $confirm_removal = 1;
+        }
 
 	if ($denied{'copy'}) {
             $copylink=(<<ENDCOPY)
@@ -3508,11 +3813,12 @@ ENDCUT
 ENDREM
         } else {
             my $formname = 'edit_remove_'.$orderidx;
-            my $js = "javascript:checkForSubmit(document.forms.renameform,'remove','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm);";
+            my $js = "javascript:checkForSubmit(document.forms.renameform,'remove','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder',$confirm_removal);";
             $removelink=(<<ENDREM);
 <form name="$formname" method="post" action="/adm/coursedocs">
 $form_common
 <input type="hidden" name="skip_$orderidx" id="skip_remove_$orderidx" value="$skip_confirm" />
+<input type="hidden" name="confirm_rem_$orderidx" id="confirm_removal_$orderidx" value="$confirm_removal" />
 <input type="checkbox" name="remove" id="remove_$orderidx" value="$orderidx" onclick="javascript:singleCheck(this,'$orderidx','remove');" class="LC_hidden" /><a href="$js" class="LC_docs_remove">$lt{'rm'}</a>
 $form_end
 ENDREM
@@ -3598,7 +3904,9 @@ END
 	        }
 	    } elsif ($url=~m|^/ext/|) {
 	        $url='/adm/wrapper'.$url;
-	    }
+	    } elsif ($url=~m{^/adm/$coursedom/$coursenum/\d+/exttools?$}) {
+		$url='/adm/wrapper'.$url;
+            }
             if (&Apache::lonnet::symbverify($symb,$url)) {
 	        $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
             } else {
@@ -3661,15 +3969,20 @@ $form_common."\n".
 $form_param."\n".
 $form_common."\n".
 '<span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" id="randomorder_'.$orderidx.'" onclick="checkForSubmit(this.form,'."'randomorder','settings'".');" '.$ro_set.' /> '.&mt('Random Order').' </label></span>'.
-$form_end;
+$form_end; 
         }
     } elsif ($supplementalflag && !$allowed) {
+        my $isexttool;
+        if ($url=~m{^/adm/$coursedom/$coursenum/\d+/exttools?$}) {
+            $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;
         }
     }
@@ -3680,6 +3993,11 @@ $form_end;
         if ($isexternal) {
             ($editlink,$extresform) = 
                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
+        } elsif ($orig_url =~ m{^/adm/$coursedom/$coursenum/\d+/exttools?$}) {
+            ($editlink,$extresform) =
+                &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
+                                                     undef,undef,undef,'tool',$coursedom,
+                                                     $coursenum,$ltitoolsref);
         } elsif (!$isfolder && !$ispage) {
             my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
                 &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
@@ -3778,9 +4096,11 @@ sub action_restrictions {
     if ($url=~ m{^/res/.+\.(page|sequence)$}) {
         # no copy for published maps
         $denied{'copy'} = 1;
-    } elsif ($url=~m{^/res/lib/templates/}) {
-       $denied{'copy'} = 1;
-       $denied{'cut'} = 1;
+    } elsif ($url=~m{^/res/lib/templates/([^/]+)\.problem$}) {
+        unless ($1 eq 'simpleproblem') {
+            $denied{'copy'} = 1;
+        }
+        $denied{'cut'} = 1;
     } elsif ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
         if ($folderpath =~ /^default&[^\&]+$/) {
             if ((ref($currgroups) eq 'HASH') && (keys(%{$currgroups}) > 0)) {
@@ -3865,7 +4185,7 @@ sub new_timebased_suffix {
         }
     }
     if ($freedlock ne 'ok') {
-        $locknotfreed =
+        $locknotfreed = 
             '<div class="LC_error">'.
             &mt('There was a problem removing a lockfile.').' ';
         if ($type eq 'paste') {
@@ -3873,9 +4193,9 @@ sub new_timebased_suffix {
                 $locknotfreed =
                     '<div class="LC_error">'.
                     &mt('A lockfile was not released when you added content to the clipboard earlier in this session.').' '.
-
-                    &mt('As a result addition of items to the clipboard wll be unavailable until your next log-in.');
-            } else {
+ 
+                    &mt('As a result addition of items to the clipboard will be unavailable until your next log-in.');
+            } else { 
                 $locknotfreed .=
                     &mt('This will prevent addition of items to the clipboard until your next log-in.');
             }
@@ -4274,7 +4594,7 @@ ENDHEADERS
         return;
     }
     $r->print(
-        '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
+       '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
         &Apache::loncommon::start_data_table().
         &Apache::loncommon::start_data_table_header_row().
         '<th>'.&mt('Resources').'</th>'.
@@ -4317,9 +4637,9 @@ ENDHEADERS
                       $setversions{$linkurl},
                       'set_version_'.$linkurl,
                       {'select_form_order' => ['',1..$currentversion,'mostrecent'],
-                       '' => '',
-                       'mostrecent' => &mt('most recent'),
-                       map {$_,$_} (1..$currentversion)}));
+                      '' => '',
+                      'mostrecent' => &mt('most recent'),
+                      map {$_,$_} (1..$currentversion)}));
             my $lastold=1;
             for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
                 my $url=$root.'.'.$prevvers.'.'.$extension;
@@ -4456,6 +4776,7 @@ sub startContentScreen {
     if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
         $output .= '<li'.(($mode eq 'navmaps')?' class="active"':'').'><a href="/adm/navmaps"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Overview').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
         $output .= '<li'.(($mode eq 'coursesearch')?' class="active"':'').'><a href="/adm/searchcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Search').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
+        $output .= '<li'.(($mode eq 'courseindex')?' class="active"':'').'><a href="/adm/indexcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Index').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
         $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
     } else {
         $output .= '<li '.(($mode eq 'docs')?' class="active"':'').' id="tabbededitor"><a href="/adm/coursedocs?forcestandard=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Main Content Editor').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
@@ -4588,6 +4909,7 @@ sub handler {
     my $container;
     my $containertag;
     my $pathitem;
+    my %ltitools;
 
 # Do we directly jump somewhere?
 
@@ -4725,11 +5047,13 @@ sub handler {
                 }
             }
             my $tabidstr = join("','",@tabids);
-	    $script .= &editing_js($udom,$uname,$supplementalflag).
+            %ltitools = &Apache::lonnet::get_domain_ltitools($coursedom);
+            my $posslti = keys(%ltitools);
+	    $script .= &editing_js($udom,$uname,$supplementalflag,$posslti).
                        &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');",
                           };
@@ -4745,7 +5069,9 @@ sub handler {
               .'// <![CDATA['."\n"
               .$script."\n"
               .'// ]]>'."\n"
-              .'</script>'."\n";
+              .'</script>'."\n"
+              .'<script type="text/javascript" 
+                src="/res/adm/includes/file_upload.js"></script>'."\n";
 
     # Breadcrumbs
     &Apache::lonhtmlcommon::clear_breadcrumbs();
@@ -4845,6 +5171,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',
@@ -4853,7 +5181,7 @@ sub handler {
                 'navc' => 'Table of Contents',
                 'sipa' => 'Simple Course Page',
                 'sipr' => 'Simple Problem',
-                'webp' => 'Blank Web Page (editable)',
+                'webp' => 'Blank Web Page (editable)', 
                 'drbx' => 'Drop Box',
                 'scuf' => 'External Scores (handgrade, upload, clicker)',
                 'bull' => 'Discussion Board',
@@ -4875,9 +5203,32 @@ sub handler {
                 'webctce4' => 'WebCT 4 Campus Edition',
         );
 # -----------------------------------------------------------------------------
+
+    # Calculate free quota space for a user or course. A javascript function checks
+    # file size to determine if upload should be allowed.
+    my $quotatype = 'unofficial';
+    if ($crstype eq 'Community') {
+        $quotatype = 'community';
+    } elsif ($crstype eq 'Placement') {
+        $quotatype = 'placement';
+    } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.coursecode'}) {
+        $quotatype = 'official';
+    } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.textbook'}) {
+        $quotatype = 'textbook';
+    }
+    my $disk_quota = &Apache::loncommon::get_user_quota($coursenum,$coursedom,
+                     'course',$quotatype); # expressed in MB
+    my $current_disk_usage = 0;
+    foreach my $subdir ('docs','supplemental') {
+        $current_disk_usage += &Apache::lonnet::diskusage($coursedom,$coursenum,
+                               "userfiles/$subdir",1); # expressed in kB
+    }
+    my $free_space = 1024 * ((1024 * $disk_quota) - $current_disk_usage);
+
 	my $fileupload=(<<FIUP);
 	$lt{'file'}:<br />
-	<input type="file" name="uploaddoc" size="40" />
+	<input type="file" name="uploaddoc" class="flUpload" size="40" />
+    <input type="hidden" id="free_space" value="$free_space" />
 FIUP
 
 	my $checkbox=(<<CHBO);
@@ -4924,7 +5275,7 @@ IMSFORM
         <fieldset id="uploaddocform" style="display: none;">
         <legend>$lt{'upfi'}</legend>
 	<input type="hidden" name="active" value="aa" />
-	$fileupload
+    $fileupload
 	<br />
 	$lt{'title'}:<br />
 	<input type="text" size="60" name="comment" />
@@ -4967,6 +5318,11 @@ SEDFFORM
         my $extresourcesform =
             &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
                                                  $help{'Adding_External_Resource'});
+        my $exttoolform =
+            &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
+                                                 $help{'Adding_External_Tool'},undef,
+                                                 undef,'tool',$coursedom,$coursenum,
+                                                 \%ltitools);
     if ($allowed) {
         my $folder = $env{'form.folder'};
         if ($folder eq '') {
@@ -5144,7 +5500,7 @@ NROSTFORM
         $help{'Web_Page'}
         </form>
 NWEBFORM
- 
+
 
 my $specialdocumentsform;
 my @specialdocumentsforma;
@@ -5212,6 +5568,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/extres.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}
@@ -5253,7 +5614,7 @@ unless ($container eq 'page') {
  $hadchanges=0;
        unless (($supplementalflag || $toolsflag)) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
-                              $supplementalflag,\%orderhash,$iconpath,$pathitem);
+                              $supplementalflag,\%orderhash,$iconpath,$pathitem,\%ltitools);
           if ($error) {
              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
@@ -5320,6 +5681,12 @@ SNFFORM
             &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
                                                  $help{'Adding_External_Resource'});
 
+        my $supexttoolform =
+            &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
+                                                 $help{'Adding_External_Tool'},
+                                                 undef,undef,'tool',$coursedom,
+                                                 $coursenum,\%ltitools);
+
 	my $supnewsylform=(<<SNSFORM);
 	<form action="/adm/coursedocs" method="post" name="supnewsyl">
 	<input type="hidden" name="active" value="ff" />
@@ -5373,10 +5740,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},
-                {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
+            =>$supextform});
+        if (keys(%ltitools)) {
+            push(@supimportdoc,
+                {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.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 = (
@@ -5386,7 +5759,7 @@ my %suporderhash = (
                 );
         if ($supplementalflag) {
            my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
-                               $supplementalflag,\%suporderhash,$iconpath,$pathitem);
+                               $supplementalflag,\%suporderhash,$iconpath,$pathitem,\%ltitools);
            if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
            } else {
@@ -5401,8 +5774,8 @@ my %suporderhash = (
                    }
                    &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
                    undef($suppchanges);
-               }
-           }
+               }  
+           } 
         }
     } elsif ($supplementalflag) {
         my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
@@ -5774,8 +6147,8 @@ END
 }
 
 sub editing_js {
-    my ($udom,$uname,$supplementalflag) = @_;
-    my %lt = &Apache::lonlocal::texthash(
+    my ($udom,$uname,$supplementalflag,$posslti) = @_;
+    my %js_lt = &Apache::lonlocal::texthash(
                                           p_mnf => 'Name of New Folder',
                                           t_mnf => 'New Folder',
                                           p_mnp => 'Name of New Page',
@@ -5792,16 +6165,18 @@ sub editing_js {
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                           p_chn => 'New Title',
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
-                                          p_rmr2a => 'Remove[_99]',
-                                          p_rmr2b => '?[_99]',
-                                          p_rmr3a => 'Remove those [_2]',
-                                          p_rmr3b => 'items?[_2]',
+                                          p_rmr2a => 'Remove',
+                                          p_rmr2b => '?',
+                                          p_rmr3a => 'Remove those',
+                                          p_rmr3b => 'items?',
+                                          p_rmr4  => 'WARNING: Removing a resource uploaded to a course cannot be undone via "Undo Delete".',
+                                          p_rmr5  => 'Push "Cancel" and then use "Cut" instead if you might need to undo this change.',
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
-                                          p_ctr2a => 'Cut[_98]',
-                                          p_ctr2b => '?[_98]',
-                                          p_ctr3a => 'Cut those[_2]',
-                                          p_ctr3b => 'items?[_2]',
+                                          p_ctr2a => 'Cut',
+                                          p_ctr2b => '?',
+                                          p_ctr3a => 'Cut those',
+                                          p_ctr3b => 'items?',
                                           rpck    => 'Enter number to pick (e.g., 3)',
                                           imsfile => 'You must choose an IMS package for import',
                                           imscms  => 'You must select which Course Management System was the source of the IMS package',
@@ -5813,7 +6188,7 @@ sub editing_js {
                                           noch    => 'No changes to settings specified.',
                                           noac    => 'No actions selected.',
                                         );
-
+    &js_escape(\%js_lt);
     my $crstype = &Apache::loncommon::course_type();
     my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
     my $main_container_page;
@@ -5835,7 +6210,7 @@ sub editing_js {
             if (&Apache::lonnet::is_on_map($res)) {
                 $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($res),'<>&"').'?symb='.
                              &HTML::Entities::encode($caller,'<>&"');
-                $backtourl = &Apache::loncommon::escape_single($backtourl); 
+                $backtourl = &Apache::loncommon::escape_single($backtourl);
             } else {
                 $backtourl = '/adm/navmaps';
             }
@@ -5849,16 +6224,22 @@ 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'";
+        }
     }
 
     return <<ENDNEWSCRIPT;
 function makenewfolder(targetform,folderseq) {
-    var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
+    var foldername=prompt('$js_lt{"p_mnf"}','$js_lt{"t_mnf"}');
     if (foldername) {
        targetform.importdetail.value=escape(foldername)+"="+folderseq;
         targetform.submit();
@@ -5866,7 +6247,7 @@ function makenewfolder(targetform,folder
 }
 
 function makenewpage(targetform,folderseq) {
-    var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
+    var pagename=prompt('$js_lt{"p_mnp"}','$js_lt{"t_mnp"}');
     if (pagename) {
         targetform.importdetail.value=escape(pagename)+"="+folderseq;
         targetform.submit();
@@ -5874,7 +6255,7 @@ function makenewpage(targetform,folderse
 }
 
 function makeexamupload() {
-   var title=prompt('$lt{"p_mxu"}');
+   var title=prompt('$js_lt{"p_mxu"}');
    if (title) {
     this.document.forms.newexamupload.importdetail.value=
 	escape(title)+'=/res/lib/templates/examupload.problem';
@@ -5883,7 +6264,7 @@ function makeexamupload() {
 }
 
 function makesmppage() {
-   var title=prompt('$lt{"p_msp"}');
+   var title=prompt('$js_lt{"p_msp"}');
    if (title) {
     this.document.forms.newsmppg.importdetail.value=
 	escape(title)+'=/adm/$udom/$uname/new/smppg';
@@ -5892,7 +6273,7 @@ function makesmppage() {
 }
 
 function makewebpage(type) {
-   var title=prompt('$lt{"p_mwp"}');
+   var title=prompt('$js_lt{"p_mwp"}');
    var formname;
    if (type == 'supp') {
        formname = this.document.forms.supwebpage;
@@ -5900,14 +6281,14 @@ function makewebpage(type) {
        formname = this.document.forms.newwebpage;
    }
    if (title) {
-       var webpage = formname.importdetail.value;
+       var webpage = formname.importdetail.value; 
        formname.importdetail.value = escape(title)+'='+webpage;
        formname.submit();
    }
 }
 
 function makesmpproblem() {
-   var title=prompt('$lt{"p_msb"}');
+   var title=prompt('$js_lt{"p_msb"}');
    if (title) {
     this.document.forms.newsmpproblem.importdetail.value=
 	escape(title)+'=/res/lib/templates/simpleproblem.problem';
@@ -5916,7 +6297,7 @@ function makesmpproblem() {
 }
 
 function makedropbox() {
-   var title=prompt('$lt{"p_mdb"}');
+   var title=prompt('$js_lt{"p_mdb"}');
    if (title) {
     this.document.forms.newdropbox.importdetail.value=
         escape(title)+'=/res/lib/templates/DropBox.problem';
@@ -5925,7 +6306,7 @@ function makedropbox() {
 }
 
 function makebulboard() {
-   var title=prompt('$lt{"p_mbb"}');
+   var title=prompt('$js_lt{"p_mbb"}');
    if (title) {
     this.document.forms.newbul.importdetail.value=
 	escape(title)+'=/adm/$udom/$uname/new/bulletinboard';
@@ -5934,20 +6315,20 @@ function makebulboard() {
 }
 
 function makeabout() {
-   var user=prompt("$lt{'p_mab'}");
+   var user=prompt("$js_lt{'p_mab'}");
    if (user) {
        var comp=new Array();
        comp=user.split(':');
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
 	   if ((comp[0]) && (comp[1])) {
 	       this.document.forms.newaboutsomeone.importdetail.value=
-		   '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
+		   '$js_lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
        this.document.forms.newaboutsomeone.submit();
    } else {
-       alert("$lt{'p_mab_alrt1'}");
+       alert("$js_lt{'p_mab_alrt1'}");
    }
 } else {
-   alert("$lt{'p_mab_alrt2'}");
+   alert("$js_lt{'p_mab_alrt2'}");
 }
 }
 }
@@ -5963,6 +6344,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;
@@ -5985,11 +6379,11 @@ function toggleMap(caller) {
 
 function makeims(imsform) {
     if ((imsform.uploaddoc.value == '')  || (!imsform.uploaddoc.value)) {
-        alert("$lt{'imsfile'}");
+        alert("$js_lt{'imsfile'}");
         return;
     }
     if (imsform.source.selectedIndex == 0) {
-        alert("$lt{'imscms'}");
+        alert("$js_lt{'imscms'}");
         return;
     }
     newWindow = window.open('', 'IMSimport',"HEIGHT=700,WIDTH=750,scrollbars=yes");
@@ -5997,7 +6391,7 @@ function makeims(imsform) {
 }
 
 function changename(folderpath,index,oldtitle) {
-var title=prompt('$lt{"p_chn"}',oldtitle);
+var title=prompt('$js_lt{"p_chn"}',oldtitle);
 if (title) {
 this.document.forms.renameform.markcopy.value='';
 this.document.forms.renameform.title.value=title;
@@ -6021,7 +6415,7 @@ function updatePick(targetform,index,cal
         picknumtext = document.getElementById('randompicknum_'+index);
     }
     if (pickitem.checked) {
-        var picknum=prompt('$lt{"rpck"}',picknumitem.value);
+        var picknum=prompt('$js_lt{"rpck"}',picknumitem.value);
         if (picknum == '' || picknum == null) {
             if (caller == 'check') {
                 pickitem.checked=false;
@@ -6171,7 +6565,7 @@ function propagateState(form,param) {
     return;
 }
 
-function checkForSubmit(targetform,param,context,idx,folderpath,index,oldtitle,skip_confirm,container,folder) {
+function checkForSubmit(targetform,param,context,idx,folderpath,index,oldtitle,skip_confirm,container,folder,confirm_removal) {
     var dosettings;
     var doaction;
     var control = document.togglemultsettings;
@@ -6209,14 +6603,28 @@ function checkForSubmit(targetform,param
             targetform.markcopy.value=idx+':'+param;
             targetform.copyfolder.value=folder+'.'+container;
             if (param == 'remove') {
-                if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
+                var doremove = 0;
+                if (skip_confirm) {
+                    if (confirm_removal) {
+                        if (confirm('$js_lt{"p_rmr4"}\\n$js_lt{"p_rmr5"}\\n\\n$js_lt{"p_rmr2a"} "'+oldtitle+'"$js_lt{"p_rmr2b"}')) {
+                            doremove = 1;
+                        }
+                    } else {
+                        doremove = 1;
+                    }
+                } else {
+                    if (confirm('$js_lt{"p_rmr1"}\\n\\n$js_lt{"p_rmr2a"} "'+oldtitle+'" $js_lt{"p_rmr2b"}')) {
+                        doremove = 1;
+                    }
+                }
+                if (doremove) {
                     targetform.markcopy.value='';
                     targetform.copyfolder.value='';
                     targetform.submit();
                 }
             }
             if (param == 'cut') {
-                if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
+                if (skip_confirm || confirm('$js_lt{"p_ctr1a"}\\n$js_lt{"p_ctr1b"}\\n\\n$js_lt{"p_ctr2a"} "'+oldtitle+'" $js_lt{"p_ctr2b"}')) {
                     targetform.submit();
                     return;
                 }
@@ -6281,11 +6689,11 @@ for (i = 0; i < currentLis.length; i++)
 
 function hideAll(current, nav, data) {
 unselectInactive(nav);
-if (current) {
+if (current) { 
     if (current.className == 'right'){
-	current.className = 'right active'
+        current.className = 'right active'
     } else {
-	current.className = 'active';
+        current.className = 'active';
     }
 }
 currentData = document.getElementById(data);
@@ -6323,11 +6731,11 @@ function showPage(current, pageId, nav,
 	unselectInactive(nav);
         if ((currstate == 'active') || (currstate == 'right active')) {
             if (currstate == 'active') {
-                current.className = '';
+	        current.className = '';
             } else {
                 current.className = 'right';
             }
-            activeTab = '';
+            activeTab = ''; 
             toggleUpload();
             toggleMap();
             resize_scrollbox('contentscroll','1','0');
@@ -6395,7 +6803,7 @@ function togglePick(caller,value) {
         }
         document.getElementById('multi'+caller).style.display=disp;
         if (value == 1) {
-            document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$lt{'more'}</a>'; 
+            document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$js_lt{'more'}</a>'; 
         } else {
             document.getElementById('more'+caller).innerHTML = '';
         }
@@ -6421,10 +6829,10 @@ function togglePick(caller,value) {
 
 function toggleCheckUncheck(caller,more) {
     if (more == 1) {
-        document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',0);" style="text-decoration:none;">$lt{'less'}</a>';
+        document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',0);" style="text-decoration:none;">$js_lt{'less'}</a>';
         document.getElementById('allfields'+caller).style.display='block';
     } else {
-        document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$lt{'more'}</a>';
+        document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$js_lt{'more'}</a>';
         document.getElementById('allfields'+caller).style.display='none';
     }
     resize_scrollbox('contentscroll','1','1');
@@ -6466,6 +6874,7 @@ function checkSubmits() {
     var doactions = multiActions();
     var cutwarnings = 0;
     var remwarnings = 0;
+    var removalinfo = 0;
     if (doactions == 1) {
         var remidxlist = document.cumulativeactions.allremoveidx.value;
         if ((remidxlist != '') && (remidxlist != null)) {
@@ -6480,6 +6889,11 @@ function checkSubmits() {
                                 remwarnings ++;
                             }
                         }
+                        if (document.getElementById('confirm_removal_'+remidxs[i])) {
+                            if (document.getElementById('confirm_removal_'+remidxs[i]).value == 1) {
+                                removalinfo ++;
+                            }
+                        }
                     }
                 }
             }
@@ -6578,14 +6992,19 @@ function checkSubmits() {
     }
     if (doactions == 1) {
         if (numchanges > 0) {
-            if ((cutwarnings > 0) || (remwarnings > 0)) {
+            if ((cutwarnings > 0) || (remwarnings > 0) || (removalinfo > 0)) {
                 if (remwarnings > 0) {
-                    if (!confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr3a"} '+remwarnings+' $lt{"p_rmr3b"}')) {
+                    if (!confirm('$js_lt{"p_rmr1"}\\n\\n$js_lt{"p_rmr3a"} '+remwarnings+' $js_lt{"p_rmr3b"}')) {
+                        return false;
+                    }
+                }
+                if (removalinfo > 0) {
+                    if (!confirm('$js_lt{"p_rmr4"}\\n$js_lt{"p_rmr5"}\\n\\n$js_lt{"p_rmr3a"} '+removalinfo+' $js_lt{"p_rmr3b"}')) {
                         return false;
                     }
                 }
                 if (cutwarnings > 0) {
-                    if (!confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr3a"} '+cutwarnings+' $lt{"p_ctr3b"}')) {
+                    if (!confirm('$js_lt{"p_ctr1a"}\\n$js_lt{"p_ctr1b"}\\n\\n$js_lt{"p_ctr3a"} '+cutwarnings+' $js_lt{"p_ctr3b"}')) {
                         return false;
                     }
                 }
@@ -6601,12 +7020,12 @@ function checkSubmits() {
         }
     }
     if ((dosettings == 1) && (doactions == 1)) {
-        alert("$lt{'noor'}");
+        alert("$js_lt{'noor'}");
     } else {
         if (dosettings == 1) {
-            alert("$lt{'noch'}");
+            alert("$js_lt{'noch'}");
         } else {
-            alert("$lt{'noac'}");
+            alert("$js_lt{'noac'}");
         }
     }
     return false;
@@ -6721,13 +7140,19 @@ ENDINJECT
 
 sub dump_switchserver_js {
     my @hosts = @_;
-    my %lt = &Apache::lonlocal::texthash(
+    my %js_lt = &Apache::lonlocal::texthash(
         dump => 'Copying content to Authoring Space requires switching server.',
         swit => 'Switch server?',
+    );
+    my %html_js_lt = &Apache::lonlocal::texthash(
+        swit => 'Switch server?',
         duco => 'Copying Content to Authoring Space',
         yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
         chos => 'Choose server',
     );
+    &js_escape(\%js_lt);
+    &html_escape(\%html_js_lt);
+    &js_escape(\%html_js_lt);
     my $role = $env{'request.role'};
     my $js = <<"ENDSWJS";
 <script type="text/javascript">
@@ -6768,7 +7193,7 @@ ENDSWJS
 
 function dump_needs_switchserver(url) {
     if (url!='' && url!= null) {
-        if (confirm("$lt{'dump'}\\n$lt{'swit'}")) {
+        if (confirm("$js_lt{'dump'}\\n$js_lt{'swit'}")) {
             go(url);
         }
     }
@@ -6779,13 +7204,13 @@ function choose_switchserver_window() {
     newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
     newWindow.document.open();
     newWindow.document.writeln('$startpage');
-    newWindow.document.write('<h3>$lt{'duco'}<\\/h3>\\n'+
-       '<p>$lt{'yone'}<\\/p>\\n'+
-       '<div class="LC_left_float"><fieldset><legend>$lt{'chos'}<\\/legend>\\n'+
+    newWindow.document.write('<h3>$html_js_lt{'duco'}<\\/h3>\\n'+
+       '<p>$html_js_lt{'yone'}<\\/p>\\n'+
+       '<div class="LC_left_float"><fieldset><legend>$html_js_lt{'chos'}<\\/legend>\\n'+
        '<form name="setserver" method="post" action="" \\/>\\n'+
        '$hostpicker\\n'+
        '<br \\/><br \\/>\\n'+
-       '<input type="button" name="makeswitch" value="$lt{'swit'}" '+
+       '<input type="button" name="makeswitch" value="$html_js_lt{'swit'}" '+
        'onclick="write_switchserver();" \\/>\\n'+
        '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
     newWindow.document.writeln('$endpage');