--- loncom/interface/londocs.pm	2017/05/10 23:58:24	1.631
+++ loncom/interface/londocs.pm	2018/04/14 00:10:48	1.652
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # Documents
 #
-# $Id: londocs.pm,v 1.631 2017/05/10 23:58:24 raeburn Exp $
+# $Id: londocs.pm,v 1.652 2018/04/14 00:10:48 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -45,6 +45,8 @@ use Apache::lontemplate();
 use Apache::lonsimplepage();
 use Apache::lonhomework();
 use Apache::lonpublisher();
+use Apache::lonparmset();
+use Apache::loncourserespicker();
 use HTML::Entities;
 use HTML::TokeParser;
 use GDBM_File;
@@ -52,6 +54,7 @@ use File::MMagic;
 use File::Copy;
 use Apache::lonlocal;
 use Cwd;
+use UUID::Tiny ':std';
 use LONCAPA qw(:DEFAULT :match);
 
 my $iconpath;
@@ -659,7 +662,7 @@ sub group_import {
                 my $marker = $2;
                 my $info = $3;
                 my ($toolid,%toolhash,%toolsettings);
-                my @extras = ('linktext','explanation','crslabel','crstitle');
+                my @extras = ('linktext','explanation','crslabel','crstitle','crsappend');
                 my @toolinfo = split(/:/,$info);
                 if ($residx) {
                     %toolsettings=&Apache::lonnet::dump('exttool_'.$marker,$coursedom,$coursenum);
@@ -669,14 +672,19 @@ sub group_import {
                 }
                 $toolid =~ s/\D//g;
                 ($toolhash{'target'},$toolhash{'width'},$toolhash{'height'},
-                 $toolhash{'linktext'},$toolhash{'explanation'},
-                 $toolhash{'crslabel'},$toolhash{'crstitle'}) = @toolinfo;
+                 $toolhash{'linktext'},$toolhash{'explanation'},$toolhash{'crslabel'},
+                 $toolhash{'crstitle'},$toolhash{'crsappend'},$toolhash{'gradable'}) = @toolinfo;
                 foreach my $item (@extras) {
                     $toolhash{$item} = &unescape($toolhash{$item});
                 }
+                if ($folder =~ /^supplemental/) {
+                    delete($toolhash{'gradable'});
+                } else {
+                    $toolhash{'gradable'} =~ s/\D+//g;
+                }
                 if (ref($ltitoolsref) eq 'HASH') {
-                    my @deleted;
                     if (ref($ltitoolsref->{$toolid}) eq 'HASH') {
+                        my @deleted;
                         $toolhash{'id'} = $toolid;
                         if (($toolhash{'target'} eq 'iframe') || ($toolhash{'target'} eq 'tab') ||
                             ($toolhash{'target'} eq 'window')) {
@@ -751,11 +759,51 @@ sub group_import {
                                 }
                             }
                         }
+                        if ($toolhash{'passback'}) {
+                            my $gradesecret = UUID::Tiny::create_uuid_as_string(UUID_V4);
+                            $toolhash{'gradesecret'} = $gradesecret;
+                            $toolhash{'gradesecretdate'} = time;
+                        }
+                        if ($toolhash{'roster'}) {
+                            my $rostersecret = UUID::Tiny::create_uuid_as_string(UUID_V4);
+                            $toolhash{'rostersecret'} = $rostersecret;
+                            $toolhash{'rostersecretdate'} = time;
+                        }
+                        my $changegradable;
+                        if (($residx) && ($folder =~ /^default/)) {
+                            if ($toolsettings{'gradable'}) {
+                                unless (($toolhash{'gradable'}) || (defined($LONCAPA::map::zombies[$residx]))) {
+                                    push(@deleted,'gradable');
+                                    $changegradable = 1;
+                                }
+                            } elsif ($toolhash{'gradable'}) {
+                                $changegradable = 1;
+                            }
+                            if (($caller eq 'londocs') && (defined($LONCAPA::map::zombies[$residx]))) {
+                                $changegradable = 1;
+                                if ($toolsettings{'gradable'}) {
+                                    $toolhash{'gradable'} = 1;
+                                }
+                            }
+                        }
                         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 (($changegradable) && ($folder =~ /^default/)) {
+                                my $val;
+                                if ($toolhash{'gradable'}) {
+                                    $val = 'yes';
+                                } else {
+                                    $val = 'no';
+                                }
+                                &LONCAPA::map::storeparameter($residx,'parameter_0_gradable',$val,
+                                                              'string_yesno');
+                                &remember_parms($residx,'gradable','set',$val);
+                            }
+                        } else {
+                            return (&mt('Failed to save update to external tool.'),1);
                         }
                     }
                 }
