--- loncom/interface/londocs.pm	2017/02/18 14:16:47	1.620
+++ loncom/interface/londocs.pm	2017/05/10 23:34:15	1.630
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # Documents
 #
-# $Id: londocs.pm,v 1.620 2017/02/18 14:16:47 raeburn Exp $
+# $Id: londocs.pm,v 1.630 2017/05/10 23:34:15 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -603,9 +603,9 @@ 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};
@@ -654,11 +654,12 @@ sub group_import {
             }
         }
 	if ($url) {
-            if ($url =~ m{^(/adm/$coursedom/$coursenum/(\d+)/exttool)s?\:?(.*)$}) {
+            if ($url =~ m{^(/adm/$coursedom/$coursenum/(\d+)/ext\.tool)\:?(.*)$}) {
                 $url = $1;
                 my $marker = $2;
                 my $info = $3;
                 my ($toolid,%toolhash,%toolsettings);
+                my @extras = ('linktext','explanation','crslabel','crstitle');
                 my @toolinfo = split(/:/,$info);
                 if ($residx) {
                     %toolsettings=&Apache::lonnet::dump('exttool_'.$marker,$coursedom,$coursenum);
@@ -668,28 +669,37 @@ sub group_import {
                 }
                 $toolid =~ s/\D//g;
                 ($toolhash{'target'},$toolhash{'width'},$toolhash{'height'},
+                 $toolhash{'linktext'},$toolhash{'explanation'},
                  $toolhash{'crslabel'},$toolhash{'crstitle'}) = @toolinfo;
-                $toolhash{'crslabel'} = &unescape($toolhash{'crslabel'});
-                $toolhash{'crstitle'} = &unescape($toolhash{'crstitle'});
+                foreach my $item (@extras) {
+                    $toolhash{$item} = &unescape($toolhash{$item});
+                }
                 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 'iframe') || ($toolhash{'target'} eq 'tab') ||
+                            ($toolhash{'target'} eq 'window')) {
                             if ($toolhash{'target'} eq 'window') {
                                 foreach my $item ('width','height') {
                                     $toolhash{$item} =~ s/^\s+//;
                                     $toolhash{$item} =~ s/\s+$//;
+                                    if ($toolhash{$item} =~ /\D/) {
+                                        delete($toolhash{$item});
+                                        if ($residx) {
+                                            if ($toolsettings{$item}) {
+                                                push(@deleted,$item);
+                                            }
+                                        }
+                                    }
                                 }
                             }
                         } elsif ($residx) {
                             $toolhash{'target'} = $toolsettings{'target'};
                             if ($toolhash{'target'} eq 'window') {
-                                $toolhash{'width'} = $toolsettings{'width'};
-                                $toolhash{'height'} = $toolsettings{'height'};  
+                                foreach my $item ('width','height') {
+                                    $toolhash{$item} = $toolsettings{$item};
+                                }
                             }
                         } elsif (ref($ltitoolsref->{$toolid}->{'display'}) eq 'HASH') {
                             $toolhash{'target'} = $ltitoolsref->{$toolid}->{'display'}->{'target'};
@@ -699,31 +709,44 @@ sub group_import {
                             }
                         }
                         if ($toolhash{'target'} eq 'iframe') {
-                            delete($toolhash{'width'});
-                            delete($toolhash{'height'});
-                            if ($residx) {
-                                if ($toolsettings{'width'}) {
-                                    push(@deleted,'width');
+                            foreach my $item ('width','height','linktext','explanation') {
+                                delete($toolhash{$item});
+                                if ($residx) {
+                                    if ($toolsettings{$item}) {
+                                        push(@deleted,$item);
+                                    }
                                 }
-                                if ($toolsettings{'height'}) {
-                                    push(@deleted,'height');
+                            }
+                        } elsif ($toolhash{'target'} eq 'tab') {
+                            foreach my $item ('width','height') {
+                                delete($toolhash{$item});
+                                if ($residx) {
+                                    if ($toolsettings{$item}) {
+                                        push(@deleted,$item);
+                                    }
                                 }
                             }
                         }
                         if (ref($ltitoolsref->{$toolid}->{'crsconf'}) eq 'HASH') {
-                            foreach my $item ('label','title') { 
+                            foreach my $item ('label','title','linktext','explanation') {
+                                my $crsitem;
+                                if (($item eq 'label') || ($item eq 'title')) {
+                                    $crsitem = 'crs'.$item;
+                                } else {
+                                    $crsitem = $item;
+                                }
                                 if ($ltitoolsref->{$toolid}->{'crsconf'}->{$item}) {
-                                    $toolhash{'crs'.$item} =~ s/^\s+//;
-                                    $toolhash{'crs'.$item} =~ s/\s+$//;
-                                    if ($toolhash{'crs'.$item} eq '') {
-                                        delete($toolhash{'crs'.$item});
+                                    $toolhash{$crsitem} =~ s/^\s+//;
+                                    $toolhash{$crsitem} =~ s/\s+$//;
+                                    if ($toolhash{$crsitem} eq '') {
+                                        delete($toolhash{$crsitem});
                                     }
                                 } else {
-                                    delete($toolhash{'crs'.$item});
+                                    delete($toolhash{$crsitem});
                                 }
-                                if (($residx) && (exists($toolsettings{'crs'.$item}))) {
-                                    unless (exists($toolhash{'crs'.$item})) {
-                                        push(@deleted,'crs'.$item);
+                                if (($residx) && (exists($toolsettings{$crsitem}))) {
+                                    unless (exists($toolhash{$crsitem})) {
+                                        push(@deleted,$crsitem);
                                     }
                                 }
                             }
@@ -748,8 +771,8 @@ sub group_import {
                     $donechk = 1;
                 }
                 if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
-                    &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
-                                         \%addedmaps,\%hierarchy,\%titles,$allmaps);
+                    &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
+                                        \%removeparam,\%addedmaps,\%hierarchy,\%titles,$allmaps);
                     $importuploaded = 1;
                 } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                     next if ($allmaps->{$url});
@@ -789,7 +812,7 @@ $initialtext
 </html>
 END
                 $env{'form.output'}=$newhtml;
-                my $result = 
+                my $result =
                     &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
                                                           'output',
                                                           "$filepath/$residx/$fname.html");
@@ -920,7 +943,7 @@ sub docs_change_log {
              '// <![CDATA['."\n".
              &Apache::loncommon::display_filter_js('docslog')."\n".
              &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag,
-                         $coursedom,$coursenum,'','',$canedit,\$navmap)."\n".
+                         $coursedom,$coursenum,'','',$canedit,'',\$navmap)."\n".
              &history_tab_js()."\n".
              &Apache::lonratedt::editscript('simple')."\n".
              '// ]]>'."\n".
@@ -948,7 +971,7 @@ sub docs_change_log {
     if ($supplementalflag) {
         $tid = 2;
     }
-    my ($breadcrumbtrail) = 
+    my ($breadcrumbtrail) =
         &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
     $r->print($breadcrumbtrail.
               &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
@@ -1147,7 +1170,7 @@ 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};           
+             my $mapidx = $env{'docs.markedcopy_map_'.$suffix};
              if (($cid =~ /^$match_domain(?:_)$match_courseid$/) &&
                  ($url ne '')) {
                  $pasteurls{$cid.'_'.$url.'_'.$mapidx} = 1;
@@ -1200,8 +1223,8 @@ sub update_paste_buffer {
                 $subdir = $prefix;
             }
             my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
-            &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
-                                 \%hierarchy,\%titles,\%allmaps);
+            &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
+                                 \%removeparam,\%addedmaps,\%hierarchy,\%titles,\%allmaps);
             if (ref($hierarchy{$url}) eq 'HASH') {
                 my ($nested,$nestednames);
                 &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
@@ -1279,7 +1302,7 @@ sub print_paste_buffer {
             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?$}) {
+            } elsif ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                 $is_exttool = 1;
             }
             if ($folder =~ /^supplemental/) {
@@ -1313,26 +1336,34 @@ 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)$})) {
+                         ($url =~ m{^/adm/($match_domain)/($match_username)/\d+/(bulletinboard|smppg|ext\.tool)$})) {
                     if ($cid ne $env{'request.course.id'}) {
                         my ($srcdom,$srcnum) = split(/_/,$cid);
                         if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
-                            $othercrs = '<br />'.&mt('(from another course)');
+                            if (($is_exttool) && ($srcdom ne $coursedom)) {
+                                $canpaste = 0;
+                                $nopaste = &mt('Paste from another domain unavailable.');
+                            } else {
+                                $othercrs = '<br />'.&mt('(from another course)');
+                            }
                         } else {
                             $canpaste = 0;
                             $nopaste = &mt('Paste from another course unavailable.');
-                        }       
+                        }
                     }
                 }
                 if ($canpaste) {
                     push(@pasteable,$suffix);
-                }  
+                }
             }
             my $buffer;