@@ -993,6 +1041,7 @@ sub docs_change_log {
 	    'encrypturl'     => 'URL hidden',
 	    'randompick'     => 'Randomly pick',
 	    'randomorder'    => 'Randomly ordered',
+            'gradable'       => 'Grade can be assigned to External Tool',
 	    'set'            => 'set to',
 	    'del'            => 'deleted');
     my $filter = &Apache::loncommon::display_filter('docslog')."\n".
@@ -1100,7 +1149,7 @@ sub docs_change_log {
 	$r->print('</ul>');
 	if ($docslog{$id}{'logentry'}{'parameter_res'}) {
 	    $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
-	    foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
+	    foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder','gradable') {
 		if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
 # FIXME: internationalization seems wrong here
 		    $r->print('<li>'.
@@ -1672,8 +1721,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|ext\.tool)$})) {
-            my $srctype= $1;
+                 ($url =~ m{^/adm/$match_domain/$match_username/\d+/(bulletinboard|smppg)$}) ||
+                 ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$})) {
             my ($srcd,$srcn) = split(/_/,$cid);
 # When paste buffer was populated using an active role in a different course
 # check for mdc privilege in the course from which the resource was pasted
@@ -1683,7 +1732,9 @@ sub do_paste_from_buffer {
                     next;
                 }
             }
-            if (($srctype eq 'ext.tool') && ($srcd ne $coursedom)) {
+# When buffer was populated using an active role in a different course
+# disallow pasting of External Tool if course is in a different domain.
+            if (($url =~ m{/ext\.tool$}) && ($srcd ne $coursedom)) {
                 $notindom{$suffix} = 1;
                 next;
             }
@@ -1850,13 +1901,18 @@ sub do_paste_from_buffer {
         }
         if ($url=~ m{/(bulletinboard|smppg|ext\.tool)$}) {
             my $prefix = $1;
-            my $fromothercrs; 
+            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,
                        );
+            if ($prefix eq 'ext.tool') {
+                if ($prefixchg{$suffix} eq 'docstosupp') { 
+                    $info{'delgradable'} = 1;
+                }
+            }
             if (($srcdom{$suffix} =~ /^$match_domain$/) && ($srcnum{$suffix} =~ /^$match_courseid$/)) {
                 unless (($srcdom{$suffix} eq $coursedom) && ($srcnum{$suffix} eq $coursenum)) {
                     $fromothercrs = 1;
@@ -1948,6 +2004,18 @@ sub do_paste_from_buffer {
                     &copy_templated_files($url,$srcdom{$suffix},$srcnum{$suffix},$srcmapidx{$suffix},
                                           $coursedom,$coursenum,$template,$newidx,"$folder.$container");
                 }
+            } elsif ($url =~ /ext\.tool$/) {
+                if (($newidx) && ($folder=~/^default/)) { 
+                    my $marker = (split(m{/},$url))[4];
+                    my %toolsettings = &Apache::lonnet::dump('exttool_'.$marker,$coursedom,$coursenum);
+                    my $val = 'no';
+                    if ($toolsettings{'gradable'}) {
+                        $val = 'yes';
+                    }
+                    &LONCAPA::map::storeparameter($newidx,'parameter_0_gradable',$val,
+                                                  'string_yesno');
+                    &remember_parms($newidx,'gradable','set',$val);
+                }
             }
             $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
                                               ':'.$ext.':normal:res';
@@ -2196,6 +2264,9 @@ sub dbcopy {
                         }
                     }
                     $db_name =~ s{_\d*$ }{_$suffix}x;
+                    if (($prefix eq 'exttool') && ($dbref->{'delgradable'}) && ($contents{'gradable'})) {
+                        delete($contents{'gradable'});
+                    }
                     $result=&Apache::lonnet::put($db_name,\%contents,
                                                  $coursedom,$coursenum);
                     if ($result eq 'ok') {
@@ -2480,16 +2551,38 @@ sub url_paste_fixups {
                         $changed = 1;
                     }
                 }
-            } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
+            } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/(.+)$}) {
                 next if ($skip);
                 my $srcdom = $1;
                 my $srcnum = $2;
+                my $rem = $3;
+                my ($is_exttool,$exttoolchg);
+                if ($rem =~ m{\d+/ext\.tool$}) {
+                    $is_exttool = 1;     
+                }
                 if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
                     $rewrites->{$oldurl}{$id} = $ressrc;
                     $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
                     $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
                     $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
                     $changed = 1;
+                    if ($is_exttool) {
+                        $exttoolchg = 1;
+                    }
+                } elsif (($rem =~ m{\d+/ext\.tool$}) &&
+                         ($env{'form.docs.markedcopy_options'} ne 'move')) {
+                    $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
+                    $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
+                    $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
+                    $changed = 1;
+                    $exttoolchg = 1;
+                }
+                if (($is_exttool) && ($prefixchg)) {
+                    if ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/default}) {
+                        if ($exttoolchg) {
+                            $dbcopies->{$oldurl}{$id}{'delgradable'} = 1;
+                        }
+                    }
                 }
             } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
                 if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