-            if (($is_external) || ($is_exttool)) {
+            if ($is_external) {
                 $buffer = &mt('External Resource').': '.
                     &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
                     &LONCAPA::map::qtescape($url).')';
+            } elsif ($is_exttool) {
+                $buffer = &mt('External Tool').': '.
+                    &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
             } else {
                 my $icon = &Apache::loncommon::icon($extension);
                 if ($extension eq 'sequence' &&
@@ -1490,7 +1521,7 @@ sub supp_pasteable {
         ($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{^/adm/$match_domain/$match_courseid/\d+/exttools?$})) {
+        ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$})) {
         return 1;
     }
     return;
@@ -1612,7 +1643,7 @@ sub do_paste_from_buffer {
         return();
     }
 
-    my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%duplicate,
+    my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%notindom,%duplicate,
         %prefixchg,%srcdom,%srcnum,%srcmapidx,%marktomove,$save_err,$lockerrors,$allresult);
 
     foreach my $suffix (@topaste) {
@@ -1641,7 +1672,8 @@ 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)$})) {
+                 ($url =~ m{^/adm/$match_domain/$match_username/\d+/(bulletinboard|smppg|ext\.tool)$})) {
+            my $srctype= $1;
             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
@@ -1651,6 +1683,10 @@ sub do_paste_from_buffer {
                     next;
                 }
             }