@@ -2753,7 +2846,8 @@ sub apply_fixups {
                     }
                 }
             }
-            for (my $i=0; $i<@LONCAPA::map::order; $i++) {
+            my $total = scalar(@LONCAPA::map::order) - 1;
+            for (my $i=$total; $i>=0; $i--) {
                 my $idx = $LONCAPA::map::order[$i];
                 if (defined($LONCAPA::map::resources[$idx])) {
                     my $changed;
@@ -2763,7 +2857,7 @@ sub apply_fixups {
                         splice(@LONCAPA::map::order,$i,1);
                         if (ref($currparam{$idx}) eq 'ARRAY') {
                             foreach my $name (@{$currparam{$idx}}) {
-                                &LONCAPA::map::delparameter($idx,'parameter_'.$name);
+                                &LONCAPA::map::delparameter($idx,$name);
                             }
                         }
                         next;
@@ -2805,7 +2899,7 @@ sub apply_fixups {
             foreach my $idx (keys(%remparam)) {
                 if (ref($remparam{$idx}) eq 'ARRAY') {
                     foreach my $name (@{$remparam{$idx}}) {   
-                        &LONCAPA::map::delparameter($idx,'parameter_'.$name);
+                        &LONCAPA::map::delparameter($idx,$name);
                     }
                 }
             }
@@ -3016,8 +3110,9 @@ sub update_parameter {
 
 sub handle_edit_cmd {
     my ($coursenum,$coursedom) =@_;
+    my $haschanges = 0;
     if ($env{'form.cmd'} eq '') {
-        return 0;
+        return $haschanges; 
     }
     my ($cmd,$idx)=split('_',$env{'form.cmd'});
 
@@ -3032,19 +3127,19 @@ sub handle_edit_cmd {
 	    &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 	}
 	splice(@LONCAPA::map::order, $idx, 1);
-
+        $haschanges = 1;
     } elsif ($cmd eq 'cut') {
 	&LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 	splice(@LONCAPA::map::order, $idx, 1);
-
+        $haschanges = 1;
     } elsif ($cmd eq 'up'
 	     && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
 	@LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
-
+        $haschanges = 1;
     } elsif ($cmd eq 'down'
 	     && defined($LONCAPA::map::order[$idx+1])) {
 	@LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
-
+        $haschanges = 1;
     } elsif ($cmd eq 'rename') {
 	my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
 	if ($comment=~/\S/) {
@@ -3054,11 +3149,26 @@ sub handle_edit_cmd {
 # Devalidate title cache
 	my $renamed_url=&LONCAPA::map::qtescape($url);
 	&Apache::lonnet::devalidate_title_cache($renamed_url);
-
-    } else {
-	return 0;
+        $haschanges = 1;
+    } elsif ($cmd eq 'setalias') {
+        my $newvalue = $env{'form.alias'};
+        if ($newvalue ne '') {
+            unless (Apache::lonnet::get_symb_from_alias($newvalue)) {
+                &LONCAPA::map::storeparameter($idx,'parameter_0_mapalias',$newvalue,
+                                              'string');
+                &remember_parms($idx,'mapalias','set',$newvalue);
+                $haschanges = 1;
+            }
+        }
+    } elsif ($cmd eq 'delalias') {
+        my $current = (&LONCAPA::map::getparameter($idx,'parameter_0_mapalias'))[0];  
+        if ($current ne '') {
+            &LONCAPA::map::delparameter($idx,'parameter_0_mapalias');
+            &remember_parms($idx,'mapalias','del');
+            $haschanges = 1;
+        }
     }
-    return 1;
+    return $haschanges;
 }
 
 sub editor {
@@ -3182,7 +3292,7 @@ sub editor {
 # Rename, cut, copy or remove a single resource
 	if (&handle_edit_cmd($coursenum,$coursedom)) {
             my $contentchg;
-            if ($env{'form.cmd'} =~ m{^(remove|cut)_}) {
+            if ($env{'form.cmd'} =~ m{^(remove|cut|setalias|delalias)_}) {
                 $contentchg = 1;
             }
 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
@@ -3422,10 +3532,10 @@ sub editor {
                           .&Apache::loncommon::start_data_table(undef,'contentlist')
                           .&Apache::loncommon::start_data_table_header_row()
                           .'<th colspan="2">'.&mt('Move').'</th>'
-                          .'<th colspan="2">'.&mt('Actions').'</th>'
+                          .'<th colspan="3">'.&mt('Actions').'</th>'
                           .'<th>'.&mt('Document').'</th>';
                 if ($folder !~ /^supplemental/) {
-                    $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
+                    $to_show .= '<th colspan="2">'.&mt('Settings').'</th>';
                 }
                 $to_show .= &Apache::loncommon::end_data_table_header_row();
                 if ($folder !~ /^supplemental/) {
@@ -3453,9 +3563,8 @@ sub editor {
                                 '<td>'.
                                 &multiple_check_form('actions',\%lists,$canedit).
                                 '</td>'.
-                                '<td>&nbsp;</td>'.
-                                '<td>&nbsp;</td>'.
-                                '<td colspan="4">'.
+                                '<td colspan="3">&nbsp;</td>'.
+                                '<td colspan="2">'.
                                 &multiple_check_form('settings',\%lists,$canedit).
                                 '</td>'.
                                 &Apache::loncommon::end_data_table_row();
@@ -3803,7 +3912,7 @@ sub entryline {
     my $line=&Apache::loncommon::start_data_table_row();
     my ($form_start,$form_end,$form_common,$form_param);
 # Edit commands
-    my ($esc_path, $path, $symb);
+    my ($esc_path, $path, $symb, $curralias);
     if ($env{'form.folderpath'}) {
 	$esc_path=&escape($env{'form.folderpath'});
 	$path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
@@ -3872,6 +3981,8 @@ END
                 'ct' => 'Cut',
 		'rn' => 'Rename',
 		'cp' => 'Copy',
+                'da' => 'Unset alias', 
+                'sa' => 'Set alias',
                 'ex' => 'External Resource',
                 'et' => 'External Tool',
                 'ed' => 'Edit',
@@ -3902,6 +4013,9 @@ END
             ($url!~/$LONCAPA::assess_page_seq_re/)) {
             $confirm_removal = 1;
         }
+        if ($url =~ /$LONCAPA::assess_re/) {
+            $curralias = (&LONCAPA::map::getparameter($orderidx,'parameter_0_mapalias'))[0];
+        }
 
 	if ($denied{'copy'}) {
             $copylink=(<<ENDCOPY)
@@ -4082,7 +4196,7 @@ END
                     }
                 }
                 if ($url ne '') {
-                    $url.=(($url=~/\?/)?'&':'?').'symb='.&HTML::Entities::encode($shownsymb,'"<>&');
+                    $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($shownsymb);
                 }
             } elsif (!$env{'request.role.adv'}) {
                 my $checkencrypt;
@@ -4103,7 +4217,7 @@ END
                     my $shownsymb = &Apache::lonenc::encrypted($symb);
                     my $shownurl = &Apache::lonenc::encrypted($url);
                     if (&Apache::lonnet::symbverify($shownsymb,$shownurl)) {
-                        $url = $shownurl.(($shownurl=~/\?/)?'&':'?').'symb='.&HTML::Entities::encode($shownsymb,'"<>&');
+                        $url = $shownurl.(($shownurl=~/\?/)?'&':'?').'symb='.&escape($shownsymb);
                         if ($env{'request.enc'} ne '') {
                             delete($env{'request.enc'});
                         }
@@ -4289,6 +4403,17 @@ $form_end;
         $reinit = &mt('(re-initialize course to access)');
     }
     $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
+    if ($orig_url =~ /$LONCAPA::assess_re/) {
+        $line.= '<br />';
+        if ($curralias ne '') {
+            $line.='<span class="LC_nobreak"><a href="javascript:delalias('."'$esc_path','$orderidx'".');" class="LC_docs_alias">'.
+                   $lt{'da'}.'</a></span>';
+        } else {
+            $line.='<span class="LC_nobreak"><a href="javascript:setalias('."'$esc_path','$orderidx'".');" class="LC_docs_alias">'.
+                   $lt{'sa'}.'</a></span>';
+        }
+    }
+    $line.='</td><td>';
     my $link;
     if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
        $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
@@ -4328,11 +4453,16 @@ $form_end;
            $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>';
+       $line.=$title.' <span class="LC_warning LC_docs_reinit_warn">('.&mt('Hidden').')</span>';
     } else {
        $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
     }
-    $line.="$extresform</td>";
+    if (($allowed) && ($curralias ne '')) {
+        $line .= '<br /><span class="LC_docs_alias_name">('.$curralias.')</span>';
+    } else {
+        $line .= $extresform;
+    }
+    $line .= '</td>';
     $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
     $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
     if (($allowed) && ($folder!~/^supplemental/)) {
@@ -4550,7 +4680,7 @@ sub untiehash {
 
 
 sub checkonthis {
-    my ($r,$url,$level,$title)=@_;
+    my ($r,$url,$level,$title,$checkstale)=@_;
     $url=&unescape($url);
     $alreadyseen{$url}=1;
     $r->rflush();
@@ -4565,10 +4695,22 @@ sub checkonthis {
        $r->print('<a href="'.$url.'" target="cat">'.
 		 ($title?$title:$url).'</a> ');
        if ($url=~/^\/res\//) {
+          my $updated;
+          if (($checkstale) && ($url !~ m{^/res/lib/templates/}) &&
+              ($url !~ /\.\d+\.\w+$/)) {
+              $updated = &Apache::lonnet::remove_stale_resfile($url);
+          }
 	  my $result=&Apache::lonnet::repcopy(
                               &Apache::lonnet::filelocation('',$url));
           if ($result eq 'ok') {
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');
+             if ($updated) {
+                 $r->print('<br />');
+                 for (my $i=0;$i<=$level*5;$i++) {
+                     $r->print('&nbsp;');
+                 }
+                 $r->print('- '.&mt('Outdated copy removed'));
+             }
              $r->rflush();
              &Apache::lonnet::countacc($url);
              $url=~/\.(\w+)$/;
@@ -4602,7 +4744,7 @@ sub checkonthis {
                 &Apache::lonnet::metadata($url,'dependencies');
              foreach my $dep (split(/\,/,$dependencies)) {
 		 if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
-                    &checkonthis($r,$dep,$level+1);
+                    &checkonthis($r,$dep,$level+1,'',$checkstale);
                  }
              }
           } elsif ($result eq 'unavailable') {
@@ -4616,6 +4758,9 @@ sub checkonthis {
           } else {
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
           }
+          if (($updated) && ($result ne 'ok')) {
+              $r->print('<br />'.&mt('Outdated copy removed'));
+          }
        }
     }
 }
@@ -4668,9 +4813,71 @@ sub list_symbs {
     $r->print(&endContentScreen());
 }
 
+sub short_urls {
+    my ($r,$canedit) = @_;
+    my $crstype = &Apache::loncommon::course_type();
+    my $formname = 'shortenurl';
+    $r->print(&Apache::loncommon::start_page('Display/Set Shortened URLs'));
+    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Shortened URLs'));
+    $r->print(&startContentScreen('tools'));
+    my ($navmap,$errormsg) =
+        &Apache::loncourserespicker::get_navmap_object($crstype,'shorturls');
+    my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
+    my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+    my (%maps,%resources,%titles);
+    if (!ref($navmap)) {
+        $r->print($errormsg.
+                  &endContentScreen());
+        return '';
+    } else {
+        $r->print('<h4 class="LC_info">'.&mt('Tiny URLs for deep-linking into course').'</h4>'."\n");
+        $r->rflush();
+        my $readonly;
+        if ($canedit) {
+            my ($numnew,$errors) = &Apache::loncommon::make_short_symbs($cdom,$cnum,$navmap);
+            if ($numnew) {
+                $r->print('<p class="LC_info">'.&mt('Created [quant,_1,URL]',$numnew).'</p>');
+            }
+            if ((ref($errors) eq 'ARRAY') && (@{$errors} > 0)) {
+                $r->print(&mt('The following errors occurred when processing your request to create shortened URLs:').'<br /><ul>');
+                foreach my $error (@{$errors}) {
+                    $r->print('<li>'.$error.'</li>');
+                }
+                $r->print('</ul><br />');
+            }
+        } else {
+            $readonly = 1;
+        }
+        my %currtiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
+        $r->print(&Apache::loncourserespicker::create_picker($navmap,'shorturls',$formname,$crstype,undef,
+                                                             undef,undef,undef,undef,undef,\%currtiny,$readonly));
+    }
+    $r->print(&endContentScreen());
+}
+
+sub contentverifyform {
+    my ($r) = @_;
+    my $crstype = &Apache::loncommon::course_type();
+    $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
+    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
+    $r->print(&startContentScreen('tools'));
+    $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>');
+    $r->print('<form method="post" action="/adm/coursedocs"><p>'.
+              &mt('Include a check if files copied from elsewhere are up to date (will increase verification time)?').
+              '&nbsp;<span class="LC_nobreak">'.
+              '<label><input type="radio" name="checkstale" value="0" checked="checked" />'.
+              &mt('No').'</label>'.('&nbsp;'x2).
+              '<label><input type="radio" name="checkstale" value="1" />'.
+              &mt('Yes').'</label></span></p><p>'.
+              '<input type="submit" value="'.&mt('Verify content').' "/>'.
+              '<input type="hidden" value="1" name="tools" />'.
+              '<input type="hidden" value="1" name="verify" /></p></form>');
+    $r->print(&endContentScreen());
+    return;
+}
 
 sub verifycontent {
-    my ($r) = @_;
+    my ($r,$checkstale) = @_;
     my $crstype = &Apache::loncommon::course_type();
     $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
@@ -4691,7 +4898,7 @@ sub verifycontent {
 	   }
        }
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
-           &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
+           &checkonthis($r,$hash{$key},0,$hash{'title_'.$1},$checkstale);
        }
    }
    &untiehash();
@@ -4699,7 +4906,6 @@ sub verifycontent {
     $r->print(&endContentScreen());
 }
 
-
 sub devalidateversioncache {
     my $src=shift;
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
@@ -5162,12 +5368,31 @@ sub handler {
         $disabled = ' disabled="disabled"';
     }
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
+    if ($env{'form.inhibitmenu'}) {
+        unless ($env{'form.inhibitmenu'} eq 'yes') {
+            delete($env{'form.inhibitmenu'});
+        }
+    }
+
   if ($allowed && $env{'form.verify'}) {
       &init_breadcrumbs('verify','Verify Content','Docs_Verify_Content');
-      &verifycontent($r);
+      if (!$canedit) {
+          &verifycontent($r);
+      } elsif (($env{'form.checkstale'} ne '') && ($env{'form.checkstale'} =~ /^\d$/)) {
+          &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1&verify=1&checkstale=$env{'form.checkstale'}",
+                                                  text=>'Results',
+                                                  faq=>273,
+                                                  bug=>'Instructor Interface'});
+          &verifycontent($r,$env{'form.checkstale'});
+      } else {
+          &contentverifyform($r);
+      }
   } elsif ($allowed && $env{'form.listsymbs'}) {
       &init_breadcrumbs('listsymbs','List Content IDs');
       &list_symbs($r);
+  } elsif ($allowed && $env{'form.shorturls'}) {
+      &init_breadcrumbs('shorturls','Set/Display Shortened URLs','Docs_Short_URLs');
+      &short_urls($r,$canedit);
   } elsif ($allowed && $env{'form.docslog'}) {
       &init_breadcrumbs('docslog','Show Log');
       my $folder = $env{'form.folder'};
@@ -5244,6 +5469,26 @@ sub handler {
                                              'forcesupplement','forcestandard',
                                              'tools','symb','command','supppath']);
 
+    foreach my $item ('forcesupplement','forcestandard','tools') {
+        next if ($env{'form.'.$item} eq '');
+        unless ($env{'form.'.$item} eq '1') {
+            delete($env{'form.'.$item});
+        }
+    }
+
+    if ($env{'form.command'}) {
+        unless ($env{'form.command'} =~ /^(direct|directnav|editdocs|editsupp|contents|home)$/) {
+            delete($env{'form.command'});
+        }
+    }
+
+    if ($env{'form.symb'}) {
+        my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
+        unless (($id =~ /^\d+$/) && (&Apache::lonnet::is_on_map($resurl))) { 
+            delete($env{'form.symb'});
+        }
+    }
+
 # standard=1: this is a "new-style" course with an uploaded map as top level
 # standard=2: this is a "old-style" course, and there is nothing we can do
 
@@ -5266,6 +5511,38 @@ sub handler {
     my $toolsflag=0;
     if ($env{'form.tools'}) { $toolsflag=1; }
 
+    if ($env{'form.folderpath'} ne '') {
+        my @items = split(/\&/,$env{'form.folderpath'});
+        my $badpath;
+        for (my $i=0; $i<@items; $i++) {
+            my $odd = $i%2;
+            if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
+                $badpath = 1;
+            } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
+                $badpath = 1;
+            }
+            last if ($badpath);
+        }
+        if ($badpath) {
+            delete($env{'form.folderpath'});
+        }
+    }
+
+    if ($env{'form.supppath'} ne '') {
+        my @items = split(/\&/,$env{'form.supppath'});
+        my $badpath;
+        for (my $i=0; $i<@items; $i++) {
+            my $odd = $i%2;
+            if ((!$odd) && ($items[$i] !~ /^supplemental(|_\d+)$/)) {
+                $badpath = 1; 
+            }
+            last if ($badpath);
+        }
+        if ($badpath) {
+            delete($env{'form.supppath'});
+        }
+    }
+
     my $script='';
     my $showdoc=0;
     my $addentries = {};
@@ -5450,7 +5727,7 @@ sub handler {
                 }
             }
             my $tabidstr = join("','",@tabids);
-            %ltitools = &Apache::lonnet::get_domain_ltitools($coursedom);
+            %ltitools = &Apache::lonnet::get_domain_lti($coursedom,'consumer');
             my $posslti = keys(%ltitools);
             my $hostname = $r->hostname();
 	    $script .= &editing_js($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
@@ -5538,6 +5815,7 @@ sub handler {
 	  undef($hadchanges);
           $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
                                               \%allfiles,\%codebase,$context,$crstype);
+          undef($navmap);
 	  if ($hadchanges) {
 	      &mark_hash_old();
 	  }
@@ -5834,6 +6112,11 @@ CRSFORM
    <input type="hidden" name="copyfolder" />
    $containertag
  </form>
+ <form name="aliasform" method="post" action="/adm/coursedocs">
+   <input type="hidden" name="alias" />
+   <input type="hidden" name="cmd" />
+   $containertag
+ </form>
 
 HIDDENFORM
         $r->print(&makesimpleeditform($pathitem)."\n".
@@ -6332,8 +6615,10 @@ unless ($container eq 'page') {
              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
           if ($hadchanges) {
-             &mark_hash_old();
-          }
+              unless (&is_hash_old()) {
+                  &mark_hash_old();
+              }
+	  }
 
           &changewarning($r,'');
         }
@@ -6531,6 +6816,7 @@ my %suporderhash = (
 sub embedded_form_elems {
     my ($phase,$primaryurl,$newidx) = @_;
     my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
+    $newidx =~s /\D+//g;
     return <<STATE;
     <input type="hidden" name="folderpath" value="$folderpath" />
     <input type="hidden" name="cmd" value="upload_embedded" />
@@ -6551,7 +6837,11 @@ sub embedded_destination {
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
         $destination .=  $2.'/';
     }
-    $destination .= $env{'form.newidx'};
+    my $newidx = $env{'form.newidx'};
+    $newidx =~s /\D+//g;
+    if ($newidx) {
+        $destination .= $newidx;
+    }
     my $dir_root = '/userfiles';
     return ($destination,$dir_root);
 }
@@ -6577,6 +6867,9 @@ sub decompression_info {
     }
     unshift(@hiddens,$pathitem);
     foreach my $item (@hiddens) {
+        if ($item eq 'newidx') {
+            next if ($env{'form.'.$item} =~ /\D/);
+        }
         if ($env{'form.'.$item}) {
             $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
                            &HTML::Entities::encode($env{'form.'.$item},'<>&"').'" />'."\n";
@@ -6689,6 +6982,7 @@ sub generate_admin_menu {
                                          'vc'   => 'Verify Content',
                                          'cv'   => 'Check/Set Resource Versions',
                                          'ls'   => 'List Resource Identifiers',
+                                         'ct'   => 'Display/Set Shortened URLs for Deep-linking',
                                          'imse' => 'Export contents to IMS Archive',
                                          'dcd'  => "Copy $crstype Content to Authoring Space",
             );
@@ -6739,6 +7033,13 @@ sub generate_admin_menu {
                     icon       => 'symbs.png',
                     linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
                 },
+                {   linktext   => $lt{'ct'},
+                    url        => "javascript:injectData(document.courseverify,'dummy','shorturls','$lt{'ct'}')",
+                    permission => 'F',
+                    help       => 'Docs_Short_URLs',
+                    icon       => 'shorturls.png',
+                    linktitle  => "Set shortened URLs for a resource or folder in your $lc_crstype for use in deep-linking"
+                },
                 ]
         });
     if ($canedit) {
@@ -6901,6 +7202,8 @@ sub editing_js {
                                           p_ctr2b => '?',
                                           p_ctr3a => 'Cut those',
                                           p_ctr3b => 'items?',
+                                          setal   => 'Enter a (unique) alias',
+                                          delal   => 'Are you sure you want to eliminate the alias?',
                                           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',
@@ -6945,8 +7248,13 @@ sub editing_js {
                 } else {
                     $url = $res;
                 }
-                $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($url),'<>&"').'?symb='.
-                             &HTML::Entities::encode($caller,'<>&"');
+                $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($url),'<>&"');
+                if ($backtourl =~ m{^\Q/uploaded/$coursedom/$coursenum/\Edefault_\d+\.sequence$}) {
+                    $backtourl .= '?navmap=1';
+                } else {
+                    $backtourl .= '?symb='.
+                                  &HTML::Entities::encode($caller,'<>&"');
+                }
                 if ($backtourl =~ m{^\Q/public/$coursedom/$coursenum/syllabus\E}) {
                     if (($ENV{'SERVER_PORT'} == 443) &&
                         ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
@@ -7103,6 +7411,24 @@ function changename(folderpath,index,old
     }
 }
 
+function setalias(folderpath,index) {
+    var alias = prompt('$js_lt{"setal"}');
+    if ((alias != null) && (alias != '')) {
+        this.document.forms.aliasform.alias.value=alias;
+        this.document.forms.aliasform.cmd.value='setalias_'+index;
+        this.document.forms.aliasform.folderpath.value=folderpath;
+        this.document.forms.aliasform.submit();
+    }
+}
+
+function delalias(folderpath,index) {
+    if (confirm('$js_lt{"delal"}')) {
+        this.document.forms.aliasform.cmd.value='delalias_'+index;
+        this.document.forms.aliasform.folderpath.value=folderpath;
+        this.document.forms.aliasform.submit();
+    }
+}
+
 ENDNEWSCRIPT
     } else {
         $jsmakefunctions = <<ENDNEWSCRIPT;
@@ -7147,6 +7473,14 @@ function changename() {
     alert("$js_lt{'edri'}");
 }
 
+function setalias() {
+    alert("$js_lt{'edri'}");
+}
+
+function delalias() {
+    alert("$js_lt{'edri'}");
+}
+
 function makenew() {
     alert("$js_lt{'edri'}");
 }
@@ -8641,7 +8975,9 @@ check on this
 
 Verify Content
 
-=item devalidateversioncache() & checkversions()
+=item devalidateversioncache() 
+
+=item checkversions()
 
 Check Versions