+            if (($srctype eq 'ext.tool') && ($srcd ne $coursedom)) {
+                $notindom{$suffix} = 1;
+                next;
+            }
             $srcdom{$suffix} = $srcd;
             $srcnum{$suffix} = $srcn;
         }
@@ -1659,7 +1695,6 @@ sub do_paste_from_buffer {
         if ($url=~/\.(page|sequence)$/) {
             $is_map{$suffix} = 1; 
         }
-
         if ($url =~ m{^/uploaded/$match_domain/$match_courseid/([^/]+)}) {
             my $oldprefix = $1;
 # When pasting content from Main Content to Supplemental Content and vice versa 
@@ -1704,6 +1739,7 @@ sub do_paste_from_buffer {
     %msgs = &Apache::lonlocal::texthash (
                 notinsupp => 'Paste failed: content type is not supported within Supplemental Content',
                 notincrs  => 'Paste failed: Item is from a different course which you do not have rights to edit.',
+                notindom  => 'Paste failed: Item is an external tool from a course in a different donain.', 
                 duplicate => 'Paste failed: only one instance of a particular published sequence or page is allowed within each course.',
             );
 
@@ -1757,8 +1793,9 @@ sub do_paste_from_buffer {
         if ($is_map{$suffix}) {
 # If pasting a map, check if map contains other maps
             my (%hierarchy,%titles);
-            &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
-                                 \%addedmaps,\%hierarchy,\%titles,$allmaps);
+            &contained_map_check($url,$folder,$coursenum,$coursedom,
+                                 \%removefrommap,\%removeparam,\%addedmaps,
+                                 \%hierarchy,\%titles,$allmaps);
             if ($url=~ m{^/uploaded/}) {
                 my $newurl;
                 unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
@@ -1811,7 +1848,7 @@ sub do_paste_from_buffer {
                 }
             }
         }
-        if ($url=~ m{/(bulletinboard|smppg)$}) {
+        if ($url=~ m{/(bulletinboard|smppg|ext\.tool)$}) {
             my $prefix = $1;
             my $fromothercrs; 
             #need to copy the db contents to a new one, unless this is a move.
@@ -1828,7 +1865,7 @@ sub do_paste_from_buffer {
                 }
             }
             unless (($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') && (!$fromothercrs)) {
-                my (%lockerr,$msg); 
+                my (%lockerr,$msg);
                 my ($newurl,$result,$errtext) =
                     &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
                 if ($result eq 'ok') {
@@ -1839,6 +1876,8 @@ sub do_paste_from_buffer {
                         $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
                     } elsif ($prefix eq 'bulletinboard') {
                         $msg = &mt('Paste failed: An error occurred when copying the discussion board.').' '.$errtext;
+                    } elsif ($prefix eq 'ext.tool') {
+                        $msg = &mt('Paste failed: An error occurred when copying the external tool.').' '.$errtext;
                     }
                     $results{$suffix} = $result;
                     $msgerrs{$suffix} = $msg;
@@ -1885,8 +1924,8 @@ sub do_paste_from_buffer {
                     if ($newdocsdir eq '') {
                         $newdocsdir = 'default';
                     }
-                    if (($prefixchg{$suffix}) || 
-                        ($srcdom{$suffix} ne $coursedom) || 
+                    if (($prefixchg{$suffix}) ||
+                        ($srcdom{$suffix} ne $coursedom) ||
                         ($srcnum{$suffix} ne $coursenum) ||
                         ($env{'form.docs.markedcopy_options_'.$suffix} ne 'move')) {
                         my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
@@ -2098,8 +2137,11 @@ sub dbcopy {
     my ($url,$result,$errtext);
     if (ref($dbref) eq 'HASH') {
         $url = $dbref->{'src'};
-        if ($url =~ m{/(smppg|bulletinboard)$}) {
+        if ($url =~ m{/(smppg|bulletinboard|ext\.tool)$}) {
             my $prefix = $1;
+            if ($prefix eq 'ext.tool') {
+                $prefix = 'exttool';
+            }
             if (($dbref->{'cdom'} =~ /^$match_domain$/) && 
                 ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
                 my $db_name;
@@ -2110,6 +2152,8 @@ sub dbcopy {
                         &Apache::lonsimplepage::get_db_name($url,$marker,
                                                             $dbref->{'cdom'},
                                                             $dbref->{'cnum'});
+                } elsif ($dbref->{'src'} =~ m{/ext\.tool$}) {
+                    $db_name = 'exttool_'.$marker;
                 } else {
                     $db_name = 'bulletinpage_'.$marker;
                 }
@@ -2153,7 +2197,7 @@ sub dbcopy {
                     $result=&Apache::lonnet::put($db_name,\%contents,
                                                  $coursedom,$coursenum);
                     if ($result eq 'ok') {
-                        $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
+                        $url =~ s{/(\d*)/(smppg|bulletinboard|ext\.tool)$}{/$suffix/$2}x;
                     }
                 }
                 if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
@@ -2163,6 +2207,9 @@ sub dbcopy {
                     if ($prefix eq 'smppg') {
                         $lockerrorsref->{$prefix} .=
                             ' '.&mt('This will prevent creation of additional simple pages in this course.');
+                    } elsif ($prefix eq 'exttool') {
+                        $lockerrorsref->{$prefix} .=
+                            ' '.&mt('This will prevent addition of more external tools to this course.');
                     } else {
                         $lockerrorsref->{$prefix} .= ' '.&mt('This will prevent creation of additional discussion boards in this course.');
                     }
@@ -2292,8 +2339,8 @@ sub uniqueness_check {
 }
 
 sub contained_map_check {
-    my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
-        $allmaps) = @_;
+    my ($url,$folder,$coursenum,$coursedom,$removefrommap,$removeparam,$addedmaps,
+        $hierarchy,$titles,$allmaps) = @_;
     my $content = &Apache::lonnet::getfile($url);
     unless ($content eq '-1') {
         my $parser = HTML::TokeParser->new(\$content);
@@ -2303,7 +2350,13 @@ sub contained_map_check {
             if ($token->[1] eq 'resource') {
                 next if ($token->[2]->{'type'} eq 'zombie');
                 my $ressrc = $token->[2]->{'src'};
-                if ($folder =~ /^supplemental/) {
+                if ($ressrc =~ m{^/adm/($match_domain)/$match_courseid/\d+/ext\.tool$}) {
+                    my $srcdom = $1;
+                    unless ($srcdom eq $coursedom) {
+                        $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
+                        next;
+                    }
+                } elsif ($folder =~ /^supplemental/) {
                     unless (&supp_pasteable($ressrc)) {
                         $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
                         next;
@@ -2322,8 +2375,8 @@ sub contained_map_check {
                             $addedmaps->{$ressrc} = [$url];
                         }
                     }
-                    &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
-                                         $addedmaps,$hierarchy,$titles,$allmaps);
+                    &contained_map_check($ressrc,$folder,$coursenum,$coursedom,$removefrommap,
+                                         $removeparam,$addedmaps,$hierarchy,$titles,$allmaps);
                 }
             } elsif ($token->[1] eq 'param') {
                 if ($folder =~ /^supplemental/) {
@@ -2858,7 +2911,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);
@@ -3009,7 +3062,7 @@ sub handle_edit_cmd {
 sub editor {
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
         $supplementalflag,$orderhash,$iconpath,$pathitem,$ltitoolsref,
-        $canedit,$navmapref,$hiddentop)=@_;
+        $canedit,$hostname,$navmapref,$hiddentop)=@_;
     my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
     if ($allowed) {
         (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
@@ -3220,7 +3273,7 @@ sub editor {
                         } else {
                             return $errortxt;
                         }
-                    } elsif ($url =~ m{^/adm/$coursedom/$coursenum/new/exttool}) {
+                    } elsif ($url =~ m{^/adm/$coursedom/$coursenum/new/ext\.tool}) {
                         my ($suffix,$errortxt,$locknotfreed) =
                             &new_timebased_suffix($coursedom,$coursenum,'exttool');
                         if ($locknotfreed) {
@@ -3340,7 +3393,7 @@ sub editor {
                               $coursenum,$coursedom,$crstype,
                               $pathitem,$supplementalflag,$container,
                               \%filters,\%curr_groups,$ltitoolsref,$canedit,
-                              $isencrypted,$navmapref);
+                              $isencrypted,$navmapref,$hostname);
         $idx++;
         $shown++;
     }
@@ -3388,11 +3441,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>'.
@@ -3640,7 +3693,7 @@ sub process_file_upload {
                     my $uploadphase = 'upload_embedded';
                     my $primaryurl = &HTML::Entities::encode($url,'<>&"');
 		    my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
-                    my ($embedded,$num) = 
+                    my ($embedded,$num) =
                         &Apache::loncommon::ask_for_embedded_content(
                             '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
                     if ($embedded) {
@@ -3721,7 +3774,7 @@ sub is_supplemental_title {
 sub entryline {
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
         $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups,
-        $ltitoolsref,$canedit,$isencrypted,$navmapref)=@_;
+        $ltitoolsref,$canedit,$isencrypted,$navmapref,$hostname)=@_;
     my ($foldertitle,$renametitle,$oldtitle);
     if (&is_supplemental_title($title)) {
 	($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
@@ -3838,7 +3891,7 @@ END
 			    |/aboutme$
 			    |/navmaps$
 			    |/bulletinboard$
-                            |/exttools?$
+                            |/ext\.tool$
 			    |\.html$)}x)
              || $isexternal) {
 	    $skip_confirm = 1;
@@ -3970,7 +4023,7 @@ END
 	}
     }
 
-    my ($editlink,$extresform,$anchor,$hiddenres);
+    my ($editlink,$extresform,$anchor,$hiddenres,$nomodal);
     my $orig_url = $url;
     $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
     $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
@@ -3988,10 +4041,23 @@ END
 	        } elsif ($url!~/\.(sequence|page)$/) {
 		    $url='/adm/coursedocs/showdoc'.$url;
 	        }
-	    } elsif ($url=~m|^/ext/|) {
-	        $url='/adm/wrapper'.$url;
-	    } elsif ($url=~m{^/adm/$coursedom/$coursenum/\d+/exttools?$}) {
+	    } elsif ($url=~m{^(|/adm/wrapper)/ext/([^#]+)}) {
+                my $wrapped = $1;
+                my $exturl = $2;
+                if ($wrapped eq '') {
+                    $url='/adm/wrapper'.$url;
+                }
+                if (($ENV{'SERVER_PORT'} == 443) && ($exturl !~ /^https:/)) {
+                    $nomodal = 1;
+                }
+	    } elsif ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
 		$url='/adm/wrapper'.$url;
+            } elsif ($url eq "/public/$coursedom/$coursenum/syllabus") {
+                if (($ENV{'SERVER_PORT'} == 443) &&
+                    ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
+                    $url .= '?usehttp=1';
+                    $nomodal = 1;
+                }
             }
             if (&Apache::lonnet::symbverify($symb,$url)) {
                 my $shownsymb = $symb;
@@ -4049,11 +4115,26 @@ END
                 $url='';
             }
 	}
-    } elsif ($supplementalflag) { 
+    } elsif ($supplementalflag) {
         if ($isexternal) {
             if ($url =~ /^([^#]+)#([^#]+)$/) {
                 $url = $1;
                 $anchor = $2;
+                if (($url =~ m{^(|/adm/wrapper)/ext/(?!https:)}) && ($ENV{'SERVER_PORT'} == 443)) {
+                    if ($hostname ne '') {
+                        $url = 'http://'.$hostname.$url;
+                    }
+                    $nomodal = 1;
+                }
+            }
+        } elsif ($url =~ m{^\Q/public/$coursedom/$coursenum/syllabus\E}) {
+            if (($ENV{'SERVER_PORT'} == 443) &&
+                ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
+                if ($hostname ne '') {
+                    $url = 'http://'.$hostname.$url;
+                }
+                $url .= (($url =~ /\?/) ? '&amp;':'?').'usehttp=1';
+                $nomodal = 1;
             }
         }
     }
@@ -4101,7 +4182,7 @@ END
                     }
                 }
             }
-            
+
 # Append randompick number, hidden, and encrypted with ":" to foldername,
 # so it gets transferred between levels
 	    $folderpath.=$containerarg.'&'.$foldername.
@@ -4144,7 +4225,7 @@ $form_end;
         }
     } elsif ($supplementalflag && !$allowed) {
         my $isexttool;
-        if ($url=~m{^/adm/$coursedom/$coursenum/\d+/exttools?$}) {
+        if ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
             $url='/adm/wrapper'.$url;
             $isexttool = 1;
         }
@@ -4162,14 +4243,14 @@ $form_end;
     }
     my ($tdalign,$tdwidth);
     if ($allowed) {
-        my $fileloc = 
+        my $fileloc =
             &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
         if ($isexternal) {
-            ($editlink,$extresform) = 
+            ($editlink,$extresform) =
                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
                                                      undef,undef,undef,undef,undef,undef,
                                                      undef,$disabled);
-        } elsif ($orig_url =~ m{^/adm/$coursedom/$coursenum/\d+/exttools?$}) {
+        } elsif ($orig_url =~ m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
             ($editlink,$extresform) =
                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
                                                      undef,undef,undef,'tool',$coursedom,
@@ -4182,13 +4263,14 @@ $form_end;
                 if ($supplementalflag) {
                     $suppanchor = $anchor;
                 }
-                my $jscall = 
+                my $jscall =
                     &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
                                                             $switchserver,
                                                             $forceedit,
                                                             undef,$symb,
                                                             &escape($env{'form.folderpath'}),
-                                                            $renametitle,'','',1,$suppanchor);
+                                                            $renametitle,$hostname,
+                                                            '','',1,$suppanchor);
                 if ($jscall) {
                     $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
                                 $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
@@ -4205,6 +4287,7 @@ $form_end;
         $reinit = &mt('(re-initialize course to access)');
     }
     $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
+    my $link;
     if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
        $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
     } elsif ($url) {
@@ -4215,9 +4298,20 @@ $form_end;
                $anchor = '#'.&HTML::Entities::encode($anchor,'"<>&');
            }
        }
-       $line.=&Apache::loncommon::modal_link(&js_escape($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes'.
-                                             (($anchor ne '')?$anchor:'')),
-                                             '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
+       if ((!$supplementalflag) && ($nomodal) && ($hostname ne '')) {
+           $link = 'http://'.$hostname.$url;
+       } else {
+           $link = $url;
+       }
+       $link = &js_escape($link.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes'.
+                                               (($anchor ne '')?$anchor:''));
+       if ($nomodal) {
+           $line.='<a href="#" onclick="javascript:window.open('."'$link','syllabuspreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1')".'; return false;" />'.
+                  '<img src="'.$icon.'" alt="" class="LC_icon" border="0" /></a>';
+       } else {
+           $line.=&Apache::loncommon::modal_link($link,
+                                                 '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
+       }
     } else {
        $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
     }
@@ -4225,9 +4319,12 @@ $form_end;
     if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
        $line.='<a href="'.$url.'">'.$title.'</a>';
     } elsif ($url) {
-       $line.=&Apache::loncommon::modal_link(&js_escape($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes'.
-                                             (($anchor ne '')?$anchor:'')),
-                                             $title,600,500);
+       if ($nomodal) {
+           $line.='<a href="#" onclick="javascript:window.open('."'$link','syllabuspreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1')".'; return false;" />'.
+                  $title.'</a>';
+       } else {
+           $line.=&Apache::loncommon::modal_link($link,$title,600,500);
+       }
     } elsif (($hiddenfolder) || ($hiddenres)) {
        $line.=$title.' <span class="LC_warning LC_docs_reinit_warn">'.&mt('(Hidden)').'</span>';
     } else {
@@ -4368,6 +4465,8 @@ sub new_timebased_suffix {
             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
         } elsif ($type eq 'smppg') {
             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
+        } elsif ($type eq 'exttool') {
+            $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new external tool.');
         } else {
             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new discussion board.');
         }
@@ -4376,7 +4475,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') {
@@ -4396,6 +4495,9 @@ sub new_timebased_suffix {
         } elsif ($type eq 'smppg') {
             $locknotfreed .=
                 &mt('This will prevent creation of additional simple pages in this course.');
+        } elsif ($type eq 'exttool') {
+            $locknotfreed .=
+                &mt('This will prevent creation of additional external tools in this course.');
         } else {
             $locknotfreed .=
                 &mt('This will prevent creation of additional discussion boards in this course.');
@@ -5021,12 +5123,12 @@ sub handler {
 #
 # --------------------------------------------- Initialize help topics for this
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
-	               'Adding_External_Resource','Navigate_Content',
-	               'Adding_Folders','Docs_Overview', 'Load_Map',
-	               'Supplemental','Score_Upload_Form','Adding_Pages',
-	               'Importing_LON-CAPA_Resource','Importing_IMS_Course',
-                       'Uploading_From_Harddrive','Course_Roster','Web_Page',
-                       'Dropbox','Simple_Problem') {
+	               'Adding_External_Resource','Adding_External_Tool',
+                       'Navigate_Content','Adding_Folders','Docs_Overview',
+	               'Load_Map','Supplemental','Score_Upload_Form',
+	               'Adding_Pages','Importing_LON-CAPA_Resource',
+	               'Importing_IMS_Course','Uploading_From_Harddrive',
+                       'Course_Roster','Web_Page','Dropbox','Simple_Problem') {
 	$help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
     }
     # Composite help files
@@ -5348,8 +5450,9 @@ sub handler {
             my $tabidstr = join("','",@tabids);
             %ltitools = &Apache::lonnet::get_domain_ltitools($coursedom);
             my $posslti = keys(%ltitools);
+            my $hostname = $r->hostname();
 	    $script .= &editing_js($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
-                                   $londocroot,$canedit,\$navmap).
+                                   $londocroot,$canedit,$hostname,\$navmap).
                        &history_tab_js().
                        &inject_data_js().
                        &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr,$tid).
@@ -5448,7 +5551,7 @@ sub handler {
           my ($destination,$dir_root) = &embedded_destination();
           my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
           my $actionurl = '/adm/coursedocs';
-          my ($result,$flag) = 
+          my ($result,$flag) =
               &Apache::loncommon::upload_embedded('coursedoc',$destination,
                   $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
                   $actionurl);
@@ -5459,11 +5562,11 @@ sub handler {
           my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
           my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
           my ($destination,$dir_root) = &embedded_destination();
-          my $result = 
+          my $result =
               &Apache::loncommon::modify_html_refs('coursedoc',$destination,
                                                    $docuname,$docudom,undef,
                                                    $dir_root);
-          $r->print($result.&return_to_editor());   
+          $r->print($result.&return_to_editor());
       } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
           $uploadphase = 'decompress_phase_one';
           $r->print(&decompression_phase_one().
@@ -5489,7 +5592,7 @@ sub handler {
                 'impo' => 'Import',
 		'lnks' => 'Import from Stored Links',
                 'impm' => 'Import from Assembled Map',
-                'imcr' => 'Import from Course Resources',   
+                'imcr' => 'Import from Course Resources',
                 'extr' => 'External Resource',
                 'extt' => 'External Tool',
                 'selm' => 'Select Map',
@@ -5500,7 +5603,7 @@ sub handler {
                 'navc' => 'Table of Contents',
                 'sipa' => 'Simple Course Page',
                 'sipr' => 'Simple Problem',
-                'webp' => 'Blank Web Page (editable)', 
+                'webp' => 'Blank Web Page (editable)',
                 'stpr' => 'Standard Problem',
                 'news' => 'New sub-directory',
                 'crpr' => 'Create Problem',
@@ -5751,7 +5854,7 @@ HIDDENFORM
     }
 
 #
-
+    my $hostname = $r->hostname();
     my $savefolderpath;
 
     if ($allowed) {
@@ -6176,7 +6279,7 @@ NGFFORM
         );
         if (keys(%ltitools)) {
             push(@importdoc,
-                {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extt}.'" onclick="toggleUpload(\'tool\');" />'=>$exttoolform},
+                {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="toggleUpload(\'tool\');" />'=>$exttoolform},
         );
         }
         unless ($container eq 'page') {
@@ -6221,7 +6324,7 @@ unless ($container eq 'page') {
        unless (($supplementalflag || $toolsflag)) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,\%orderhash,$iconpath,$pathitem,
-                              \%ltitools,$canedit,\$navmap,$hiddentop);
+                              \%ltitools,$canedit,$hostname,\$navmap,$hiddentop);
           undef($navmap);
           if ($error) {
              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
@@ -6258,7 +6361,7 @@ unless ($container eq 'page') {
 	<form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
         <fieldset id="uploadsuppdocform" style="display: none;">
         <legend>$lt{'upfi'}</legend>
-	<input type="hidden" name="active" value="ee" />	
+	<input type="hidden" name="active" value="ee" />
 	$fileupload
 	<br />
 	<br />
@@ -6353,7 +6456,7 @@ my @supimportdoc = (
             =>$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\')" />'
+                {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="javascript:toggleUpload(\'supptool\')" />'
             =>$supexttoolform});
         }
         push(@supimportdoc, 
@@ -6370,7 +6473,7 @@ my %suporderhash = (
         if ($supplementalflag) {
            my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                $supplementalflag,\%suporderhash,$iconpath,$pathitem,
-                               \%ltitools,$canedit);
+                               \%ltitools,$canedit,$hostname);
            if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
            } else {
@@ -6385,12 +6488,12 @@ my %suporderhash = (
                    }
                    &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
                    undef($suppchanges);
-               }  
-           } 
+               }
+           }
         }
     } elsif ($supplementalflag) {
         my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
-                            $supplementalflag,'',$iconpath,$pathitem);
+                            $supplementalflag,'',$iconpath,$pathitem,'','',$hostname);
         if ($error) {
             $r->print('<p><span class="LC_error">'.$error.'</span></p>');
         }
@@ -6417,7 +6520,7 @@ my %suporderhash = (
                 &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
   }
  }
- unless ($noendpage) { 
+ unless ($noendpage) {
      $r->print(&Apache::loncommon::end_page());
  }
  return OK;
@@ -6489,7 +6592,7 @@ sub decompression_phase_one {
         $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
     } else {
         my $file = $1;
-        $output = 
+        $output =
             &Apache::loncommon::process_decompression($docudom,$docuname,$file,
                                                       $destination,$dir_root,
                                                       $hiddenelem);
@@ -6764,7 +6867,8 @@ END
 }
 
 sub editing_js {
-    my ($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,$londocroot,$canedit,$navmapref) = @_;
+    my ($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
+        $londocroot,$canedit,$hostname,$navmapref) = @_;
     my %js_lt = &Apache::lonlocal::texthash(
                                           p_mnf => 'Name of New Folder',
                                           t_mnf => 'New Folder',
@@ -6841,6 +6945,19 @@ sub editing_js {
                 }
                 $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($url),'<>&"').'?symb='.
                              &HTML::Entities::encode($caller,'<>&"');
+                if ($backtourl =~ m{^\Q/public/$coursedom/$coursenum/syllabus\E}) {
+                    if (($ENV{'SERVER_PORT'} == 443) &&
+                        ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
+                        if ($hostname ne '') {
+                            $backtourl = 'http://'.$hostname.$backtourl;
+                        }
+                        $backtourl .= (($backtourl =~ /\?/) ? '&amp;':'?').'usehttp=1';
+                    }
+                } elsif ($backtourl =~ m{^/adm/wrapper/ext/(?!https:)}) {
+                    if (($ENV{'SERVER_PORT'} == 443) && ($hostname ne '')) {
+                        $backtourl = 'http://'.$hostname.$backtourl;
+                    }
+                }
                 if ($anchor ne '') {
                     $backtourl .= '#'.&HTML::Entities::encode($anchor,'<>&"');
                 }