File:  [LON-CAPA] / loncom / interface / londocs.pm
Revision 1.645: download - view: text, annotated - select for diffs
Mon Dec 18 22:56:45 2017 UTC (6 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Consumer
 - Course Coordinator can set an instance of a Tool Provider to be gradable,
   e.g., when the provider will be passing grades back to LON-CAPA.

    1: # The LearningOnline Network
    2: # Documents
    3: #
    4: # $Id: londocs.pm,v 1.645 2017/12/18 22:56:45 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::londocs;
   30: 
   31: use strict;
   32: use Apache::Constants qw(:common :http);
   33: use Apache::imsexport;
   34: use Apache::lonnet;
   35: use Apache::loncommon;
   36: use Apache::lonhtmlcommon;
   37: use LONCAPA::map();
   38: use Apache::lonratedt();
   39: use Apache::lonxml;
   40: use Apache::lonclonecourse;
   41: use Apache::lonnavmaps;
   42: use Apache::lonnavdisplay();
   43: use Apache::lonextresedit();
   44: use Apache::lontemplate();
   45: use Apache::lonsimplepage();
   46: use Apache::lonhomework();
   47: use Apache::lonpublisher();
   48: use Apache::lonparmset();
   49: use HTML::Entities;
   50: use HTML::TokeParser;
   51: use GDBM_File;
   52: use File::MMagic;
   53: use File::Copy;
   54: use Apache::lonlocal;
   55: use Cwd;
   56: use UUID::Tiny ':std';
   57: use LONCAPA qw(:DEFAULT :match);
   58: 
   59: my $iconpath;
   60: 
   61: my %hash;
   62: 
   63: my $hashtied;
   64: my %alreadyseen=();
   65: 
   66: my $hadchanges;
   67: my $suppchanges;
   68: 
   69: 
   70: my %help=();
   71: 
   72: 
   73: sub mapread {
   74:     my ($coursenum,$coursedom,$map)=@_;
   75:     return
   76:       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   77: 			     $map);
   78: }
   79: 
   80: sub storemap {
   81:     my ($coursenum,$coursedom,$map,$contentchg)=@_;
   82:     my $report;
   83:     if (($contentchg) && ($map =~ /^default/)) {
   84:        $report = 1;
   85:     }
   86:     my ($outtext,$errtext)=
   87:       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   88: 			      $map,1,$report);
   89:     if ($errtext) { return ($errtext,2); }
   90: 
   91:     if ($map =~ /^default/) {
   92:         $hadchanges=1;
   93:     } else {
   94:         $suppchanges=1;
   95:     }
   96:     return ($errtext,0);
   97: }
   98: 
   99: 
  100: 
  101: sub authorhosts {
  102:     my %outhash=();
  103:     my $home=0;
  104:     my $other=0;
  105:     foreach my $key (keys(%env)) {
  106: 	if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
  107: 	    my $role=$1;
  108: 	    my $realm=$2;
  109: 	    my ($start,$end)=split(/\./,$env{$key});
  110: 	    if (($start) && ($start>time)) { next; }
  111: 	    if (($end) && (time>$end)) { next; }
  112: 	    my ($ca,$cd);
  113: 	    if ($1 eq 'au') {
  114: 		$ca=$env{'user.name'};
  115: 		$cd=$env{'user.domain'};
  116: 	    } else {
  117: 		($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  118: 	    }
  119: 	    my $allowed=0;
  120: 	    my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  121: 	    my @ids=&Apache::lonnet::current_machine_ids();
  122: 	    foreach my $id (@ids) {
  123:                 if ($id eq $myhome) {
  124:                     $allowed=1;
  125:                     last;
  126:                 }
  127:             }
  128: 	    if ($allowed) {
  129: 		$home++;
  130: 		$outhash{'home_'.$ca.':'.$cd}=1;
  131: 	    } else {
  132: 		$outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
  133: 		$other++;
  134: 	    }
  135: 	}
  136:     }
  137:     return ($home,$other,%outhash);
  138: }
  139: 
  140: 
  141: sub clean {
  142:     my ($title)=@_;
  143:     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
  144:     return $title;
  145: }
  146: 
  147: sub default_folderpath {
  148:     my ($coursenum,$coursedom,$navmapref) = @_;
  149:     return unless ($coursenum && $coursedom && ref($navmapref));
  150: # Check if entire course is hidden and/or encrypted
  151:     my ($hiddenmap,$encryptmap,$folderpath,$hiddentop);
  152:     my $toplevel = "uploaded/$coursedom/$coursenum/default.sequence";
  153:     unless (ref($$navmapref)) {
  154:         $$navmapref = Apache::lonnavmaps::navmap->new();
  155:     }
  156:     if (ref($$navmapref)) {
  157:         if (lc($$navmapref->get_mapparam(undef,$toplevel,"0.hiddenresource")) eq 'yes') {
  158:             my $filterFunc = sub { my $res = shift; return (!$res->randomout() && !$res->is_map()) };
  159:             my @resources = $$navmapref->retrieveResources($toplevel,$filterFunc,1,1);
  160:             unless (@resources) {
  161:                 $hiddenmap = 1;
  162:                 unless ($env{'request.role.adv'}) {
  163:                     $hiddentop = 1;
  164:                     if ($env{'form.folder'}) {
  165:                         undef($env{'form.folder'});
  166:                     }
  167:                 }
  168:             }
  169:         }
  170:         if (lc($$navmapref->get_mapparam(undef,$toplevel,"0.encrypturl")) eq 'yes') {
  171:             $encryptmap = 1;
  172:         }
  173:     }
  174:     unless ($hiddentop) {
  175:         $folderpath='default&'.&escape(&mt('Main Content')).
  176:                     '::'.$hiddenmap.':'.$encryptmap.'::';
  177:     }
  178:     if (wantarray) {
  179:         return ($folderpath,$hiddentop);
  180:     } else {
  181:         return $folderpath;
  182:     }
  183: }
  184: 
  185: sub dumpcourse {
  186:     my ($r) = @_;
  187:     my $crstype = &Apache::loncommon::course_type();
  188:     my ($starthash,$js);
  189:     unless (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  190:         $js = <<"ENDJS";
  191: <script type="text/javascript">
  192: // <![CDATA[
  193: 
  194: function hide_searching() {
  195:     if (document.getElementById('searching')) {
  196:         document.getElementById('searching').style.display = 'none';
  197:     }
  198:     return;
  199: }
  200: 
  201: // ]]>
  202: </script>
  203: ENDJS
  204:         $starthash = {
  205:                          add_entries => {'onload' => "hide_searching();"},
  206:                      };
  207:     }
  208:     $r->print(&Apache::loncommon::start_page('Copy '.$crstype.' Content to Authoring Space',$js,$starthash)."\n".
  209:               &Apache::lonhtmlcommon::breadcrumbs('Copy '.$crstype.' Content to Authoring Space')."\n");
  210:     $r->print(&startContentScreen('tools'));
  211:     my ($home,$other,%outhash)=&authorhosts();
  212:     unless ($home) {
  213:         $r->print(&endContentScreen());
  214:         return '';
  215:     }
  216:     my $origcrsid=$env{'request.course.id'};
  217:     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
  218:     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  219: # Do the dumping
  220: 	unless ($outhash{'home_'.$env{'form.authorspace'}}) {
  221:             $r->print(&endContentScreen());
  222:             return '';
  223:         }
  224: 	my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  225: 	$r->print('<h3>'.&mt('Copying Files').'</h3>');
  226: 	my $title=$env{'form.authorfolder'};
  227: 	$title=&clean($title);
  228:         my ($navmap,$errormsg) =
  229:             &Apache::loncourserespicker::get_navmap_object($crstype,'dumpdocs');
  230:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  231:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  232:         my (%maps,%resources,%titles);
  233:         if (!ref($navmap)) {
  234:             $r->print($errormsg.
  235:                       &endContentScreen());
  236:             return '';
  237:         } else {
  238:             &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
  239:                                                                    'dumpdocs',$cdom,$cnum);
  240: 	}
  241:         my @todump = &Apache::loncommon::get_env_multiple('form.archive');
  242:         my (%tocopy,%replacehash,%lookup,%deps,%display,%result,%depresult,%simpleproblems,%simplepages,
  243:             %newcontent,%has_simpleprobs);
  244:         foreach my $item (sort {$a <=> $b} (@todump)) {
  245:             my $name = $env{'form.namefor_'.$item};
  246:             if ($resources{$item}) {
  247:                 my ($map,$id,$res) = &Apache::lonnet::decode_symb($resources{$item});
  248:                 if ($res =~ m{^uploaded/$cdom/$cnum/\E((?:docs|supplemental)/.+)$}) {
  249:                     $tocopy{$1} = $name;
  250:                     $display{$item} = $1;
  251:                     $lookup{$1} = $item; 
  252:                 } elsif ($res eq 'lib/templates/simpleproblem.problem') {
  253:                     $simpleproblems{$item} = {
  254:                                                 symb => $resources{$item},
  255:                                                 name => $name,
  256:                                              };
  257:                     $display{$item} = 'simpleproblem_'.$name;
  258:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(.+)$}) {
  259:                         $has_simpleprobs{$1}{$id} = $item;
  260:                     }
  261:                 } elsif ($res =~ m{^adm/$match_domain/$match_username/(\d+)/smppg}) {
  262:                     my $marker = $1;
  263:                     my $db_name = &Apache::lonsimplepage::get_db_name($res,$marker,$cdom,$cnum);
  264:                     $simplepages{$item} = {
  265:                                             res    => $res,
  266:                                             title  => $titles{$item},
  267:                                             db     => $db_name,
  268:                                             marker => $marker,
  269:                                             symb   => $resources{$item},
  270:                                             name   => $name,
  271:                                           };
  272:                     $display{$item} = '/'.$res;
  273:                 }
  274:             } elsif ($maps{$item}) {
  275:                 if ($maps{$item} =~ m{^\Quploaded/$cdom/$cnum/\E((?:default|supplemental)_\d+\.(?:sequence|page))$}) {
  276:                     $tocopy{$1} = $name;
  277:                     $display{$item} = $1;
  278:                     $lookup{$1} = $item;
  279:                 }
  280:             } else {
  281:                 next;
  282:             }
  283:         }
  284: 	my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  285: 	$crs=~s/\_/\//g;
  286:         my $mm = new File::MMagic;
  287:         my $prefix = "/uploaded/$cdom/$cnum/";
  288:         %replacehash = %tocopy;
  289:         foreach my $item (sort(keys(%simpleproblems))) {
  290:             my $content = &Apache::imsexport::simpleproblem($simpleproblems{$item}{'symb'});
  291:             $newcontent{$display{$item}} = $content;
  292:         }
  293:         my $gateway = Apache::lonhtmlgateway->new('web');
  294:         foreach my $item (sort(keys(%simplepages))) {
  295:             if (ref($simplepages{$item}) eq 'HASH') {
  296:                 my $pagetitle = $simplepages{$item}{'title'};
  297:                 my %fields = &Apache::lonnet::dump($simplepages{$item}{'db'},$cdom,$cnum);
  298:                 my %contents;
  299:                 foreach my $field (keys(%fields)) {
  300:                     if ($field =~ /^(?:aaa|bbb|ccc)_(\w+)$/) {
  301:                         my $name = $1;
  302:                         my $msg = $fields{$field};
  303:                         if ($name eq 'webreferences') {
  304:                             if ($msg =~ m{^https?://}) {
  305:                                 $contents{$name} = '<a href="'.$msg.'"><tt>'.$msg.'</tt></a>';
  306:                             }
  307:                         } else {
  308:                             $msg = &Encode::decode('utf8',$msg);
  309:                             $msg = $gateway->process_outgoing_html($msg,1);
  310:                             $contents{$name} = $msg;
  311:                         }
  312:                     } elsif ($field eq 'uploaded.photourl') {
  313:                         my $marker = $simplepages{$item}{marker};
  314:                         if ($fields{$field} =~ m{^\Q$prefix\E(simplepage/$marker/.+)$}) {
  315:                             my $filepath = $1;
  316:                             my ($relpath,$fname) = ($filepath =~ m{^(.+/)([^/]+)$});
  317:                             if ($fname ne '') {
  318:                                 $fname=~s/\.(\w+)$//;
  319:                                 my $ext=$1;
  320:                                 $fname = &clean($fname);
  321:                                 $fname.='.'.$ext;
  322:                                 $contents{image} = '<img src="'.$relpath.$fname.'" alt="Image" />';
  323:                                 $replacehash{$filepath} = $relpath.$fname;
  324:                                 $deps{$item}{$filepath} = 1;
  325:                             }
  326:                         }
  327:                     }
  328:                 }
  329:                 $replacehash{'/'.$simplepages{$item}{'res'}} = $simplepages{$item}{'name'};
  330:                 $lookup{'/'.$simplepages{$item}{'res'}} = $item;
  331:                 my $content = '
  332: <html>
  333: <head>
  334: <title>'.$pagetitle.'</title>
  335: </head>
  336: <body bgcolor="#ffffff">';
  337:                 if ($contents{title}) {
  338:                     $content .= "\n".'<h2>'.$contents{title}.'</h2>';
  339:                 }
  340:                 if ($contents{image}) {
  341:                     $content .= "\n".$contents{image};
  342:                 }
  343:                 if ($contents{content}) {
  344:                     $content .= '
  345: <div class="LC_Box">
  346: <h4 class="LC_hcell">'.&mt('Content').'</h4>'.
  347: $contents{content}.'
  348: </div>';
  349:                 }
  350:                 if ($contents{webreferences}) {
  351:                     $content .= ' 
  352: <div class="LC_Box">
  353: <h4 class="LC_hcell">'.&mt('Web References').'</h4>'.
  354: $contents{webreferences}.'
  355: </div>';
  356:                 }
  357:                 $content .= '
  358: </body>
  359: </html>
  360: ';
  361:                 $newcontent{'/'.$simplepages{$item}{res}} = $content; 
  362:             }
  363:         }
  364: 	foreach my $item (keys(%tocopy)) {
  365:             unless ($item=~/\.(sequence|page)$/) {
  366:                 my $currurlpath = $prefix.$item;
  367:                 my $currdirpath = &Apache::lonnet::filelocation('',$currurlpath);
  368:                 &recurse_html($mm,$prefix,$currdirpath,$currurlpath,$item,$lookup{$item},\%replacehash,\%deps);
  369:             }
  370:         }
  371:         foreach my $num (sort {$a <=> $b} (@todump)) {
  372:             my $src = $display{$num};
  373:             next if ($src eq '');
  374:             my @needcopy = ();
  375:             if ($replacehash{$src}) {
  376:                 push(@needcopy,$src);
  377:                 if (ref($deps{$num}) eq 'HASH') {
  378:                     foreach my $dep (sort(keys(%{$deps{$num}}))) {
  379:                         if ($replacehash{$dep}) {
  380:                             push(@needcopy,$dep);
  381:                         }
  382:                     }
  383:                 }
  384:             } elsif ($src =~ /^simpleproblem_/) {
  385:                 push(@needcopy,$src);
  386:             }
  387:             next if (@needcopy == 0);
  388:             my ($result,$depresult);
  389:             for (my $i=0; $i<@needcopy; $i++) {
  390:                 my $item = $needcopy[$i];
  391:                 my $newfilename;
  392:                 if ($simpleproblems{$num}) {
  393:                     $newfilename=$title.'/'.$simpleproblems{$num}{'name'};
  394:                 } else {
  395: 	            $newfilename=$title.'/'.$replacehash{$item};
  396:                 }
  397: 	        $newfilename=~s/\.(\w+)$//;
  398: 	        my $ext=$1;
  399: 	        $newfilename=&clean($newfilename);
  400: 	        $newfilename.='.'.$ext;
  401:                 my ($newrelpath) = ($newfilename =~ m{^\Q$title/\E(.+)$}); 
  402:                 if ($newrelpath ne $replacehash{$item}) {
  403:                     $replacehash{$item} = $newrelpath;
  404:                 }
  405: 	        my @dirs=split(/\//,$newfilename);
  406: 	        my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
  407: 	        my $makepath=$path;
  408: 	        my $fail;
  409:                 my $origin;
  410: 	        for (my $i=0;$i<$#dirs;$i++) {
  411: 		    $makepath.='/'.$dirs[$i];
  412: 		    unless (-e $makepath) {
  413: 		        unless(mkdir($makepath,0755)) { 
  414:                             $fail = &mt('Directory creation failed.');
  415:                         }
  416: 		    }
  417: 	        }
  418:                 if ($i == 0) {
  419: 	            $result = '<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ';
  420:                 } else {
  421:                     $depresult .= '<li><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt> '.
  422:                                   '<span class="LC_fontsize_small" style="font-weight: bold;">'.
  423:                                   &mt('(dependency)').'</span>: ';
  424:                 }
  425:                 if (-e $path.'/'.$newfilename) {
  426:                     $fail = &mt('Destination already exists -- not overwriting.'); 
  427: 	        } else {
  428:                     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
  429:                         if (($item =~ m{^/adm/$match_domain/$match_username/\d+/smppg}) ||
  430:                             ($item =~ /^simpleproblem_/)) {
  431:                             print $fh $newcontent{$item};
  432:                         } else {
  433:                             my $fileloc = &Apache::lonnet::filelocation('',$prefix.$item);
  434:                             if (-e $fileloc) {
  435:                                 if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  436:                                     if ((($1 eq 'sequence') || ($1 eq 'page')) &&
  437:                                         (ref($has_simpleprobs{$item}) eq 'HASH')) {
  438:                                         my %changes = %{$has_simpleprobs{$item}};
  439:                                         my $content = &Apache::lonclonecourse::rewritefile(
  440:                      &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  441:                                                       (%replacehash,$crs => '')
  442:                                                                                           );
  443:                                         my $updatedcontent = '';
  444:                                         my $parser = HTML::TokeParser->new(\$content);
  445:                                         $parser->attr_encoded(1);
  446:                                         while (my $token = $parser->get_token) {
  447:                                             if ($token->[0] eq 'S') {
  448:                                                 if (($token->[1] eq 'resource') &&
  449:                                                     ($token->[2]->{'src'} eq '/res/lib/templates/simpleproblem.problem') && 
  450:                                                     ($changes{$token->[2]->{'id'}})) {
  451:                                                     my $id = $token->[2]->{'id'};
  452:                                                     $updatedcontent .= '<'.$token->[1];
  453:                                                     foreach my $attrib (@{$token->[3]}) {
  454:                                                         next unless ($attrib =~ /^(src|type|title|id)$/);
  455:                                                         if ($attrib eq 'src') {
  456:                                                             my ($file) = ($display{$changes{$id}} =~ /^\Qsimpleproblem_\E(.+)$/); 
  457:                                                             if ($file) {
  458:                                                                 $updatedcontent .= ' '.$attrib.'="'.$file.'"';
  459:                                                             } else {
  460:                                                                 $updatedcontent .= ' '.$attrib.'="'.$token->[2]->{$attrib}.'"'; 
  461:                                                             }
  462:                                                         } else {
  463:                                                             $updatedcontent .= ' '.$attrib.'="'.$token->[2]->{$attrib}.'"';
  464:                                                         }
  465:                                                     }
  466:                                                     $updatedcontent .= ' />'."\n";
  467:                                                 } else {
  468:                                                     $updatedcontent .= $token->[4]."\n";
  469:                                                 }
  470:                                              } else {
  471:                                                  $updatedcontent .= $token->[2];
  472:                                              }
  473:                                          }
  474:                                          print $fh $updatedcontent;
  475:                                     } else {  
  476: 		                        print $fh &Apache::lonclonecourse::rewritefile(
  477:                      &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  478: 		                                      (%replacehash,$crs => '')
  479: 							                              );
  480:                                     }
  481:                                 } else {
  482: 		                    print $fh
  483:                                         &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  484: 		                }
  485:                             } else {
  486:                                 $fail = &mt('Source does not exist.');  
  487:                             }
  488:                         }
  489:                         $fh->close();
  490: 	            } else {
  491: 		        $fail = &mt('Could not write to destination.');
  492:                     }
  493: 	        }
  494:                 my $text;
  495: 	        if ($fail) {
  496:                     $text = '<span class="LC_error">'.&mt('fail').('&nbsp;'x3).$fail.'</span>';
  497: 	        } else {
  498:                     $text = '<span class="LC_success">'.&mt('ok').'</span>';
  499:                 }
  500:                 if ($i == 0) {
  501:                     $result .= $text;
  502:                 } else {
  503:                     $depresult .= $text.'</li>';
  504: 	        }
  505:             }
  506:             $r->print($result);
  507:             if ($depresult) {
  508:                 $r->print('<ul>'.$depresult.'</ul>');
  509:             }
  510:         }
  511:     } else {
  512:         my ($navmap,$errormsg) =
  513:             &Apache::loncourserespicker::get_navmap_object($crstype,'dumpdocs');
  514:         if (!ref($navmap)) {
  515:             $r->print($errormsg);
  516:         } else {
  517:             $r->print('<div id="searching">'.&mt('Searching ...').'</div>');
  518:             $r->rflush();
  519:             my ($preamble,$formname);
  520:             $formname = 'dumpdoc';
  521: 	    unless ($home==1) {
  522: 	        $preamble = '<div class="LC_left_float">'.
  523: 		            '<fieldset><legend>'.
  524:                             &mt('Select the Authoring Space').
  525:                             '</legend><select name="authorspace">';
  526: 	    }
  527:             my @orderspaces = ();
  528: 	    foreach my $key (sort(keys(%outhash))) {
  529:                 if ($key=~/^home_(.+)$/) {
  530:                     if ($1 eq $env{'user.name'}.':'.$env{'user.domain'}) {
  531:                         unshift(@orderspaces,$1);
  532:                     } else {
  533:                         push(@orderspaces,$1);
  534:                     }
  535:                 } 
  536:             }
  537:             if ($home>1) {
  538:                 $preamble .= '<option value="" selected="selected">'.&mt('Select').'</option>';
  539:             }
  540:             foreach my $user (@orderspaces) {
  541: 		if ($home==1) {
  542: 		    $preamble .= '<input type="hidden" name="authorspace" value="'.$user.'" />';
  543: 		} else {
  544: 		    $preamble .= '<option value="'.$user.'">'.$user.' - '.
  545: 			         &Apache::loncommon::plainname(split(/\:/,$user)).'</option>';
  546: 	        }
  547: 	    }
  548: 	    unless ($home==1) {
  549: 	        $preamble .= '</select></fieldset></div>'."\n";
  550: 	    }
  551: 	    my $title=$origcrsdata{'description'};
  552: 	    $title=~s/[\/\s]+/\_/gs;
  553: 	    $title=&clean($title);
  554: 	    $preamble .= '<div class="LC_left_float">'.
  555:                          '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
  556:                          '<input type="text" size="50" name="authorfolder" value="'.
  557:                          $title.'" />'.
  558:                          '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>'."\n";
  559:             my %uploadedfiles;
  560: 	    &tiehash();
  561: 	    foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  562: 	        my ($ext)=($file=~/\.(\w+)$/);
  563: # FIXME Check supplemental here
  564: 	        my $title=$hash{'title_'.$hash{
  565: 		                'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
  566: 	        if (!$title) {
  567: 		    $title=$file;
  568: 	        } else {
  569: 		    $title=~s|/|_|g;
  570: 	        }
  571: 	        $title=~s/\.(\w+)$//;
  572: 	        $title=&clean($title);
  573: 	        $title.='.'.$ext;
  574: #	    $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
  575:                 $uploadedfiles{$file} = $title;
  576: 	    }
  577: 	    &untiehash();
  578:             $r->print(&Apache::loncourserespicker::create_picker($navmap,'dumpdocs',$formname,$crstype,undef,
  579:                                                                  undef,undef,$preamble,$home,\%uploadedfiles));
  580:         }
  581:     }
  582:     $r->print(&endContentScreen());
  583: }
  584: 
  585: sub recurse_html {
  586:     my ($mm,$prefix,$currdirpath,$currurlpath,$container,$item,$replacehash,$deps) = @_;
  587:     return unless ((ref($replacehash) eq 'HASH') && (ref($deps) eq 'HASH'));
  588:     my (%allfiles,%codebase);
  589:     if (&Apache::lonnet::extract_embedded_items($currdirpath,\%allfiles,\%codebase) eq 'ok') {
  590:         if (keys(%allfiles)) {
  591:             foreach my $dependency (keys(%allfiles)) {
  592:                 next if (($dependency =~ m{^/(res|adm)/}) || ($dependency =~ m{^https?://}));
  593:                 my ($depurl,$relfile,$newcontainer);
  594:                 if ($dependency =~ m{^/}) {
  595:                     if ($dependency =~ m{^\Q$currurlpath/\E(.+)$}) {
  596:                         $relfile = $1;
  597:                         if ($dependency =~ m{^\Q$prefix\E(.+)$}) {
  598:                             $newcontainer = $1;
  599:                             next if ($replacehash->{$newcontainer});
  600:                         }
  601:                         $depurl = $dependency;
  602:                     } else {
  603:                         next;
  604:                     }
  605:                 } else {
  606:                     $relfile = $dependency;
  607:                     $depurl = $currurlpath;
  608:                     $depurl =~ s{[^/]+$}{};
  609:                     $depurl .= $dependency;
  610:                     ($newcontainer) = ($depurl =~ m{^\Q$prefix\E(.+)$});
  611:                 }
  612:                 next if ($relfile eq '');
  613:                 my $newname = $replacehash->{$container};
  614:                 $newname =~ s{[^/]+$}{};
  615:                 $replacehash->{$newcontainer} = $newname.$relfile;
  616:                 $deps->{$item}{$newcontainer} = 1;
  617:                 my ($newurlpath) = ($depurl =~ m{^(.*)/[^/]+$});  
  618:                 my $depfile = &Apache::lonnet::filelocation('',$depurl);
  619:                 my $type = $mm->checktype_filename($depfile);
  620:                 if ($type eq 'text/html') {
  621:                     &recurse_html($mm,$prefix,$depfile,$newurlpath,$newcontainer,$item,$replacehash,$deps);
  622:                 }
  623:             }
  624:         }
  625:     }
  626:     return;
  627: }
  628: 
  629: sub group_import {
  630:     my ($coursenum, $coursedom, $folder, $container, $caller, $ltitoolsref, @files) = @_;
  631:     my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
  632:         %removeparam,$importuploaded,$fixuperrors);
  633:     $allmaps = {};
  634:     while (@files) {
  635: 	my ($name, $url, $residx) = @{ shift(@files) };
  636:         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
  637: 	     && ($caller eq 'londocs')
  638: 	     && (!&Apache::lonnet::stat_file($url))) {
  639: 
  640:             my $errtext = '';
  641:             my $fatal = 0;
  642:             my $newmapstr = '<map>'."\n".
  643:                             '<resource id="1" src="" type="start"></resource>'."\n".
  644:                             '<link from="1" to="2" index="1"></link>'."\n".
  645:                             '<resource id="2" src="" type="finish"></resource>'."\n".
  646:                             '</map>';
  647:             $env{'form.output'}=$newmapstr;
  648:             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
  649:                                                 'output',$1.$2);
  650:             if ($result !~ m{^/uploaded/}) {
  651:                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
  652:                 $fatal = 2;
  653:             }
  654:             if ($fatal) {
  655:                 return ($errtext,$fatal);
  656:             }
  657:         }
  658: 	if ($url) {
  659:             if ($url =~ m{^(/adm/$coursedom/$coursenum/(\d+)/ext\.tool)\:?(.*)$}) {
  660:                 $url = $1;
  661:                 my $marker = $2;
  662:                 my $info = $3;
  663:                 my ($toolid,%toolhash,%toolsettings);
  664:                 my @extras = ('linktext','explanation','crslabel','crstitle','crsappend');
  665:                 my @toolinfo = split(/:/,$info);
  666:                 if ($residx) {
  667:                     %toolsettings=&Apache::lonnet::dump('exttool_'.$marker,$coursedom,$coursenum);
  668:                     $toolid = $toolsettings{'id'};
  669:                 } else {
  670:                     $toolid = shift(@toolinfo);
  671:                 }
  672:                 $toolid =~ s/\D//g;
  673:                 ($toolhash{'target'},$toolhash{'width'},$toolhash{'height'},
  674:                  $toolhash{'linktext'},$toolhash{'explanation'},$toolhash{'crslabel'},
  675:                  $toolhash{'crstitle'},$toolhash{'crsappend'},$toolhash{'gradable'}) = @toolinfo;
  676:                 foreach my $item (@extras) {
  677:                     $toolhash{$item} = &unescape($toolhash{$item});
  678:                 }
  679:                 if ($folder =~ /^supplemental/) {
  680:                     delete($toolhash{'gradable'}); 
  681:                 }
  682:                 if (ref($ltitoolsref) eq 'HASH') {
  683:                     if (ref($ltitoolsref->{$toolid}) eq 'HASH') {
  684:                         my @deleted;
  685:                         $toolhash{'id'} = $toolid;
  686:                         if (($toolhash{'target'} eq 'iframe') || ($toolhash{'target'} eq 'tab') ||
  687:                             ($toolhash{'target'} eq 'window')) {
  688:                             if ($toolhash{'target'} eq 'window') {
  689:                                 foreach my $item ('width','height') {
  690:                                     $toolhash{$item} =~ s/^\s+//;
  691:                                     $toolhash{$item} =~ s/\s+$//;
  692:                                     if ($toolhash{$item} =~ /\D/) {
  693:                                         delete($toolhash{$item});
  694:                                         if ($residx) {
  695:                                             if ($toolsettings{$item}) {
  696:                                                 push(@deleted,$item);
  697:                                             }
  698:                                         }
  699:                                     }
  700:                                 }
  701:                             }
  702:                         } elsif ($residx) {
  703:                             $toolhash{'target'} = $toolsettings{'target'};
  704:                             if ($toolhash{'target'} eq 'window') {
  705:                                 foreach my $item ('width','height') {
  706:                                     $toolhash{$item} = $toolsettings{$item};
  707:                                 }
  708:                             }
  709:                         } elsif (ref($ltitoolsref->{$toolid}->{'display'}) eq 'HASH') {
  710:                             $toolhash{'target'} = $ltitoolsref->{$toolid}->{'display'}->{'target'};
  711:                             if ($toolhash{'target'} eq 'window') {
  712:                                 $toolhash{'width'} = $ltitoolsref->{$toolid}->{'display'}->{'width'};
  713:                                 $toolhash{'height'} = $ltitoolsref->{$toolid}->{'display'}->{'height'};
  714:                             }
  715:                         }
  716:                         if ($toolhash{'target'} eq 'iframe') {
  717:                             foreach my $item ('width','height','linktext','explanation') {
  718:                                 delete($toolhash{$item});
  719:                                 if ($residx) {
  720:                                     if ($toolsettings{$item}) {
  721:                                         push(@deleted,$item);
  722:                                     }
  723:                                 }
  724:                             }
  725:                         } elsif ($toolhash{'target'} eq 'tab') {
  726:                             foreach my $item ('width','height') {
  727:                                 delete($toolhash{$item});
  728:                                 if ($residx) {
  729:                                     if ($toolsettings{$item}) {
  730:                                         push(@deleted,$item);
  731:                                     }
  732:                                 }
  733:                             }
  734:                         }
  735:                         if (ref($ltitoolsref->{$toolid}->{'crsconf'}) eq 'HASH') {
  736:                             foreach my $item ('label','title','linktext','explanation') {
  737:                                 my $crsitem;
  738:                                 if (($item eq 'label') || ($item eq 'title')) {
  739:                                     $crsitem = 'crs'.$item;
  740:                                 } else {
  741:                                     $crsitem = $item;
  742:                                 }
  743:                                 if ($ltitoolsref->{$toolid}->{'crsconf'}->{$item}) {
  744:                                     $toolhash{$crsitem} =~ s/^\s+//;
  745:                                     $toolhash{$crsitem} =~ s/\s+$//;
  746:                                     if ($toolhash{$crsitem} eq '') {
  747:                                         delete($toolhash{$crsitem});
  748:                                     }
  749:                                 } else {
  750:                                     delete($toolhash{$crsitem});
  751:                                 }
  752:                                 if (($residx) && (exists($toolsettings{$crsitem}))) {
  753:                                     unless (exists($toolhash{$crsitem})) {
  754:                                         push(@deleted,$crsitem);
  755:                                     }
  756:                                 }
  757:                             }
  758:                         }
  759:                         if ($toolhash{'passback'}) {
  760:                             my $gradesecret = UUID::Tiny::create_uuid_as_string(UUID_V4);
  761:                             $toolhash{'gradesecret'} = $gradesecret;
  762:                             $toolhash{'gradesecretdate'} = time;
  763:                         }
  764:                         if ($toolhash{'roster'}) {
  765:                             my $rostersecret = UUID::Tiny::create_uuid_as_string(UUID_V4);
  766:                             $toolhash{'rostersecret'} = $rostersecret;
  767:                             $toolhash{'rostersecretdate'} = time;
  768:                         }
  769:                         my $changegradable;
  770:                         if (($residx) && ($folder =~ /^default/)) {
  771:                             if (exists($toolsettings{'gradable'})) {
  772:                                 if (!exists($toolhash{'gradable'})) {
  773:                                     push(@deleted,'gradable');
  774:                                     $changegradable = 1;
  775:                                 }
  776:                             } elsif (exists($toolhash{'gradable'})) {
  777:                                 $changegradable = 1;
  778:                             }
  779:                         }
  780:                         my $putres = &Apache::lonnet::put('exttool_'.$marker,\%toolhash,$coursedom,$coursenum);
  781:                         if ($putres eq 'ok') {
  782:                             if (@deleted) {
  783:                                 &Apache::lonnet::del('exttool_'.$marker,\@deleted,$coursedom,$coursenum);
  784:                             }
  785:                             if (($changegradable) && ($folder =~ /^default/)) {
  786:                                 my $val;
  787:                                 if ($toolhash{'gradable'}) {
  788:                                     $val = 'yes';
  789:                                 } else {
  790:                                     $val = 'no';
  791:                                 }
  792:                                 &LONCAPA::map::storeparameter($residx,'parameter_0_gradable',$val,
  793:                                                               'string_yesno');
  794:                                 &remember_parms($residx,'gradable','set',$val);
  795:                             }
  796:                         } else {
  797:                             return (&mt('Failed to save update to external tool.'),1);
  798:                         }
  799:                     }
  800:                 }
  801:             }
  802:             if (($caller eq 'londocs') &&
  803:                 ($folder =~ /^default/)) {
  804:                 if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
  805:                     my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
  806:                     my $cid = $coursedom.'_'.$coursenum;
  807:                     $allmaps =
  808:                         &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
  809:                                                              $chome,$cid);
  810:                     $donechk = 1;
  811:                 }
  812:                 if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
  813:                     &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
  814:                                         \%removeparam,\%addedmaps,\%hierarchy,\%titles,$allmaps);
  815:                     $importuploaded = 1;
  816:                 } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
  817:                     next if ($allmaps->{$url});
  818:                 }
  819:             }
  820: 	    if (!$residx
  821: 		|| defined($LONCAPA::map::zombies[$residx])) {
  822: 		$residx = &LONCAPA::map::getresidx($url,$residx);
  823: 		push(@LONCAPA::map::order, $residx);
  824: 	    }
  825: 	    my $ext = 'false';
  826: 	    if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
  827: 	    $name = &LONCAPA::map::qtunescape($name);
  828:             if ($name eq '') {
  829:                 $name = &LONCAPA::map::qtunescape(&mt('Web Page'));
  830:             }
  831:             if ($url =~ m{^/uploaded/$coursedom/$coursenum/((?:docs|supplemental)/(?:default|\d+))/new\.html$}) {
  832:                 my $filepath = $1;
  833:                 my $fname = $name;
  834:                 if ($fname =~ /^\W+$/) {
  835:                     $fname = 'web';
  836:                 } else {
  837:                     $fname =~ s/\W/_/g;
  838:                 }
  839:                 if (length($fname) > 15) {
  840:                     $fname = substr($fname,0,14);
  841:                 }
  842:                 my $initialtext = &mt('Replace with your own content.');
  843:                 my $newhtml = <<END;
  844: <html>
  845: <head>
  846: <title>$name</title>
  847: </head>
  848: <body bgcolor="#ffffff">
  849: $initialtext
  850: </body>
  851: </html>
  852: END
  853:                 $env{'form.output'}=$newhtml;
  854:                 my $result =
  855:                     &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
  856:                                                           'output',
  857:                                                           "$filepath/$residx/$fname.html");
  858:                 if ($result =~ m{^/uploaded/}) {
  859:                     $url = $result;
  860:                     if ($filepath =~ /^supplemental/) {
  861:                         $name = time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  862:                                 $env{'user.domain'}.'___&&&___'.$name;
  863:                     }
  864:                 } else {
  865:                     return (&mt('Failed to save new web page.'),1);
  866:                 }
  867:             }
  868:             $url  = &LONCAPA::map::qtunescape($url);
  869: 	    $LONCAPA::map::resources[$residx] =
  870: 		join(':', ($name, $url, $ext, 'normal', 'res'));
  871: 	}
  872:     }
  873:     if ($importuploaded) {
  874:         my %import_errors;
  875:         my %updated = (
  876:                           removefrommap => \%removefrommap,
  877:                           removeparam   => \%removeparam,
  878:                       );
  879:         my ($result,$msgsarray,$lockerror) = 
  880:             &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
  881:         if (keys(%import_errors) > 0) {
  882:             $fixuperrors =
  883:                 '<p span class="LC_warning">'."\n".
  884:                 &mt('The following files are either dependencies of a web page or references within a folder and/or composite page for which errors occurred during import:')."\n".
  885:                 '<ul>'."\n";
  886:             foreach my $key (sort(keys(%import_errors))) {
  887:                 $fixuperrors .= '<li>'.$key.'</li>'."\n";
  888:             }
  889:             $fixuperrors .= '</ul></p>'."\n";
  890:         }
  891:         if (ref($msgsarray) eq 'ARRAY') {
  892:             if (@{$msgsarray} > 0) {
  893:                 $fixuperrors .= '<p class="LC_info">'.
  894:                                 join('<br />',@{$msgsarray}).
  895:                                 '</p>';
  896:             }
  897:         }
  898:         if ($lockerror) {
  899:             $fixuperrors .= '<p class="LC_error">'.
  900:                             $lockerror.
  901:                             '</p>';
  902:         }
  903:     }
  904:     my ($errtext,$fatal) =
  905:         &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
  906:     unless ($fatal) {
  907:         if ($folder =~ /^supplemental/) {
  908:             &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
  909:             my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  910:                                             $folder.'.'.$container);
  911:         }
  912:     }
  913:     return ($errtext,$fatal,$fixuperrors);
  914: }
  915: 
  916: sub log_docs {
  917:     return &Apache::lonnet::write_log('course','docslog',@_);
  918: }
  919: 
  920: {
  921:     my @oldresources=();
  922:     my @oldorder=();
  923:     my $parmidx;
  924:     my %parmaction=();
  925:     my %parmvalue=();
  926:     my $changedflag;
  927: 
  928:     sub snapshotbefore {
  929:         @oldresources=@LONCAPA::map::resources;
  930:         @oldorder=@LONCAPA::map::order;
  931:         $parmidx=undef;
  932:         %parmaction=();
  933:         %parmvalue=();
  934:         $changedflag=0;
  935:     }
  936: 
  937:     sub remember_parms {
  938:         my ($idx,$parameter,$action,$value)=@_;
  939:         $parmidx=$idx;
  940:         $parmaction{$parameter}=$action;
  941:         $parmvalue{$parameter}=$value;
  942:         $changedflag=1;
  943:     }
  944: 
  945:     sub log_differences {
  946:         my ($plain)=@_;
  947:         my %storehash=('folder' => $plain,
  948:                        'currentfolder' => $env{'form.folder'});
  949:         if ($parmidx) {
  950:            $storehash{'parameter_res'}=$oldresources[$parmidx];
  951:            foreach my $parm (keys(%parmaction)) {
  952:               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
  953:               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
  954:            }
  955:         }
  956:         my $maxidx=$#oldresources;
  957:         if ($#LONCAPA::map::resources>$#oldresources) {
  958:            $maxidx=$#LONCAPA::map::resources;
  959:         }
  960:         for (my $idx=0; $idx<=$maxidx; $idx++) {
  961:            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
  962:               $storehash{'before_resources_'.$idx}=$oldresources[$idx];
  963:               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
  964:               $changedflag=1;
  965:            }
  966:            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
  967:               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
  968:               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  969:               $changedflag=1;
  970:            }
  971:         }
  972: 	$storehash{'maxidx'}=$maxidx;
  973:         if ($changedflag) { &log_docs(\%storehash); }
  974:     }
  975: }
  976: 
  977: sub docs_change_log {
  978:     my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath,$canedit)=@_;
  979:     my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
  980:     my $navmap; 
  981:     my $js = '<script type="text/javascript">'."\n".
  982:              '// <![CDATA['."\n".
  983:              &Apache::loncommon::display_filter_js('docslog')."\n".
  984:              &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag,
  985:                          $coursedom,$coursenum,'','',$canedit,'',\$navmap)."\n".
  986:              &history_tab_js()."\n".
  987:              &Apache::lonratedt::editscript('simple')."\n".
  988:              '// ]]>'."\n".
  989:              '</script>'."\n";
  990:     $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
  991:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
  992:     $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
  993:     my %orderhash;
  994:     my $container='sequence';
  995:     my $pathitem;
  996:     if ($env{'form.folderpath'} =~ /\:1$/) {
  997:         $container='page';
  998:     }
  999:     my $folderpath=$env{'form.folderpath'};
 1000:     if ($folderpath eq '') {
 1001:         $folderpath = &default_folderpath($coursenum,$coursedom,\$navmap);
 1002:     }
 1003:     undef($navmap);
 1004:     $pathitem = '<input type="hidden" name="folderpath" value="'.
 1005:                 &HTML::Entities::encode($folderpath,'<>&"').'" />';
 1006:     my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
 1007:     my $jumpto = $readfile;
 1008:     $jumpto =~ s{^/}{};
 1009:     my $tid = 1;
 1010:     if ($supplementalflag) {
 1011:         $tid = 2;
 1012:     }
 1013:     my ($breadcrumbtrail) =
 1014:         &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 1015:     $r->print($breadcrumbtrail.
 1016:               &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
 1017:               $readfile));
 1018:     my %docslog=&Apache::lonnet::dump('nohist_docslog',
 1019:                                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 1020:                                       $env{'course.'.$env{'request.course.id'}.'.num'});
 1021: 
 1022:     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 1023: 
 1024:     my %saveable_parameters = ('show' => 'scalar',);
 1025:     &Apache::loncommon::store_course_settings('docs_log',
 1026:                                               \%saveable_parameters);
 1027:     &Apache::loncommon::restore_course_settings('docs_log',
 1028:                                                 \%saveable_parameters);
 1029:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1030: # FIXME: internationalization seems wrong here
 1031:     my %lt=('hiddenresource' => 'Resources hidden',
 1032: 	    'encrypturl'     => 'URL hidden',
 1033: 	    'randompick'     => 'Randomly pick',
 1034: 	    'randomorder'    => 'Randomly ordered',
 1035:             'gradable'       => 'Grade can be assigned to External Tool',
 1036: 	    'set'            => 'set to',
 1037: 	    'del'            => 'deleted');
 1038:     my $filter = &Apache::loncommon::display_filter('docslog')."\n".
 1039:                  $pathitem."\n".
 1040:                  '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
 1041:                  ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
 1042:     $r->print('<div class="LC_left_float">'.
 1043:               '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
 1044:               &makedocslogform($filter,1).
 1045:               '</fieldset></div><br clear="all" />');
 1046:     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
 1047:               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
 1048:               &mt('After').'</th>'.
 1049:               &Apache::loncommon::end_data_table_header_row());
 1050:     my $shown=0;
 1051:     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
 1052: 	if ($env{'form.displayfilter'} eq 'currentfolder') {
 1053: 	    if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
 1054: 	}
 1055:         my @changes=keys(%{$docslog{$id}{'logentry'}});
 1056:         if ($env{'form.displayfilter'} eq 'containing') {
 1057: 	    my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
 1058: 		&Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
 1059: 	    foreach my $key (@changes) {
 1060: 		$wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
 1061: 	    }
 1062: 	    if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
 1063: 	}
 1064:         my $count = 0;
 1065:         my $time =
 1066:             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
 1067:         my $plainname =
 1068:             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
 1069:                                           $docslog{$id}{'exe_udom'});
 1070:         my $about_me_link =
 1071:             &Apache::loncommon::aboutmewrapper($plainname,
 1072:                                                $docslog{$id}{'exe_uname'},
 1073:                                                $docslog{$id}{'exe_udom'});
 1074:         my $send_msg_link='';
 1075:         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
 1076:              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
 1077:             $send_msg_link ='<br />'.
 1078:                 &Apache::loncommon::messagewrapper(&mt('Send message'),
 1079:                                                    $docslog{$id}{'exe_uname'},
 1080:                                                    $docslog{$id}{'exe_udom'});
 1081:         }
 1082:         $r->print(&Apache::loncommon::start_data_table_row());
 1083:         $r->print('<td>'.$time.'</td>
 1084:                        <td>'.$about_me_link.
 1085:                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.
 1086:                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
 1087:                   $send_msg_link.'</td><td>'.
 1088:                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
 1089:         my $is_supp = 0; 
 1090:         if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
 1091:             $is_supp = 1;
 1092:         }
 1093: # Before
 1094: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1095: 	    my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
 1096: 	    my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
 1097: 	    if ($oldname ne $newname) {
 1098:                 my $shown = &LONCAPA::map::qtescape($oldname);
 1099:                 if ($is_supp) {
 1100:                     $shown = &Apache::loncommon::parse_supplemental_title($shown);
 1101:                 }
 1102:                 $r->print($shown);
 1103: 	    }
 1104: 	}
 1105: 	$r->print('<ul>');
 1106: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1107:             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
 1108:                 my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
 1109:                 if ($is_supp) {
 1110:                     $shown = &Apache::loncommon::parse_supplemental_title($shown);
 1111:                 }
 1112: 		$r->print('<li>'.$shown.'</li>');
 1113: 	    }
 1114: 	}
 1115: 	$r->print('</ul>');
 1116: # After
 1117:         $r->print('</td><td>');
 1118: 
 1119: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1120: 	    my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
 1121: 	    my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
 1122: 	    if ($oldname ne '' && $oldname ne $newname) {
 1123:                 my $shown = &LONCAPA::map::qtescape($newname);
 1124:                 if ($is_supp) {
 1125:                     $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
 1126:                 }
 1127:                 $r->print($shown);
 1128: 	    }
 1129: 	}
 1130: 	$r->print('<ul>');
 1131: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1132:             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
 1133:                 my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
 1134:                 if ($is_supp) {
 1135:                     $shown = &Apache::loncommon::parse_supplemental_title($shown);
 1136:                 }
 1137:                 $r->print('<li>'.$shown.'</li>');
 1138: 	    }
 1139: 	}
 1140: 	$r->print('</ul>');
 1141: 	if ($docslog{$id}{'logentry'}{'parameter_res'}) {
 1142: 	    $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
 1143: 	    foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder','gradable') {
 1144: 		if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
 1145: # FIXME: internationalization seems wrong here
 1146: 		    $r->print('<li>'.
 1147: 			      &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
 1148: 				  $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
 1149: 			      .'</li>');
 1150: 		}
 1151: 	    }
 1152: 	    $r->print('</ul>');
 1153: 	}
 1154: # End
 1155:         $r->print('</td>'.&Apache::loncommon::end_data_table_row());
 1156:         $shown++;
 1157:         if (!($env{'form.show'} eq &mt('all')
 1158:               || $shown<=$env{'form.show'})) { last; }
 1159:     }
 1160:     $r->print(&Apache::loncommon::end_data_table()."\n".
 1161:               &makesimpleeditform($pathitem)."\n".
 1162:               '</div></div>');
 1163:     $r->print(&endContentScreen());
 1164: }
 1165: 
 1166: sub update_paste_buffer {
 1167:     my ($coursenum,$coursedom,$folder) = @_;
 1168:     my (@possibles,%removals,%cuts,$output);
 1169:     if ($env{'form.multiremove'}) {
 1170:         $env{'form.multiremove'} =~ s/,$//;
 1171:         map { $removals{$_} = 1; } split(/,/,$env{'form.multiremove'});
 1172:     }
 1173:     if (($env{'form.multicopy'}) || ($env{'form.multicut'})) {
 1174:         if ($env{'form.multicut'}) {
 1175:             $env{'form.multicut'} =~ s/,$//;
 1176:             foreach my $item (split(/,/,$env{'form.multicut'})) {
 1177:                 unless ($removals{$item}) {
 1178:                     $cuts{$item} = 1;
 1179:                     push(@possibles,$item.':cut');
 1180:                 }
 1181:             }
 1182:         }
 1183:         if ($env{'form.multicopy'}) {
 1184:             $env{'form.multicopy'} =~ s/,$//;
 1185:             foreach my $item (split(/,/,$env{'form.multicopy'})) {
 1186:                 unless ($removals{$item} || $cuts{$item}) {
 1187:                     push(@possibles,$item.':copy'); 
 1188:                 }
 1189:             }
 1190:         }
 1191:     } elsif ($env{'form.markcopy'}) {
 1192:         @possibles = split(/,/,$env{'form.markcopy'});
 1193:     }
 1194: 
 1195:     return if (@possibles == 0);
 1196:     return if (!defined($env{'form.copyfolder'}));
 1197: 
 1198:     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 1199: 				    $env{'form.copyfolder'});
 1200:     return if ($fatal);
 1201: 
 1202:     my %curr_groups = &Apache::longroup::coursegroups();
 1203: 
 1204: # Retrieve current paste buffer suffixes.
 1205:     my @currpaste = split(/,/,$env{'docs.markedcopies'});
 1206:     my (%pasteurls,@newpaste);
 1207: 
 1208: # Construct identifiers for current contents of user's paste buffer
 1209:     if (@currpaste) {
 1210:         foreach my $suffix (@currpaste) {
 1211:              my $cid = $env{'docs.markedcopy_crs_'.$suffix};
 1212:              my $url = $env{'docs.markedcopy_url_'.$suffix};
 1213:              my $mapidx = $env{'docs.markedcopy_map_'.$suffix};
 1214:              if (($cid =~ /^$match_domain(?:_)$match_courseid$/) &&
 1215:                  ($url ne '')) {
 1216:                  $pasteurls{$cid.'_'.$url.'_'.$mapidx} = 1;
 1217:              }
 1218:         }
 1219:     }
 1220: 
 1221: # Mark items for copying (skip any items already in user's paste buffer)
 1222:     my %addtoenv;
 1223: 
 1224:     my @pathitems = split(/\&/,$env{'form.folderpath'});
 1225:     my @folderconf = split(/\:/,$pathitems[-1]);
 1226:     my $ispage = $folderconf[4];
 1227: 
 1228:     foreach my $item (@possibles) {
 1229:         my ($orderidx,$cmd) = split(/:/,$item);
 1230:         next if ($orderidx =~ /\D/);
 1231:         next unless (($cmd eq 'cut') || ($cmd eq 'copy') || ($cmd eq 'remove'));
 1232:         my $mapidx = $folder.':'.$orderidx.':'.$ispage;
 1233:         my ($title,$url)=split(':',$LONCAPA::map::resources[$orderidx]);
 1234:         my %denied = &action_restrictions($coursenum,$coursedom,
 1235:                                           &LONCAPA::map::qtescape($url),
 1236:                                           $env{'form.folderpath'},\%curr_groups);
 1237:         next if ($denied{'copy'});
 1238:         $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 1239:         next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$mapidx}));
 1240:         my ($suffix,$errortxt,$locknotfreed) =
 1241:             &new_timebased_suffix($env{'user.domain'},$env{'user.name'},'paste');
 1242:         if ($suffix ne '') {
 1243:             push(@newpaste,$suffix);
 1244:         } else {
 1245:             if ($locknotfreed) {
 1246:                 return $locknotfreed;
 1247:             }
 1248:         }
 1249:         if (&is_supplemental_title($title)) {
 1250:             &Apache::lonnet::appenv({'docs.markedcopy_supplemental_'.$suffix => $title});
 1251: 	    ($title) = &Apache::loncommon::parse_supplemental_title($title);
 1252:         }
 1253: 
 1254:         $addtoenv{'docs.markedcopy_title_'.$suffix} = $title,
 1255:         $addtoenv{'docs.markedcopy_url_'.$suffix}   = $url,
 1256:         $addtoenv{'docs.markedcopy_cmd_'.$suffix}   = $cmd,
 1257:         $addtoenv{'docs.markedcopy_crs_'.$suffix}   = $env{'request.course.id'};
 1258:         $addtoenv{'docs.markedcopy_map_'.$suffix}   = $mapidx;
 1259:         if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
 1260:             my $prefix = $1;
 1261:             my $subdir =$2;
 1262:             if ($subdir eq '') {
 1263:                 $subdir = $prefix;
 1264:             }
 1265:             my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
 1266:             &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
 1267:                                  \%removeparam,\%addedmaps,\%hierarchy,\%titles,\%allmaps);
 1268:             if (ref($hierarchy{$url}) eq 'HASH') {
 1269:                 my ($nested,$nestednames);
 1270:                 &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
 1271:                 $nested =~ s/\&$//;
 1272:                 $nestednames =~ s/\Q___&&&___\E$//;
 1273:                 if ($nested ne '') {
 1274:                     $addtoenv{'docs.markedcopy_nested_'.$suffix} = $nested;
 1275:                 }
 1276:                 if ($nestednames ne '') {
 1277:                     $addtoenv{'docs.markedcopy_nestednames_'.$suffix} = $nestednames;
 1278:                 }
 1279:             }
 1280:         }
 1281:         if ($locknotfreed) {
 1282:             $output = $locknotfreed;
 1283:             last;
 1284:         }
 1285:     }
 1286:     if (@newpaste) {
 1287:         $addtoenv{'docs.markedcopies'} = join(',',(@currpaste,@newpaste));
 1288:     }
 1289:     &Apache::lonnet::appenv(\%addtoenv);
 1290:     delete($env{'form.markcopy'});
 1291:     return $output;
 1292: }
 1293: 
 1294: sub recurse_uploaded_maps {
 1295:     my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
 1296:     if (ref($hierarchy->{$url}) eq 'HASH') {
 1297:         my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
 1298:         my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
 1299:         my (@uploaded,@names,%shorter);
 1300:         for (my $i=0; $i<@maps; $i++) {
 1301:             my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
 1302:             if ($inner ne '') {
 1303:                 push(@uploaded,$inner);
 1304:                 push(@names,&escape($titles[$i]));
 1305:                 $shorter{$maps[$i]} = $inner;
 1306:             }
 1307:         }
 1308:         $$nestref .= "$dir:".join(',',@uploaded).'&';
 1309:         $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
 1310:         foreach my $map (@maps) {
 1311:             if ($shorter{$map} ne '') {
 1312:                 &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
 1313:             }
 1314:         }
 1315:     }
 1316:     return;
 1317: }
 1318: 
 1319: sub print_paste_buffer {
 1320:     my ($r,$container,$folder,$coursedom,$coursenum) = @_;
 1321:     return if (!defined($env{'docs.markedcopies'}));
 1322: 
 1323:     unless (($env{'form.pastemarked'}) || ($env{'form.clearmarked'})) {
 1324:         return if ($env{'docs.markedcopies'} eq '');
 1325:     }
 1326: 
 1327:     my @currpaste = split(/,/,$env{'docs.markedcopies'});
 1328:     my ($pasteitems,@pasteable);
 1329:     my $clipboardcount = 0;
 1330: 
 1331: # Construct identifiers for current contents of user's paste buffer
 1332:     foreach my $suffix (@currpaste) {
 1333:         next if ($suffix =~ /\D/);
 1334:         my $cid = $env{'docs.markedcopy_crs_'.$suffix};
 1335:         my $url = $env{'docs.markedcopy_url_'.$suffix};
 1336:         my $mapidx = $env{'docs.markedcopy_map_'.$suffix};
 1337:         if (($cid =~ /^$match_domain\_$match_courseid$/) &&
 1338:             ($url ne '')) {
 1339:             $clipboardcount ++;
 1340:             my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent,
 1341:                 $canpaste,$nopaste,$othercrs,$areachange,$is_exttool);
 1342:             my $extension = (split(/\./,$env{'docs.markedcopy_url_'.$suffix}))[-1];
 1343:             if ($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
 1344:                 $is_external = 1;
 1345:             } elsif ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
 1346:                 $is_exttool = 1;
 1347:             }
 1348:             if ($folder =~ /^supplemental/) {
 1349:                 $canpaste = &supp_pasteable($env{'docs.markedcopy_url_'.$suffix});
 1350:                 unless ($canpaste) {
 1351:                     $nopaste = &mt('Paste into Supplemental Content unavailable.');
 1352:                 }
 1353:             } else {
 1354:                 $canpaste = 1;
 1355:             }
 1356:             if ($canpaste) {
 1357:                 if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
 1358:                     my $srcdom = $1;
 1359:                     my $srcnum = $2;
 1360:                     my $rem = $3;
 1361:                     if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
 1362:                         $othercourse = 1;
 1363:                         if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
 1364:                             $othercrs = '<br />'.&mt('(from another course)');
 1365:                         } else {
 1366:                             $canpaste = 0;
 1367:                             $nopaste = &mt('Paste from another course unavailable.'); 
 1368:                         }
 1369:                     }
 1370:                     if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
 1371:                         my $prefix = $1;
 1372:                         $parent = $2;
 1373:                         if ($folder !~ /^\Q$prefix\E/) {
 1374:                             $areachange = 1;
 1375:                         }
 1376:                         $is_uploaded_map = 1;
 1377:                     }
 1378:                 } elsif (($url =~ m{^/res/lib/templates/\w+\.problem$}) ||
 1379:                          ($url =~ m{^/adm/($match_domain)/($match_username)/\d+/(bulletinboard|smppg|ext\.tool)$})) {
 1380:                     if ($cid ne $env{'request.course.id'}) {
 1381:                         my ($srcdom,$srcnum) = split(/_/,$cid);
 1382:                         if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
 1383:                             if (($is_exttool) && ($srcdom ne $coursedom)) {
 1384:                                 $canpaste = 0;
 1385:                                 $nopaste = &mt('Paste from another domain unavailable.');
 1386:                             } else {
 1387:                                 $othercrs = '<br />'.&mt('(from another course)');
 1388:                             }
 1389:                         } else {
 1390:                             $canpaste = 0;
 1391:                             $nopaste = &mt('Paste from another course unavailable.');
 1392:                         }
 1393:                     }
 1394:                 }
 1395:                 if ($canpaste) {
 1396:                     push(@pasteable,$suffix);
 1397:                 }
 1398:             }
 1399:             my $buffer;
 1400:             if ($is_external) {
 1401:                 $buffer = &mt('External Resource').': '.
 1402:                     &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
 1403:                     &LONCAPA::map::qtescape($url).')';
 1404:             } elsif ($is_exttool) {
 1405:                 $buffer = &mt('External Tool').': '.
 1406:                     &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
 1407:             } else {
 1408:                 my $icon = &Apache::loncommon::icon($extension);
 1409:                 if ($extension eq 'sequence' &&
 1410:                     $url =~ m{/default_\d+\.sequence$}x) {
 1411:                     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
 1412:                     $icon .= '/navmap.folder.closed.gif';
 1413:                 }
 1414:                 my $title = $env{'docs.markedcopy_title_'.$suffix};
 1415:                 if ($title eq '') {
 1416:                     ($title) = ($url =~ m{/([^/]+)$});
 1417:                 }
 1418:                 $buffer = '<img src="'.$icon.'" alt="" class="LC_icon" />'.
 1419:                           ': '.
 1420:                           &Apache::loncommon::parse_supplemental_title(
 1421:                              &LONCAPA::map::qtescape($title));
 1422:             }
 1423:             $pasteitems .= '<div class="LC_left_float">';
 1424:             my ($options,$onclick);
 1425:             if (($canpaste) && (!$areachange) && (!$othercourse) &&
 1426:                 ($env{'docs.markedcopy_cmd_'.$suffix} eq 'cut')) {
 1427:                 if (($is_uploaded_map) ||
 1428:                     ($url =~ /(bulletinboard|smppg)$/) ||
 1429:                     ($url =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
 1430:                     $options = &paste_options($suffix,$is_uploaded_map,$parent);
 1431:                     $onclick= 'onclick="showOptions(this,'."'$suffix'".');" ';
 1432:                 }
 1433:             }
 1434:             $pasteitems .= '<label><input type="checkbox" name="pasting" id="pasting_'.$suffix.'" value="'.$suffix.'" '.$onclick.'/>'.$buffer.'</label>';
 1435:             if ($nopaste) {
 1436:                  $pasteitems .= $nopaste;   
 1437:             } else {
 1438:                 if ($othercrs) {
 1439:                     $pasteitems .= $othercrs;
 1440:                 }
 1441:                 if ($options) {
 1442:                     $pasteitems .= $options;
 1443:                 }
 1444:             }
 1445:             $pasteitems .= '</div>';
 1446:         }
 1447:     }
 1448:     if ($pasteitems eq '') {
 1449:         &Apache::lonnet::delenv('docs.markedcopies');
 1450:     }
 1451:     my ($pasteform,$form_start,$buttons,$form_end);
 1452:     if ($pasteitems) {
 1453:         $pasteitems .= '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1454:         $form_start = '<form name="pasteform" action="/adm/coursedocs" method="post" onsubmit="return validateClipboard();">';
 1455:         if (@pasteable) {
 1456:             my $value = &mt('Paste to current folder');
 1457:             if ($container eq 'page') {
 1458:                 $value = &mt('Paste to current page');
 1459:             } 
 1460:             $buttons = '<input type="submit" name="pastemarked" value="'.$value.'" />'.('&nbsp;'x2);
 1461:         }
 1462:         $buttons .= '<input type="submit" name="clearmarked" value="'.&mt('Remove from clipboard').'" />'.('&nbsp;'x2);
 1463:         if ($clipboardcount > 1) {
 1464:             $buttons .=
 1465:                 '<span style="text-decoration:line-through">'.('&nbsp;'x20).'</span>'.('&nbsp;'x2).
 1466:                 '<input type="button" name="checkallclip" value="'.&mt('Check all').'" style="height:20px;" onclick="checkClipboard();" />'.
 1467:                 ('&nbsp;'x2).
 1468:                 '<input type="button" name="uncheckallclip" value="'.&mt('Uncheck all').'" style="height:20px;" onclick="uncheckClipboard();" />'.
 1469:                 ('&nbsp;'x2);
 1470:         }
 1471:         $form_end = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />'.
 1472:                     '</form>';
 1473:     } else {
 1474:         $pasteitems = &mt('Clipboard is empty');
 1475:     }
 1476:     $r->print($form_start
 1477:              .'<fieldset>'
 1478:              .'<legend>'.&mt('Clipboard').('&nbsp;' x2).$buttons.'</legend>'
 1479:              .$pasteitems
 1480:              .'</fieldset>'
 1481:              .$form_end);
 1482: }
 1483: 
 1484: sub paste_options {
 1485:     my ($suffix,$is_uploaded_map,$parent) = @_;
 1486:     my ($copytext,$movetext);
 1487:     if ($is_uploaded_map) {
 1488:         $copytext = &mt('Copy to new folder');
 1489:         $movetext = &mt('Move old');
 1490:     } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /bulletinboard$/) {
 1491:         $copytext = &mt('Copy to new board');
 1492:         $movetext = &mt('Move (not posts)');
 1493:     } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /smppg$/) {
 1494:         $copytext = &mt('Copy to new page');
 1495:         $movetext = &mt('Move');
 1496:     } else {
 1497:         $copytext = &mt('Copy to new file');
 1498:         $movetext = &mt('Move');
 1499:     }
 1500:     my $output = '<br />'.
 1501:                  '<span id="pasteoptionstext_'.$suffix.'" class="LC_fontsize_small LC_nobreak"></span>'.
 1502:                  '<div id="pasteoptions_'.$suffix.'" class="LC_dccid" style="display:none;"><span class="LC_nobreak">'.('&nbsp;'x 4).
 1503:                  '<label>'.
 1504:                  '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="new" checked="checked" />'.
 1505:                  $copytext.'</label></span>'.('&nbsp;'x2).' '.
 1506:                  '<span class="LC_nobreak"><label>'.
 1507:                  '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="move" />'.
 1508:                  $movetext.'</label></span>';
 1509:     if (($is_uploaded_map) && ($env{'docs.markedcopy_nested_'.$suffix})) {
 1510:         $output .= '<br /><fieldset><legend>'.&mt('Folder to paste contains sub-folders').
 1511:                    '</legend><table border="0">';
 1512:         my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
 1513:         my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames_'.$suffix});
 1514:         my $lastdir = $parent;
 1515:         my %depths = (
 1516:                        $lastdir => 0,
 1517:                      );
 1518:         my (%display,%deps);
 1519:         for (my $i=0; $i<@pastemaps; $i++) {
 1520:             ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
 1521:             my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
 1522:             my @subfolders = split(/,/,$subfolderstr);
 1523:             $deps{$lastdir} = \@subfolders;
 1524:             my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
 1525:             my $depth = $depths{$lastdir} + 1;
 1526:             my $offset = int($depth * 4);
 1527:             my $indent = ('&nbsp;' x $offset);
 1528:             for (my $j=0; $j<@subfolders; $j++) {
 1529:                 $depths{$subfolders[$j]} = $depth;
 1530:                 $display{$subfolders[$j]} =
 1531:                     '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
 1532:                     '<td><label>'.
 1533:                     '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
 1534:                     '<label>'.
 1535:                     '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="move" />'.
 1536:                     &mt('Move old').'</label>'.
 1537:                     '</td></tr>';
 1538:              }
 1539:         }
 1540:         &recurse_print(\$output,$parent,\%deps,\%display);
 1541:         $output .= '</table></fieldset>';
 1542:     }
 1543:     $output .= '</div>';
 1544:     return $output;
 1545: }
 1546: 
 1547: sub recurse_print {
 1548:     my ($outputref,$dir,$deps,$display) = @_;
 1549:     $$outputref .= $display->{$dir}."\n";
 1550:     if (ref($deps->{$dir}) eq 'ARRAY') {
 1551:         foreach my $subdir (@{$deps->{$dir}}) {
 1552:             &recurse_print($outputref,$subdir,$deps,$display);
 1553:         }
 1554:     }
 1555: }
 1556: 
 1557: sub supp_pasteable {
 1558:     my ($url) = @_;
 1559:     if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
 1560:         (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
 1561:         ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
 1562:         ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
 1563:         ($url =~ m{^/public/$match_domain/$match_courseid/syllabus}) ||
 1564:         ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$})) {
 1565:         return 1;
 1566:     }
 1567:     return;
 1568: }
 1569: 
 1570: sub paste_popup_js {
 1571:     my %html_js_lt = &Apache::lonlocal::texthash(
 1572:                                           show => 'Show Options',
 1573:                                           hide => 'Hide Options',
 1574:                                         );
 1575:     my %js_lt = &Apache::lonlocal::texthash(
 1576:                                           none => 'No items selected from clipboard.',
 1577:                                         );
 1578:     &html_escape(\%html_js_lt);
 1579:     &js_escape(\%html_js_lt);
 1580:     &js_escape(\%js_lt);
 1581:     return <<"END";
 1582: 
 1583: function showPasteOptions(suffix) {
 1584:     document.getElementById('pasteoptions_'+suffix).style.display='block';
 1585:     document.getElementById('pasteoptionstext_'+suffix).innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:hidePasteOptions(\\''+suffix+'\\');" class="LC_menubuttons_link">$html_js_lt{'hide'}</a>';
 1586:     return;
 1587: }
 1588: 
 1589: function hidePasteOptions(suffix) {
 1590:     document.getElementById('pasteoptions_'+suffix).style.display='none';
 1591:     document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$html_js_lt{'show'}</a>';
 1592:     return;
 1593: }
 1594: 
 1595: function showOptions(caller,suffix) {
 1596:     if (document.getElementById('pasteoptionstext_'+suffix)) {
 1597:         if (caller.checked) {
 1598:             document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$html_js_lt{'show'}</a>';
 1599:         } else {
 1600:             document.getElementById('pasteoptionstext_'+suffix).innerHTML ='';
 1601:         }
 1602:         if (document.getElementById('pasteoptions_'+suffix)) {
 1603:             document.getElementById('pasteoptions_'+suffix).style.display='none';
 1604:         }
 1605:     }
 1606:     return;
 1607: }
 1608: 
 1609: function validateClipboard() {
 1610:     var numchk = 0;
 1611:     if (document.pasteform.pasting.length > 1) {
 1612:         for (var i=0; i<document.pasteform.pasting.length; i++) {
 1613:             if (document.pasteform.pasting[i].checked) {
 1614:                 numchk ++;
 1615:             }
 1616:         }
 1617:     } else {
 1618:         if (document.pasteform.pasting.type == 'checkbox') {
 1619:             if (document.pasteform.pasting.checked) {
 1620:                 numchk ++; 
 1621:             } 
 1622:         }
 1623:     }
 1624:     if (numchk > 0) { 
 1625:         return true;
 1626:     } else {
 1627:         alert("$js_lt{'none'}");
 1628:         return false;
 1629:     }
 1630: }
 1631: 
 1632: function checkClipboard() {
 1633:     if (document.pasteform.pasting.length > 1) {
 1634:         for (var i=0; i<document.pasteform.pasting.length; i++) {
 1635:             document.pasteform.pasting[i].checked = true;
 1636:         } 
 1637:     }
 1638:     return;
 1639: }
 1640: 
 1641: function uncheckClipboard() {
 1642:     if (document.pasteform.pasting.length >1) {
 1643:         for (var i=0; i<document.pasteform.pasting.length; i++) {
 1644:             document.pasteform.pasting[i].checked = false;
 1645:         }
 1646:     }
 1647:     return;
 1648: }
 1649: 
 1650: END
 1651: 
 1652: }
 1653: 
 1654: sub do_paste_from_buffer {
 1655:     my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
 1656: 
 1657: # Array of items in paste buffer
 1658:     my (@currpaste,%pastebuffer,%allerrors);
 1659:     @currpaste = split(/,/,$env{'docs.markedcopies'});
 1660: 
 1661: # Early out if paste buffer is empty
 1662:     if (@currpaste == 0) {
 1663:         return ();
 1664:     } 
 1665:     map { $pastebuffer{$_} = 1; } @currpaste;
 1666: 
 1667: # Array of items selected items to paste
 1668:     my @reqpaste = &Apache::loncommon::get_env_multiple('form.pasting');
 1669: 
 1670: # Early out if nothing selected to paste
 1671:     if (@reqpaste == 0) {
 1672:         return();
 1673:     }
 1674:     my @topaste;
 1675:     foreach my $suffix (@reqpaste) {
 1676:         next if ($suffix =~ /\D/);
 1677:         next unless (exists($pastebuffer{$suffix}));
 1678:         push(@topaste,$suffix);
 1679:     }
 1680: 
 1681: # Early out if nothing available to paste
 1682:     if (@topaste == 0) {
 1683:         return();
 1684:     }
 1685: 
 1686:     my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%notindom,%duplicate,
 1687:         %prefixchg,%srcdom,%srcnum,%srcmapidx,%marktomove,$save_err,$lockerrors,$allresult);
 1688: 
 1689:     foreach my $suffix (@topaste) {
 1690:         my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
 1691:         my $cid=&LONCAPA::map::qtescape($env{'docs.markedcopy_crs_'.$suffix});
 1692:         my $mapidx=&LONCAPA::map::qtescape($env{'docs.markedcopy_map_'.$suffix}); 
 1693: # Supplemental content may only include certain types of content
 1694: # Early out if pasted content is not supported in Supplemental area
 1695:         if ($folder =~ /^supplemental/) {
 1696:             unless (&supp_pasteable($url)) {
 1697:                 $notinsupp{$suffix} = 1;
 1698:                 next;
 1699:             }
 1700:         }
 1701:         if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/}) {
 1702:             my $srcd = $1;
 1703:             my $srcn = $2;
 1704: # When paste buffer was populated using an active role in a different course
 1705: # check for mdc privilege in the course from which the resource was pasted
 1706:             if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
 1707:                 unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
 1708:                     $notincrs{$suffix} = 1;
 1709:                     next;
 1710:                 }
 1711:             }
 1712:             $srcdom{$suffix} = $srcd;
 1713:             $srcnum{$suffix} = $srcn;
 1714:         } elsif (($url =~ m{^/res/lib/templates/\w+\.problem$}) ||
 1715:                  ($url =~ m{^/adm/$match_domain/$match_username/\d+/(bulletinboard|smppg)$}) ||
 1716:                  ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$})) {
 1717:             my ($srcd,$srcn) = split(/_/,$cid);
 1718: # When paste buffer was populated using an active role in a different course
 1719: # check for mdc privilege in the course from which the resource was pasted
 1720:             if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
 1721:                 unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
 1722:                     $notincrs{$suffix} = 1;
 1723:                     next;
 1724:                 }
 1725:             }
 1726: # When buffer was populated using an active role in a different course
 1727: # disallow pasting of External Tool if course is in a different domain.
 1728:             if (($url =~ m{/ext\.tool$}) && ($srcd ne $coursedom)) {
 1729:                 $notindom{$suffix} = 1;
 1730:                 next;
 1731:             }
 1732:             $srcdom{$suffix} = $srcd;
 1733:             $srcnum{$suffix} = $srcn;
 1734:         }
 1735:         $srcmapidx{$suffix} = $mapidx;
 1736:         push(@dopaste,$suffix);
 1737:         if ($url=~/\.(page|sequence)$/) {
 1738:             $is_map{$suffix} = 1; 
 1739:         }
 1740:         if ($url =~ m{^/uploaded/$match_domain/$match_courseid/([^/]+)}) {
 1741:             my $oldprefix = $1;
 1742: # When pasting content from Main Content to Supplemental Content and vice versa 
 1743: # URLs will contain different paths (which depend on whether pasted item is
 1744: # a folder/page or a document).
 1745:             if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
 1746:                 $prefixchg{$suffix} = 'docstosupp';
 1747:             } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
 1748:                 $prefixchg{$suffix} = 'supptodocs';
 1749:             }
 1750: 
 1751: # If pasting an uploaded map, get list of contained uploaded maps.
 1752:             if ($env{'docs.markedcopy_nested_'.$suffix}) {
 1753:                 my @nested;
 1754:                 my ($type) = ($oldprefix =~ /^(default|supplemental)/);
 1755:                 my @items = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
 1756:                 my @deps = map { /\d+:([\d,]+$)/ } @items;
 1757:                 foreach my $dep (@deps) {
 1758:                     if ($dep =~ /,/) {
 1759:                         push(@nested,split(/,/,$dep));
 1760:                     } else {
 1761:                         push(@nested,$dep);
 1762:                     }
 1763:                 }
 1764:                 foreach my $item (@nested) {
 1765:                     if ($env{'form.docs.markedcopy_'.$suffix.'_'.$item} eq 'move') {
 1766:                         push(@{$marktomove{$suffix}},$type.'_'.$item);
 1767:                     }
 1768:                 }
 1769:             }
 1770:         }
 1771:     }
 1772: 
 1773: # Early out if nothing available to paste
 1774:     if (@dopaste == 0) {
 1775:         return ();
 1776:     }
 1777: 
 1778: # Populate message hash and hashes used for main content <=> supplemental content
 1779: # changes    
 1780: 
 1781:     %msgs = &Apache::lonlocal::texthash (
 1782:                 notinsupp => 'Paste failed: content type is not supported within Supplemental Content',
 1783:                 notincrs  => 'Paste failed: Item is from a different course which you do not have rights to edit.',
 1784:                 notindom  => 'Paste failed: Item is an external tool from a course in a different donain.', 
 1785:                 duplicate => 'Paste failed: only one instance of a particular published sequence or page is allowed within each course.',
 1786:             );
 1787: 
 1788:     %before = (
 1789:                  docstosupp => {
 1790:                                    map => 'default',
 1791:                                    doc => 'docs',
 1792:                                },
 1793:                  supptodocs => {
 1794:                                    map => 'supplemental',
 1795:                                    doc => 'supplemental',
 1796:                                },
 1797:               );
 1798: 
 1799:     %after = (
 1800:                  docstosupp => {
 1801:                                    map => 'supplemental',
 1802:                                    doc => 'supplemental'
 1803:                                },
 1804:                  supptodocs => {
 1805:                                    map => 'default',
 1806:                                    doc => 'docs',
 1807:                                },
 1808:              );
 1809: 
 1810: # Retrieve information about all course maps in main content area 
 1811: 
 1812:     my $allmaps = {};
 1813:     if ($folder =~ /^default/) {
 1814:         $allmaps =
 1815:             &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
 1816:                                                  $env{"course.$env{'request.course.id'}.home"},
 1817:                                                  $env{'request.course.id'});
 1818:     }
 1819: 
 1820:     my (@toclear,%mapurls,%lockerrs,%msgerrs,%results);
 1821: 
 1822: # Loop over the items to paste
 1823:     foreach my $suffix (@dopaste) {
 1824: # Maps need to be copied first
 1825:         my (%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
 1826:             %dbcopies,%zombies,%params,%docmoves,%mapmoves,%mapchanges,%newsubdir,
 1827:             %newurls,%tomove,%resdatacopy);
 1828:         if (ref($marktomove{$suffix}) eq 'ARRAY') {
 1829:             map { $tomove{$_} = 1; } @{$marktomove{$suffix}};
 1830:         }
 1831:         my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
 1832:         my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
 1833:         my $cid=&LONCAPA::map::qtescape($env{'docs.markedcopy_crs_'.$suffix}); 
 1834:         my $oldurl = $url;
 1835:         if ($is_map{$suffix}) {
 1836: # If pasting a map, check if map contains other maps
 1837:             my (%hierarchy,%titles);
 1838:             &contained_map_check($url,$folder,$coursenum,$coursedom,
 1839:                                  \%removefrommap,\%removeparam,\%addedmaps,
 1840:                                  \%hierarchy,\%titles,$allmaps);
 1841:             if ($url=~ m{^/uploaded/}) {
 1842:                 my $newurl;
 1843:                 unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
 1844:                     ($newurl,my $error) = 
 1845:                         &get_newmap_url($url,$folder,$prefixchg{$suffix},$coursedom,
 1846:                                         $coursenum,$srcdom{$suffix},$srcnum{$suffix},
 1847:                                         \$title,$allmaps,\%newurls);
 1848:                     if ($error) {
 1849:                         $allerrors{$suffix} = $error;
 1850:                         next;
 1851:                     }
 1852:                     if ($newurl ne '') {
 1853:                         if ($newurl ne $url) {
 1854:                             if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
 1855:                                 $newsubdir{$url} = $1;
 1856:                             }
 1857:                             $mapchanges{$url} = 1;
 1858:                         }
 1859:                     }
 1860:                 }
 1861:                 if (($srcdom{$suffix} ne $coursedom) ||
 1862:                     ($srcnum{$suffix} ne $coursenum) ||
 1863:                     ($prefixchg{$suffix}) || (($newurl ne '') && ($newurl ne $url))) {
 1864:                     unless (&url_paste_fixups($url,$folder,$prefixchg{$suffix},
 1865:                                               $coursedom,$coursenum,$srcdom{$suffix},
 1866:                                               $srcnum{$suffix},$allmaps,\%rewrites,
 1867:                                               \%retitles,\%copies,\%dbcopies,
 1868:                                               \%zombies,\%params,\%mapmoves,
 1869:                                               \%mapchanges,\%tomove,\%newsubdir,
 1870:                                               \%newurls,\%resdatacopy)) {
 1871:                         $mapmoves{$url} = 1;
 1872:                     }
 1873:                     $url = $newurl;
 1874:                 } elsif ($env{'docs.markedcopy_nested_'.$suffix}) {
 1875:                     &url_paste_fixups($url,$folder,$prefixchg{$suffix},$coursedom,
 1876:                                       $coursenum,$srcdom{$suffix},$srcnum{$suffix},
 1877:                                       $allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
 1878:                                       \%zombies,\%params,\%mapmoves,\%mapchanges,
 1879:                                       \%tomove,\%newsubdir,\%newurls,\%resdatacopy);
 1880:                 }
 1881:             } elsif ($url=~m {^/res/}) {
 1882: # published map can only exist once, so remove from paste buffer when done
 1883:                 push(@toclear,$suffix);
 1884: # if pasting published map (main content area only) check map not already in course
 1885:                 if ($folder =~ /^default/) {
 1886:                     if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
 1887:                         $duplicate{$suffix} = 1; 
 1888:                         next;
 1889:                     }
 1890:                 }
 1891:             }
 1892:         }
 1893:         if ($url=~ m{/(bulletinboard|smppg|ext\.tool)$}) {
 1894:             my $prefix = $1;
 1895:             my $fromothercrs; 
 1896:             #need to copy the db contents to a new one, unless this is a move.
 1897:             my %info = (
 1898:                          src  => $url,
 1899:                          cdom => $coursedom,
 1900:                          cnum => $coursenum,
 1901:                        );
 1902:             if (($srcdom{$suffix} =~ /^$match_domain$/) && ($srcnum{$suffix} =~ /^$match_courseid$/)) {
 1903:                 unless (($srcdom{$suffix} eq $coursedom) && ($srcnum{$suffix} eq $coursenum)) {
 1904:                     $fromothercrs = 1;
 1905:                     $info{'cdom'} = $srcdom{$suffix};
 1906:                     $info{'cnum'} = $srcnum{$suffix};
 1907:                 }
 1908:             }
 1909:             unless (($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') && (!$fromothercrs)) {
 1910:                 my (%lockerr,$msg);
 1911:                 my ($newurl,$result,$errtext) =
 1912:                     &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
 1913:                 if ($result eq 'ok') {
 1914:                     $url = $newurl;
 1915:                     $title=&mt('Copy of').' '.$title;
 1916:                 } else {
 1917:                     if ($prefix eq 'smppg') {
 1918:                         $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
 1919:                     } elsif ($prefix eq 'bulletinboard') {
 1920:                         $msg = &mt('Paste failed: An error occurred when copying the discussion board.').' '.$errtext;
 1921:                     } elsif ($prefix eq 'ext.tool') {
 1922:                         $msg = &mt('Paste failed: An error occurred when copying the external tool.').' '.$errtext;
 1923:                     }
 1924:                     $results{$suffix} = $result;
 1925:                     $msgerrs{$suffix} = $msg;
 1926:                     $lockerrs{$suffix} = $lockerr{$prefix}; 
 1927:                     next;
 1928: 	        }
 1929:                 if ($lockerr{$prefix}) {
 1930:                     $lockerrs{$suffix} = $lockerr{$prefix};  
 1931:                 }
 1932:             }
 1933:         }
 1934:         $title = &LONCAPA::map::qtunescape($title);
 1935:         my $ext='false';
 1936:         if ($url=~m{^http(|s)://}) { $ext='true'; }
 1937:         if ($env{'docs.markedcopy_supplemental_'.$suffix}) {
 1938:             if ($folder !~ /^supplemental/) {
 1939:                 (undef,undef,$title) =
 1940:                     &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental_'.$suffix});
 1941:             }
 1942:         } else {
 1943:             if ($folder=~/^supplemental/) {
 1944:                 $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 1945:                        $env{'user.domain'}.'___&&&___'.$title;
 1946:             }
 1947:         }
 1948: 
 1949: # For uploaded files (excluding pages/sequences) path in copied file is changed
 1950: # if paste is from Main to Supplemental (or vice versa), or if pasting between
 1951: # courses.
 1952: 
 1953:         unless ($is_map{$suffix}) {
 1954:             my $newidx;
 1955: # Now insert the URL at the bottom
 1956:             $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
 1957:             if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
 1958:                 my $relpath = $1;
 1959:                 if ($relpath ne '') {
 1960:                     my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
 1961:                     my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
 1962:                     my $newprefix = $newloc;
 1963:                     if ($newloc eq 'default') {
 1964:                         $newprefix = 'docs';
 1965:                     }
 1966:                     if ($newdocsdir eq '') {
 1967:                         $newdocsdir = 'default';
 1968:                     }
 1969:                     if (($prefixchg{$suffix}) ||
 1970:                         ($srcdom{$suffix} ne $coursedom) ||
 1971:                         ($srcnum{$suffix} ne $coursenum) ||
 1972:                         ($env{'form.docs.markedcopy_options_'.$suffix} ne 'move')) {
 1973:                         my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
 1974:                         $url =
 1975:                             &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
 1976:                                                                &Apache::lonnet::getfile($oldurl));
 1977:                         if ($url eq '/adm/notfound.html') {
 1978:                             $msgs{$suffix} = &mt('Paste failed: an error occurred saving the file.');
 1979:                             next;
 1980:                         } else {
 1981:                             my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
 1982:                             $newsubpath =~ s{/+$}{/};
 1983:                             $docmoves{$oldurl} = $newsubpath;
 1984:                         }
 1985:                     }
 1986:                 }
 1987:             } elsif ($url =~ m{^/res/lib/templates/(\w+)\.problem$}) {
 1988:                 my $template = $1;
 1989:                 if ($newidx) {
 1990:                     &copy_templated_files($url,$srcdom{$suffix},$srcnum{$suffix},$srcmapidx{$suffix},
 1991:                                           $coursedom,$coursenum,$template,$newidx,"$folder.$container");
 1992:                 }
 1993:             }
 1994:             $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
 1995:                                               ':'.$ext.':normal:res';
 1996:             push(@LONCAPA::map::order,$newidx);
 1997: # Store the result
 1998:             my ($errtext,$fatal) =
 1999:                 &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 2000:             if ($fatal) {
 2001:                 $save_err .= $errtext;
 2002:                 $allresult = 'fail';
 2003:             }
 2004:         }
 2005: 
 2006: # Apply any changes to maps, or copy dependencies for uploaded HTML pages, or update
 2007: # resourcedata for simpleproblems copied from another course 
 2008:         unless ($allresult eq 'fail') {
 2009:             my %updated = (
 2010:                             rewrites      => \%rewrites,
 2011:                             zombies       => \%zombies,
 2012:                             removefrommap => \%removefrommap,
 2013:                             removeparam   => \%removeparam,
 2014:                             dbcopies      => \%dbcopies,
 2015:                             resdatacopy   => \%resdatacopy,
 2016:                             retitles      => \%retitles,
 2017:                           );
 2018:             my %info = (
 2019:                            newsubdir => \%newsubdir,
 2020:                            params    => \%params,
 2021:                        );
 2022:             if ($prefixchg{$suffix}) {
 2023:                 $info{'before'} = $before{$prefixchg{$suffix}};
 2024:                 $info{'after'} = $after{$prefixchg{$suffix}};
 2025:             }
 2026:             my %moves = (
 2027:                            copies   => \%copies,
 2028:                            docmoves => \%docmoves,
 2029:                            mapmoves => \%mapmoves,
 2030:                         );
 2031:             (my $result,$msgs{$suffix},my $lockerror) =
 2032:                 &apply_fixups($folder,$is_map{$suffix},$coursedom,$coursenum,$errors,
 2033:                               \%updated,\%info,\%moves,$prefixchg{$suffix},$oldurl,
 2034:                               $url,'paste');
 2035:             $lockerrors .= $lockerror;
 2036:             if ($result eq 'ok') {
 2037:                 if ($is_map{$suffix}) {
 2038:                     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 2039:                                                     $folder.'.'.$container);
 2040:                     if ($fatal) {
 2041:                         $allresult = 'failread';
 2042:                     } else {
 2043:                         if ($#LONCAPA::map::order<1) {
 2044:                             my $idx=&LONCAPA::map::getresidx();
 2045:                             if ($idx<=0) { $idx=1; }
 2046:                             $LONCAPA::map::order[0]=$idx;
 2047:                             $LONCAPA::map::resources[$idx]='';
 2048:                         }
 2049:                         my $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
 2050:                         $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
 2051:                                                           ':'.$ext.':normal:res';
 2052:                         push(@LONCAPA::map::order,$newidx);
 2053: 
 2054: # Store the result
 2055:                         my ($errtext,$fatal) = 
 2056:                             &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 2057:                         if ($fatal) {
 2058:                             $save_err .= $errtext;
 2059:                             $allresult = 'failstore';
 2060:                         }
 2061:                     } 
 2062:                 }
 2063:                 if ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
 2064:                      push(@toclear,$suffix);
 2065:                 }
 2066:             }
 2067:         }
 2068:     }
 2069:     &clear_from_buffer(\@toclear,\@currpaste);
 2070:     my $msgsarray;
 2071:     foreach my $suffix (keys(%msgs)) {
 2072:          if (ref($msgs{$suffix}) eq 'ARRAY') {
 2073:              $msgsarray .= join(',',@{$msgs{$suffix}});
 2074:          }
 2075:     }
 2076:     return ($allresult,$save_err,$msgsarray,$lockerrors);
 2077: }
 2078: 
 2079: sub do_buffer_empty {
 2080:     my @currpaste = split(/,/,$env{'docs.markedcopies'});
 2081:     if (@currpaste == 0) {
 2082:         return &mt('Clipboard is already empty');
 2083:     }
 2084:     my @toclear = &Apache::loncommon::get_env_multiple('form.pasting');
 2085:     if (@toclear == 0) {
 2086:         return &mt('Nothing selected to clear from clipboard');
 2087:     }
 2088:     my $numdel = &clear_from_buffer(\@toclear,\@currpaste);
 2089:     if ($numdel) {
 2090:         return &mt('[quant,_1,item] cleared from clipboard',$numdel);
 2091:     } else {
 2092:         return &mt('Clipboard unchanged');
 2093:     }
 2094:     return;
 2095: }
 2096: 
 2097: sub clear_from_buffer {
 2098:     my ($toclear,$currpaste) = @_;
 2099:     return unless ((ref($toclear) eq 'ARRAY') && (ref($currpaste) eq 'ARRAY'));
 2100:     my %pastebuffer;
 2101:     map { $pastebuffer{$_} = 1; } @{$currpaste};
 2102:     my $numdel = 0;
 2103:     foreach my $suffix (@{$toclear}) {
 2104:         next if ($suffix =~ /\D/);
 2105:         next unless (exists($pastebuffer{$suffix}));
 2106:         my $regexp = 'docs.markedcopy_[a-z]+_'.$suffix;
 2107:         if (&Apache::lonnet::delenv($regexp,1) eq 'ok') {
 2108:             delete($pastebuffer{$suffix});
 2109:             $numdel ++;
 2110:         }
 2111:     }
 2112:     my $newbuffer = join(',',sort(keys(%pastebuffer)));
 2113:     &Apache::lonnet::appenv({'docs.markedcopies' => $newbuffer});
 2114:     return $numdel;
 2115: }
 2116: 
 2117: sub get_newmap_url {
 2118:     my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
 2119:         $titleref,$allmaps,$newurls) = @_;
 2120:     my $newurl;
 2121:     if ($url=~ m{^/uploaded/}) {
 2122:         $$titleref=&mt('Copy of').' '.$$titleref;
 2123:     }
 2124:     my $now = time;
 2125:     my $suffix=$$.int(rand(100)).$now;
 2126:     my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
 2127:     if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
 2128:         my $path = $1;
 2129:         my $prefix = $2;
 2130:         my $ancestor = $3;
 2131:         if (length($ancestor) > 10) {
 2132:             $ancestor = substr($ancestor,-10,10);
 2133:         }
 2134:         my $newid;
 2135:         if ($prefixchg) {
 2136:             if ($folder =~ /^supplemental/) {
 2137:                 $prefix =~ s/^default/supplemental/;
 2138:             } else {
 2139:                 $prefix =~ s/^supplemental/default/;
 2140:             }
 2141:         }
 2142:         if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
 2143:             $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
 2144:         } else {
 2145:             $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
 2146:         }
 2147:         my $counter = 0;
 2148:         my $is_unique = &uniqueness_check($newurl);
 2149:         if ($folder =~ /^default/) {
 2150:             if ($allmaps->{$newurl}) {
 2151:                 $is_unique = 0;
 2152:             }
 2153:         }
 2154:         while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
 2155:             $counter ++;
 2156:             $suffix ++;
 2157:             if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
 2158:                 $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
 2159:             } else {
 2160:                 $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
 2161:             }
 2162:             $is_unique = &uniqueness_check($newurl);
 2163:         }
 2164:         if ($is_unique) {
 2165:             $newurls->{$newurl} = 1;
 2166:         } else {
 2167:             if ($url=~/\.page$/) {
 2168:                 return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
 2169:             } else {
 2170:                 return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
 2171:             }
 2172:         }
 2173:     }
 2174:     return ($newurl);
 2175: }
 2176: 
 2177: sub dbcopy {
 2178:     my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
 2179:     my ($url,$result,$errtext);
 2180:     if (ref($dbref) eq 'HASH') {
 2181:         $url = $dbref->{'src'};
 2182:         if ($url =~ m{/(smppg|bulletinboard|ext\.tool)$}) {
 2183:             my $prefix = $1;
 2184:             if ($prefix eq 'ext.tool') {
 2185:                 $prefix = 'exttool';
 2186:             }
 2187:             if (($dbref->{'cdom'} =~ /^$match_domain$/) && 
 2188:                 ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
 2189:                 my $db_name;
 2190:                 my $marker = (split(m{/},$url))[4];
 2191:                 $marker=~s/\D//g;
 2192:                 if ($dbref->{'src'} =~ m{/smppg$}) {
 2193:                     $db_name =
 2194:                         &Apache::lonsimplepage::get_db_name($url,$marker,
 2195:                                                             $dbref->{'cdom'},
 2196:                                                             $dbref->{'cnum'});
 2197:                 } elsif ($dbref->{'src'} =~ m{/ext\.tool$}) {
 2198:                     $db_name = 'exttool_'.$marker;
 2199:                 } else {
 2200:                     $db_name = 'bulletinpage_'.$marker;
 2201:                 }
 2202:                 my ($suffix,$freedlock,$error) =
 2203:                     &Apache::lonnet::get_timebased_id($prefix,'num','templated',
 2204:                                                       $coursedom,$coursenum,
 2205:                                                       'concat');
 2206:                 if (!$suffix) {
 2207:                     if ($prefix eq 'smppg') {
 2208:                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
 2209:                     } elsif ($prefix eq 'exttool') {
 2210:                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying an external tool [_1].',$url);
 2211:                     } else {
 2212:                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a discussion board [_1].',$url);
 2213:                     }
 2214:                     if ($error) {
 2215:                         $errtext .= '<br />'.$error;
 2216:                     }
 2217:                 } else {
 2218:                     #need to copy the db contents to a new one.
 2219:                     my %contents=&Apache::lonnet::dump($db_name,
 2220:                                                        $dbref->{'cdom'},
 2221:                                                        $dbref->{'cnum'});
 2222:                     if (exists($contents{'uploaded.photourl'})) {
 2223:                         my $photo = $contents{'uploaded.photourl'};
 2224:                         my ($subdir,$fname) =
 2225:                             ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
 2226:                         my $newphoto;
 2227:                         if ($fname ne '') {
 2228:                             my $content = &Apache::lonnet::getfile($photo);
 2229:                             unless ($content eq '-1') {
 2230:                                 $env{'form.'.$suffix.'.photourl'} = $content;
 2231:                                 $newphoto = 
 2232:                                     &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
 2233:                                 delete($env{'form.'.$suffix.'.photourl'});
 2234:                             }
 2235:                         }
 2236:                         if ($newphoto =~ m{^/uploaded/}) {
 2237:                             $contents{'uploaded.photourl'} = $newphoto;
 2238:                         }
 2239:                     }
 2240:                     $db_name =~ s{_\d*$ }{_$suffix}x;
 2241:                     $result=&Apache::lonnet::put($db_name,\%contents,
 2242:                                                  $coursedom,$coursenum);
 2243:                     if ($result eq 'ok') {
 2244:                         $url =~ s{/(\d*)/(smppg|bulletinboard|ext\.tool)$}{/$suffix/$2}x;
 2245:                     }
 2246:                 }
 2247:                 if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
 2248:                     $lockerrorsref->{$prefix} =
 2249:                         '<div class="LC_error">'.
 2250:                         &mt('There was a problem removing a lockfile.');
 2251:                     if ($prefix eq 'smppg') {
 2252:                         $lockerrorsref->{$prefix} .=
 2253:                             ' '.&mt('This will prevent creation of additional simple pages in this course.');
 2254:                     } elsif ($prefix eq 'exttool') {
 2255:                         $lockerrorsref->{$prefix} .=
 2256:                             ' '.&mt('This will prevent addition of more external tools to this course.');
 2257:                     } else {
 2258:                         $lockerrorsref->{$prefix} .= ' '.&mt('This will prevent creation of additional discussion boards in this course.');
 2259:                     }
 2260:                     $lockerrorsref->{$prefix} .= ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
 2261:                                                      '<a href="/adm/helpdesk" target="_helpdesk">','</a>').
 2262:                                                  '</div>';
 2263:                 }
 2264:             }
 2265:         } elsif ($url =~ m{/syllabus$}) {
 2266:             if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
 2267:                 ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
 2268:                 if (($dbref->{'cdom'} ne $coursedom) ||
 2269:                     ($dbref->{'cnum'} ne $coursenum)) {
 2270:                     my %contents=&Apache::lonnet::dump('syllabus',
 2271:                                                        $dbref->{'cdom'},
 2272:                                                        $dbref->{'cnum'});
 2273:                     $result=&Apache::lonnet::put('syllabus',\%contents,
 2274:                                                  $coursedom,$coursenum);
 2275:                 }
 2276:             }
 2277:         }
 2278:     }
 2279:     return ($url,$result,$errtext);
 2280: }
 2281: 
 2282: sub copy_templated_files {
 2283:     my ($srcurl,$srcdom,$srcnum,$srcmapinfo,$coursedom,$coursenum,$template,$newidx,$newmapname) = @_;
 2284:     my ($srcfolder,$srcid,$srcwaspage) = split(/:/,$srcmapinfo);
 2285:     my $srccontainer = 'sequence';
 2286:     if ($srcwaspage) {
 2287:         $srccontainer = 'page';
 2288:     }
 2289:     my $srcsymb = "uploaded/$srcdom/$srcnum/$srcfolder.$srccontainer".
 2290:                   '___'.$srcid.'___'.&Apache::lonnet::declutter($srcurl);
 2291:     my $srcprefix = $srcdom.'_'.$srcnum.'.'.$srcsymb;
 2292:     my %srcparms=&Apache::lonnet::dump('resourcedata',$srcdom,$srcnum,$srcprefix);
 2293:     my $newsymb = "uploaded/$coursedom/$coursenum/$newmapname".'___'.$newidx.'___lib/templates/'.
 2294:                   $template.'.problem';
 2295:     my $newprefix = $coursedom.'_'.$coursenum.'.'.$newsymb;
 2296:     if ($template eq 'simpleproblem') {
 2297:         $srcprefix .= '.0.';
 2298:         my $weightprefix = $newprefix;
 2299:         $newprefix .= '.0.';
 2300:         my @simpleprobqtypes = qw(radio option string essay numerical);
 2301:         my $qtype=$srcparms{$srcprefix.'questiontype'};
 2302:         if (grep(/^\Q$qtype\E$/,@simpleprobqtypes)) {
 2303:             my %newdata;
 2304:             foreach my $type (@simpleprobqtypes) {
 2305:                 if ($type eq $qtype) {
 2306:                     $newdata{"$weightprefix.$type.weight"}=1;
 2307:                 } else {
 2308:                     $newdata{"$weightprefix.$type.weight"}=0;
 2309:                 }
 2310:             }
 2311:             $newdata{$newprefix.'hiddenparts'} = '!'.$qtype;
 2312:             $newdata{$newprefix.'questiontext'} = $srcparms{$srcprefix.'questiontext'};
 2313:             $newdata{$newprefix.'hinttext'} = $srcparms{$srcprefix.'hinttext'};
 2314:             if ($qtype eq 'numerical') {
 2315:                 $newdata{$newprefix.'numericalscript'} = $srcparms{$srcprefix.'numericalscript'};
 2316:                 $newdata{$newprefix.'numericalanswer'} = $srcparms{$srcprefix.'numericalanswer'};
 2317:                 $newdata{$newprefix.'numericaltolerance'} = $srcparms{$srcprefix.'numericaltolerance'};
 2318:                 $newdata{$newprefix.'numericalsigfigs'} = $srcparms{$srcprefix.'numericalsigfigs'};
 2319:             } elsif (($qtype eq 'option') || ($qtype eq 'radio')) {
 2320:                 my $maxfoils=$srcparms{$srcprefix.'maxfoils'};
 2321:                 unless (defined($maxfoils)) { $maxfoils=10; }
 2322:                     unless ($maxfoils=~/^\d+$/) { $maxfoils=10; }
 2323:                         if ($maxfoils<=0) { $maxfoils=10; }
 2324:                             my $randomize=$srcparms{$srcprefix.'randomize'};
 2325:                             unless (defined($randomize)) { $randomize='yes'; }
 2326:                             unless ($randomize eq 'no') { $randomize='yes'; }
 2327:                             $newdata{$newprefix.'maxfoils'} = $maxfoils;
 2328:                             $newdata{$newprefix.'randomize'} = $randomize;
 2329:                             if ($qtype eq 'option') {
 2330:                                 $newdata{$newprefix.'options'} = $srcparms{$srcprefix.'options'};
 2331:                             }
 2332:                             for (my $i=1; $i<=10; $i++) {
 2333:                                 $newdata{$newprefix.'value'.$i} = $srcparms{$srcprefix.'value'.$i};
 2334:                                 $newdata{$newprefix.'position'.$i} = $srcparms{$srcprefix.'position'.$i};
 2335:                                 $newdata{$newprefix.'text'.$i} = $srcparms{$srcprefix.'text'.$i};
 2336:                             }
 2337: 
 2338:             } elsif (($qtype eq 'option') || ($qtype eq 'radio')) {
 2339:                 my $maxfoils=$srcparms{$srcprefix.'maxfoils'};
 2340:                 unless (defined($maxfoils)) { $maxfoils=10; }
 2341:                 unless ($maxfoils=~/^\d+$/) { $maxfoils=10; }
 2342:                 if ($maxfoils<=0) { $maxfoils=10; }
 2343:                 my $randomize=$srcparms{$srcprefix.'randomize'};
 2344:                 unless (defined($randomize)) { $randomize='yes'; }
 2345:                 unless ($randomize eq 'no') { $randomize='yes'; }
 2346:                 $newdata{$newprefix.'maxfoils'} = $maxfoils;
 2347:                 $newdata{$newprefix.'randomize'} = $randomize;
 2348:                 if ($qtype eq 'option') {
 2349:                     $newdata{$newprefix.'options'} = $srcparms{$srcprefix.'options'};
 2350:                 }
 2351:                 for (my $i=1; $i<=10; $i++) {
 2352:                     $newdata{$newprefix.'value'.$i} = $srcparms{$srcprefix.'value'.$i};
 2353:                     $newdata{$newprefix.'position'.$i} = $srcparms{$srcprefix.'position'.$i};
 2354:                     $newdata{$newprefix.'text'.$i} = $srcparms{$srcprefix.'text'.$i};
 2355:                 }
 2356:             } elsif ($qtype eq 'string') {
 2357:                 $newdata{$newprefix.'stringanswer'} = $srcparms{$srcprefix.'stringanswer'};
 2358:                 $newdata{$newprefix.'stringtype'} = $srcparms{$srcprefix.'stringtype'};
 2359:             }
 2360:             if (keys(%newdata)) {
 2361:                 my $putres = &Apache::lonnet::cput('resourcedata',\%newdata,$coursedom,
 2362:                                                    $coursenum);
 2363:                 if ($putres eq 'ok') {
 2364:                     &Apache::lonnet::devalidatecourseresdata($coursenum,$coursedom);
 2365:                 }
 2366:             }
 2367:         }
 2368:     }
 2369: }
 2370: 
 2371: sub uniqueness_check {
 2372:     my ($newurl) = @_;
 2373:     my $unique = 1;
 2374:     foreach my $res (@LONCAPA::map::order) {
 2375:         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 2376:         $url=&LONCAPA::map::qtescape($url);
 2377:         if ($newurl eq $url) {
 2378:             $unique = 0;
 2379:             last;
 2380:         }
 2381:     }
 2382:     return $unique;
 2383: }
 2384: 
 2385: sub contained_map_check {
 2386:     my ($url,$folder,$coursenum,$coursedom,$removefrommap,$removeparam,$addedmaps,
 2387:         $hierarchy,$titles,$allmaps) = @_;
 2388:     my $content = &Apache::lonnet::getfile($url);
 2389:     unless ($content eq '-1') {
 2390:         my $parser = HTML::TokeParser->new(\$content);
 2391:         $parser->attr_encoded(1);
 2392:         while (my $token = $parser->get_token) {
 2393:             next if ($token->[0] ne 'S');
 2394:             if ($token->[1] eq 'resource') {
 2395:                 next if ($token->[2]->{'type'} eq 'zombie');
 2396:                 my $ressrc = $token->[2]->{'src'};
 2397:                 if ($ressrc =~ m{^/adm/($match_domain)/$match_courseid/\d+/ext\.tool$}) {
 2398:                     my $srcdom = $1;
 2399:                     unless ($srcdom eq $coursedom) {
 2400:                         $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 2401:                         next;
 2402:                     }
 2403:                 } elsif ($folder =~ /^supplemental/) {
 2404:                     unless (&supp_pasteable($ressrc)) {
 2405:                         $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 2406:                         next;
 2407:                     }
 2408:                 }
 2409:                 if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
 2410:                     if ($1 eq 'uploaded') {
 2411:                         $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
 2412:                         $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
 2413:                     } else {
 2414:                         if ($allmaps->{$ressrc}) {
 2415:                             $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 2416:                         } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
 2417:                             $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 2418:                         } else {
 2419:                             $addedmaps->{$ressrc} = [$url];
 2420:                         }
 2421:                     }
 2422:                     &contained_map_check($ressrc,$folder,$coursenum,$coursedom,$removefrommap,
 2423:                                          $removeparam,$addedmaps,$hierarchy,$titles,$allmaps);
 2424:                 }
 2425:             } elsif ($token->[1] eq 'param') {
 2426:                 if ($folder =~ /^supplemental/) {
 2427:                     if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
 2428:                         push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
 2429:                     } else {
 2430:                         $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
 2431:                     }
 2432:                 }
 2433:             }
 2434:         }
 2435:     }
 2436:     return;
 2437: }
 2438: 
 2439: sub url_paste_fixups {
 2440:     my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
 2441:         $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
 2442:         $mapchanges,$tomove,$newsubdir,$newurls,$resdatacopy) = @_;
 2443:     my $checktitle;
 2444:     if (($prefixchg) &&
 2445:         ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
 2446:         $checktitle = 1;
 2447:     }
 2448:     my $skip;
 2449:     if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
 2450:         my $mapid = $1.$2;
 2451:         if ($tomove->{$mapid}) {
 2452:             $skip = 1;
 2453:         }
 2454:     }
 2455:     my $file = &Apache::lonnet::getfile($oldurl);
 2456:     return if ($file eq '-1');
 2457:     my $parser = HTML::TokeParser->new(\$file);
 2458:     $parser->attr_encoded(1);
 2459:     my $changed = 0;
 2460:     while (my $token = $parser->get_token) {
 2461:         next if ($token->[0] ne 'S');
 2462:         if ($token->[1] eq 'resource') {
 2463:             my $ressrc = $token->[2]->{'src'};
 2464:             next if ($ressrc eq '');
 2465:             my $id = $token->[2]->{'id'};
 2466:             my $title = $token->[2]->{'title'};
 2467:             if ($checktitle) {
 2468:                 if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
 2469:                     $retitles->{$oldurl}{$id} = $ressrc;
 2470:                 }
 2471:             }
 2472:             next if ($token->[2]->{'type'} eq 'external');
 2473:             if ($token->[2]->{'type'} eq 'zombie') {
 2474:                 next if ($skip);  
 2475:                 $zombies->{$oldurl}{$id} = $ressrc;
 2476:                 $changed = 1;
 2477:             } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
 2478:                 my $srcdom = $1;
 2479:                 my $srcnum = $2;
 2480:                 my $rem = $3;
 2481:                 my $newurl;
 2482:                 my $mapname;
 2483:                 if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
 2484:                     my $prefix = $1;
 2485:                     $mapname = $prefix.$2;
 2486:                     if ($tomove->{$mapname}) {
 2487:                         &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
 2488:                                           $srcdom,$srcnum,$allmaps,$rewrites,
 2489:                                           $retitles,$copies,$dbcopies,$zombies,
 2490:                                           $params,$mapmoves,$mapchanges,$tomove,
 2491:                                           $newsubdir,$newurls,$resdatacopy);
 2492:                         next;
 2493:                     } else {
 2494:                         ($newurl,my $error) =
 2495:                             &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
 2496:                                             $srcdom,$srcnum,\$title,$allmaps,$newurls);
 2497:                         if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
 2498:                             $newsubdir->{$ressrc} = $1;
 2499:                         }
 2500:                         if ($error) {
 2501:                             next;
 2502:                         }
 2503:                     }
 2504:                 }
 2505:                 if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
 2506:                     ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
 2507:                    
 2508:                     if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
 2509:                         $rewrites->{$oldurl}{$id} = $ressrc;
 2510:                         $mapchanges->{$ressrc} = 1;
 2511:                         unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
 2512:                                                   $cnum,$srcdom,$srcnum,$allmaps,
 2513:                                                   $rewrites,$retitles,$copies,$dbcopies,
 2514:                                                   $zombies,$params,$mapmoves,$mapchanges,
 2515:                                                   $tomove,$newsubdir,$newurls,$resdatacopy)) {
 2516:                             $mapmoves->{$ressrc} = 1;
 2517:                         }
 2518:                         $changed = 1;
 2519:                     } else {
 2520:                         $rewrites->{$oldurl}{$id} = $ressrc;
 2521:                         $copies->{$oldurl}{$ressrc} = $id;
 2522:                         $changed = 1;
 2523:                     }
 2524:                 }
 2525:             } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
 2526:                 next if ($skip);
 2527:                 my $srcdom = $1;
 2528:                 my $srcnum = $2;
 2529:                 if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
 2530:                     $rewrites->{$oldurl}{$id} = $ressrc;
 2531:                     $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
 2532:                     $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
 2533:                     $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
 2534:                     $changed = 1;
 2535:                 }
 2536:             } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
 2537:                 if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
 2538:                     ($env{'form.docs.markedcopy_options'} ne 'move')) {
 2539:                     $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
 2540:                     $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
 2541:                     $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
 2542:                     $changed = 1;
 2543:                 }
 2544:             } elsif ($ressrc eq '/res/lib/templates/simpleproblem.problem') {
 2545:                 if (($fromcdom ne $cdom) || ($fromcnum ne $cnum)) {
 2546:                     $resdatacopy->{$oldurl}{$id}{'src'} = $ressrc;
 2547:                     $resdatacopy->{$oldurl}{$id}{'cdom'} = $fromcdom;
 2548:                     $resdatacopy->{$oldurl}{$id}{'cnum'} = $fromcnum;
 2549:                 }
 2550:             } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
 2551:                 next if ($skip);
 2552:                 my $srcdom = $1;
 2553:                 my $srcnum = $2;
 2554:                 if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
 2555:                     $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
 2556:                     $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
 2557:                     $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
 2558:                     $changed = 1;
 2559:                 }
 2560:             }
 2561:         } elsif ($token->[1] eq 'param') {
 2562:             next if ($skip);
 2563:             my $to = $token->[2]->{'to'}; 
 2564:             if ($to ne '') {
 2565:                 if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
 2566:                     push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
 2567:                 } else {
 2568:                     @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
 2569:                 }
 2570:             }
 2571:         }
 2572:     }
 2573:     return $changed;
 2574: }
 2575: 
 2576: sub apply_fixups {
 2577:     my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
 2578:         $oldurl,$url,$caller) = @_;
 2579:     my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
 2580:         %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
 2581:         %resdatacopy,%lockerrors,$lockmsg);
 2582:     if (ref($updated) eq 'HASH') {
 2583:         if (ref($updated->{'rewrites'}) eq 'HASH') {
 2584:             %rewrites = %{$updated->{'rewrites'}};
 2585:         }
 2586:         if (ref($updated->{'zombies'}) eq 'HASH') {
 2587:             %zombies = %{$updated->{'zombies'}};
 2588:         }
 2589:         if (ref($updated->{'removefrommap'}) eq 'HASH') {
 2590:             %removefrommap = %{$updated->{'removefrommap'}};
 2591:         }
 2592:         if (ref($updated->{'removeparam'}) eq 'HASH') {
 2593:             %removeparam = %{$updated->{'removeparam'}};
 2594:         }
 2595:         if (ref($updated->{'dbcopies'}) eq 'HASH') {
 2596:             %dbcopies = %{$updated->{'dbcopies'}};
 2597:         }
 2598:         if (ref($updated->{'retitles'}) eq 'HASH') {
 2599:             %retitles = %{$updated->{'retitles'}};
 2600:         }
 2601:         if (ref($updated->{'resdatacopy'}) eq 'HASH') {
 2602:             %resdatacopy = %{$updated->{'resdatacopy'}};
 2603:         }
 2604:     }
 2605:     if (ref($info) eq 'HASH') {
 2606:         if (ref($info->{'newsubdir'}) eq 'HASH') {
 2607:             %newsubdir = %{$info->{'newsubdir'}};
 2608:         }
 2609:         if (ref($info->{'params'}) eq 'HASH') {
 2610:             %params = %{$info->{'params'}};
 2611:         }
 2612:         if (ref($info->{'before'}) eq 'HASH') {
 2613:             %before = %{$info->{'before'}};
 2614:         }
 2615:         if (ref($info->{'after'}) eq 'HASH') {
 2616:             %after = %{$info->{'after'}};
 2617:         }
 2618:     }
 2619:     if (ref($moves) eq 'HASH') {
 2620:         if (ref($moves->{'copies'}) eq 'HASH') {
 2621:             %copies = %{$moves->{'copies'}};
 2622:         }
 2623:         if (ref($moves->{'docmoves'}) eq 'HASH') {
 2624:             %docmoves = %{$moves->{'docmoves'}};
 2625:         }
 2626:         if (ref($moves->{'mapmoves'}) eq 'HASH') {
 2627:             %mapmoves = %{$moves->{'mapmoves'}};
 2628:         }
 2629:     }
 2630:     foreach my $key (keys(%copies),keys(%docmoves)) {
 2631:         my @allcopies;
 2632:         if (exists($copies{$key})) {
 2633:             if (ref($copies{$key}) eq 'HASH') {
 2634:                 my %added;
 2635:                 foreach my $innerkey (keys(%{$copies{$key}})) {
 2636:                     if (($innerkey ne '') && (!$added{$innerkey})) {
 2637:                         push(@allcopies,$innerkey);
 2638:                         $added{$innerkey} = 1;
 2639:                     }
 2640:                 }
 2641:                 undef(%added);
 2642:             }
 2643:         }
 2644:         if ($key eq $oldurl) {
 2645:             if ((exists($docmoves{$key}))) {
 2646:                 unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
 2647:                     push(@allcopies,$oldurl);
 2648:                 }
 2649:             }
 2650:         }
 2651:         if (@allcopies > 0) {
 2652:             foreach my $item (@allcopies) {
 2653:                 my ($relpath,$oldsubdir,$fname) = 
 2654:                     ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
 2655:                 if ($fname ne '') {
 2656:                     my $content = &Apache::lonnet::getfile($item);
 2657:                     unless ($content eq '-1') {
 2658:                         my $storefn;
 2659:                         if (($key eq $oldurl) && (exists($docmoves{$key}))) {
 2660:                             $storefn = $docmoves{$key};
 2661:                         } else {
 2662:                             $storefn = $relpath;
 2663:                             $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
 2664:                             if ($prefixchg && $before{'doc'} && $after{'doc'}) {
 2665:                                 $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
 2666:                             }
 2667:                             if ($newsubdir{$key}) {
 2668:                                 $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
 2669:                             }
 2670:                         }
 2671:                         &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
 2672:                         my $copyurl = 
 2673:                             &Apache::lonclonecourse::writefile($env{'request.course.id'},
 2674:                                                                $storefn.$fname,$content);
 2675:                         if ($copyurl eq '/adm/notfound.html') {
 2676:                             if (exists($docmoves{$oldurl})) {
 2677:                                 return &mt('Paste failed: an error occurred copying the file.');
 2678:                             } elsif (ref($errors) eq 'HASH') {
 2679:                                 $errors->{$item} = 1;
 2680:                             }
 2681:                         }
 2682:                     }
 2683:                 }
 2684:             }
 2685:         }
 2686:     }
 2687:     foreach my $key (keys(%mapmoves)) {
 2688:         my $storefn=$key;
 2689:         $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 2690:         if ($prefixchg && $before{'map'} && $after{'map'}) {
 2691:             $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
 2692:         }
 2693:         if ($newsubdir{$key}) {
 2694:             $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
 2695:         }
 2696:         my $mapcontent = &Apache::lonnet::getfile($key);
 2697:         if ($mapcontent eq '-1') {
 2698:             if (ref($errors) eq 'HASH') {
 2699:                 $errors->{$key} = 1;
 2700:             }
 2701:         } else {
 2702:             my $newmap =
 2703:                 &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
 2704:                                                    $mapcontent);
 2705:             if ($newmap eq '/adm/notfound.html') {
 2706:                 if (ref($errors) eq 'HASH') {
 2707:                     $errors->{$key} = 1;
 2708:                 }
 2709:             }
 2710:         }
 2711:     }
 2712:     my %updates;
 2713:     if ($is_map) {
 2714:         if (ref($updated) eq 'HASH') {
 2715:             foreach my $type (keys(%{$updated})) {
 2716:                 if (ref($updated->{$type}) eq 'HASH') {
 2717:                     foreach my $key (keys(%{$updated->{$type}})) {
 2718:                         $updates{$key} = 1;
 2719:                     }
 2720:                 }
 2721:             }
 2722:         }
 2723:         foreach my $key (keys(%updates)) {
 2724:             my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
 2725:             if (ref($rewrites{$key}) eq 'HASH') {
 2726:                 %torewrite = %{$rewrites{$key}};
 2727:             }
 2728:             if (ref($retitles{$key}) eq 'HASH') {
 2729:                 %toretitle = %{$retitles{$key}};
 2730:             }
 2731:             if (ref($removefrommap{$key}) eq 'HASH') {
 2732:                 %toremove = %{$removefrommap{$key}};
 2733:             }
 2734:             if (ref($removeparam{$key}) eq 'HASH') {
 2735:                 %remparam = %{$removeparam{$key}};
 2736:             }
 2737:             if (ref($zombies{$key}) eq 'HASH') {
 2738:                 %zombie = %{$zombies{$key}};
 2739:             }
 2740:             if (ref($dbcopies{$key}) eq 'HASH') {
 2741:                 foreach my $idx (keys(%{$dbcopies{$key}})) {
 2742:                     if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
 2743:                         my ($newurl,$result,$errtext) =
 2744:                             &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
 2745:                         if ($result eq 'ok') {
 2746:                             $newdb{$idx} = $newurl;
 2747:                         } elsif (ref($errors) eq 'HASH') {
 2748:                             $errors->{$key} = 1;
 2749:                         }
 2750:                         push(@msgs,$errtext);
 2751:                     }
 2752:                 }
 2753:             }
 2754:             if (ref($resdatacopy{$key}) eq 'HASH') {
 2755:                 if ($newsubdir{$key}) {
 2756: 
 2757:                 }
 2758:                 foreach my $idx (keys(%{$resdatacopy{$key}})) {
 2759:                     if (ref($resdatacopy{$key}{$idx}) eq 'HASH') {
 2760:                         my $srcurl = $resdatacopy{$key}{$idx}{'src'};
 2761:                         if ($srcurl =~ m{^/res/lib/templates/(\w+)\.problem$}) {
 2762:                             my $template = $1;
 2763:                             if (($resdatacopy{$key}{$idx}{'cdom'} =~ /^$match_domain$/) &&
 2764:                                 ($resdatacopy{$key}{$idx}{'cnum'} =~ /^$match_courseid$/)) {
 2765:                                 my $srcdom = $resdatacopy{$key}{$idx}{'cdom'};
 2766:                                 my $srcnum = $resdatacopy{$key}{$idx}{'cnum'};
 2767:                                 my ($newmapname) = ($key =~ m{/([^/]+)$});
 2768:                                 my ($srcfolder,$srccontainer) = split(/\./,$newmapname);
 2769:                                 my $srcmapinfo = $srcfolder.':'.$idx;
 2770:                                 if ($srccontainer eq 'page') {
 2771:                                     $srcmapinfo .= ':1';
 2772:                                 }
 2773:                                 if ($newsubdir{$key}) {
 2774:                                     $newmapname =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
 2775:                                 }
 2776:                                 &copy_templated_files($srcurl,$srcdom,$srcnum,$srcmapinfo,$cdom,
 2777:                                                       $cnum,$template,$idx,$newmapname);
 2778:                             }
 2779:                         }
 2780:                     }
 2781:                 }
 2782:             }
 2783:             if (ref($params{$key}) eq 'HASH') {
 2784:                 %currparam = %{$params{$key}};
 2785:             }
 2786:             my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
 2787:             if ($fatal) {
 2788:                 return ($errtext);
 2789:             }
 2790:             for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
 2791:                 if (defined($LONCAPA::map::zombies[$i])) {
 2792:                     my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
 2793:                     if ($zombie{$i} eq $src) {
 2794:                         undef($LONCAPA::map::zombies[$i]);
 2795:                     }
 2796:                 }
 2797:             }
 2798:             for (my $i=0; $i<@LONCAPA::map::order; $i++) {
 2799:                 my $idx = $LONCAPA::map::order[$i];
 2800:                 if (defined($LONCAPA::map::resources[$idx])) {
 2801:                     my $changed;
 2802:                     my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
 2803:                     if ((exists($toremove{$idx})) && 
 2804:                         ($toremove{$idx} eq &LONCAPA::map::qtescape($src))) {
 2805:                         splice(@LONCAPA::map::order,$i,1);
 2806:                         if (ref($currparam{$idx}) eq 'ARRAY') {
 2807:                             foreach my $name (@{$currparam{$idx}}) {
 2808:                                 &LONCAPA::map::delparameter($idx,'parameter_'.$name);
 2809:                             }
 2810:                         }
 2811:                         next;
 2812:                     }
 2813:                     my $origsrc = $src;
 2814:                     if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
 2815:                         if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
 2816:                             $changed = 1;
 2817:                         }
 2818:                     }
 2819:                     if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
 2820:                         $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
 2821:                         if ($origsrc =~ m{^/uploaded/}) {
 2822:                             if ($prefixchg && $before{'map'} && $after{'map'}) {
 2823:                                 if ($src =~ /\.(page|sequence)$/) {
 2824:                                     $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
 2825:                                 } else {
 2826:                                     $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
 2827:                                 }
 2828:                             }
 2829:                             if ($origsrc =~ /\.(page|sequence)$/) {
 2830:                                 if ($newsubdir{$origsrc}) {
 2831:                                     $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
 2832:                                 }
 2833:                             } elsif ($newsubdir{$key}) {
 2834:                                 $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
 2835:                             }
 2836:                         }
 2837:                         $changed = 1;
 2838:                     } elsif ($newdb{$idx} ne '') {
 2839:                         $src = $newdb{$idx};
 2840:                         $changed = 1;
 2841:                     }
 2842:                     if ($changed) {
 2843:                         $LONCAPA::map::resources[$idx] = join(':',($title,&LONCAPA::map::qtunescape($src),$ext,$type));
 2844:                     }
 2845:                 }
 2846:             }
 2847:             foreach my $idx (keys(%remparam)) {
 2848:                 if (ref($remparam{$idx}) eq 'ARRAY') {
 2849:                     foreach my $name (@{$remparam{$idx}}) {   
 2850:                         &LONCAPA::map::delparameter($idx,'parameter_'.$name);
 2851:                     }
 2852:                 }
 2853:             }
 2854:             if (values(%lockerrors) > 0) {
 2855:                 $lockmsg = join('<br />',values(%lockerrors));
 2856:             }
 2857:             my $storefn;
 2858:             if ($key eq $oldurl) {
 2859:                 $storefn = $url;
 2860:                 $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 2861:             } else {
 2862:                 $storefn = $key;
 2863:                 $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 2864:                 if ($prefixchg && $before{'map'} && $after{'map'}) {
 2865:                     $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
 2866:                 }
 2867:                 if ($newsubdir{$key}) {
 2868:                     $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
 2869:                 }
 2870:             }
 2871:             my $report;
 2872:             if ($folder !~ /^supplemental/) {
 2873:                 $report = 1;
 2874:             }
 2875:             (my $outtext,$errtext) =
 2876:                 &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
 2877:             if ($errtext) {
 2878:                 if ($caller eq 'paste') {
 2879:                     return (&mt('Paste failed: an error occurred saving the folder or page.'));
 2880:                 }
 2881:             }
 2882:         }
 2883:     }
 2884:     return ('ok',\@msgs,$lockmsg);
 2885: }
 2886: 
 2887: sub copy_dependencies {
 2888:     my ($item,$storefn,$relpath,$errors,$contentref) = @_;
 2889:     my $content;
 2890:     if (ref($contentref)) {
 2891:         $content = $$contentref;
 2892:     } else {
 2893:         $content = &Apache::lonnet::getfile($item);
 2894:     }
 2895:     unless ($content eq '-1') {
 2896:         my $mm = new File::MMagic;
 2897:         my $mimetype = $mm->checktype_contents($content);
 2898:         if ($mimetype eq 'text/html') {
 2899:             my (%allfiles,%codebase,$state);
 2900:             my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
 2901:             if ($res eq 'ok') {
 2902:                 my ($numexisting,$numpathchanges,$existing);
 2903:                 (undef,$numexisting,$numpathchanges,$existing) =
 2904:                     &Apache::loncommon::ask_for_embedded_content(
 2905:                         '/adm/coursedocs',$state,\%allfiles,\%codebase,
 2906:                         {'error_on_invalid_names'   => 1,
 2907:                          'ignore_remote_references' => 1,
 2908:                          'docs_url'                 => $item,
 2909:                          'context'                  => 'paste'});
 2910:                 if ($numexisting > 0) {
 2911:                     if (ref($existing) eq 'HASH') {
 2912:                         foreach my $dep (keys(%{$existing})) {
 2913:                             my $depfile = $dep;
 2914:                             unless ($depfile =~ m{^\Q$relpath\E}) {
 2915:                                 $depfile = $relpath.$dep;
 2916:                             }
 2917:                             my $depcontent = &Apache::lonnet::getfile($depfile);
 2918:                             unless ($depcontent eq '-1') {
 2919:                                 my $storedep = $dep;
 2920:                                 $storedep =~ s{^\Q$relpath\E}{};
 2921:                                 my $dep_url =
 2922:                                     &Apache::lonclonecourse::writefile(
 2923:                                         $env{'request.course.id'},
 2924:                                         $storefn.$storedep,$depcontent);
 2925:                                 if ($dep_url eq '/adm/notfound.html') {
 2926:                                     if (ref($errors) eq 'HASH') {
 2927:                                         $errors->{$depfile} = 1;
 2928:                                     }
 2929:                                 } else {
 2930:                                     &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
 2931:                                 }
 2932:                             }
 2933:                         }
 2934:                     }
 2935:                 }
 2936:             }
 2937:         }
 2938:     }
 2939:     return;
 2940: }
 2941: 
 2942: my %parameter_type = ( 'randompick'     => 'int_pos',
 2943: 		       'hiddenresource' => 'string_yesno',
 2944: 		       'encrypturl'     => 'string_yesno',
 2945: 		       'randomorder'    => 'string_yesno',);
 2946: my $valid_parameters_re = join('|',keys(%parameter_type));
 2947: # set parameters
 2948: sub update_parameter {
 2949:     if ($env{'form.changeparms'} eq 'all') {
 2950:         my (@allidx,@allmapidx,%allchecked,%currchecked);
 2951:         %allchecked = (
 2952:                          'hiddenresource' => {},
 2953:                          'encrypturl'     => {},
 2954:                          'randompick'     => {},
 2955:                          'randomorder'    => {},
 2956:                       );
 2957:         foreach my $which (keys(%allchecked)) {
 2958:             $env{'form.all'.$which} =~ s/,$//;
 2959:             if ($which eq 'randompick') {
 2960:                 foreach my $item (split(/,/,$env{'form.all'.$which})) {
 2961:                     my ($res,$value) = split(/:/,$item);
 2962:                     if ($value =~ /^\d+$/) {
 2963:                         $allchecked{$which}{$res} = $value;
 2964:                     }
 2965:                 }
 2966:             } else {
 2967:                 if ($env{'form.all'.$which}) {
 2968:                     map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.all'.$which});
 2969:                 }
 2970:             }
 2971:         }
 2972:         my $haschanges = 0;
 2973:         foreach my $res (@LONCAPA::map::order) {
 2974:             my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 2975:             $name=&LONCAPA::map::qtescape($name);
 2976:             $url=&LONCAPA::map::qtescape($url);
 2977:             next unless ($name && $url);
 2978:             my $is_map;
 2979:             if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
 2980:                 $is_map = 1;
 2981:             }
 2982:             foreach my $which (keys(%allchecked)) {
 2983:                 if (($which eq 'randompick' || $which eq 'randomorder')) {
 2984:                     next if (!$is_map);
 2985:                 } 
 2986:                 my $oldvalue = 0;
 2987:                 my $newvalue = 0;
 2988:                 if ($allchecked{$which}{$res}) {
 2989:                     $newvalue = $allchecked{$which}{$res};
 2990:                 }
 2991:                 my $current = (&LONCAPA::map::getparameter($res,'parameter_'.$which))[0];
 2992:                 if ($which eq 'randompick') {
 2993:                     if ($current =~ /^(\d+)$/) {
 2994:                         $oldvalue = $1;
 2995:                     }
 2996:                 } else {
 2997:                     if ($current =~ /^yes$/i) {
 2998:                         $oldvalue = 1;
 2999:                     }
 3000:                 }
 3001:                 if ($oldvalue ne $newvalue) {
 3002:                     $haschanges = 1;
 3003:                     if ($newvalue) {
 3004:                         my $storeval = 'yes';
 3005:                         if ($which eq 'randompick') {
 3006:                             $storeval = $newvalue;
 3007:                         }
 3008:                         &LONCAPA::map::storeparameter($res,'parameter_'.$which,
 3009:                                                       $storeval,
 3010:                                                       $parameter_type{$which});
 3011:                         &remember_parms($res,$which,'set',$storeval);
 3012:                     } elsif ($oldvalue) {
 3013:                         &LONCAPA::map::delparameter($res,'parameter_'.$which);
 3014:                         &remember_parms($res,$which,'del');
 3015:                     }
 3016:                 }
 3017:             }
 3018:         }
 3019:         return $haschanges;
 3020:     } else {
 3021:         my $haschanges = 0;
 3022:         return $haschanges if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
 3023: 
 3024:         my $which = $env{'form.changeparms'};
 3025:         my $idx = $env{'form.setparms'};
 3026:         my $oldvalue = 0;
 3027:         my $newvalue = 0;
 3028:         my $current = (&LONCAPA::map::getparameter($idx,'parameter_'.$which))[0];
 3029:         if ($which eq 'randompick') {
 3030:             if ($current =~ /^(\d+)$/) {
 3031:                 $oldvalue = $1;
 3032:             }
 3033:         } elsif ($current =~ /^yes$/i) {
 3034:             $oldvalue = 1;
 3035:         }
 3036:         if ($env{'form.'.$which.'_'.$idx}) {
 3037: 	    $newvalue = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
 3038: 	                                         : 1;
 3039:         }
 3040:         if ($oldvalue ne $newvalue) {
 3041:             $haschanges = 1;
 3042:             if ($newvalue) {
 3043:                 my $storeval = 'yes';
 3044:                 if ($which eq 'randompick') {
 3045:                     $storeval = $newvalue;
 3046:                 }
 3047: 	        &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $storeval,
 3048: 				              $parameter_type{$which});
 3049: 	        &remember_parms($idx,$which,'set',$storeval);
 3050:             } else {
 3051: 	        &LONCAPA::map::delparameter($idx,'parameter_'.$which);
 3052: 	        &remember_parms($idx,$which,'del');
 3053:             }
 3054:         }
 3055:         return $haschanges;
 3056:     }
 3057: }
 3058: 
 3059: sub handle_edit_cmd {
 3060:     my ($coursenum,$coursedom) =@_;
 3061:     my $haschanges = 0;
 3062:     if ($env{'form.cmd'} eq '') {
 3063:         return $haschanges; 
 3064:     }
 3065:     my ($cmd,$idx)=split('_',$env{'form.cmd'});
 3066: 
 3067:     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
 3068:     my ($title, $url, @rrest) = split(':', $ratstr);
 3069: 
 3070:     if ($cmd eq 'remove') {
 3071: 	if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 3072: 	    ($url!~/$LONCAPA::assess_page_seq_re/)) {
 3073: 	    &Apache::lonnet::removeuploadedurl($url);
 3074: 	} else {
 3075: 	    &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 3076: 	}
 3077: 	splice(@LONCAPA::map::order, $idx, 1);
 3078:         $haschanges = 1;
 3079:     } elsif ($cmd eq 'cut') {
 3080: 	&LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 3081: 	splice(@LONCAPA::map::order, $idx, 1);
 3082:         $haschanges = 1;
 3083:     } elsif ($cmd eq 'up'
 3084: 	     && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
 3085: 	@LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
 3086:         $haschanges = 1;
 3087:     } elsif ($cmd eq 'down'
 3088: 	     && defined($LONCAPA::map::order[$idx+1])) {
 3089: 	@LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
 3090:         $haschanges = 1;
 3091:     } elsif ($cmd eq 'rename') {
 3092: 	my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
 3093: 	if ($comment=~/\S/) {
 3094: 	    $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
 3095: 		$comment.':'.join(':', $url, @rrest);
 3096: 	}
 3097: # Devalidate title cache
 3098: 	my $renamed_url=&LONCAPA::map::qtescape($url);
 3099: 	&Apache::lonnet::devalidate_title_cache($renamed_url);
 3100:         $haschanges = 1;
 3101:     } elsif ($cmd eq 'setalias') {
 3102:         my $newvalue = $env{'form.alias'};
 3103:         if ($newvalue ne '') {
 3104:             unless (Apache::lonnet::get_symb_from_alias($newvalue)) {
 3105:                 &LONCAPA::map::storeparameter($idx,'parameter_0_mapalias',$newvalue,
 3106:                                               'string');
 3107:                 &remember_parms($idx,'mapalias','set',$newvalue);
 3108:                 $haschanges = 1;
 3109:             }
 3110:         }
 3111:     } elsif ($cmd eq 'delalias') {
 3112:         my $current = (&LONCAPA::map::getparameter($idx,'parameter_0_mapalias'))[0];  
 3113:         if ($current ne '') {
 3114:             &LONCAPA::map::delparameter($idx,'parameter_0_mapalias');
 3115:             &remember_parms($idx,'mapalias','del');
 3116:             $haschanges = 1;
 3117:         }
 3118:     }
 3119:     return $haschanges;
 3120: }
 3121: 
 3122: sub editor {
 3123:     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 3124:         $supplementalflag,$orderhash,$iconpath,$pathitem,$ltitoolsref,
 3125:         $canedit,$hostname,$navmapref,$hiddentop)=@_;
 3126:     my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
 3127:     if ($allowed) {
 3128:         (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
 3129:          $is_random_order,$container) =
 3130:             &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 3131:         $r->print($breadcrumbtrail);
 3132:     } elsif ($env{'form.folderpath'} =~ /\:1$/) {
 3133:         $container = 'page'; 
 3134:     } else {
 3135:         $container = 'sequence';
 3136:     }
 3137: 
 3138:     my $jumpto;
 3139: 
 3140:     unless ($supplementalflag) {
 3141:         $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
 3142:     }
 3143: 
 3144:     unless ($allowed) {
 3145:         $randompick = -1;
 3146:     }
 3147: 
 3148:     my ($errtext,$fatal);
 3149:     if (($folder eq '') && (!$supplementalflag)) {
 3150:         if (@LONCAPA::map::order) {
 3151:             undef(@LONCAPA::map::order);
 3152:             undef(@LONCAPA::map::resources);
 3153:             undef(@LONCAPA::map::resparms);
 3154:             undef(@LONCAPA::map::zombies);
 3155:         }
 3156:         $folder = 'default';
 3157:         $container = 'sequence'; 
 3158:     } else {
 3159:         ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 3160: 				     $folder.'.'.$container);
 3161:         return $errtext if ($fatal);
 3162:     }
 3163: 
 3164:     if ($#LONCAPA::map::order<1) {
 3165: 	my $idx=&LONCAPA::map::getresidx();
 3166: 	if ($idx<=0) { $idx=1; }
 3167:        	$LONCAPA::map::order[0]=$idx;
 3168:         $LONCAPA::map::resources[$idx]='';
 3169:     }
 3170: 
 3171: # ------------------------------------------------------------ Process commands
 3172: 
 3173: # ---------------- if they are for this folder and user allowed to make changes
 3174:     if (($allowed && $canedit) && ($env{'form.folder'} eq $folder)) {
 3175: # set parameters and change order
 3176: 	&snapshotbefore();
 3177: 
 3178: 	if (&update_parameter()) {
 3179: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 3180: 	    return $errtext if ($fatal);
 3181: 	}
 3182: 
 3183: 	if ($env{'form.newpos'} && $env{'form.currentpos'}) {
 3184: # change order
 3185: 	    my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
 3186: 	    splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
 3187: 
 3188: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 3189: 	    return $errtext if ($fatal);
 3190: 	}
 3191: 
 3192: 	if ($env{'form.pastemarked'}) {
 3193:             my %paste_errors;
 3194:             my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
 3195:                 &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
 3196:                                       \%paste_errors);
 3197:             if (ref($pastemsgarray) eq 'ARRAY') {
 3198:                 if (@{$pastemsgarray} > 0) {
 3199:                     $r->print('<p class="LC_info">'.
 3200:                               join('<br />',@{$pastemsgarray}).
 3201:                               '</p>');
 3202:                 }
 3203:             }
 3204:             if ($lockerror) {
 3205:                 $r->print('<p class="LC_error">'.
 3206:                           $lockerror.
 3207:                           '</p>');
 3208:             }
 3209:             if ($save_error ne '') {
 3210:                 return $save_error; 
 3211:             }
 3212:             if ($paste_res) {
 3213:                 my %errortext = &Apache::lonlocal::texthash (
 3214:                                     fail      => 'Storage of folder contents failed',
 3215:                                     failread  => 'Reading folder contents failed',
 3216:                                     failstore => 'Storage of folder contents failed',
 3217:                                 );
 3218:                 if ($errortext{$paste_res}) {
 3219:                     $r->print('<p class="LC_error">'.$errortext{$paste_res}.'</p>');
 3220:                 }
 3221:             }
 3222:             if (keys(%paste_errors) > 0) {
 3223:                 $r->print('<p class="LC_warning">'."\n".
 3224:                           &mt('The following files are either dependencies of a web page or references within a folder and/or composite page which could not be copied during the paste operation:')."\n".
 3225:                           '<ul>'."\n");
 3226:                 foreach my $key (sort(keys(%paste_errors))) {
 3227:                     $r->print('<li>'.$key.'</li>'."\n");
 3228:                 }
 3229:                 $r->print('</ul></p>'."\n");
 3230:             }
 3231: 	} elsif ($env{'form.clearmarked'}) {
 3232:             my $output = &do_buffer_empty();
 3233:             if ($output) {
 3234:                 $r->print('<p class="LC_info">'.$output.'</p>');
 3235:             }
 3236:         }
 3237: 
 3238: 	$r->print($upload_output);
 3239: 
 3240: # Rename, cut, copy or remove a single resource
 3241: 	if (&handle_edit_cmd($coursenum,$coursedom)) {
 3242:             my $contentchg;
 3243:             if ($env{'form.cmd'} =~ m{^(remove|cut|setalias|delalias)_}) {
 3244:                 $contentchg = 1;
 3245:             }
 3246: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
 3247: 	    return $errtext if ($fatal);
 3248: 	}
 3249: 
 3250: # Cut, copy and/or remove multiple resources
 3251:         if ($env{'form.multichange'}) {
 3252:             my %allchecked = (
 3253:                                cut     => {},
 3254:                                remove  => {},
 3255:                              );
 3256:             my $needsupdate;
 3257:             foreach my $which (keys(%allchecked)) {
 3258:                 $env{'form.multi'.$which} =~ s/,$//;
 3259:                 if ($env{'form.multi'.$which}) {
 3260:                     map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.multi'.$which});
 3261:                     if (ref($allchecked{$which}) eq 'HASH') {
 3262:                         $needsupdate += scalar(keys(%{$allchecked{$which}}));
 3263:                     }
 3264:                 }
 3265:             }
 3266:             if ($needsupdate) {
 3267:                 my $haschanges = 0;
 3268:                 my %curr_groups = &Apache::longroup::coursegroups();
 3269:                 my $total = scalar(@LONCAPA::map::order) - 1; 
 3270:                 for (my $i=$total; $i>=0; $i--) {
 3271:                     my $res = $LONCAPA::map::order[$i];
 3272:                     my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 3273:                     $name=&LONCAPA::map::qtescape($name);
 3274:                     $url=&LONCAPA::map::qtescape($url);
 3275:                     next unless $url;
 3276:                     my %denied =
 3277:                         &action_restrictions($coursenum,$coursedom,$url,
 3278:                                              $env{'form.folderpath'},\%curr_groups);
 3279:                     foreach my $which (keys(%allchecked)) {
 3280:                         next if ($denied{$which});
 3281:                         next unless ($allchecked{$which}{$res});
 3282:                         if ($which eq 'remove') {
 3283:                             if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 3284:                                 ($url!~/$LONCAPA::assess_page_seq_re/)) {
 3285:                                 &Apache::lonnet::removeuploadedurl($url);
 3286:                             } else {
 3287:                                 &LONCAPA::map::makezombie($res);
 3288:                             }
 3289:                             splice(@LONCAPA::map::order,$i,1);
 3290:                             $haschanges ++;
 3291:                         } elsif ($which eq 'cut') {
 3292:                             &LONCAPA::map::makezombie($res);
 3293:                             splice(@LONCAPA::map::order,$i,1);
 3294:                             $haschanges ++;
 3295:                         }
 3296:                     }
 3297:                 }
 3298:                 if ($haschanges) {
 3299:                     ($errtext,$fatal) = 
 3300:                         &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 3301:                     return $errtext if ($fatal);
 3302:                 }
 3303:             }
 3304:         }
 3305: 
 3306: # Group import/search
 3307: 	if ($env{'form.importdetail'}) {
 3308: 	    my @imports;
 3309: 	    foreach my $item (split(/\&/,$env{'form.importdetail'})) {
 3310: 		if (defined($item)) {
 3311: 		    my ($name,$url,$residx)=
 3312: 			map { &unescape($_); } split(/\=/,$item);
 3313:                     if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
 3314:                         my ($suffix,$errortxt,$locknotfreed) =
 3315:                             &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
 3316:                         if ($locknotfreed) {
 3317:                             $r->print($locknotfreed);
 3318:                         }
 3319:                         if ($suffix) {
 3320:                             $url =~ s/_new\./_$suffix./; 
 3321:                         } else {
 3322:                             return $errortxt;
 3323:                         }
 3324:                     } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
 3325:                         my $type = $1;
 3326:                         my ($suffix,$errortxt,$locknotfreed) =
 3327:                             &new_timebased_suffix($coursedom,$coursenum,$type);
 3328:                         if ($locknotfreed) {
 3329:                             $r->print($locknotfreed);
 3330:                         }
 3331:                         if ($suffix) {
 3332:                             $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
 3333:                         } else {
 3334:                             return $errortxt;
 3335:                         }
 3336:                     } elsif ($url =~ m{^/adm/$coursedom/$coursenum/new/ext\.tool}) {
 3337:                         my ($suffix,$errortxt,$locknotfreed) =
 3338:                             &new_timebased_suffix($coursedom,$coursenum,'exttool');
 3339:                         if ($locknotfreed) {
 3340:                             $r->print($locknotfreed);
 3341:                         }
 3342:                         if ($suffix) {
 3343:                             $url =~ s{^(/adm/$coursedom/$coursenum)/new}{$1/$suffix};
 3344:                         } else {
 3345:                             return $errortxt;
 3346:                         }
 3347:                     } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
 3348:                         if ($supplementalflag) {
 3349:                             next unless ($1 eq 'supplemental');
 3350:                             if ($folder eq 'supplemental') {
 3351:                                 next unless ($2 eq 'default');
 3352:                             } else {
 3353:                                 next unless ($folder eq 'supplemental_'.$2);
 3354:                             }
 3355:                         } else {
 3356:                             next unless ($1 eq 'docs');
 3357:                             if ($folder eq 'default') {
 3358:                                 next unless ($2 eq 'default');
 3359:                             } else {
 3360:                                 next unless ($folder eq 'default_'.$2);
 3361:                             }
 3362:                         }
 3363:                     }
 3364: 		    push(@imports, [$name, $url, $residx]);
 3365: 		}
 3366: 	    }
 3367:             ($errtext,$fatal,my $fixuperrors) =
 3368:                 &group_import($coursenum, $coursedom, $folder,$container,
 3369:                               'londocs',$ltitoolsref,@imports);
 3370: 	    return $errtext if ($fatal);
 3371:             if ($fixuperrors) {
 3372:                 $r->print($fixuperrors);
 3373:             }
 3374: 	}
 3375: # Loading a complete map
 3376: 	if ($env{'form.loadmap'}) {
 3377: 	    if ($env{'form.importmap'}=~/\w/) {
 3378: 		foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
 3379: 		    my ($title,$url,$ext,$type)=split(/\:/,$res);
 3380: 		    my $idx=&LONCAPA::map::getresidx($url);
 3381: 		    $LONCAPA::map::resources[$idx]=$res;
 3382: 		    $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
 3383: 		}
 3384: 		($errtext,$fatal)=&storemap($coursenum,$coursedom,
 3385: 					    $folder.'.'.$container,1);
 3386: 		return $errtext if ($fatal);
 3387: 	    } else {
 3388: 		$r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
 3389: 
 3390: 	    }
 3391: 	}
 3392: 	&log_differences($plain);
 3393:     }
 3394: # ---------------------------------------------------------------- End commands
 3395: # ---------------------------------------------------------------- Print screen
 3396:     my $idx=0;
 3397:     my $shown=0;
 3398:     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
 3399: 	$r->print('<div class="LC_Box">'.
 3400:           '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
 3401: 		  ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
 3402: 		  ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
 3403: 		  ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
 3404: 		  ($is_random_order?'<li>'.&mt('random order').'</li>':'').
 3405: 		  '</ol>');
 3406:         if ($randompick>=0) {
 3407:             $r->print('<p class="LC_warning">'
 3408:                  .&mt('Caution: this folder is set to randomly pick a subset'
 3409:                      .' of resources. Adding or removing resources from this'
 3410:                      .' folder will change the set of resources that the'
 3411:                      .' students see, resulting in spurious or missing credit'
 3412:                      .' for completed problems, not limited to ones you'
 3413:                      .' modify. Do not modify the contents of this folder if'
 3414:                      .' it is in active student use.')
 3415:                  .'</p>'
 3416:             );
 3417:         }
 3418:         if ($is_random_order) {
 3419:             $r->print('<p class="LC_warning">'
 3420:                  .&mt('Caution: this folder is set to randomly order its'
 3421:                      .' contents. Adding or removing resources from this folder'
 3422:                      .' will change the order of resources shown.')
 3423:                  .'</p>'
 3424:             );
 3425:         }
 3426:         $r->print('</div>');
 3427:     }
 3428: 
 3429:     my ($to_show,$output,@allidx,@allmapidx,%filters,%lists,%curr_groups);
 3430:     %filters =  (
 3431:                   canremove      => [],
 3432:                   cancut         => [],
 3433:                   cancopy        => [],
 3434:                   hiddenresource => [],
 3435:                   encrypturl     => [],
 3436:                   randomorder    => [],
 3437:                   randompick     => [],
 3438:                 );
 3439:     %curr_groups = &Apache::longroup::coursegroups();
 3440:     &Apache::loncommon::start_data_table_count(); #setup a row counter 
 3441:     foreach my $res (@LONCAPA::map::order) {
 3442:         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 3443:         $name=&LONCAPA::map::qtescape($name);
 3444:         $url=&LONCAPA::map::qtescape($url);
 3445:         unless ($name) {  $name=(split(/\//,$url))[-1]; }
 3446:         unless ($name) { $idx++; next; }
 3447:         push(@allidx,$res);
 3448:         if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
 3449:             push(@allmapidx,$res);
 3450:         }
 3451: 
 3452:         $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
 3453:                               $coursenum,$coursedom,$crstype,
 3454:                               $pathitem,$supplementalflag,$container,
 3455:                               \%filters,\%curr_groups,$ltitoolsref,$canedit,
 3456:                               $isencrypted,$navmapref,$hostname);
 3457:         $idx++;
 3458:         $shown++;
 3459:     }
 3460:     &Apache::loncommon::end_data_table_count();
 3461: 
 3462:     my $need_save;
 3463:     if ($allowed || ($supplementalflag && $folder eq 'supplemental')) {
 3464:         my $toolslink;
 3465:         if ($allowed) {
 3466:             $toolslink = '<table><tr><td>'
 3467:                        .&Apache::loncommon::help_open_menu('Navigation Screen',
 3468:                                                            'Navigation_Screen',undef,'RAT')
 3469:                        .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
 3470:                        .'<td align="left"><ul id="LC_toolbar">'
 3471:                        .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
 3472:                        .'id="LC_content_toolbar_edittoplevel" '
 3473:                        .'class="LC_toolbarItem" '
 3474:                        .'title="'.&mt('Supplemental Content Editor').'">'
 3475:                        .'</a></li></ul></td></tr></table><br />';
 3476:         }
 3477:         if ($shown) {
 3478:             if ($allowed) {
 3479:                 $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
 3480:                           .&Apache::loncommon::start_data_table(undef,'contentlist')
 3481:                           .&Apache::loncommon::start_data_table_header_row()
 3482:                           .'<th colspan="2">'.&mt('Move').'</th>'
 3483:                           .'<th colspan="3">'.&mt('Actions').'</th>'
 3484:                           .'<th>'.&mt('Document').'</th>';
 3485:                 if ($folder !~ /^supplemental/) {
 3486:                     $to_show .= '<th colspan="2">'.&mt('Settings').'</th>';
 3487:                 }
 3488:                 $to_show .= &Apache::loncommon::end_data_table_header_row();
 3489:                 if ($folder !~ /^supplemental/) {
 3490:                     $lists{'canhide'} = join(',',@allidx);
 3491:                     $lists{'canrandomlyorder'} = join(',',@allmapidx);
 3492:                     my @possfilters = ('canremove','cancut','cancopy','hiddenresource','encrypturl',
 3493:                                        'randomorder','randompick');
 3494:                     foreach my $item (@possfilters) {
 3495:                         if (ref($filters{$item}) eq 'ARRAY') {
 3496:                             if (@{$filters{$item}} > 0) {
 3497:                                 $lists{$item} = join(',',@{$filters{$item}});
 3498:                             }
 3499:                         }
 3500:                     }
 3501:                     if (@allidx > 0) {
 3502:                         my $path;
 3503:                         if ($env{'form.folderpath'}) {
 3504:                             $path =
 3505:                                 &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 3506:                         }
 3507:                         if (@allidx > 1) {
 3508:                             $to_show .=
 3509:                                 &Apache::loncommon::continue_data_table_row().
 3510:                                 '<td colspan="2">&nbsp;</td>'.
 3511:                                 '<td>'.
 3512:                                 &multiple_check_form('actions',\%lists,$canedit).
 3513:                                 '</td>'.
 3514:                                 '<td colspan="3">&nbsp;</td>'.
 3515:                                 '<td colspan="2">'.
 3516:                                 &multiple_check_form('settings',\%lists,$canedit).
 3517:                                 '</td>'.
 3518:                                 &Apache::loncommon::end_data_table_row();
 3519:                              $need_save = 1;
 3520:                         }
 3521:                     }
 3522:                 }
 3523:                 $to_show .= $output.' '
 3524:                            .&Apache::loncommon::end_data_table()
 3525:                            .'<br style="line-height:2px;" />'
 3526:                            .&Apache::loncommon::end_scrollbox();
 3527:             } else {
 3528:                 $to_show .= $toolslink
 3529:                            .&Apache::loncommon::start_data_table('LC_tableOfContent')
 3530:                            .$output.' '
 3531:                            .&Apache::loncommon::end_data_table();
 3532:             }
 3533:         } else {
 3534:             if (!$allowed) {
 3535:                 $to_show .= $toolslink;
 3536:             }
 3537:             my $noresmsg;
 3538:             if ($allowed && $hiddentop && !$supplementalflag) {
 3539:                 $noresmsg = &mt('Main Content Hidden'); 
 3540:             } else {
 3541:                 $noresmsg = &mt('Currently empty');
 3542:             }
 3543:             $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
 3544:                        .'<div class="LC_info" id="contentlist">'
 3545:                        .$noresmsg
 3546:                        .'</div>'
 3547:                        .&Apache::loncommon::end_scrollbox();
 3548:         }
 3549:     } else {
 3550:         if ($shown) {
 3551:             $to_show = '<div>'
 3552:                       .&Apache::loncommon::start_data_table('LC_tableOfContent')
 3553:                       .$output
 3554:                       .&Apache::loncommon::end_data_table()
 3555:                       .'</div>';
 3556:         } else {
 3557:             $to_show = '<div class="LC_info" id="contentlist">'
 3558:                       .&mt('Currently empty')
 3559:                       .'</div>'
 3560:         }
 3561:     }
 3562:     my $tid = 1;
 3563:     if ($supplementalflag) {
 3564:         $tid = 2;
 3565:     }
 3566:     if ($allowed) {
 3567:         my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
 3568:         $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,
 3569:                                        $jumpto,$readfile,$need_save,"$folder.$container",$canedit));
 3570:         if ($canedit) {
 3571:             &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
 3572:         }
 3573:     } else {
 3574:         $r->print($to_show);
 3575:     }
 3576:     return;
 3577: }
 3578: 
 3579: sub multiple_check_form {
 3580:     my ($caller,$listsref,$canedit) = @_;
 3581:     return unless (ref($listsref) eq 'HASH');
 3582:     my $disabled;
 3583:     unless ($canedit) {
 3584:         $disabled = 'disabled="disabled"'; 
 3585:     }
 3586:     my $output =
 3587:     '<form action="/adm/coursedocs" method="post" name="togglemult'.$caller.'">'.
 3588:     '<span class="LC_nobreak" style="font-size:x-small;font-weight:bold;">'.
 3589:     '<label><input type="radio" name="showmultpick" value="0" onclick="javascript:togglePick('."'$caller','0'".');" checked="checked" />'.&mt('one').'</label>'.('&nbsp;'x2).'<label><input type="radio" name="showmultpick" value="1" onclick="javascript:togglePick('."'$caller','1'".');" />'.&mt('multiple').'</label></span><span id="more'.$caller.'" class="LC_nobreak LC_docs_ext_edit"></span></form>'.
 3590:     '<div id="multi'.$caller.'" style="display:none;margin:0;padding:0;border:0">'.
 3591:     '<form action="/adm/coursedocs" method="post" name="cumulative'.$caller.'">'."\n".
 3592:     '<fieldset id="allfields'.$caller.'" style="display:none"><legend style="font-size:x-small;">'.&mt('check/uncheck all').'</legend>'."\n";
 3593:     if ($caller eq 'settings') {
 3594:         $output .= 
 3595:             '<table><tr>'.
 3596:             '<td class="LC_docs_entry_parameter">'.
 3597:             '<span class="LC_nobreak"><label>'.
 3598:             '<input type="checkbox" name="hiddenresourceall" id="hiddenresourceall" onclick="propagateState(this.form,'."'hiddenresource'".')"'.$disabled.' />'.&mt('Hidden').
 3599:             '</label></span></td>'.
 3600:             '<td class="LC_docs_entry_parameter">'.
 3601:             '<span class="LC_nobreak"><label><input type="checkbox" name="randompickall" id="randompickall" onclick="updatePick(this.form,'."'all','check'".');propagateState(this.form,'."'randompick'".');propagateState(this.form,'."'rpicknum'".');"'.$disabled.' />'.&mt('Randomly Pick').'</label><span id="rpicktextall"></span><input type="hidden" name="rpicknumall" id="rpicknumall" value="" />'.
 3602:             '</span></td>'.
 3603:             '</tr>'."\n".
 3604:             '<tr>'.
 3605:             '<td class="LC_docs_entry_parameter">'.
 3606:             '<span class="LC_nobreak"><label><input type="checkbox" name="encrypturlall" id="encrypturlall" onclick="propagateState(this.form,'."'encrypturl'".')"'.$disabled.' />'.&mt('URL hidden').'</label></span></td><td class="LC_docs_entry_parameter"><span class="LC_nobreak"><label><input type="checkbox" name="randomorderall" id="randomorderall" onclick="propagateState(this.form,'."'randomorder'".')"'.$disabled.' />'.&mt('Random Order').
 3607:             '</label></span>'.
 3608:             '</td></tr></table>'."\n";
 3609:     } else {
 3610:         $output .=
 3611:             '<table><tr>'.
 3612:             '<td class="LC_docs_entry_parameter">'.
 3613:             '<span class="LC_nobreak LC_docs_remove">'.
 3614:             '<label><input type="checkbox" name="removeall" id="removeall" onclick="propagateState(this.form,'."'remove'".')"'.$disabled.' />'.&mt('Remove').
 3615:             '</label></span></td>'.
 3616:             '<td class="LC_docs_entry_parameter">'.
 3617:             '<span class="LC_nobreak LC_docs_cut">'.
 3618:             '<label><input type="checkbox" name="cut" id="cutall" onclick="propagateState(this.form,'."'cut'".');"'.$disabled.' />'.&mt('Cut').
 3619:             '</label></span></td>'."\n".
 3620:             '<td class="LC_docs_entry_parameter">'.
 3621:             '<span class="LC_nobreak LC_docs_copy">'.
 3622:             '<label><input type="checkbox" name="copyall" id="copyall" onclick="propagateState(this.form,'."'copy'".')"'. $disabled.' />'.&mt('Copy').
 3623:             '</label></span></td>'.
 3624:             '</tr></table>'."\n";
 3625:     }
 3626:     $output .= 
 3627:         '</fieldset>'.
 3628:         '<input type="hidden" name="allidx" value="'.$listsref->{'canhide'}.'" />';
 3629:     if ($caller eq 'settings') {
 3630:         $output .= 
 3631:         '<input type="hidden" name="allmapidx" value="'.$listsref->{'canrandomlyorder'}.'" />'."\n".
 3632:         '<input type="hidden" name="currhiddenresource" value="'.$listsref->{'hiddenresource'}.'" />'."\n".
 3633:         '<input type="hidden" name="currencrypturl" value="'.$listsref->{'encrypturl'}.'" />'."\n".
 3634:         '<input type="hidden" name="currrandomorder" value="'.$listsref->{'randomorder'}.'" />'."\n".
 3635:         '<input type="hidden" name="currrandompick" value="'.$listsref->{'randompick'}.'" />'."\n";
 3636:     } elsif ($caller eq 'actions') {
 3637:         $output .=
 3638:         '<input type="hidden" name="allremoveidx" id="allremoveidx" value="'.$listsref->{'canremove'}.'" />'.
 3639:         '<input type="hidden" name="allcutidx" id="allcutidx" value="'.$listsref->{'cancut'}.'" />'.
 3640:         '<input type="hidden" name="allcopyidx" id="allcopyidx" value="'.$listsref->{'cancopy'}.'" />';
 3641:     }
 3642:     $output .= 
 3643:         '</form>'.
 3644:         '</div>';
 3645:     return $output;
 3646: }
 3647: 
 3648: sub process_file_upload {
 3649:     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd,$crstype) = @_;
 3650: # upload a file, if present
 3651:     my $filesize = length($env{'form.uploaddoc'});
 3652:     if (!$filesize) {
 3653:         $$upload_output = '<div class="LC_error">'.
 3654:                            &mt('Unable to upload [_1]. (size = [_2] bytes)',
 3655:                           '<span class="LC_filename">'.$env{'form.uploaddoc.filename'}.'</span>',
 3656:                           $filesize).'<br />'.
 3657:                           &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
 3658:                           '</div>';
 3659:         return;
 3660:     }
 3661:     my $quotatype = 'unofficial';
 3662:     if ($crstype eq 'Community') {
 3663:         $quotatype = 'community';
 3664:     } elsif ($crstype eq 'Placement') {
 3665:         $quotatype = 'placement';
 3666:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.coursecode'}) {
 3667:         $quotatype = 'official';
 3668:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.textbook'}) {
 3669:         $quotatype = 'textbook';
 3670:     }
 3671:     if (&Apache::loncommon::get_user_quota($coursenum,$coursedom,'course',$quotatype)) {
 3672:         $filesize = int($filesize/1000); #expressed in kb
 3673:         $$upload_output = &Apache::loncommon::excess_filesize_warning($coursenum,$coursedom,'course',
 3674:                                                                       $env{'form.uploaddoc.filename'},$filesize,
 3675:                                                                       'upload',$quotatype);
 3676:         return if ($$upload_output);
 3677:     }
 3678:     my ($parseaction,$showupload,$nextphase,$mimetype);
 3679:     if ($env{'form.parserflag'}) {
 3680:         $parseaction = 'parse';
 3681:     }
 3682:     my $folder=$env{'form.folder'};
 3683:     if ($folder eq '') {
 3684:         $folder='default';
 3685:     }
 3686:     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
 3687:         my $errtext='';
 3688:         my $fatal=0;
 3689:         my $container='sequence';
 3690:         if ($env{'form.folderpath'} =~ /:1$/) {
 3691:             $container='page';
 3692:         }
 3693:         ($errtext,$fatal)=
 3694:             &mapread($coursenum,$coursedom,$folder.'.'.$container);
 3695:         if ($#LONCAPA::map::order<1) {
 3696:             $LONCAPA::map::order[0]=1;
 3697:             $LONCAPA::map::resources[1]='';
 3698:         }
 3699:         my $destination = 'docs/';
 3700:         if ($folder =~ /^supplemental/) {
 3701:             $destination = 'supplemental/';
 3702:         }
 3703:         if (($folder eq 'default') || ($folder eq 'supplemental')) {
 3704:             $destination .= 'default/';
 3705:         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 3706:             $destination .=  $2.'/';
 3707:         }
 3708:         if ($fatal) {
 3709:             $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('The uploaded file has not been stored as an error occurred reading the contents of the current folder.').'</div>';
 3710:             return;
 3711:         }
 3712: # this is for a course, not a user, so set context to coursedoc.
 3713:         my $newidx=&LONCAPA::map::getresidx();
 3714:         $destination .= $newidx;
 3715:         my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
 3716: 						$parseaction,$allfiles,
 3717: 						$codebase,undef,undef,undef,undef,
 3718:                                                 undef,undef,\$mimetype);
 3719:         if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
 3720:             my $stored = $1;
 3721:             $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 3722:                           $stored.'</span>').'</p>';
 3723:         } else {
 3724:             my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
 3725:             
 3726:             $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
 3727:             return;
 3728:         }
 3729:         my $ext='false';
 3730:         if ($url=~m{^http://}) { $ext='true'; }
 3731: 	$url     = &LONCAPA::map::qtunescape($url);
 3732:         my $comment=$env{'form.comment'};
 3733: 	$comment = &LONCAPA::map::qtunescape($comment);
 3734:         if ($folder=~/^supplemental/) {
 3735:               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 3736:                   $env{'user.domain'}.'___&&&___'.$comment;
 3737:         }
 3738: 
 3739:         $LONCAPA::map::resources[$newidx]=
 3740: 	    $comment.':'.$url.':'.$ext.':normal:res';
 3741:         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
 3742:         ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 3743: 				    $folder.'.'.$container,1);
 3744:         if ($fatal) {
 3745:             $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
 3746:             return;
 3747:         } else {
 3748:             if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
 3749:                 $$upload_output = $showupload;
 3750:                 my $total_embedded = scalar(keys(%{$allfiles}));
 3751:                 if ($total_embedded > 0) {
 3752:                     my $uploadphase = 'upload_embedded';
 3753:                     my $primaryurl = &HTML::Entities::encode($url,'<>&"');
 3754: 		    my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
 3755:                     my ($embedded,$num) =
 3756:                         &Apache::loncommon::ask_for_embedded_content(
 3757:                             '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
 3758:                     if ($embedded) {
 3759:                         if ($num) {
 3760:                             $$upload_output .=
 3761: 			         '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
 3762:                             $nextphase = $uploadphase;
 3763:                         } else {
 3764:                             $$upload_output .= $embedded;
 3765:                         }
 3766:                     } else {
 3767:                         $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
 3768:                     }
 3769:                 } else {
 3770:                     $$upload_output .= &mt('No embedded items identified').'<br />';
 3771:                 }
 3772:                 $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
 3773:             } elsif ((&Apache::loncommon::is_archive_file($mimetype)) &&
 3774:                      ($env{'form.uploaddoc.filename'} =~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i)) {
 3775:                 $nextphase = 'decompress_uploaded';
 3776:                 my $position = scalar(@LONCAPA::map::order)-1;
 3777:                 my $noextract = &return_to_editor();
 3778:                 my $archiveurl = &HTML::Entities::encode($url,'<>&"');
 3779:                 my %archiveitems = (
 3780:                     folderpath => $env{'form.folderpath'},
 3781:                     cmd        => $nextphase,
 3782:                     newidx     => $newidx,
 3783:                     position   => $position,
 3784:                     phase      => $nextphase,
 3785:                     comment    => $comment,
 3786:                 );
 3787:                 my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
 3788:                 my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
 3789:                 $$upload_output = $showupload.
 3790:                                   &Apache::loncommon::decompress_form($mimetype,
 3791:                                       $archiveurl,'/adm/coursedocs',$noextract,
 3792:                                       \%archiveitems,\@current);
 3793:             }
 3794:         }
 3795:     }
 3796:     return $nextphase;
 3797: }
 3798: 
 3799: sub get_dir_list {
 3800:     my ($url,$coursenum,$coursedom,$newidx) = @_;
 3801:     my ($destination,$dir_root) = &embedded_destination();
 3802:     my ($dirlistref,$listerror) =  
 3803:         &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
 3804:     my @dir_lines;
 3805:     my $dirptr=16384;
 3806:     if (ref($dirlistref) eq 'ARRAY') {
 3807:         foreach my $dir_line (sort
 3808:                           {
 3809:                               my ($afile)=split('&',$a,2);
 3810:                               my ($bfile)=split('&',$b,2);
 3811:                               return (lc($afile) cmp lc($bfile));
 3812:                           } (@{$dirlistref})) {
 3813:             my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
 3814:             $filename =~ s/\s+$//;
 3815:             next if ($filename =~ /^\.\.?$/); 
 3816:             my $isdir = 0;
 3817:             if ($dirptr&$testdir) {
 3818:                 $isdir = 1;
 3819:             }
 3820:             push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
 3821:         }
 3822:     }
 3823:     return @dir_lines;
 3824: }
 3825: 
 3826: sub is_supplemental_title {
 3827:     my ($title) = @_;
 3828:     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
 3829: }
 3830: 
 3831: # --------------------------------------------------------------- An entry line
 3832: 
 3833: sub entryline {
 3834:     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
 3835:         $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups,
 3836:         $ltitoolsref,$canedit,$isencrypted,$navmapref,$hostname)=@_;
 3837:     my ($foldertitle,$renametitle,$oldtitle);
 3838:     if (&is_supplemental_title($title)) {
 3839: 	($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
 3840:     } else {
 3841: 	$title=&HTML::Entities::encode($title,'"<>&\'');
 3842: 	$renametitle=$title;
 3843: 	$foldertitle=$title;
 3844:     }
 3845: 
 3846:     my ($disabled,$readonly,$js_lt);
 3847:     unless ($canedit) {
 3848:         $disabled = 'disabled="disabled"';
 3849:         $readonly = 1;
 3850:     }
 3851: 
 3852:     my $orderidx=$LONCAPA::map::order[$index];
 3853: 
 3854:     $renametitle=~s/\\/\\\\/g;
 3855:     $renametitle=~s/\&quot\;/\\\"/g;
 3856:     $renametitle=~s/"/%22/g;
 3857:     $renametitle=~s/ /%20/g;
 3858:     $oldtitle = $renametitle;
 3859:     $renametitle=~s/\&#39;/\\\'/g;
 3860:     my $line=&Apache::loncommon::start_data_table_row();
 3861:     my ($form_start,$form_end,$form_common,$form_param);
 3862: # Edit commands
 3863:     my ($esc_path, $path, $symb, $curralias);
 3864:     if ($env{'form.folderpath'}) {
 3865: 	$esc_path=&escape($env{'form.folderpath'});
 3866: 	$path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 3867: 	# $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 3868:     }
 3869:     my $isexternal;
 3870:     if ($residx) {
 3871:         my $currurl = $url;
 3872:         $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
 3873:         if ($currurl =~ m{^/adm/wrapper/ext/}) {
 3874:             $isexternal = 1;
 3875:         }
 3876:         if (!$supplementalflag) {
 3877:             my $path = 'uploaded/'.
 3878:                        $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 3879:                        $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 3880:             $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
 3881:                                                  $residx,
 3882:                                                  &Apache::lonnet::declutter($currurl));
 3883:         }
 3884:     }
 3885:     my ($renamelink,%lt,$ishash);
 3886:     if (ref($filtersref) eq 'HASH') {
 3887:         $ishash = 1;
 3888:     }
 3889: 
 3890:     if ($allowed) {
 3891:         $form_start = '
 3892:    <form action="/adm/coursedocs" method="post">
 3893: ';
 3894:         $form_common=(<<END);
 3895:    <input type="hidden" name="folderpath" value="$path" />
 3896:    <input type="hidden" name="symb" value="$symb" />
 3897: END
 3898:         $form_param=(<<END);
 3899:    <input type="hidden" name="setparms" value="$orderidx" />
 3900:    <input type="hidden" name="changeparms" value="0" />
 3901: END
 3902:         $form_end = '</form>';
 3903: 
 3904: 	my $incindex=$index+1;
 3905: 	my $selectbox='';
 3906: 	if (($#LONCAPA::map::order>0) &&
 3907: 	    ((split(/\:/,
 3908: 	     $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
 3909: 	     ne '') &&
 3910: 	    ((split(/\:/,
 3911: 	     $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
 3912: 	     ne '')) {
 3913: 	    $selectbox=
 3914: 		'<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
 3915: 		'<select name="newpos" onchange="this.form.submit()"'.$disabled.'>';
 3916: 	    for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
 3917: 		if ($i==$incindex) {
 3918: 		    $selectbox.='<option value="" selected="selected">('.$i.')</option>';
 3919: 		} else {
 3920: 		    $selectbox.='<option value="'.$i.'">'.$i.'</option>';
 3921: 		}
 3922: 	    }
 3923: 	    $selectbox.='</select>';
 3924: 	}
 3925: 	%lt=&Apache::lonlocal::texthash(
 3926:                 'up' => 'Move Up',
 3927: 		'dw' => 'Move Down',
 3928: 		'rm' => 'Remove',
 3929:                 'ct' => 'Cut',
 3930: 		'rn' => 'Rename',
 3931: 		'cp' => 'Copy',
 3932:                 'da' => 'Unset alias', 
 3933:                 'sa' => 'Set alias',
 3934:                 'ex' => 'External Resource',
 3935:                 'et' => 'External Tool',
 3936:                 'ed' => 'Edit',
 3937:                 'pr' => 'Preview',
 3938:                 'sv' => 'Save',
 3939:                 'ul' => 'URL',
 3940:                 'ti' => 'Title',
 3941:                 'er' => 'Editing rights unavailable for your current role.', 
 3942:                 );
 3943: 	my %denied = &action_restrictions($coursenum,$coursedom,$url,
 3944:                                           $env{'form.folderpath'},
 3945:                                           $currgroups);
 3946:         my ($copylink,$cutlink,$removelink);
 3947: 	my $skip_confirm = 0;
 3948:         my $confirm_removal = 0;
 3949: 	if ( $folder =~ /^supplemental/
 3950: 	     || ($url =~ m{( /smppg$
 3951: 			    |/syllabus$
 3952: 			    |/aboutme$
 3953: 			    |/navmaps$
 3954: 			    |/bulletinboard$
 3955:                             |/ext\.tool$
 3956: 			    |\.html$)}x)
 3957:              || $isexternal) {
 3958: 	    $skip_confirm = 1;
 3959: 	}
 3960:         if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 3961:             ($url!~/$LONCAPA::assess_page_seq_re/)) {
 3962:             $confirm_removal = 1;
 3963:         }
 3964:         if ($url =~ /$LONCAPA::assess_re/) {
 3965:             $curralias = (&LONCAPA::map::getparameter($orderidx,'parameter_0_mapalias'))[0];
 3966:         }
 3967: 
 3968: 	if ($denied{'copy'}) {
 3969:             $copylink=(<<ENDCOPY)
 3970: <span style="visibility: hidden;">$lt{'cp'}</span>
 3971: ENDCOPY
 3972:         } else {
 3973:             my $formname = 'edit_copy_'.$orderidx;
 3974:             my $js = "javascript:checkForSubmit(document.forms.renameform,'copy','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 3975: 	    $copylink=(<<ENDCOPY);
 3976: <form name="$formname" method="post" action="/adm/coursedocs">
 3977: $form_common
 3978: <input type="checkbox" name="copy" id="copy_$orderidx" value="$orderidx" onclick="javascript:singleCheck(this,'$orderidx','copy');" class="LC_hidden" $disabled /><a href="$js" class="LC_docs_copy">$lt{'cp'}</a>
 3979: $form_end
 3980: ENDCOPY
 3981:             if (($ishash) && (ref($filtersref->{'cancopy'}) eq 'ARRAY')) {
 3982:                 push(@{$filtersref->{'cancopy'}},$orderidx);
 3983:             }
 3984:         }
 3985: 	if ($denied{'cut'}) {
 3986:             $cutlink=(<<ENDCUT);
 3987: <span style="visibility: hidden;">$lt{'ct'}</span>
 3988: ENDCUT
 3989:         } else {
 3990:             my $formname = 'edit_cut_'.$orderidx;
 3991:             my $js = "javascript:checkForSubmit(document.forms.renameform,'cut','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 3992: 	    $cutlink=(<<ENDCUT);
 3993: <form name="$formname" method="post" action="/adm/coursedocs">
 3994: $form_common
 3995: <input type="hidden" name="skip_$orderidx" id="skip_cut_$orderidx" value="$skip_confirm" />
 3996: <input type="checkbox" name="cut" id="cut_$orderidx" value="$orderidx" onclick="javascript:singleCheck(this,'$orderidx','cut');" class="LC_hidden" $disabled /><a href="$js" class="LC_docs_cut">$lt{'ct'}</a>
 3997: $form_end
 3998: ENDCUT
 3999:             if (($ishash) && (ref($filtersref->{'cancut'}) eq 'ARRAY')) {
 4000:                 push(@{$filtersref->{'cancut'}},$orderidx);
 4001:             }
 4002:         }
 4003:         if ($denied{'remove'}) {
 4004:             $removelink=(<<ENDREM);
 4005: <span style="visibility: hidden;">$lt{'rm'}</a>
 4006: ENDREM
 4007:         } else {
 4008:             my $formname = 'edit_remove_'.$orderidx;
 4009:             my $js = "javascript:checkForSubmit(document.forms.renameform,'remove','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder',$confirm_removal);";
 4010:             $removelink=(<<ENDREM);
 4011: <form name="$formname" method="post" action="/adm/coursedocs">
 4012: $form_common
 4013: <input type="hidden" name="skip_$orderidx" id="skip_remove_$orderidx" value="$skip_confirm" />
 4014: <input type="hidden" name="confirm_rem_$orderidx" id="confirm_removal_$orderidx" value="$confirm_removal" />
 4015: <input type="checkbox" name="remove" id="remove_$orderidx" value="$orderidx" onclick="javascript:singleCheck(this,'$orderidx','remove');" class="LC_hidden" $disabled /><a href="$js" class="LC_docs_remove">$lt{'rm'}</a>
 4016: $form_end
 4017: ENDREM
 4018:             if (($ishash) && (ref($filtersref->{'canremove'}) eq 'ARRAY')) {
 4019:                 push(@{$filtersref->{'canremove'}},$orderidx);
 4020:             }
 4021:         }
 4022:         $renamelink=(<<ENDREN);
 4023: <a href='javascript:changename("$esc_path","$index","$oldtitle");' class="LC_docs_rename">$lt{'rn'}</a>
 4024: ENDREN
 4025:         my ($uplink,$downlink);
 4026:         if ($canedit) {
 4027:             $uplink = "/adm/coursedocs?cmd=up_$index&amp;folderpath=$esc_path&amp;symb=$symb";
 4028:             $downlink = "/adm/coursedocs?cmd=down_$index&amp;folderpath=$esc_path&amp;symb=$symb";
 4029:         } else {
 4030:             $uplink = "javascript:alert('".&js_escape($lt{'er'})."');";
 4031:             $downlink = $uplink;
 4032:         }
 4033: 	$line.=(<<END);
 4034: <td>
 4035: <div class="LC_docs_entry_move">
 4036:   <a href="$uplink">
 4037:     <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
 4038:   </a>
 4039: </div>
 4040: <div class="LC_docs_entry_move">
 4041:   <a href="$downlink">
 4042:     <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
 4043:   </a>
 4044: </div>
 4045: </td>
 4046: <td>
 4047:    $form_start
 4048:    $form_param
 4049:    $form_common
 4050:    $selectbox
 4051:    $form_end
 4052: </td>
 4053: <td class="LC_docs_entry_commands LC_nobreak">
 4054: $removelink
 4055: $cutlink
 4056: $copylink
 4057: </td>
 4058: END
 4059:     }
 4060: # Figure out what kind of a resource this is
 4061:     my ($extension)=($url=~/\.(\w+)$/);
 4062:     my $uploaded=($url=~/^\/*uploaded\//);
 4063:     my $icon=&Apache::loncommon::icon($url);
 4064:     my $isfolder;
 4065:     my $ispage;
 4066:     my $containerarg;
 4067:     my $folderurl;
 4068:     if ($uploaded) {
 4069:         if (($extension eq 'sequence') || ($extension eq 'page')) {
 4070:             $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
 4071:             $containerarg = $1;
 4072: 	    if ($extension eq 'sequence') {
 4073: 	        $icon=$iconpath.'navmap.folder.closed.gif';
 4074:                 $isfolder=1;
 4075:             } else {
 4076:                 $icon=$iconpath.'page.gif';
 4077:                 $ispage=1;
 4078:             }
 4079:             $folderurl = &Apache::lonnet::declutter($url);
 4080:             if ($allowed) {
 4081:                 $url='/adm/coursedocs?';
 4082:             } else {
 4083:                 $url='/adm/supplemental?';
 4084:             }
 4085: 	} else {
 4086: 	    &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 4087: 	}
 4088:     }
 4089: 
 4090:     my ($editlink,$extresform,$anchor,$hiddenres,$nomodal);
 4091:     my $orig_url = $url;
 4092:     $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 4093:     $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
 4094:     if (!$supplementalflag && $residx && $symb) {
 4095:         if ((!$isfolder) && (!$ispage)) {
 4096: 	    (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4097: 	    $url=&Apache::lonnet::clutter($url);
 4098: 	    if ($url=~/^\/*uploaded\//) {
 4099: 	        $url=~/\.(\w+)$/;
 4100: 	        my $embstyle=&Apache::loncommon::fileembstyle($1);
 4101: 	        if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
 4102: 		    $url='/adm/wrapper'.$url;
 4103: 	        } elsif ($embstyle eq 'ssi') {
 4104: 		    #do nothing with these
 4105: 	        } elsif ($url!~/\.(sequence|page)$/) {
 4106: 		    $url='/adm/coursedocs/showdoc'.$url;
 4107: 	        }
 4108: 	    } elsif ($url=~m{^(|/adm/wrapper)/ext/([^#]+)}) {
 4109:                 my $wrapped = $1;
 4110:                 my $exturl = $2;
 4111:                 if ($wrapped eq '') {
 4112:                     $url='/adm/wrapper'.$url;
 4113:                 }
 4114:                 if (($ENV{'SERVER_PORT'} == 443) && ($exturl !~ /^https:/)) {
 4115:                     $nomodal = 1;
 4116:                 }
 4117: 	    } elsif ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
 4118: 		$url='/adm/wrapper'.$url;
 4119:             } elsif ($url eq "/public/$coursedom/$coursenum/syllabus") {
 4120:                 if (($ENV{'SERVER_PORT'} == 443) &&
 4121:                     ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 4122:                     $url .= '?usehttp=1';
 4123:                     $nomodal = 1;
 4124:                 }
 4125:             }
 4126:             if (&Apache::lonnet::symbverify($symb,$url)) {
 4127:                 my $shownsymb = $symb;
 4128:                 if ($isexternal) {
 4129:                     if ($url =~ /^([^#]+)#([^#]+)$/) {
 4130:                         $url = $1;
 4131:                         $anchor = $2;
 4132:                         if ($symb =~ m{^([^#]+)\Q#$anchor\E$}) {
 4133:                             $shownsymb = $1.&escape('#').$anchor;
 4134:                         }
 4135:                     }
 4136:                 }
 4137:                 unless ($env{'request.role.adv'}) {
 4138:                     if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4139:                         $url = '';
 4140:                     }
 4141:                     if (&Apache::lonnet::EXT('resource.0.hiddenresource',$symb) =~ /^yes$/i) {
 4142:                         $url = '';
 4143:                         $hiddenres = 1;
 4144:                     }
 4145:                 }
 4146:                 if ($url ne '') {
 4147:                     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($shownsymb);
 4148:                 }
 4149:             } elsif (!$env{'request.role.adv'}) {
 4150:                 my $checkencrypt;
 4151:                 if (((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i) ||
 4152:                       $isencrypted || (&Apache::lonnet::EXT('resource.0.encrypturl',$symb) =~ /^yes$/i)) {
 4153:                     $checkencrypt = 1;
 4154:                 } elsif (ref($navmapref)) {
 4155:                     unless (ref($$navmapref)) {
 4156:                         $$navmapref = Apache::lonnavmaps::navmap->new();
 4157:                     }
 4158:                     if (ref($$navmapref)) {
 4159:                         if (lc($$navmapref->get_mapparam($symb,undef,"0.encrypturl")) eq 'yes') {
 4160:                             $checkencrypt = 1;       
 4161:                         }
 4162:                     }
 4163:                 }
 4164:                 if ($checkencrypt) {
 4165:                     my $shownsymb = &Apache::lonenc::encrypted($symb);
 4166:                     my $shownurl = &Apache::lonenc::encrypted($url);
 4167:                     if (&Apache::lonnet::symbverify($shownsymb,$shownurl)) {
 4168:                         $url = $shownurl.(($shownurl=~/\?/)?'&':'?').'symb='.&escape($shownsymb);
 4169:                         if ($env{'request.enc'} ne '') {
 4170:                             delete($env{'request.enc'});
 4171:                         }
 4172:                     } else {
 4173:                         $url='';
 4174:                     }
 4175:                 } else {
 4176:                     $url='';
 4177:                 }
 4178:             } else {
 4179:                 $url='';
 4180:             }
 4181: 	}
 4182:     } elsif ($supplementalflag) {
 4183:         if ($isexternal) {
 4184:             if ($url =~ /^([^#]+)#([^#]+)$/) {
 4185:                 $url = $1;
 4186:                 $anchor = $2;
 4187:                 if (($url =~ m{^(|/adm/wrapper)/ext/(?!https:)}) && ($ENV{'SERVER_PORT'} == 443)) {
 4188:                     if ($hostname ne '') {
 4189:                         $url = 'http://'.$hostname.$url;
 4190:                     }
 4191:                     $nomodal = 1;
 4192:                 }
 4193:             }
 4194:         } elsif ($url =~ m{^\Q/public/$coursedom/$coursenum/syllabus\E}) {
 4195:             if (($ENV{'SERVER_PORT'} == 443) &&
 4196:                 ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 4197:                 if ($hostname ne '') {
 4198:                     $url = 'http://'.$hostname.$url;
 4199:                 }
 4200:                 $url .= (($url =~ /\?/) ? '&amp;':'?').'usehttp=1';
 4201:                 $nomodal = 1;
 4202:             }
 4203:         }
 4204:     }
 4205:     my ($rand_pick_text,$rand_order_text,$hiddenfolder);
 4206:     my $filterFunc = sub { my $res = shift; return (!$res->randomout() && !$res->is_map()) };
 4207:     if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
 4208: 	my $foldername=&escape($foldertitle);
 4209: 	my $folderpath=$env{'form.folderpath'};
 4210: 	if ($folderpath) { $folderpath.='&' };
 4211:         if (!$allowed && $supplementalflag) {
 4212:             $folderpath.=$containerarg.'&'.$foldername;
 4213:             $url.='folderpath='.&escape($folderpath);
 4214:         } else {
 4215:             my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
 4216:                                                         'parameter_randompick'))[0];
 4217:             my $randorder = ((&LONCAPA::map::getparameter($orderidx,
 4218:                                               'parameter_randomorder'))[0]=~/^yes$/i);
 4219:             my $hiddenmap = ((&LONCAPA::map::getparameter($orderidx,
 4220:                                               'parameter_hiddenresource'))[0]=~/^yes$/i);
 4221:             my $encryptmap = ((&LONCAPA::map::getparameter($orderidx,
 4222:                                               'parameter_encrypturl'))[0]=~/^yes$/i);
 4223:             unless ($hiddenmap) {
 4224:                 if (ref($navmapref)) {
 4225:                     unless (ref($$navmapref)) {
 4226:                         $$navmapref = Apache::lonnavmaps::navmap->new();
 4227:                     }
 4228:                     if (ref($$navmapref)) {
 4229:                         if (lc($$navmapref->get_mapparam(undef,$folderurl,"0.hiddenresource")) eq 'yes') {
 4230:                             my @resources = $$navmapref->retrieveResources($folderurl,$filterFunc,1,1);
 4231:                             unless (@resources) {
 4232:                                 $hiddenmap = 1;
 4233:                                 unless ($env{'request.role.adv'}) {  
 4234:                                     $url = '';
 4235:                                     $hiddenfolder = 1;
 4236:                                 }
 4237:                             }
 4238:                         }
 4239:                     }
 4240:                 }
 4241:             }
 4242:             unless ($encryptmap) {
 4243:                 if ((ref($navmapref)) && (ref($$navmapref))) {
 4244:                     if (lc($$navmapref->get_mapparam(undef,$folderurl,"0.encrypturl")) eq 'yes') {
 4245:                         $encryptmap = 1;
 4246:                     }
 4247:                 }
 4248:             }
 4249: 
 4250: # Append randompick number, hidden, and encrypted with ":" to foldername,
 4251: # so it gets transferred between levels
 4252: 	    $folderpath.=$containerarg.'&'.$foldername.
 4253:                          ':'.$rpicknum.':'.$hiddenmap.':'.$encryptmap.':'.$randorder.':'.$ispage;
 4254:             unless ($url eq '') {
 4255:                 $url.='folderpath='.&escape($folderpath);
 4256:             }
 4257:             my $rpckchk;
 4258:             if ($rpicknum) {
 4259:                 $rpckchk = ' checked="checked"';
 4260:                 if (($ishash) && (ref($filtersref->{'randompick'}) eq 'ARRAY')) {
 4261:                     push(@{$filtersref->{'randompick'}},$orderidx.':'.$rpicknum);
 4262:                 }
 4263:             }
 4264:             my $formname = 'edit_randompick_'.$orderidx;
 4265: 	    $rand_pick_text = 
 4266: '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
 4267: $form_param."\n".
 4268: $form_common."\n".
 4269: '<span class="LC_nobreak"><label><input type="checkbox" name="randompick_'.$orderidx.'" id="randompick_'.$orderidx.'" onclick="'."updatePick(this.form,'$orderidx','check');".'"'.$rpckchk.$disabled.' /> '.&mt('Randomly Pick').'</label><input type="hidden" name="rpicknum_'.$orderidx.'" id="rpicknum_'.$orderidx.'" value="'.$rpicknum.'" /><span id="randompicknum_'.$orderidx.'">';
 4270:             if ($rpicknum ne '') {
 4271:                 $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
 4272:             }
 4273:             $rand_pick_text .= '</span></span>'.
 4274:                                $form_end;
 4275:             my $ro_set;
 4276:             if ($randorder) {
 4277:                 $ro_set = 'checked="checked"';
 4278:                 if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
 4279:                     push(@{$filtersref->{'randomorder'}},$orderidx);
 4280:                 }
 4281:             }
 4282:             $formname = 'edit_rorder_'.$orderidx;
 4283: 	    $rand_order_text = 
 4284: '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
 4285: $form_param."\n".
 4286: $form_common."\n".
 4287: '<span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" id="randomorder_'.$orderidx.'" onclick="checkForSubmit(this.form,'."'randomorder','settings'".');" '.$ro_set.$disabled.' /> '.&mt('Random Order').' </label></span>'.
 4288: $form_end; 
 4289:         }
 4290:     } elsif ($supplementalflag && !$allowed) {
 4291:         my $isexttool;
 4292:         if ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
 4293:             $url='/adm/wrapper'.$url;
 4294:             $isexttool = 1;
 4295:         }
 4296:         $url .= ($url =~ /\?/) ? '&amp;':'?';
 4297:         $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
 4298:         if ($title) {
 4299:             $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
 4300:         }
 4301:         if ((($isexternal) || ($isexttool)) && $orderidx) {
 4302:             $url .= '&amp;idx='.$orderidx;
 4303:         }
 4304:         if ($anchor ne '') {
 4305:             $url .= '&amp;anchor='.&HTML::Entities::encode($anchor,'"<>&');
 4306:         }
 4307:     }
 4308:     my ($tdalign,$tdwidth);
 4309:     if ($allowed) {
 4310:         my $fileloc =
 4311:             &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
 4312:         if ($isexternal) {
 4313:             ($editlink,$extresform) =
 4314:                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
 4315:                                                      undef,undef,undef,undef,undef,undef,
 4316:                                                      undef,$disabled);
 4317:         } elsif ($orig_url =~ m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
 4318:             ($editlink,$extresform) =
 4319:                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
 4320:                                                      undef,undef,undef,'tool',$coursedom,
 4321:                                                      $coursenum,$ltitoolsref,$disabled);
 4322:         } elsif (!$isfolder && !$ispage) {
 4323:             my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
 4324:                 &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
 4325:             if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
 4326:                 my $suppanchor;
 4327:                 if ($supplementalflag) {
 4328:                     $suppanchor = $anchor;
 4329:                 }
 4330:                 my $jscall =
 4331:                     &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
 4332:                                                             $switchserver,
 4333:                                                             $forceedit,
 4334:                                                             undef,$symb,
 4335:                                                             &escape($env{'form.folderpath'}),
 4336:                                                             $renametitle,$hostname,
 4337:                                                             '','',1,$suppanchor);
 4338:                 if ($jscall) {
 4339:                     $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
 4340:                                 $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
 4341:                 }
 4342:             }
 4343:         }
 4344:         $tdalign = ' align="right" valign="top"';
 4345:         $tdwidth = ' width="80%"';
 4346:     }
 4347:     my $reinit;
 4348:     if ($crstype eq 'Community') {
 4349:         $reinit = &mt('(re-initialize community to access)');
 4350:     } else {
 4351:         $reinit = &mt('(re-initialize course to access)');
 4352:     }
 4353:     $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
 4354:     if ($url =~ /$LONCAPA::assess_re/) {
 4355:         $line.= '<br />';
 4356:         if ($curralias ne '') {
 4357:             $line.='<span class="LC_nobreak"><a href="javascript:delalias('."'$esc_path','$orderidx'".');" class="LC_docs_alias">'.
 4358:                    $lt{'da'}.'</a></span>';
 4359:         } else {
 4360:             $line.='<span class="LC_nobreak"><a href="javascript:setalias('."'$esc_path','$orderidx'".');" class="LC_docs_alias">'.
 4361:                    $lt{'sa'}.'</a></span>';
 4362:         }
 4363:     }
 4364:     $line.='</td><td>';
 4365:     my $link;
 4366:     if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 4367:        $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
 4368:     } elsif ($url) {
 4369:        if ($anchor ne '') {
 4370:            if ($supplementalflag) {
 4371:                $anchor = '&amp;anchor='.&HTML::Entities::encode($anchor,'"<>&');
 4372:            } else {
 4373:                $anchor = '#'.&HTML::Entities::encode($anchor,'"<>&');
 4374:            }
 4375:        }
 4376:        if ((!$supplementalflag) && ($nomodal) && ($hostname ne '')) {
 4377:            $link = 'http://'.$hostname.$url;
 4378:        } else {
 4379:            $link = $url;
 4380:        }
 4381:        $link = &js_escape($link.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes'.
 4382:                                                (($anchor ne '')?$anchor:''));
 4383:        if ($nomodal) {
 4384:            $line.='<a href="#" onclick="javascript:window.open('."'$link','syllabuspreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1')".'; return false;" />'.
 4385:                   '<img src="'.$icon.'" alt="" class="LC_icon" border="0" /></a>';
 4386:        } else {
 4387:            $line.=&Apache::loncommon::modal_link($link,
 4388:                                                  '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
 4389:        }
 4390:     } else {
 4391:        $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
 4392:     }
 4393:     $line.='</span></td><td'.$tdwidth.'>';
 4394:     if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 4395:        $line.='<a href="'.$url.'">'.$title.'</a>';
 4396:     } elsif ($url) {
 4397:        if ($nomodal) {
 4398:            $line.='<a href="#" onclick="javascript:window.open('."'$link','syllabuspreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1')".'; return false;" />'.
 4399:                   $title.'</a>';
 4400:        } else {
 4401:            $line.=&Apache::loncommon::modal_link($link,$title,600,500);
 4402:        }
 4403:     } elsif (($hiddenfolder) || ($hiddenres)) {
 4404:        $line.=$title.' <span class="LC_warning LC_docs_reinit_warn">('.&mt('Hidden').')</span>';
 4405:     } else {
 4406:        $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
 4407:     }
 4408:     if (($allowed) && ($curralias ne '')) {
 4409:         $line .= '<br /><span class="LC_docs_alias_name">('.$curralias.')</span>';
 4410:     } else {
 4411:         $line .= $extresform;
 4412:     }
 4413:     $line .= '</td>';
 4414:     $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
 4415:     $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
 4416:     if (($allowed) && ($folder!~/^supplemental/)) {
 4417:  	my %lt=&Apache::lonlocal::texthash(
 4418:  			      'hd' => 'Hidden',
 4419:  			      'ec' => 'URL hidden');
 4420:         my ($enctext,$hidtext);
 4421:         if ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i) {
 4422:             $enctext = ' checked="checked"';
 4423:             if (($ishash) && (ref($filtersref->{'encrypturl'}) eq 'ARRAY')) {
 4424:                 push(@{$filtersref->{'encrypturl'}},$orderidx);
 4425:             }
 4426:         }
 4427:         if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4428:             $hidtext = ' checked="checked"';
 4429:             if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
 4430:                 push(@{$filtersref->{'hiddenresource'}},$orderidx);
 4431:             }
 4432:         }
 4433:         my $formhidden = 'edit_hiddenresource_'.$orderidx;
 4434:         my $formurlhidden = 'edit_encrypturl_'.$orderidx;
 4435: 	$line.=(<<ENDPARMS);
 4436:   <td class="LC_docs_entry_parameter">
 4437:     <form action="/adm/coursedocs" method="post" name="$formhidden">
 4438:     $form_param
 4439:     $form_common
 4440:     <label><input type="checkbox" name="hiddenresource_$orderidx" id="hiddenresource_$orderidx" onclick="checkForSubmit(this.form,'hiddenresource','settings');" $hidtext $disabled /> $lt{'hd'}</label>
 4441:     $form_end
 4442:     <br />
 4443:     <form action="/adm/coursedocs" method="post" name="$formurlhidden">
 4444:     $form_param
 4445:     $form_common
 4446:     <label><input type="checkbox" name="encrypturl_$orderidx" id="encrypturl_$orderidx" onclick="checkForSubmit(this.form,'encrypturl','settings');" $enctext $disabled /> $lt{'ec'}</label>
 4447:     $form_end
 4448:   </td>
 4449:   <td class="LC_docs_entry_parameter">$rand_pick_text<br />
 4450:                                       $rand_order_text</td>
 4451: ENDPARMS
 4452:     }
 4453:     $line.=&Apache::loncommon::end_data_table_row();
 4454:     return $line;
 4455: }
 4456: 
 4457: sub action_restrictions {
 4458:     my ($cnum,$cdom,$url,$folderpath,$currgroups) = @_;
 4459:     my %denied = (
 4460:                    cut    => 0,
 4461:                    copy   => 0,
 4462:                    remove => 0,
 4463:                  );
 4464:     if ($url=~ m{^/res/.+\.(page|sequence)$}) {
 4465:         # no copy for published maps
 4466:         $denied{'copy'} = 1;
 4467:     } elsif ($url=~m{^/res/lib/templates/([^/]+)\.problem$}) {
 4468:         unless ($1 eq 'simpleproblem') {
 4469:             $denied{'copy'} = 1;
 4470:         }
 4471:         $denied{'cut'} = 1;
 4472:     } elsif ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
 4473:         if ($folderpath =~ /^default&[^\&]+$/) {
 4474:             if ((ref($currgroups) eq 'HASH') && (keys(%{$currgroups}) > 0)) {
 4475:                 $denied{'remove'} = 1;
 4476:             }
 4477:             $denied{'cut'} = 1;
 4478:             $denied{'copy'} = 1;
 4479:         }
 4480:     } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
 4481:         my $group = $1;
 4482:         if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
 4483:             if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
 4484:                 $denied{'remove'} = 1;
 4485:             }
 4486:         }
 4487:         $denied{'cut'} = 1;
 4488:         $denied{'copy'} = 1;
 4489:     } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
 4490:         my $group = $1;
 4491:         if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
 4492:             if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
 4493:                 my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
 4494:                 if (keys(%groupsettings) > 0) {
 4495:                     $denied{'remove'} = 1;
 4496:                 }
 4497:                 $denied{'cut'} = 1;
 4498:                 $denied{'copy'} = 1;
 4499:             }
 4500:         }
 4501:     } elsif ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
 4502:         my $group = $1;
 4503:         if ($url =~ /group_boards_\Q$group\E/) {
 4504:             if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
 4505:                 my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
 4506:                 if (keys(%groupsettings) > 0) {
 4507:                     if (ref($groupsettings{'functions'}) eq 'HASH') {
 4508:                         if ($groupsettings{'functions'}{'discussion'} eq 'on') {
 4509:                             $denied{'remove'} = 1;
 4510:                         }
 4511:                     }
 4512:                 }
 4513:                 $denied{'cut'} = 1;
 4514:                 $denied{'copy'} = 1;
 4515:             }
 4516:         }
 4517:     }
 4518:     return %denied;
 4519: }
 4520: 
 4521: sub new_timebased_suffix {
 4522:     my ($dom,$num,$type,$area,$container) = @_;
 4523:     my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
 4524:     if ($type eq 'paste') {
 4525:         $prefix = $type;
 4526:         $namespace = 'courseeditor';
 4527:         $idtype = 'addcode';
 4528:     } elsif ($type eq 'map') {
 4529:         $prefix = 'docs';
 4530:         if ($area eq 'supplemental') {
 4531:             $prefix = 'supp';
 4532:         }
 4533:         $prefix .= $container;
 4534:         $namespace = 'uploadedmaps';
 4535:     } else {
 4536:         $prefix = $type;
 4537:         $namespace = 'templated';
 4538:     }
 4539:     my ($suffix,$freedlock,$error) =
 4540:         &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,$dom,$num,$idtype);
 4541:     if (!$suffix) {
 4542:         if ($type eq 'paste') {
 4543:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix when adding to the paste buffer.');
 4544:         } elsif ($type eq 'map') {
 4545:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
 4546:         } elsif ($type eq 'smppg') {
 4547:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
 4548:         } elsif ($type eq 'exttool') {
 4549:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new external tool.');
 4550:         } else {
 4551:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new discussion board.');
 4552:         }
 4553:         if ($error) {
 4554:             $errtext .= '<br />'.$error;
 4555:         }
 4556:     }
 4557:     if ($freedlock ne 'ok') {
 4558:         $locknotfreed =
 4559:             '<div class="LC_error">'.
 4560:             &mt('There was a problem removing a lockfile.').' ';
 4561:         if ($type eq 'paste') {
 4562:             if ($freedlock eq 'nolock') {
 4563:                 $locknotfreed =
 4564:                     '<div class="LC_error">'.
 4565:                     &mt('A lockfile was not released when you added content to the clipboard earlier in this session.').' '.
 4566:  
 4567:                     &mt('As a result addition of items to the clipboard will be unavailable until your next log-in.');
 4568:             } else { 
 4569:                 $locknotfreed .=
 4570:                     &mt('This will prevent addition of items to the clipboard until your next log-in.');
 4571:             }
 4572:         } elsif ($type eq 'map') {
 4573:             $locknotfreed .=
 4574:                 &mt('This will prevent creation of additional folders or composite pages in this course.');
 4575:         } elsif ($type eq 'smppg') {
 4576:             $locknotfreed .=
 4577:                 &mt('This will prevent creation of additional simple pages in this course.');
 4578:         } elsif ($type eq 'exttool') {
 4579:             $locknotfreed .=
 4580:                 &mt('This will prevent creation of additional external tools in this course.');
 4581:         } else {
 4582:             $locknotfreed .=
 4583:                 &mt('This will prevent creation of additional discussion boards in this course.');
 4584:         }
 4585:         unless ($type eq 'paste') {
 4586:             $locknotfreed .=
 4587:                 ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
 4588:                         '<a href="/adm/helpdesk" target="_helpdesk">','</a>');
 4589:         }
 4590:         $locknotfreed .= '</div>';
 4591:     }
 4592:     return ($suffix,$errtext,$locknotfreed);
 4593: }
 4594: 
 4595: =pod
 4596: 
 4597: =item tiehash()
 4598: 
 4599: tie the hash
 4600: 
 4601: =cut
 4602: 
 4603: sub tiehash {
 4604:     my ($mode)=@_;
 4605:     $hashtied=0;
 4606:     if ($env{'request.course.fn'}) {
 4607: 	if ($mode eq 'write') {
 4608: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 4609: 		    &GDBM_WRCREAT(),0640)) {
 4610:                 $hashtied=2;
 4611: 	    }
 4612: 	} else {
 4613: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 4614: 		    &GDBM_READER(),0640)) {
 4615:                 $hashtied=1;
 4616: 	    }
 4617: 	}
 4618:     }
 4619: }
 4620: 
 4621: sub untiehash {
 4622:     if ($hashtied) { untie %hash; }
 4623:     $hashtied=0;
 4624:     return OK;
 4625: }
 4626: 
 4627: 
 4628: 
 4629: 
 4630: sub checkonthis {
 4631:     my ($r,$url,$level,$title,$checkstale)=@_;
 4632:     $url=&unescape($url);
 4633:     $alreadyseen{$url}=1;
 4634:     $r->rflush();
 4635:     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 4636:        $r->print("\n<br />");
 4637:        if ($level==0) {
 4638:            $r->print("<br />");
 4639:        }
 4640:        for (my $i=0;$i<=$level*5;$i++) {
 4641:            $r->print('&nbsp;');
 4642:        }
 4643:        $r->print('<a href="'.$url.'" target="cat">'.
 4644: 		 ($title?$title:$url).'</a> ');
 4645:        if ($url=~/^\/res\//) {
 4646:           my $updated;
 4647:           if (($checkstale) && ($url !~ m{^/res/lib/templates/}) &&
 4648:               ($url !~ /\.\d+\.\w+$/)) {
 4649:               $updated = &Apache::lonnet::remove_stale_resfile($url);
 4650:           }
 4651: 	  my $result=&Apache::lonnet::repcopy(
 4652:                               &Apache::lonnet::filelocation('',$url));
 4653:           if ($result eq 'ok') {
 4654:              $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 4655:              if ($updated) {
 4656:                  $r->print('<br />');
 4657:                  for (my $i=0;$i<=$level*5;$i++) {
 4658:                      $r->print('&nbsp;');
 4659:                  }
 4660:                  $r->print('- '.&mt('Outdated copy removed'));
 4661:              }
 4662:              $r->rflush();
 4663:              &Apache::lonnet::countacc($url);
 4664:              $url=~/\.(\w+)$/;
 4665:              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 4666: 		 $r->print('<br />');
 4667:                  $r->rflush();
 4668:                  for (my $i=0;$i<=$level*5;$i++) {
 4669:                      $r->print('&nbsp;');
 4670:                  }
 4671:                  $r->print('- '.&mt('Rendering:').' ');
 4672: 		 my ($errorcount,$warningcount)=split(/:/,
 4673: 	       &Apache::lonnet::ssi_body($url,
 4674: 			       ('grade_target'=>'web',
 4675: 				'return_only_error_and_warning_counts' => 1)));
 4676:                  if (($errorcount) ||
 4677:                      ($warningcount)) {
 4678: 		     if ($errorcount) {
 4679:                         $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
 4680:                           &mt('[quant,_1,error]',$errorcount).'</span>');
 4681:                      }
 4682: 		     if ($warningcount) {
 4683:                         $r->print('<span class="LC_warning">'.
 4684:                           &mt('[quant,_1,warning]',$warningcount).'</span>');
 4685:                      }
 4686:                  } else {
 4687:                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 4688:                  }
 4689:                  $r->rflush();
 4690:              }
 4691: 	     my $dependencies=
 4692:                 &Apache::lonnet::metadata($url,'dependencies');
 4693:              foreach my $dep (split(/\,/,$dependencies)) {
 4694: 		 if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 4695:                     &checkonthis($r,$dep,$level+1,'',$checkstale);
 4696:                  }
 4697:              }
 4698:           } elsif ($result eq 'unavailable') {
 4699:              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 4700:           } elsif ($result eq 'not_found') {
 4701: 	      unless ($url=~/\$/) {
 4702: 		  $r->print('<span class="LC_error">'.&mt('not found').'</span>');
 4703: 	      } else {
 4704: 		  $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
 4705: 	      }
 4706:           } else {
 4707:              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
 4708:           }
 4709:           if (($updated) && ($result ne 'ok')) {
 4710:               $r->print('<br />'.&mt('Outdated copy removed'));
 4711:           }
 4712:        }
 4713:     }
 4714: }
 4715: 
 4716: 
 4717: 
 4718: =pod
 4719: 
 4720: =item list_symbs()
 4721: 
 4722: List Content Identifiers
 4723: 
 4724: =cut
 4725: 
 4726: sub list_symbs {
 4727:     my ($r) = @_;
 4728: 
 4729:     my $crstype = &Apache::loncommon::course_type();
 4730:     $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
 4731:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
 4732:     $r->print(&startContentScreen('tools'));
 4733:     my $navmap = Apache::lonnavmaps::navmap->new();
 4734:     if (!defined($navmap)) {
 4735:         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
 4736:                   '<div class="LC_error">'.
 4737:                   &mt('Unable to retrieve information about course contents').
 4738:                   '</div>');
 4739:         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
 4740:     } else {
 4741:         $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
 4742:                   &Apache::loncommon::start_data_table().
 4743:                   &Apache::loncommon::start_data_table_header_row().
 4744:                   '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
 4745:                   &Apache::loncommon::end_data_table_header_row()."\n");
 4746:         my $count;
 4747:         foreach my $res ($navmap->retrieveResources()) {
 4748:             $r->print(&Apache::loncommon::start_data_table_row().
 4749:                       '<td>'.$res->compTitle().'</td>'.
 4750:                       '<td>'.$res->symb().'</td>'.
 4751:                       &Apache::loncommon::end_data_table_row());
 4752:             $count ++;
 4753:         }
 4754:         if (!$count) {
 4755:             $r->print(&Apache::loncommon::start_data_table_row().
 4756:                       '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
 4757:                       &Apache::loncommon::end_data_table_row()); 
 4758:         }
 4759:         $r->print(&Apache::loncommon::end_data_table());
 4760:     }
 4761:     $r->print(&endContentScreen());
 4762: }
 4763: 
 4764: sub contentverifyform {
 4765:     my ($r) = @_;
 4766:     my $crstype = &Apache::loncommon::course_type();
 4767:     $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
 4768:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
 4769:     $r->print(&startContentScreen('tools'));
 4770:     $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>');
 4771:     $r->print('<form method="post" action="/adm/coursedocs"><p>'.
 4772:               &mt('Include a check if files copied from elsewhere are up to date (will increase verification time)?').
 4773:               '&nbsp;<span class="LC_nobreak">'.
 4774:               '<label><input type="radio" name="checkstale" value="0" checked="checked" />'.
 4775:               &mt('No').'</label>'.('&nbsp;'x2).
 4776:               '<label><input type="radio" name="checkstale" value="1" />'.
 4777:               &mt('Yes').'</label></span></p><p>'.
 4778:               '<input type="submit" value="'.&mt('Verify content').' "/>'.
 4779:               '<input type="hidden" value="1" name="tools" />'.
 4780:               '<input type="hidden" value="1" name="verify" /></p></form>');
 4781:     $r->print(&endContentScreen());
 4782:     return;
 4783: }
 4784: 
 4785: sub verifycontent {
 4786:     my ($r,$checkstale) = @_;
 4787:     my $crstype = &Apache::loncommon::course_type();
 4788:     $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
 4789:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
 4790:     $r->print(&startContentScreen('tools'));
 4791:     $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
 4792:    $hashtied=0;
 4793:    undef %alreadyseen;
 4794:    %alreadyseen=();
 4795:    &tiehash();
 4796:    
 4797:    foreach my $key (keys(%hash)) {
 4798:        if ($hash{$key}=~/\.(page|sequence)$/) {
 4799: 	   if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
 4800: 	       $r->print('<hr /><span class="LC_error">'.
 4801: 			 &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
 4802: 			 &unescape($hash{$key}).'</span><br />'.
 4803: 			 &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
 4804: 	   }
 4805:        }
 4806:        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 4807:            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1},$checkstale);
 4808:        }
 4809:    }
 4810:    &untiehash();
 4811:    $r->print('<p class="LC_success">'.&mt('Done').'</p>');
 4812:     $r->print(&endContentScreen());
 4813: }
 4814: 
 4815: sub devalidateversioncache {
 4816:     my $src=shift;
 4817:     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
 4818: 					  &Apache::lonnet::clutter($src));
 4819: }
 4820: 
 4821: sub checkversions {
 4822:     my ($r,$canedit) = @_;
 4823:     my $crstype = &Apache::loncommon::course_type();
 4824:     $r->print(&Apache::loncommon::start_page("Check $crstype Resource Versions"));
 4825:     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Resource Versions"));
 4826:     $r->print(&startContentScreen('tools'));
 4827: 
 4828:     my $header='';
 4829:     my $startsel='';
 4830:     my $monthsel='';
 4831:     my $weeksel='';
 4832:     my $daysel='';
 4833:     my $allsel='';
 4834:     my %changes=();
 4835:     my $starttime=0;
 4836:     my $haschanged=0;
 4837:     my %setversions=&Apache::lonnet::dump('resourceversions',
 4838: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 4839: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 4840: 
 4841:     $hashtied=0;
 4842:     &tiehash();
 4843:     if ($canedit) {
 4844:         my %newsetversions=();
 4845:         if ($env{'form.setmostrecent'}) {
 4846: 	    $haschanged=1;
 4847: 	    foreach my $key (keys(%hash)) {
 4848: 	        if ($key=~/^ids\_(\/res\/.+)$/) {
 4849: 		    $newsetversions{$1}='mostrecent';
 4850:                     &devalidateversioncache($1);
 4851: 	        }
 4852: 	    }
 4853:         } elsif ($env{'form.setcurrent'}) {
 4854: 	    $haschanged=1;
 4855: 	    foreach my $key (keys(%hash)) {
 4856: 	        if ($key=~/^ids\_(\/res\/.+)$/) {
 4857: 		    my $getvers=&Apache::lonnet::getversion($1);
 4858: 		    if ($getvers>0) {
 4859: 		        $newsetversions{$1}=$getvers;
 4860: 		        &devalidateversioncache($1);
 4861: 		    }
 4862: 	        }
 4863: 	    }
 4864:         } elsif ($env{'form.setversions'}) {
 4865: 	    $haschanged=1;
 4866: 	    foreach my $key (keys(%env)) {
 4867: 	        if ($key=~/^form\.set_version_(.+)$/) {
 4868: 		    my $src=$1;
 4869: 		    if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
 4870: 		        $newsetversions{$src}=$env{$key};
 4871: 		        &devalidateversioncache($src);
 4872: 		    }
 4873: 	        }
 4874: 	    }
 4875:         }
 4876:         if ($haschanged) {
 4877:             if (&Apache::lonnet::put('resourceversions',\%newsetversions,
 4878: 			             $env{'course.'.$env{'request.course.id'}.'.domain'},
 4879: 			             $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 4880: 	        $r->print(&Apache::loncommon::confirmwrapper(
 4881:                     &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
 4882: 	    } else {
 4883: 	        $r->print(&Apache::loncommon::confirmwrapper(
 4884:                     &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
 4885: 	    }
 4886: 	    &mark_hash_old();
 4887:         }
 4888:         &changewarning($r,'');
 4889:     }
 4890:     if ($env{'form.timerange'} eq 'all') {
 4891: # show all documents
 4892: 	$header=&mt('All content in '.$crstype);
 4893: 	$allsel=' selected="selected"';
 4894: 	foreach my $key (keys(%hash)) {
 4895: 	    if ($key=~/^ids\_(\/res\/.+)$/) {
 4896: 		my $src=$1;
 4897: 		$changes{$src}=1;
 4898: 	    }
 4899: 	}
 4900:     } else {
 4901: # show documents which changed
 4902: 	%changes=&Apache::lonnet::dump
 4903: 	 ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
 4904:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 4905: 	my $firstkey=(keys(%changes))[0];
 4906: 	unless ($firstkey=~/^error\:/) {
 4907: 	    unless ($env{'form.timerange'}) {
 4908: 		$env{'form.timerange'}=604800;
 4909: 	    }
 4910: 	    my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 4911: 		.&mt('seconds');
 4912: 	    if ($env{'form.timerange'}==-1) {
 4913: 		$seltext='since start of course';
 4914: 		$startsel=' selected="selected"';
 4915: 		$env{'form.timerange'}=time;
 4916: 	    }
 4917: 	    $starttime=time-$env{'form.timerange'};
 4918: 	    if ($env{'form.timerange'}==2592000) {
 4919: 		$seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 4920: 		$monthsel=' selected="selected"';
 4921: 	    } elsif ($env{'form.timerange'}==604800) {
 4922: 		$seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 4923: 		$weeksel=' selected="selected"';
 4924: 	    } elsif ($env{'form.timerange'}==86400) {
 4925: 		$seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 4926: 		$daysel=' selected="selected"';
 4927: 	    }
 4928: 	    $header=&mt('Content changed').' '.$seltext;
 4929: 	} else {
 4930: 	    $header=&mt('No content modifications yet.');
 4931: 	}
 4932:     }
 4933:     %setversions=&Apache::lonnet::dump('resourceversions',
 4934: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 4935: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 4936:     my %lt=&Apache::lonlocal::texthash
 4937: 	      ('st' => 'Version changes since start of '.$crstype,
 4938: 	       'lm' => 'Version changes since last Month',
 4939: 	       'lw' => 'Version changes since last Week',
 4940: 	       'sy' => 'Version changes since Yesterday',
 4941:                'al' => 'All Resources (possibly large output)',
 4942:                'cd' => 'Change display', 
 4943: 	       'sd' => 'Display',
 4944: 	       'fi' => 'File',
 4945: 	       'md' => 'Modification Date',
 4946:                'mr' => 'Most recently published Version',
 4947: 	       've' => 'Version used in '.$crstype,
 4948:                'vu' => 'Set Version to be used in '.$crstype,
 4949: 'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
 4950: 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 4951: 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 4952: 	       'di' => 'Differences',
 4953: 	       'save' => 'Save changes',
 4954:                'vers' => 'Version choice(s) for specific resources', 
 4955: 	       'act' => 'Actions');
 4956:     my ($disabled,$readonly);
 4957:     unless ($canedit) {
 4958:         $disabled = 'disabled="disabled"';
 4959:         $readonly = 1;
 4960:     }
 4961:     $r->print(<<ENDHEADERS);
 4962: <h4 class="LC_info">$header</h4>
 4963: <form action="/adm/coursedocs" method="post">
 4964: <input type="hidden" name="versions" value="1" />
 4965: <div class="LC_left_float">
 4966: <fieldset>
 4967: <legend>$lt{'cd'}</legend>
 4968: <select name="timerange">
 4969: <option value='all'$allsel>$lt{'al'}</option>
 4970: <option value="-1"$startsel>$lt{'st'}</option>
 4971: <option value="2592000"$monthsel>$lt{'lm'}</option>
 4972: <option value="604800"$weeksel>$lt{'lw'}</option>
 4973: <option value="86400"$daysel>$lt{'sy'}</option>
 4974: </select>
 4975: <input type="submit" name="display" value="$lt{'sd'}" />
 4976: </fieldset>
 4977: </div>
 4978: <div class="LC_left_float">
 4979: <fieldset>
 4980: <legend>$lt{'act'}</legend>
 4981: $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" $disabled /><br />
 4982: $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" $disabled />
 4983: </fieldset>
 4984: </div>
 4985: <br clear="all" />
 4986: <hr />
 4987: <h4>$lt{'vers'}</h4>
 4988: ENDHEADERS
 4989:     #number of columns for version history
 4990:     my %changedbytime;
 4991:     foreach my $key (keys(%changes)) {
 4992:         #excludes not versionable problems from resource version history:
 4993:         next if ($key =~ /^\/res\/lib\/templates/);
 4994:         my $chg;
 4995:         if ($env{'form.timerange'} eq 'all') {
 4996:             my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
 4997:             $chg = &Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate');
 4998:         } else {
 4999:             $chg = $changes{$key};
 5000:             next if ($chg < $starttime);
 5001:         }
 5002:         push(@{$changedbytime{$chg}},$key);
 5003:     }
 5004:     if (keys(%changedbytime) == 0) {
 5005:         &untiehash();
 5006:         $r->print(&mt('No content changes in imported content in specified time frame').
 5007:                   &endContentScreen());
 5008:         return;
 5009:     }
 5010:     $r->print(
 5011:        '<input type="submit" name="setversions" value="'.$lt{'save'}.'"'.$disabled.' />'.
 5012:         &Apache::loncommon::start_data_table().
 5013:         &Apache::loncommon::start_data_table_header_row().
 5014:         '<th>'.&mt('Resources').'</th>'.
 5015:         "<th>$lt{'mr'}</th>".
 5016:         "<th>$lt{'ve'}</th>".
 5017:         "<th>$lt{'vu'}</th>".
 5018:         '<th>'.&mt('History').'</th>'.
 5019:         &Apache::loncommon::end_data_table_header_row()
 5020:     );
 5021:     foreach my $chg (sort {$b <=> $a } keys(%changedbytime)) {
 5022:         foreach my $key (sort(@{$changedbytime{$chg}})) {
 5023:             my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
 5024:             my $currentversion=&Apache::lonnet::getversion($key);
 5025:             if ($currentversion<0) {
 5026:                 $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
 5027:             }
 5028:             my $linkurl=&Apache::lonnet::clutter($key);
 5029:             $r->print(
 5030:                 &Apache::loncommon::start_data_table_row().
 5031:                 '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
 5032:                 '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
 5033:                 '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
 5034:                 &Apache::lonlocal::locallocaltime($chg).')</span></td>'.
 5035:                 '<td align="right">'
 5036:             );
 5037:             # Used in course
 5038:             my $usedversion=$hash{'version_'.$linkurl};
 5039:             if (($usedversion) && ($usedversion ne 'mostrecent')) {
 5040:                 if ($usedversion != $currentversion) {
 5041:                     $r->print('<span class="LC_warning">'.$usedversion.'</span>');
 5042:                 } else {
 5043:                     $r->print($usedversion);
 5044:                 }
 5045:             } else {
 5046:                 $r->print($currentversion);
 5047:             }
 5048:             $r->print('</td><td title="'.$lt{'vu'}.'">');
 5049:             # Set version
 5050:             $r->print(&Apache::loncommon::select_form(
 5051:                       $setversions{$linkurl},
 5052:                       'set_version_'.$linkurl,
 5053:                       {'select_form_order' => ['',1..$currentversion,'mostrecent'],
 5054:                       '' => '',
 5055:                       'mostrecent' => &mt('most recent'),
 5056:                       map {$_,$_} (1..$currentversion)},'',$readonly));
 5057:             my $lastold=1;
 5058:             for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
 5059:                 my $url=$root.'.'.$prevvers.'.'.$extension;
 5060:                 if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
 5061:                     $lastold=$prevvers;
 5062:                 }
 5063:             }
 5064:             $r->print('</td>');
 5065:             # List all available versions
 5066:             $r->print('<td valign="top"><span class="LC_fontsize_medium">');
 5067:             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
 5068:                 my $url=$root.'.'.$prevvers.'.'.$extension;
 5069:                 $r->print(
 5070:                     '<span class="LC_nobreak">'
 5071:                    .'<a href="'.&Apache::lonnet::clutter($url).'">'
 5072:                    .&mt('Version [_1]',$prevvers).'</a>'
 5073:                    .' ('.&Apache::lonlocal::locallocaltime(
 5074:                          &Apache::lonnet::metadata($url,'lastrevisiondate'))
 5075:                    .')');
 5076:                 if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
 5077:                     $r->print(
 5078:                         ' <a href="/adm/diff?filename='.
 5079:                         &Apache::lonnet::clutter($root.'.'.$extension).
 5080:                         &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
 5081:                         '" target="diffs">'.&mt('Diffs').'</a>');
 5082:                 }
 5083:                 $r->print('</span><br />');
 5084:             }
 5085:             $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
 5086:         }
 5087:     }
 5088:     $r->print(
 5089:         &Apache::loncommon::end_data_table().
 5090:         '<input type="submit" name="setversions" value="'.$lt{'save'}.'"'.$disabled.' />'.
 5091:         '</form>'
 5092:     );
 5093: 
 5094:     &untiehash();
 5095:     $r->print(&endContentScreen());
 5096:     return;
 5097: }
 5098: 
 5099: sub mark_hash_old {
 5100:     my $retie_hash=0;
 5101:     if ($hashtied) {
 5102: 	$retie_hash=1;
 5103: 	&untiehash();
 5104:     }
 5105:     &tiehash('write');
 5106:     $hash{'old'}=1;
 5107:     &untiehash();
 5108:     if ($retie_hash) { &tiehash(); }
 5109: }
 5110: 
 5111: sub is_hash_old {
 5112:     my $untie_hash=0;
 5113:     if (!$hashtied) {
 5114: 	$untie_hash=1;
 5115: 	&tiehash();
 5116:     }
 5117:     my $return=$hash{'old'};
 5118:     if ($untie_hash) { &untiehash(); }
 5119:     return $return;
 5120: }
 5121: 
 5122: sub changewarning {
 5123:     my ($r,$postexec,$message,$url)=@_;
 5124:     if (!&is_hash_old()) { return; }
 5125:     my $pathvar='folderpath';
 5126:     my $path=&escape($env{'form.folderpath'});
 5127:     if (!defined($url)) {
 5128: 	$url='/adm/coursedocs?'.$pathvar.'='.$path;
 5129:     }
 5130:     my $course_type = &Apache::loncommon::course_type();
 5131:     if (!defined($message)) {
 5132: 	$message='Changes will become active for your current session after [_1], or the next time you log in.';
 5133:     }
 5134:     $r->print("\n\n".
 5135: '<script type="text/javascript">'."\n".
 5136: '// <![CDATA['."\n".
 5137: 'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
 5138: '// ]]>'."\n".
 5139: '</script>'."\n".
 5140: '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 5141: '<input type="hidden" name="orgurl" value="'.$url.
 5142: '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
 5143: &mt($message,' <input type="hidden" name="'.
 5144:     $env{'request.role'}.'" value="1" /><input type="button" value="'.
 5145:     &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
 5146: $help{'Caching'}.'</p></form>'."\n\n");
 5147: }
 5148: 
 5149: 
 5150: sub init_breadcrumbs {
 5151:     my ($form,$text,$help)=@_;
 5152:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5153:     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
 5154: 					    text=>&Apache::loncommon::course_type().' Editor',
 5155: 					    faq=>273,
 5156: 					    bug=>'Instructor Interface',
 5157:                                             help => $help});
 5158:     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
 5159: 					    text=>$text,
 5160: 					    faq=>273,
 5161: 					    bug=>'Instructor Interface'});
 5162: }
 5163: 
 5164: # subroutine to list form elements
 5165: sub create_list_elements {
 5166:    my @formarr = @_;
 5167:    my $list = '';
 5168:    foreach my $button (@formarr){
 5169:         foreach my $picture (keys(%{$button})) {
 5170:             $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
 5171:         }
 5172:    }
 5173:    return $list;
 5174: }
 5175: 
 5176: # subroutine to create ul from list elements
 5177: sub create_form_ul {
 5178:    my $list = shift;
 5179:    my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
 5180:    return $ul;
 5181: }
 5182: 
 5183: #
 5184: # Start tabs
 5185: #
 5186: 
 5187: sub startContentScreen {
 5188:     my ($mode) = @_;
 5189:     my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
 5190:     if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
 5191:         $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";
 5192:         $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";
 5193:         $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";
 5194:         $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
 5195:     } else {
 5196:         $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";
 5197:         $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
 5198:         $output .= '<li '.(($mode eq 'tools')?' class="active"':'').'><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
 5199:                    '><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>';
 5200:     }
 5201:     $output .= "\n".'</ul>'."\n";
 5202:     $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
 5203:                '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
 5204:                '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
 5205:     return $output;
 5206: }
 5207: 
 5208: #
 5209: # End tabs
 5210: #
 5211: 
 5212: sub endContentScreen {
 5213:     return '</div></div></div>';
 5214: }
 5215: 
 5216: sub supplemental_base {
 5217:     return 'supplemental&'.&escape(&mt('Supplemental Content'));
 5218: }
 5219: 
 5220: sub handler {
 5221:     my $r = shift;
 5222:     &Apache::loncommon::content_type($r,'text/html');
 5223:     $r->send_http_header;
 5224:     return OK if $r->header_only;
 5225: 
 5226: # get course data
 5227:     my $crstype = &Apache::loncommon::course_type();
 5228:     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 5229:     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5230: 
 5231: # get docroot
 5232:     my $londocroot = $r->dir_config('lonDocRoot');
 5233: 
 5234: # graphics settings
 5235:     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
 5236: 
 5237: #
 5238: # --------------------------------------------- Initialize help topics for this
 5239:     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
 5240: 	               'Adding_External_Resource','Adding_External_Tool',
 5241:                        'Navigate_Content','Adding_Folders','Docs_Overview',
 5242: 	               'Load_Map','Supplemental','Score_Upload_Form',
 5243: 	               'Adding_Pages','Importing_LON-CAPA_Resource',
 5244: 	               'Importing_IMS_Course','Uploading_From_Harddrive',
 5245:                        'Course_Roster','Web_Page','Dropbox','Simple_Problem') {
 5246: 	$help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 5247:     }
 5248:     # Composite help files
 5249:     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 5250: 		    'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 5251:     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 5252: 		    'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 5253:     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 5254: 		    'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 5255:     $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
 5256: 		  'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 5257:     $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 5258:     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 5259:  
 5260:     my ($allowed,$canedit,$canview,$noendpage,$disabled);
 5261: # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
 5262:     unless ($r->uri eq '/adm/supplemental') {
 5263:         # does this user have privileges to modify content.  
 5264:         if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 5265:             $allowed = 1;
 5266:             $canedit = 1;
 5267:             $canview = 1;
 5268:         } elsif (&Apache::lonnet::allowed('cev',$env{'request.course.id'})) {
 5269:             $allowed = 1;
 5270:             $canview = 1;
 5271:         }
 5272:     }
 5273:     unless ($canedit) {
 5274:         $disabled = ' disabled="disabled"';
 5275:     }
 5276:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
 5277:     if ($env{'form.inhibitmenu'}) {
 5278:         unless ($env{'form.inhibitmenu'} eq 'yes') {
 5279:             delete($env{'form.inhibitmenu'});
 5280:         }
 5281:     }
 5282: 
 5283:   if ($allowed && $env{'form.verify'}) {
 5284:       &init_breadcrumbs('verify','Verify Content','Docs_Verify_Content');
 5285:       if (!$canedit) {
 5286:           &verifycontent($r);
 5287:       } elsif (($env{'form.checkstale'} ne '') && ($env{'form.checkstale'} =~ /^\d$/)) {
 5288:           &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1&verify=1&checkstale=$env{'form.checkstale'}",
 5289:                                                   text=>'Results',
 5290:                                                   faq=>273,
 5291:                                                   bug=>'Instructor Interface'});
 5292:           &verifycontent($r,$env{'form.checkstale'});
 5293:       } else {
 5294:           &contentverifyform($r);
 5295:       }
 5296:   } elsif ($allowed && $env{'form.listsymbs'}) {
 5297:       &init_breadcrumbs('listsymbs','List Content IDs');
 5298:       &list_symbs($r);
 5299:   } elsif ($allowed && $env{'form.docslog'}) {
 5300:       &init_breadcrumbs('docslog','Show Log');
 5301:       my $folder = $env{'form.folder'};
 5302:       if ($folder eq '') {
 5303:           $folder='default';
 5304:       }
 5305:       &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath,$canedit);
 5306:   } elsif ($allowed && $env{'form.versions'}) {
 5307:       &init_breadcrumbs('versions','Check/Set Resource Versions','Docs_Check_Resource_Versions');
 5308:       &checkversions($r,$canedit);
 5309:   } elsif ($canedit && $env{'form.dumpcourse'}) {
 5310:       &init_breadcrumbs('dumpcourse','Copy '.&Apache::loncommon::course_type().' Content to Authoring Space');
 5311:       &dumpcourse($r);
 5312:   } elsif ($canedit && $env{'form.exportcourse'}) {
 5313:       &init_breadcrumbs('exportcourse','IMS Export');
 5314:       &Apache::imsexport::exportcourse($r);
 5315:   } else {
 5316:       if ($canedit && $env{'form.authorrole'}) {
 5317:           $noendpage = 1;
 5318:           my ($redirect,$error) = &makenewproblem($r,$coursedom,$coursenum);
 5319:           if ($redirect) {
 5320:               if (($env{'form.newresourceadd'}) && ($env{'form.folderpath'})) {
 5321:                   my $container = 'sequence'; 
 5322:                   my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
 5323:                       $is_random_order,$container) =
 5324:                       &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 5325:                   my (@folders)=split('&',$env{'form.folderpath'});
 5326:                   $env{'form.foldername'}=&unescape(pop(@folders));
 5327:                   my $folder=pop(@folders);
 5328:                   my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 5329:                                                   $folder.'.'.$container);
 5330:                   my $warning;
 5331:                   if ($fatal) {
 5332:                       if ($container eq 'page') {
 5333:                           $warning = &mt('An error occurred retrieving the contents of the current page.');
 5334:                       } else {
 5335:                           $warning = &mt('An error occurred retrieving the contents of the current folder.');
 5336:                       }
 5337:                   } else {
 5338:                       my $url = $redirect;
 5339:                       my $srcfile = $londocroot.$url;
 5340:                       $url =~ s{^/priv/}{/res/};
 5341:                       my $targetfile = $londocroot.$url;
 5342:                       my $nokeyref = &Apache::lonpublisher::getnokey($r->dir_config('lonIncludes'));
 5343:                       my $output = &Apache::lonpublisher::batchpublish($r,$srcfile,$targetfile,$nokeyref,1);
 5344:                       $env{'form.folder'} = $folder;
 5345:                       &snapshotbefore();
 5346:                       my $title = &LONCAPA::map::qtunescape($env{'form.newresourcetitle'});
 5347:                       my $ext = 'false';
 5348:                       my $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
 5349:                       $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
 5350:                                                         ':'.$ext.':normal:res';
 5351:                       push(@LONCAPA::map::order,$newidx);
 5352:                       &LONCAPA::map::storeparameter($newidx,'parameter_hiddenresource','yes',
 5353:                                                    'string_yesno');
 5354:                       &remember_parms($newidx,'hiddenresource','set','yes');
 5355:                       ($errtext,$fatal) =
 5356:                           &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
 5357:                       &log_differences($plain);
 5358:                       &mark_hash_old();
 5359:                       $r->internal_redirect($redirect);
 5360:                       return OK;
 5361:                   }
 5362:               }
 5363:           }
 5364:       }
 5365: #
 5366: # Done catching special calls
 5367: # The whole rest is for course and supplemental documents and utilities menu
 5368: # Get the parameters that may be needed
 5369: #
 5370:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5371:                                             ['folderpath',
 5372:                                              'forcesupplement','forcestandard',
 5373:                                              'tools','symb','command','supppath']);
 5374: 
 5375:     foreach my $item ('forcesupplement','forcestandard','tools') {
 5376:         next if ($env{'form.'.$item} eq '');
 5377:         unless ($env{'form.'.$item} eq '1') {
 5378:             delete($env{'form.'.$item});
 5379:         }
 5380:     }
 5381: 
 5382:     if ($env{'form.command'}) {
 5383:         unless ($env{'form.command'} =~ /^(direct|directnav|editdocs|editsupp|contents|home)$/) {
 5384:             delete($env{'form.command'});
 5385:         }
 5386:     }
 5387: 
 5388:     if ($env{'form.symb'}) {
 5389:         my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
 5390:         unless (($id =~ /^\d+$/) && (&Apache::lonnet::is_on_map($resurl))) { 
 5391:             delete($env{'form.symb'});
 5392:         }
 5393:     }
 5394: 
 5395: # standard=1: this is a "new-style" course with an uploaded map as top level
 5396: # standard=2: this is a "old-style" course, and there is nothing we can do
 5397: 
 5398:     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 5399: 
 5400: # Decide whether this should display supplemental or main content or utilities
 5401: # supplementalflag=1: show supplemental documents
 5402: # supplementalflag=0: show standard documents
 5403: # toolsflag=1: show utilities
 5404: 
 5405:     my $unesc_folderpath = &unescape($env{'form.folderpath'});
 5406:     my $supplementalflag=($unesc_folderpath=~/^supplemental/);
 5407:     if (($unesc_folderpath=~/^default/) || ($unesc_folderpath eq "")) {
 5408:        $supplementalflag=0;
 5409:     }
 5410:     if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 5411:     if ($env{'form.forcestandard'})   { $supplementalflag=0; }
 5412:     unless ($allowed) { $supplementalflag=1; }
 5413:     unless ($standard) { $supplementalflag=1; }
 5414:     my $toolsflag=0;
 5415:     if ($env{'form.tools'}) { $toolsflag=1; }
 5416: 
 5417:     if ($env{'form.folderpath'} ne '') {
 5418:         my @items = split(/\&/,$env{'form.folderpath'});
 5419:         my $badpath;
 5420:         for (my $i=0; $i<@items; $i++) {
 5421:             my $odd = $i%2;
 5422:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
 5423:                 $badpath = 1;
 5424:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
 5425:                 $badpath = 1;
 5426:             }
 5427:             last if ($badpath);
 5428:         }
 5429:         if ($badpath) {
 5430:             delete($env{'form.folderpath'});
 5431:         }
 5432:     }
 5433: 
 5434:     if ($env{'form.supppath'} ne '') {
 5435:         my @items = split(/\&/,$env{'form.supppath'});
 5436:         my $badpath;
 5437:         for (my $i=0; $i<@items; $i++) {
 5438:             my $odd = $i%2;
 5439:             if ((!$odd) && ($items[$i] !~ /^supplemental(|_\d+)$/)) {
 5440:                 $badpath = 1; 
 5441:             }
 5442:             last if ($badpath);
 5443:         }
 5444:         if ($badpath) {
 5445:             delete($env{'form.supppath'});
 5446:         }
 5447:     }
 5448: 
 5449:     my $script='';
 5450:     my $showdoc=0;
 5451:     my $addentries = {};
 5452:     my $container;
 5453:     my $containertag;
 5454:     my $pathitem;
 5455:     my %ltitools;
 5456:     my $hiddentop;
 5457:     my $navmap;
 5458:     my $filterFunc = sub { my $res = shift; return (!$res->randomout() && !$res->is_map()) };
 5459: 
 5460: # Do we directly jump somewhere?
 5461:    if (($env{'form.command'} eq 'direct') || ($env{'form.command'} eq 'directnav')) {
 5462:        if ($env{'form.symb'} ne '') {
 5463:            $env{'form.folderpath'}=
 5464:                &Apache::loncommon::symb_to_docspath($env{'form.symb'},\$navmap);
 5465:            &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
 5466:                $env{'form.command'}.'_'.$env{'form.symb'}});
 5467:        } elsif ($env{'form.supppath'} ne '') {
 5468:            $env{'form.folderpath'}=$env{'form.supppath'};
 5469:            &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
 5470:                $env{'form.command'}.'_'.$env{'form.supppath'}});
 5471:        }
 5472:    } elsif ($env{'form.command'} eq 'editdocs') {
 5473:        $env{'form.folderpath'} = &default_folderpath($coursenum,$coursedom,\$navmap);
 5474:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => $env{'form.command'}});
 5475:    } elsif ($env{'form.command'} eq 'editsupp') {
 5476:        $env{'form.folderpath'} = &supplemental_base();
 5477:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/supplemental'});
 5478:    } elsif ($env{'form.command'} eq 'contents') {
 5479:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/navmaps'});
 5480:    } elsif ($env{'form.command'} eq 'home') {
 5481:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/menu'});
 5482:    }
 5483: 
 5484: 
 5485: # Where do we store these for when we come back?
 5486:     my $stored_folderpath='docs_folderpath';
 5487:     if ($supplementalflag) {
 5488:        $stored_folderpath='docs_sup_folderpath';
 5489:     }
 5490: 
 5491: # No folderpath, and in edit mode, see if we have something stored
 5492:     if ((!$env{'form.folderpath'}) && $allowed) {
 5493:         &Apache::loncommon::restore_course_settings($stored_folderpath,
 5494:                                           {'folderpath' => 'scalar'});
 5495: 
 5496:         if (&unescape($env{'form.folderpath'}) =~ m{^(default|supplemental)&}) {
 5497:             if ($supplementalflag) {
 5498:                 undef($env{'form.folderpath'}) if ($1 eq 'default'); 
 5499:             } else {
 5500:                 undef($env{'form.folderpath'}) if ($1 eq 'supplemental');
 5501:             }
 5502:         } else {
 5503:             undef($env{'form.folderpath'});
 5504:         }
 5505:     }
 5506:    
 5507: # If we are not allowed to make changes, all we can see are supplemental docs
 5508:     if (!$allowed) {
 5509:         unless ($env{'form.folderpath'} =~ /^supplemental/) {
 5510:             $env{'form.folderpath'} = &supplemental_base();
 5511:         }
 5512:     }
 5513: # Make the zeroth entry in supplemental docs page paths, so we can get to top level
 5514:     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 5515:         $env{'form.folderpath'} = &supplemental_base()
 5516:                                   .'&'.
 5517:                                   $env{'form.folderpath'};
 5518:     }
 5519: # If allowed and user's role is not advanced check folderpath is not hidden  
 5520:     if (($allowed) && (!$env{'request.role.adv'}) && 
 5521:         ($env{'form.folderpath'} ne '') && (!$supplementalflag)) {
 5522:         my $folderurl;
 5523:         my @pathitems = split(/\&/,$env{'form.folderpath'});
 5524:         my $folder = $pathitems[-2];
 5525:         if ($folder eq '') {
 5526:             undef($env{'form.folderpath'});
 5527:         } else {
 5528:             $folderurl = "uploaded/$coursedom/$coursenum/$folder";
 5529:             if ((split(/\:/,$pathitems[-1]))[4]) {
 5530:                 $folderurl .= '.page';
 5531:             } else {
 5532:                 $folderurl .= '.sequence';
 5533:             }
 5534:             unless (ref($navmap)) {
 5535:                 $navmap = Apache::lonnavmaps::navmap->new();
 5536:             }
 5537:             if (ref($navmap)) {
 5538:                 if (lc($navmap->get_mapparam(undef,$folderurl,"0.hiddenresource")) eq 'yes') {
 5539:                     my @resources = $navmap->retrieveResources($folderurl,$filterFunc,1,1);
 5540:                     unless (@resources) {
 5541:                         undef($env{'form.folderpath'});
 5542:                     }
 5543:                 }
 5544:             }
 5545:         }
 5546:     }
 5547: 
 5548: 
 5549: # If after all of this, we still don't have any paths, make them
 5550:     unless ($env{'form.folderpath'}) {
 5551:        if ($supplementalflag) {
 5552:           $env{'form.folderpath'}=&supplemental_base();
 5553:        } elsif ($allowed) {
 5554:           ($env{'form.folderpath'},$hiddentop) = &default_folderpath($coursenum,$coursedom,\$navmap);
 5555:        }
 5556:     }
 5557: 
 5558: # Store this
 5559:     unless ($toolsflag) {
 5560:         if (($allowed) && ($env{'form.folderpath'} ne '')) {
 5561:             &Apache::loncommon::store_course_settings($stored_folderpath,
 5562:                                                       {'folderpath' => 'scalar'});
 5563:         }
 5564:         my $folderpath;
 5565:         if ($env{'form.folderpath'}) {
 5566:             $folderpath = $env{'form.folderpath'};
 5567: 	    my (@folders)=split('&',$env{'form.folderpath'});
 5568: 	    $env{'form.foldername'}=&unescape(pop(@folders));
 5569:             if ($env{'form.foldername'} =~ /\:1$/) {
 5570:                 $container = 'page';
 5571:             } else {
 5572:                 $container = 'sequence';
 5573:             }
 5574: 	    $env{'form.folder'}=pop(@folders);
 5575:         } else {
 5576:             if ($env{'form.folder'} eq '' ||
 5577:                 $env{'form.folder'} eq 'supplemental') {
 5578:                 if ($env{'form.folder'} eq 'supplemental') {
 5579:                     $folderpath=&supplemental_base();
 5580:                 } elsif (!$hiddentop) {
 5581:                     $folderpath='default&'.
 5582:                                  &escape(&mt('Main Content').':::::');
 5583:                 }
 5584:             }
 5585:         }
 5586:         $containertag = '<input type="hidden" name="folderpath" value="" />';
 5587:         $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
 5588:         if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 5589:            $showdoc='/'.$1;
 5590:         }
 5591:         if ($showdoc) { # got called in sequence from course
 5592: 	    $allowed=0; 
 5593:         } else {
 5594:             if ($canedit) {
 5595:                 &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
 5596:                 $script=&Apache::lonratedt::editscript('simple');
 5597:             }
 5598:         }
 5599:     }
 5600: 
 5601: # get personal data
 5602:     my $uname=$env{'user.name'};
 5603:     my $udom=$env{'user.domain'};
 5604:     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 5605: 
 5606:     if ($allowed) {
 5607:         if ($toolsflag) {
 5608:             $script .= &inject_data_js();
 5609:             my ($home,$other,%outhash)=&authorhosts();
 5610:             if (!$home && $other) {
 5611:                 my @hosts;
 5612:                 foreach my $aurole (keys(%outhash)) {
 5613:                     unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
 5614:                         push(@hosts,$outhash{$aurole});
 5615:                     }
 5616:                 }
 5617:                 $script .= &dump_switchserver_js(@hosts); 
 5618:             }
 5619:         } else {
 5620:             my $tid = 1;
 5621:             my @tabids;
 5622:             if ($supplementalflag) {
 5623:                 @tabids = ('002','ee2','ff2');
 5624:                 $tid = 2;
 5625:             } else {
 5626:                 @tabids = ('aa1','bb1','cc1','ff1');
 5627:                 unless ($env{'form.folderpath'} =~ /\:1$/) {
 5628:                     unshift(@tabids,'001');
 5629:                     push(@tabids,('dd1','ee1'));
 5630:                 }
 5631:             }
 5632:             my $tabidstr = join("','",@tabids);
 5633:             %ltitools = &Apache::lonnet::get_domain_lti($coursedom,'consumer');
 5634:             my $posslti = keys(%ltitools);
 5635:             my $hostname = $r->hostname();
 5636: 	    $script .= &editing_js($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
 5637:                                    $londocroot,$canedit,$hostname,\$navmap).
 5638:                        &history_tab_js().
 5639:                        &inject_data_js().
 5640:                        &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr,$tid).
 5641:                        &Apache::lonextresedit::extedit_javascript(\%ltitools);
 5642:             $addentries = {
 5643:                             onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
 5644:                           };
 5645:         }
 5646:         $script .= &paste_popup_js(); 
 5647:         my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
 5648:                              &mt('Switch server?');
 5649:         
 5650: 
 5651:     }
 5652: # -------------------------------------------------------------------- Body tag
 5653:     $script = '<script type="text/javascript">'."\n"
 5654:               .'// <![CDATA['."\n"
 5655:               .$script."\n"
 5656:               .'// ]]>'."\n"
 5657:               .'</script>'."\n"
 5658:               .'<script type="text/javascript" 
 5659:                 src="/res/adm/includes/file_upload.js"></script>'."\n";
 5660: 
 5661:     # Breadcrumbs
 5662:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5663: 
 5664:     if ($showdoc) {
 5665:         $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
 5666:                                                 {'force_register' => $showdoc,}));
 5667:     } elsif ($toolsflag) {
 5668:         my ($breadtext,$breadtitle);
 5669:         $breadtext = "$crstype Editor";
 5670:         if ($canedit) {
 5671:             $breadtitle = 'Editing '.$crstype.' Contents';
 5672:         } else {
 5673:             $breadtext .= ' (View-only mode)';
 5674:             $breadtitle = 'Viewing '.$crstype.' Contents';
 5675:         }
 5676:         &Apache::lonhtmlcommon::add_breadcrumb({
 5677:             href=>"/adm/coursedocs",text=>$breadtext});
 5678:         $r->print(&Apache::loncommon::start_page("$crstype Contents", $script)
 5679:                  .&Apache::loncommon::help_open_menu('','',273,'RAT')
 5680:                  .&Apache::lonhtmlcommon::breadcrumbs(
 5681:                      $breadtitle)
 5682:                  );
 5683:     } elsif ($r->uri eq '/adm/supplemental') {
 5684:         my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype);
 5685:         $r->print(&Apache::loncommon::start_page("Supplemental $crstype Content",undef,
 5686:                                                 {'bread_crumbs' => $brcrum,}));
 5687:     } else {
 5688:         my ($breadtext,$breadtitle,$helpitem);
 5689:         $breadtext = "$crstype Editor";
 5690:         if ($canedit) {
 5691:             $breadtitle = 'Editing '.$crstype.' Contents';
 5692:             $helpitem = 'Docs_Adding_Course_Doc';
 5693:         } else {
 5694:             $breadtext .= ' (View-only mode)';
 5695:             $breadtitle = 'Viewing '.$crstype.' Contents';
 5696:             $helpitem = 'Docs_Viewing_Course_Doc';
 5697:         }
 5698:         &Apache::lonhtmlcommon::add_breadcrumb({
 5699:             href=>"/adm/coursedocs",text=>$breadtext});
 5700:         $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
 5701:                                                  {'add_entries'    => $addentries}
 5702:                                                 )
 5703:                  .&Apache::loncommon::help_open_menu('','',273,'RAT')
 5704:                  .&Apache::lonhtmlcommon::breadcrumbs(
 5705:                      $breadtitle,
 5706:                      $helpitem)
 5707:         );
 5708:     }
 5709: 
 5710:   my %allfiles = ();
 5711:   my %codebase = ();
 5712:   my ($upload_result,$upload_output,$uploadphase);
 5713:   if ($canedit) {
 5714:       if (($env{'form.uploaddoc.filename'}) &&
 5715: 	  ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 5716:           my $context = $1; 
 5717:           # Process file upload - phase one - upload and parse primary file.
 5718: 	  undef($hadchanges);
 5719:           $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
 5720:                                               \%allfiles,\%codebase,$context,$crstype);
 5721:           undef($navmap);
 5722: 	  if ($hadchanges) {
 5723: 	      &mark_hash_old();
 5724: 	  }
 5725:           $r->print($upload_output);
 5726:       } elsif ($env{'form.phase'} eq 'upload_embedded') {
 5727:           # Process file upload - phase two - upload embedded objects 
 5728:           $uploadphase = 'check_embedded';
 5729:           my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
 5730:           my $state = &embedded_form_elems($uploadphase,$primaryurl,
 5731:                                            $env{'form.newidx'});
 5732:           my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5733:           my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5734:           my ($destination,$dir_root) = &embedded_destination();
 5735:           my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
 5736:           my $actionurl = '/adm/coursedocs';
 5737:           my ($result,$flag) =
 5738:               &Apache::loncommon::upload_embedded('coursedoc',$destination,
 5739:                   $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
 5740:                   $actionurl);
 5741:           $r->print($result.&return_to_editor());
 5742:       } elsif ($env{'form.phase'} eq 'check_embedded') {
 5743:           # Process file upload - phase three - modify references in HTML file
 5744:           $uploadphase = 'modified_orightml';
 5745:           my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5746:           my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5747:           my ($destination,$dir_root) = &embedded_destination();
 5748:           my $result =
 5749:               &Apache::loncommon::modify_html_refs('coursedoc',$destination,
 5750:                                                    $docuname,$docudom,undef,
 5751:                                                    $dir_root);
 5752:           $r->print($result.&return_to_editor());
 5753:       } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
 5754:           $uploadphase = 'decompress_phase_one';
 5755:           $r->print(&decompression_phase_one().
 5756:                     &return_to_editor());
 5757:       } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
 5758:           $uploadphase = 'decompress_phase_two';
 5759:           $r->print(&decompression_phase_two().
 5760:                     &return_to_editor());
 5761:       }
 5762:   }
 5763: 
 5764:   if ($allowed && $toolsflag) {
 5765:       $r->print(&startContentScreen('tools'));
 5766:       $r->print(&generate_admin_menu($crstype,$canedit));
 5767:       $r->print(&endContentScreen());
 5768:   } elsif ((!$showdoc) && (!$uploadphase)) {
 5769: # -----------------------------------------------------------------------------
 5770:        my %lt=&Apache::lonlocal::texthash(
 5771: 		'copm' => 'All documents out of a published map into this folder',
 5772:                 'upfi' => 'Upload File',
 5773:                 'upld' => 'Upload Content',
 5774:                 'srch' => 'Search',
 5775:                 'impo' => 'Import',
 5776: 		'lnks' => 'Import from Stored Links',
 5777:                 'impm' => 'Import from Assembled Map',
 5778:                 'imcr' => 'Import from Course Resources',
 5779:                 'extr' => 'External Resource',
 5780:                 'extt' => 'External Tool',
 5781:                 'selm' => 'Select Map',
 5782:                 'load' => 'Load Map',
 5783:                 'newf' => 'New Folder',
 5784:                 'newp' => 'New Composite Page',
 5785:                 'syll' => 'Syllabus',
 5786:                 'navc' => 'Table of Contents',
 5787:                 'sipa' => 'Simple Course Page',
 5788:                 'sipr' => 'Simple Problem',
 5789:                 'webp' => 'Blank Web Page (editable)',
 5790:                 'stpr' => 'Standard Problem',
 5791:                 'news' => 'New sub-directory',
 5792:                 'crpr' => 'Create Problem',
 5793:                 'drbx' => 'Drop Box',
 5794:                 'scuf' => 'External Scores (handgrade, upload, clicker)',
 5795:                 'bull' => 'Discussion Board',
 5796:                 'mypi' => 'My Personal Information Page',
 5797:                 'grpo' => 'Group Portfolio',
 5798:                 'rost' => 'Course Roster',
 5799:                 'abou' => 'Personal Information Page for a User',
 5800:                 'imsf' => 'IMS Upload',
 5801:                 'imsl' => 'Upload IMS package',
 5802:                 'cms'  => 'Origin of IMS package',
 5803:                 'se'   => 'Select',
 5804:                 'file' =>  'File',
 5805:                 'title' => 'Title',
 5806:                 'addp' => 'Add Placeholder to course?',
 5807:                 'uste' => 'Use Template?',
 5808:                 'fnam' => 'File Name:',
 5809:                 'loca' => 'Location:',
 5810:                 'dire' => 'Directory:',
 5811:                 'cate' => 'Category:',
 5812:                 'tmpl' => 'Template:',
 5813:                 'comment' => 'Comment',
 5814:                 'parse' => 'Upload embedded images/multimedia files if HTML file',
 5815:                 'bb5'      => 'Blackboard 5',
 5816:                 'bb6'      => 'Blackboard 6',
 5817:                 'angel5'   => 'ANGEL 5.5',
 5818:                 'webctce4' => 'WebCT 4 Campus Edition',
 5819:                 'yes'      => 'Yes',
 5820:                 'no'       => 'No',
 5821:                 'er' => 'Editing rights unavailable for your current role.',
 5822:         );
 5823: # -----------------------------------------------------------------------------
 5824: 
 5825:     # Calculate free quota space for a user or course. A javascript function checks
 5826:     # file size to determine if upload should be allowed.
 5827:     my $quotatype = 'unofficial';
 5828:     if ($crstype eq 'Community') {
 5829:         $quotatype = 'community';
 5830:     } elsif ($crstype eq 'Placement') {
 5831:         $quotatype = 'placement';
 5832:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.coursecode'}) {
 5833:         $quotatype = 'official';
 5834:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.textbook'}) {
 5835:         $quotatype = 'textbook';
 5836:     }
 5837:     my $disk_quota = &Apache::loncommon::get_user_quota($coursenum,$coursedom,
 5838:                      'course',$quotatype); # expressed in MB
 5839:     my $current_disk_usage = 0;
 5840:     foreach my $subdir ('docs','supplemental') {
 5841:         $current_disk_usage += &Apache::lonnet::diskusage($coursedom,$coursenum,
 5842:                                "userfiles/$subdir",1); # expressed in kB
 5843:     }
 5844:     my $free_space = 1024 * ((1024 * $disk_quota) - $current_disk_usage);
 5845:     my $usage = $current_disk_usage/1024; # in MB
 5846:     my $quota = $disk_quota;
 5847:     my $percent;
 5848:     if ($disk_quota == 0) {
 5849:         $percent = 100.0;
 5850:     } else {
 5851:         $percent = 100*($usage/$disk_quota);
 5852:     }
 5853:     $usage = sprintf("%.2f",$usage);
 5854:     $quota = sprintf("%.2f",$quota);
 5855:     $percent = sprintf("%.0f",$percent);
 5856:     my $quotainfo = '<p>'.&mt('Currently using [_1] of the [_2] available.',
 5857:                               $percent.'%',$quota.' MB').'</p>';
 5858: 
 5859: 	my $fileupload=(<<FIUP);
 5860:         $quotainfo
 5861: 	$lt{'file'}:<br />
 5862: 	<input type="file" name="uploaddoc" class="flUpload" size="40" $disabled />
 5863:         <input type="hidden" id="free_space" value="$free_space" />
 5864: FIUP
 5865: 
 5866: 	my $checkbox=(<<CHBO);
 5867: 	<!-- <label>$lt{'parse'}?
 5868: 	<input type="checkbox" name="parserflag" />
 5869: 	</label> -->
 5870: 	<label>
 5871: 	<input type="checkbox" name="parserflag" checked="checked" $disabled /> $lt{'parse'}
 5872: 	</label>
 5873: CHBO
 5874:         my $imsfolder = $env{'form.folder'};
 5875:         if ($imsfolder eq '') {
 5876:             $imsfolder = 'default';  
 5877:         }
 5878:         my $imspform=(<<IMSFORM);
 5879:         <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
 5880:         $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
 5881:         <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
 5882:         <fieldset id="uploadimsform" style="display: none;">
 5883:         <legend>$lt{'imsf'}</legend>
 5884:         $fileupload
 5885:         <br />
 5886:         <p>
 5887:         $lt{'cms'}:&nbsp; 
 5888:         <select name="source" $disabled>
 5889:         <option value="-1" selected="selected">$lt{'se'}</option>
 5890:         <option value="bb5">$lt{'bb5'}</option>
 5891:         <option value="bb6">$lt{'bb6'}</option>
 5892:         <option value="angel5">$lt{'angel5'}</option>
 5893:         <option value="webctce4">$lt{'webctce4'}</option>
 5894:         </select>
 5895:         <input type="hidden" name="folder" value="$imsfolder" />
 5896:         </p>
 5897:         <input type="hidden" name="phase" value="one" />
 5898:         <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" $disabled />
 5899:         </fieldset>
 5900:         </form>
 5901: IMSFORM
 5902: 
 5903: 	my $fileuploadform=(<<FUFORM);
 5904:         <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
 5905:         $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
 5906:         <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 5907:         <fieldset id="uploaddocform" style="display: none;">
 5908:         <legend>$lt{'upfi'}</legend>
 5909: 	<input type="hidden" name="active" value="aa" />
 5910:     $fileupload
 5911: 	<br />
 5912: 	$lt{'title'}:<br />
 5913: 	<input type="text" size="60" name="comment" $disabled />
 5914: 	$pathitem
 5915: 	<input type="hidden" name="cmd" value="upload_default" />
 5916: 	<br />
 5917: 	<span class="LC_nobreak" style="float:left">
 5918: 	$checkbox
 5919: 	</span>
 5920:         <br clear="all" />
 5921:         <input type="submit" value="$lt{'upld'}" $disabled />
 5922:         </fieldset>
 5923:         </form>
 5924: FUFORM
 5925: 
 5926:         my $mapimportjs;
 5927:         if ($canedit) {
 5928:             $mapimportjs = "javascript:openbrowser('mapimportform','importmap','sequence,page','');"; 
 5929:         } else {
 5930:             $mapimportjs = "javascript:alert('".&js_escape($lt{'er'})."');";
 5931:         }
 5932: 	my $importpubform=(<<SEDFFORM);
 5933:         <a class="LC_menubuttons_link" href="javascript:toggleMap('map');">
 5934:         $lt{'impm'}</a>$help{'Load_Map'}
 5935: 	<form action="/adm/coursedocs" method="post" name="mapimportform">
 5936:         <fieldset id="importmapform" style="display: none;">
 5937:         <legend>$lt{'impm'}</legend>
 5938: 	<input type="hidden" name="active" value="bb" />
 5939:         $lt{'copm'}<br />
 5940:         <span class="LC_nobreak">
 5941:         <input type="text" name="importmap" size="40" value="" 
 5942:         onfocus="this.blur();$mapimportjs" $disabled />
 5943:         &nbsp;<a href="$mapimportjs">$lt{'selm'}</a></span><br />
 5944:         <input type="submit" name="loadmap" value="$lt{'load'}" $disabled />
 5945:         </fieldset>
 5946:         </form>
 5947: 
 5948: SEDFFORM
 5949:         my $importcrsresform;
 5950:         my ($numdirs,$pickfile) = 
 5951:             &Apache::loncommon::import_crsauthor_form('crsresimportform','coursepath','coursefile',
 5952:                                                       "resize_scrollbox('contentscroll','1','0');",
 5953:                                                       undef,'res');
 5954:         if ($pickfile) {
 5955:             $importcrsresform=(<<CRSFORM);
 5956:         <a class="LC_menubuttons_link" href="javascript:toggleImportCrsres('res','$numdirs');">
 5957:         $lt{'imcr'}</a>$help{'Course_Resources'}
 5958:         <form action="/adm/coursedocs" method="post" name="crsresimportform" onsubmit="return validImportCrsRes();">
 5959:         <fieldset id="importcrsresform" style="display: none;">
 5960:         <legend>$lt{'imcr'}</legend>
 5961:         <input type="hidden" name="active" value="bb" />
 5962:         $pickfile
 5963:         <p>
 5964:         $lt{'title'}: <input type="textbox" name="crsrestitle" value="" $disabled />
 5965:         </p>
 5966:         <input type="hidden" name="importdetail" value="" />
 5967:         <input type="submit" name="crsres" value="$lt{'impo'}" $disabled />
 5968:         </fieldset>
 5969:         </form>
 5970: CRSFORM
 5971:         }
 5972: 
 5973:         my $fromstoredjs;
 5974:         if ($canedit) {
 5975:             $fromstoredjs = 'open_StoredLinks_Import()'; 
 5976:         } else {
 5977:             $fromstoredjs = "alert('".&js_escape($lt{'er'})."')";
 5978:         }
 5979: 
 5980: 	my @importpubforma = (
 5981: 	{ '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => $pathitem."<a class='LC_menubuttons_link' href='javascript:groupsearch()'>$lt{'srch'}</a>" },
 5982: 	{ '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{impo}.'"  onclick="javascript:groupimport();"/>' => "<a class='LC_menubuttons_link' href='javascript:groupimport();'>$lt{'impo'}</a>$help{'Importing_LON-CAPA_Resource'}" },
 5983: 	{ '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{lnks}.'" onclick="javascript:'.$fromstoredjs.';" />' => '<a class="LC_menubuttons_link" href="javascript:'.$fromstoredjs.';">'.$lt{'lnks'}.'</a>' },
 5984:         { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/sequence.png" alt="'.$lt{impm}.'" onclick="javascript:toggleMap(\'map\');" />' => $importpubform },
 5985:         );
 5986:         if ($pickfile) {
 5987:             push(@importpubforma,{ '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{imcr}.'"  onclick="javascript:toggleImportCrsres(\'res\','."'$numdirs'".');"/>' => $importcrsresform});
 5988: 	}
 5989: 	$importpubform = &create_form_ul(&create_list_elements(@importpubforma));
 5990:         my $extresourcesform =
 5991:             &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
 5992:                                                  $help{'Adding_External_Resource'},
 5993:                                                  undef,undef,undef,undef,undef,undef,$disabled);
 5994:         my $exttoolform =
 5995:             &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
 5996:                                                  $help{'Adding_External_Tool'},undef,
 5997:                                                  undef,'tool',$coursedom,$coursenum,
 5998:                                                  \%ltitools,$disabled);
 5999:     if ($allowed) {
 6000:         my $folder = $env{'form.folder'};
 6001:         if ($folder eq '') {
 6002:             $folder='default';
 6003:         }
 6004:         if ($canedit) {
 6005: 	    my $output = &update_paste_buffer($coursenum,$coursedom,$folder);
 6006:             if ($output) {
 6007:                 $r->print($output);
 6008:             }
 6009:         }
 6010: 	$r->print(<<HIDDENFORM);
 6011: 	<form name="renameform" method="post" action="/adm/coursedocs">
 6012:    <input type="hidden" name="title" />
 6013:    <input type="hidden" name="cmd" />
 6014:    <input type="hidden" name="markcopy" />
 6015:    <input type="hidden" name="copyfolder" />
 6016:    $containertag
 6017:  </form>
 6018:  <form name="aliasform" method="post" action="/adm/coursedocs">
 6019:    <input type="hidden" name="alias" />
 6020:    <input type="hidden" name="cmd" />
 6021:    $containertag
 6022:  </form>
 6023: 
 6024: HIDDENFORM
 6025:         $r->print(&makesimpleeditform($pathitem)."\n".
 6026:                   &makedocslogform($pathitem."\n".
 6027:                                    '<input type="hidden" name="folder" value="'.
 6028:                                    $env{'form.folder'}.'" />'."\n"));
 6029:     }
 6030: 
 6031: # Generate the tabs
 6032:     my ($mode,$needs_end);
 6033:     if (($supplementalflag) && (!$allowed)) {
 6034:         my @folders = split('&',$env{'form.folderpath'});
 6035:         unless (@folders > 2) {
 6036:             &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
 6037:             $needs_end = 1;
 6038:         }
 6039:     } else {
 6040:         $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
 6041:         $needs_end = 1;
 6042:     }
 6043: 
 6044: #
 6045:     my $hostname = $r->hostname();
 6046:     my $savefolderpath;
 6047: 
 6048:     if ($allowed) {
 6049:        my $folder=$env{'form.folder'};
 6050:        if ((($folder eq '') && (!$hiddentop)) || ($supplementalflag)) {
 6051:            $folder='default';
 6052: 	   $savefolderpath = $env{'form.folderpath'};
 6053: 	   $env{'form.folderpath'}='default&'.&escape(&mt('Main Content'));
 6054:            $pathitem = '<input type="hidden" name="folderpath" value="'.
 6055: 	       &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 6056:        }
 6057:        my $postexec='';
 6058:        if ($folder eq 'default') {
 6059:            $r->print('<script type="text/javascript">'."\n"
 6060:                     .'// <![CDATA['."\n"
 6061:                     .'this.window.name="loncapaclient";'."\n"
 6062:                     .'// ]]>'."\n"
 6063:                     .'</script>'."\n"
 6064:        );
 6065:        } else {
 6066:            #$postexec='self.close();';
 6067:        }
 6068:        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.sequence';
 6069:        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.page';
 6070: 	my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 6071: 
 6072: 	my $newnavform=(<<NNFORM);
 6073: 	<form action="/adm/coursedocs" method="post" name="newnav">
 6074: 	<input type="hidden" name="active" value="ee" />
 6075: 	$pathitem
 6076: 	<input type="hidden" name="importdetail" 
 6077: 	value="$lt{'navc'}=/adm/navmaps" />
 6078: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newnav);">$lt{'navc'}</a>
 6079: 	$help{'Navigate_Content'}
 6080: 	</form>
 6081: NNFORM
 6082: 	my $newsmppageform=(<<NSPFORM);
 6083: 	<form action="/adm/coursedocs" method="post" name="newsmppg">
 6084: 	<input type="hidden" name="active" value="ee" />
 6085: 	$pathitem
 6086: 	<input type="hidden" name="importdetail" value="" />
 6087: 	<a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
 6088: 	$help{'Simple Page'}
 6089: 	</form>
 6090: NSPFORM
 6091: 
 6092: 	my $newsmpproblemform=(<<NSPROBFORM);
 6093: 	<form action="/adm/coursedocs" method="post" name="newsmpproblem">
 6094: 	<input type="hidden" name="active" value="cc" />
 6095: 	$pathitem
 6096: 	<input type="hidden" name="importdetail" value="" />
 6097: 	<a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
 6098: 	$help{'Simple_Problem'}
 6099: 	</form>
 6100: 
 6101: NSPROBFORM
 6102: 
 6103: 	my $newdropboxform=(<<NDBFORM);
 6104: 	<form action="/adm/coursedocs" method="post" name="newdropbox">
 6105: 	<input type="hidden" name="active" value="cc" />
 6106: 	$pathitem
 6107: 	<input type="hidden" name="importdetail" value="" />
 6108: 	<a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
 6109:         $help{'Dropbox'}
 6110: 	</form>
 6111: NDBFORM
 6112: 
 6113: 	my $newexuploadform=(<<NEXUFORM);
 6114: 	<form action="/adm/coursedocs" method="post" name="newexamupload">
 6115: 	<input type="hidden" name="active" value="cc" />
 6116: 	$pathitem
 6117: 	<input type="hidden" name="importdetail" value="" />
 6118: 	<a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
 6119: 	$help{'Score_Upload_Form'}
 6120: 	</form>
 6121: NEXUFORM
 6122: 
 6123: 	my $newbulform=(<<NBFORM);
 6124: 	<form action="/adm/coursedocs" method="post" name="newbul">
 6125: 	<input type="hidden" name="active" value="dd" />
 6126: 	$pathitem
 6127: 	<input type="hidden" name="importdetail" value="" />
 6128: 	<a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
 6129: 	$help{'Bulletin Board'}
 6130: 	</form>
 6131: NBFORM
 6132: 
 6133: 	my $newaboutmeform=(<<NAMFORM);
 6134: 	<form action="/adm/coursedocs" method="post" name="newaboutme">
 6135: 	<input type="hidden" name="active" value="dd" />
 6136: 	$pathitem
 6137: 	<input type="hidden" name="importdetail" 
 6138: 	value="$plainname=/adm/$udom/$uname/aboutme" />
 6139: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newaboutme);">$lt{'mypi'}</a>
 6140: 	$help{'My Personal Information Page'}
 6141: 	</form>
 6142: NAMFORM
 6143: 
 6144: 	my $newaboutsomeoneform=(<<NASOFORM);
 6145: 	<form action="/adm/coursedocs" method="post" name="newaboutsomeone">
 6146: 	<input type="hidden" name="active" value="dd" />
 6147: 	$pathitem
 6148: 	<input type="hidden" name="importdetail" value="" />
 6149: 	<a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
 6150: 	</form>
 6151: NASOFORM
 6152: 
 6153: 	my $newrosterform=(<<NROSTFORM);
 6154: 	<form action="/adm/coursedocs" method="post" name="newroster">
 6155: 	<input type="hidden" name="active" value="dd" />
 6156: 	$pathitem
 6157: 	<input type="hidden" name="importdetail" 
 6158: 	value="$lt{'rost'}=/adm/viewclasslist" />
 6159: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newroster);">$lt{'rost'}</a>
 6160: 	$help{'Course_Roster'}
 6161: 	</form>
 6162: NROSTFORM
 6163: 
 6164:         my $newwebpage;
 6165:         if ($folder =~ /^default_?(\d*)$/) {
 6166:             $newwebpage = "/uploaded/$coursedom/$coursenum/docs/";
 6167:             if ($1) {
 6168:                 $newwebpage .= $1;
 6169:             } else {
 6170:                 $newwebpage .= 'default';
 6171:             }
 6172:             $newwebpage .= '/new.html';
 6173:         }
 6174:         my $newwebpageform =(<<NWEBFORM);
 6175:         <form action="/adm/coursedocs" method="post" name="newwebpage">
 6176:         <input type="hidden" name="active" value="ee" />
 6177:         $pathitem
 6178:         <input type="hidden" name="importdetail" value="$newwebpage" />
 6179:         <a class="LC_menubuttons_link" href="javascript:makewebpage();">$lt{'webp'}</a>
 6180:         $help{'Web_Page'}
 6181:         </form>
 6182: NWEBFORM
 6183: 
 6184:         my @ids=&Apache::lonnet::current_machine_ids();
 6185:         my %select_menus;
 6186:         my $numauthor = 0;
 6187:         my $numcrsdirs = 0;
 6188:         my $toppath = "/priv/$env{'user.domain'}/$env{'user.name'}"; 
 6189:         if ($env{'user.author'}) {
 6190:             $numauthor ++;
 6191:             $select_menus{'author'}->{'text'} = &Apache::lonnet::plaintext('au');
 6192:             if (grep(/^\Q$env{'user.home'}\E$/,@ids)) {
 6193:                 my $is_home = 1;
 6194:                 my %subdirs;
 6195:                 &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$toppath,'',\%subdirs);
 6196:                 $select_menus{'author'}->{'default'} = '/'; 
 6197:                 $select_menus{'author'}->{'select2'}->{'/'} = '/';
 6198:                 my @ordered = ('/');
 6199:                 foreach my $relpath (sort { lc($a) cmp lc($b) } (keys(%subdirs))) {
 6200:                     $select_menus{'author'}->{'select2'}->{$relpath} = $relpath;
 6201:                     push(@ordered,$relpath);
 6202:                 }
 6203:                 $select_menus{'author'}->{'order'} = \@ordered;
 6204:             } else {
 6205:                 $select_menus{'author'}->{'select2'}->{'switch'} = &mt('Switch server required');
 6206:                 $select_menus{'author'}->{'default'} = 'switch';
 6207:                 $select_menus{'author'}->{'order'} = ['switch'];
 6208:             }
 6209:         }
 6210:         my %roleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',
 6211:                                                       ['active'],['ca','aa']);
 6212:         my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 6213:         my %by_roletype;
 6214:         if (keys(%roleshash)) {
 6215:             foreach my $entry (keys(%roleshash)) {
 6216:                 my ($auname,$audom,$roletype) = split(/:/,$entry);
 6217:                 my $key = $entry;
 6218:                 $key =~ s/:/___/g;
 6219:                 $by_roletype{$roletype}{$auname.'___'.$audom} = 1;
 6220:                 $select_menus{$key}->{'text'} = &Apache::lonnet::plaintext($roletype)." ($audom/$auname)";
 6221:                 my $rolehome = &Apache::lonnet::homeserver($auname,$audom);
 6222:                 if (grep(/^\Q$rolehome\E$/,@ids)) {    
 6223:                     my $is_home = 1;
 6224:                     my (%subdirs,@ordered);
 6225:                     my $toppath="/priv/$audom/$auname";
 6226:                     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$toppath,'',\%subdirs);
 6227:                     $select_menus{$key}->{'default'} = '/';
 6228:                     $select_menus{$key}->{'select2'}->{'/'} = '/';
 6229:                     my @ordered = ('/');
 6230:                     foreach my $relpath (sort { lc($a) cmp lc($b) } (keys(%subdirs))) {
 6231:                         $select_menus{$key}->{'select2'}->{$relpath} = $relpath;
 6232:                         push(@ordered,$relpath);
 6233:                     }
 6234:                     $select_menus{$key}->{'order'} = \@ordered;
 6235:                 } else {
 6236:                     $select_menus{$key}->{'select2'}->{'switch'} = &mt('Switch server required');
 6237:                     $select_menus{$key}->{'default'} = 'switch';
 6238:                     $select_menus{$key}->{'order'} = ['switch'];
 6239:                 }
 6240:                 $numauthor ++;
 6241:             }
 6242:         }
 6243:         my ($pickdir,$showtitle);
 6244:         if ($numauthor) {
 6245:             my @order;
 6246:             my $defrole;
 6247:             if ($env{'user.author'}) {
 6248:                 push(@order,'author');
 6249:                 $defrole = 'author';
 6250:             }
 6251:             if (keys(%by_roletype)) {
 6252:                 foreach my $possrole ('ca','aa') {
 6253:                     if (ref($by_roletype{$possrole}) eq 'HASH') {
 6254:                         foreach my $author (sort { lc($a) cmp lc($b) } (keys(%{$by_roletype{$possrole}}))) {
 6255:                             unless ($defrole) {
 6256:                                 $defrole = $author;
 6257:                             }
 6258:                             push(@order,$author.'___'.$possrole);
 6259:                         }
 6260:                     }
 6261:                 }
 6262:             }
 6263:             $select_menus{'course'}->{'text'} = &mt('Course Resource');
 6264:             if (grep(/^\Q$crshome\E$/,@ids)) {
 6265:                 my $is_home = 1;
 6266:                 my %subdirs;
 6267:                 my $toppath="/priv/$coursedom/$coursenum";
 6268:                 &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$toppath,'',\%subdirs);
 6269:                 $numcrsdirs = keys(%subdirs);
 6270:                 $select_menus{'course'}->{'default'} = '/';
 6271:                 $select_menus{'course'}->{'select2'}->{'/'} = '/';
 6272:                 my @ordered = ('/');
 6273:                 foreach my $relpath (sort { lc($a) cmp lc($b) } (keys(%subdirs))) {
 6274:                     $select_menus{'course'}->{'select2'}->{$relpath} = $relpath;
 6275:                     push(@ordered,$relpath);
 6276:                 }
 6277:                 $select_menus{'course'}->{'order'} = \@ordered;
 6278:             } else {
 6279:                 $select_menus{'course'}->{'select2'}->{'switch'} = &mt('Switch server required');
 6280:                 $select_menus{'course'}->{'default'} = 'switch';
 6281:                 $select_menus{'course'}->{'order'} = ['switch'];
 6282:             }
 6283:             push(@order,'course');
 6284:             $pickdir = $lt{'loca'}.
 6285:                        &Apache::loncommon::linked_select_forms('courseresform','<br />'.$lt{'dire'},
 6286:                                                                $defrole,'authorrole','authorpath',
 6287:                                                                \%select_menus,\@order,'toggleCrsResTitle();',
 6288:                                                                '','priv').'<br />';
 6289:             $showtitle = 'none';
 6290:         } else {
 6291:             my $is_home;
 6292:             $showtitle = 'inline';
 6293:             if (grep(/^\Q$crshome\E$/,@ids)) {
 6294:                 $is_home = 1;
 6295:                 $pickdir .= '<input type="hidden" name="authorrole" value="course" />'; 
 6296:                 my $toppath="/priv/$coursedom/$coursenum'}";
 6297:                 my %subdirs;
 6298:                 &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$toppath,'',\%subdirs);
 6299:                 $numcrsdirs = keys(%subdirs); 
 6300:                 if ($numcrsdirs) {
 6301:                     $pickdir .= &mt('Directory: ').'<select name="authorpath">'."\n".
 6302:                                  '<option value="/">/</option>'."\n";
 6303:                     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%subdirs))) {
 6304:                         $pickdir .= '<option value="'.$key.'">'.$key.'</option>'."\n";
 6305:                     }
 6306:                     $pickdir .= '</select>';
 6307:                 } else {
 6308:                     $pickdir .= '<input type="hidden" name="authorpath" value="/" />'."\n";   
 6309:                 }
 6310:             }
 6311:         }
 6312: 
 6313:         my %seltemplate_menus;
 6314:         my @files = &Apache::lonhomework::get_template_list('problem');
 6315:         my @noexamplelink = ('blank.problem','blank.library','script.library');
 6316:         my $currentcategory = '';
 6317:         my @ordered = ('');
 6318:         my %templatehelp;
 6319:         my $defcategory = '';
 6320:         my @catorder = ($defcategory);
 6321:         $seltemplate_menus{$defcategory}->{'order'} = [''];
 6322:         $seltemplate_menus{$defcategory}->{'text'} = '';
 6323:         foreach my $file (@files) {
 6324:             if (ref($file) eq 'ARRAY') {
 6325:                 my ($path,$title,$category,$help) = @{$file};
 6326:                 next if ($title !~ /\S/);
 6327:                 if (&js_escape($category) ne $currentcategory) {
 6328:                     $currentcategory = &js_escape($category);
 6329:                     push(@catorder,&js_escape($currentcategory));
 6330:                     $seltemplate_menus{$currentcategory}->{'text'} = $category;
 6331:                     $seltemplate_menus{$currentcategory}->{'default'} = '';
 6332:                     $seltemplate_menus{$currentcategory}->{'select2'}->{''} = '';
 6333:                     push(@{$seltemplate_menus{$currentcategory}->{'order'}},'');
 6334:                 }
 6335:                 if ($path) {
 6336:                     $seltemplate_menus{$currentcategory}->{'select2'}->{&js_escape($path)} = $title;
 6337:                     push(@{$seltemplate_menus{$currentcategory}->{'order'}},&js_escape($path));
 6338:                     if ($help) {
 6339:                         $templatehelp{$path} = $help;
 6340:                     }
 6341:                 }
 6342:             }
 6343:         }
 6344: 
 6345:         my $templates = $lt{'cate'}.' '.
 6346:                         &Apache::loncommon::linked_select_forms('courseresform','<br />'.$lt{'tmpl'}.' ',
 6347:                                                                 $defcategory,'tempcategory','template',
 6348:                                                                 \%seltemplate_menus,\@catorder,
 6349:                                                                 "resize_scrollbox('contentscroll','1','0');",
 6350:                                                                 "toggleExampleText();",'template').'<br />';
 6351:         my $templatepreview =  '<a href="#" target="sample" onclick="javascript:getExample(600,420,\'yes\',true);  return false;">'.
 6352:                                '<span id="newresexample">'.&mt('Example').'<span></a>';
 6353:         my $crsresform=(<<RESFORM);
 6354:         <a class="LC_menubuttons_link" href="javascript:toggleCrsRes('res','$numauthor','$numcrsdirs');">
 6355:         $lt{'stpr'}</a>$help{'Course_Resource'}
 6356:         <form action="/adm/coursedocs" method="post" name="courseresform">
 6357:         <fieldset id="crsresform" style="display:none;">
 6358:         <legend>$lt{'stpr'}</legend>
 6359:         <input type="hidden" name="active" value="ee" />
 6360:         <p>
 6361:         $pickdir
 6362:         <span class="LC_nobreak">$lt{'news'}?&nbsp;
 6363:         <label><input type="radio" name="newsubdir" value="0" onclick="toggleNewsubdir(this.form);" checked="checked" $disabled />No</label>
 6364:         &nbsp;
 6365:         <label><input type="radio" name="newsubdir" value="1" onclick="toggleNewsubdir(this.form);" $disabled />Yes</label>
 6366:         </span><span id="newsubdir"></span>
 6367:         <input type="hidden" name="newsubdirname" id="newsubdirname" value="" autocomplete="off" />
 6368:         </p>
 6369:         $lt{'fnam'}
 6370:         <input type="text" size="20" name="newresourcename" autocomplete="off" $disabled />
 6371:         <p>
 6372:         <div id="newresource" style="display:$showtitle">
 6373:         $lt{'addp'}
 6374:         <label><input type="radio" name="newresourceadd" value="0" checked="checked" onclick="toggleNewInCourse(this.form);" $disabled />
 6375:         $lt{'no'}</label>&nbsp;&nbsp;
 6376:         <label><input type="radio" name="newresourceadd" value="1" onclick="toggleNewInCourse(this.form);" $disabled />
 6377:         $lt{'yes'}</label>
 6378:         <span id="newrestitle"></span>
 6379:         <input type="hidden" size="20" name="newresourcetitle" id="newresourcetitle" autocomplete="off" $disabled />
 6380:         </div>
 6381:         </p>
 6382:         <p>
 6383:         $lt{'uste'}
 6384:         <label><input type="radio" name="newresusetemp" value="0" checked="checked" onclick="toggleWithTemplate(this.form);" $disabled />
 6385:         $lt{'no'}</label>&nbsp;&nbsp;
 6386:         <label><input type="radio" name="newresusetemp" value="1" onclick="toggleWithTemplate(this.form);" $disabled />
 6387:         $lt{'yes'}</label>
 6388:         <div id="newrestemplate" style="display:none">
 6389:         $templates
 6390:         $templatepreview
 6391:         </div>
 6392:         </p>
 6393:         <span class="LC_nobreak">
 6394:         <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 6395:         <input type="submit" name="newcrs" value="$lt{'crpr'}" $disabled />
 6396:         </span>
 6397:         </fieldset>
 6398:         </form>
 6399: 
 6400: RESFORM
 6401: 
 6402: my $specialdocumentsform;
 6403: my @specialdocumentsforma;
 6404: my $gradingform;
 6405: my @gradingforma;
 6406: my $communityform;
 6407: my @communityforma;
 6408: my $newfolderform;
 6409: my $newfolderb;
 6410: 
 6411: 	my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 6412: 	
 6413: 	my $newpageform=(<<NPFORM);
 6414: 	<form action="/adm/coursedocs" method="post" name="newpage">
 6415: 	<input type="hidden" name="folderpath" value="$path" />
 6416: 	<input type="hidden" name="importdetail" value="" />
 6417: 	<input type="hidden" name="active" value="ee" />
 6418: 	<a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
 6419: 	$help{'Adding_Pages'}
 6420: 	</form>
 6421: NPFORM
 6422: 
 6423: 
 6424: 	$newfolderform=(<<NFFORM);
 6425: 	<form action="/adm/coursedocs" method="post" name="newfolder">
 6426: 	$pathitem
 6427: 	<input type="hidden" name="importdetail" value="" />
 6428: 	<input type="hidden" name="active" value="" />
 6429: 	<a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
 6430: 	</form>
 6431: NFFORM
 6432: 
 6433: 	my $newsylform=(<<NSYLFORM);
 6434: 	<form action="/adm/coursedocs" method="post" name="newsyl">
 6435: 	<input type="hidden" name="active" value="ee" />
 6436: 	$pathitem
 6437: 	<input type="hidden" name="importdetail" 
 6438: 	value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
 6439: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newsyl);">$lt{'syll'}</a>
 6440: 	$help{'Syllabus'}
 6441: 
 6442: 	</form>
 6443: NSYLFORM
 6444: 
 6445: 	my $newgroupfileform=(<<NGFFORM);
 6446: 	<form action="/adm/coursedocs" method="post" name="newgroupfiles">
 6447: 	<input type="hidden" name="active" value="dd" />
 6448: 	$pathitem
 6449: 	<input type="hidden" name="importdetail"
 6450: 	value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
 6451: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newgroupfiles);">$lt{'grpo'}</a>
 6452: 	$help{'Group Portfolio'}
 6453: 	</form>
 6454: NGFFORM
 6455: 	@specialdocumentsforma=(
 6456: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
 6457: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="javascript:makenew(document.newsyl);" />'=>$newsylform},
 6458: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="javascript:makenew(document.newnav);" />'=>$newnavform},
 6459:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
 6460:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage();" />'=>$newwebpageform},
 6461:         );
 6462:         $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
 6463: 
 6464: 
 6465:         my @importdoc = (
 6466:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform}
 6467:         );
 6468:         if (keys(%ltitools)) {
 6469:             push(@importdoc,
 6470:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="toggleUpload(\'tool\');" />'=>$exttoolform},
 6471:         );
 6472:         }
 6473:         unless ($container eq 'page') {
 6474:             push(@importdoc,
 6475:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform}
 6476:             );
 6477:         }
 6478:         push(@importdoc,
 6479:             {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'doc\');" />'=>$fileuploadform}
 6480:         );
 6481:         $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc));
 6482: 
 6483:         @gradingforma=(
 6484:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
 6485:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
 6486:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
 6487:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{stpr}.'" onclick="javascript:toggleCrsRes(\'res\','."'$numauthor','$numcrsdirs'".');" />'=>$crsresform},
 6488:         );
 6489:         $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
 6490: 
 6491:         @communityforma=(
 6492:        {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
 6493:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
 6494:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
 6495:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="javascript:makenew(document.newroster);" />'=>$newrosterform},
 6496:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="javascript:makenew(document.newgroupfiles);" />'=>$newgroupfileform},
 6497:         );
 6498:         $communityform = &create_form_ul(&create_list_elements(@communityforma));
 6499: 
 6500: my %orderhash = (
 6501:                 'aa' => ['Upload',$fileuploadform],
 6502:                 'bb' => ['Import',$importpubform],
 6503:                 'cc' => ['Grading',$gradingform],
 6504:                 );
 6505: unless ($container eq 'page') {
 6506:     $orderhash{'00'} = ['Newfolder',$newfolderform];
 6507:     $orderhash{'dd'} = ['Collaboration',$communityform];
 6508:     $orderhash{'ee'} = ['Other',$specialdocumentsform];
 6509: }
 6510: 
 6511:  $hadchanges=0;
 6512:        unless (($supplementalflag || $toolsflag)) {
 6513:           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 6514:                               $supplementalflag,\%orderhash,$iconpath,$pathitem,
 6515:                               \%ltitools,$canedit,$hostname,\$navmap,$hiddentop);
 6516:           undef($navmap);
 6517:           if ($error) {
 6518:              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 6519:           }
 6520:           if ($hadchanges) {
 6521:               unless (&is_hash_old()) {
 6522:                   &mark_hash_old();
 6523:               }
 6524: 	  }
 6525: 
 6526:           &changewarning($r,'');
 6527:         }
 6528:     }
 6529: 
 6530: # Supplemental documents start here
 6531: 
 6532:        my $folder=$env{'form.folder'};
 6533:        unless ($supplementalflag) {
 6534: 	   $folder='supplemental';
 6535:        }
 6536:        if ($folder =~ /^supplemental$/ &&
 6537: 	   (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
 6538:           $env{'form.folderpath'} = &supplemental_base();
 6539:        } elsif ($allowed) {
 6540: 	  $env{'form.folderpath'} = $savefolderpath;
 6541:        }
 6542:        $pathitem = '<input type="hidden" name="folderpath" value="'.
 6543:                     &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 6544:        if ($allowed) {
 6545: 	   my $folderseq=
 6546: 	       '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_new.sequence';
 6547: 
 6548: 	my $supupdocform=(<<SUPDOCFORM);
 6549:         <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppdoc');">
 6550:         $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
 6551: 	<form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
 6552:         <fieldset id="uploadsuppdocform" style="display: none;">
 6553:         <legend>$lt{'upfi'}</legend>
 6554: 	<input type="hidden" name="active" value="ee" />
 6555: 	$fileupload
 6556: 	<br />
 6557: 	<br />
 6558: 	<span class="LC_nobreak">
 6559: 	$checkbox
 6560: 	</span>
 6561: 	<br /><br />
 6562: 	$lt{'comment'}:<br />
 6563: 	<textarea cols="50" rows="4" name="comment"></textarea>
 6564: 	<br />
 6565: 	$pathitem
 6566: 	<input type="hidden" name="cmd" value="upload_supplemental" />
 6567:         <input type='submit' value="$lt{'upld'}" />
 6568:         </form>
 6569: SUPDOCFORM
 6570: 
 6571: 	my $supnewfolderform=(<<SNFFORM);
 6572: 	<form action="/adm/coursedocs" method="post" name="supnewfolder">
 6573: 	<input type="hidden" name="active" value="" />
 6574:         $pathitem
 6575: 	<input type="hidden" name="importdetail" value="" />
 6576: 	<a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
 6577: 	$help{'Adding_Folders'}
 6578: 	</form>
 6579: SNFFORM
 6580: 	
 6581:         my $supextform =
 6582:             &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
 6583:                                                  $help{'Adding_External_Resource'},
 6584:                                                  undef,undef,undef,undef,undef,undef,
 6585:                                                  $disabled);
 6586: 
 6587:         my $supexttoolform =
 6588:             &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
 6589:                                                  $help{'Adding_External_Tool'},
 6590:                                                  undef,undef,'tool',$coursedom,
 6591:                                                  $coursenum,\%ltitools,$disabled);
 6592: 
 6593: 	my $supnewsylform=(<<SNSFORM);
 6594: 	<form action="/adm/coursedocs" method="post" name="supnewsyl">
 6595: 	<input type="hidden" name="active" value="ff" />
 6596:         $pathitem
 6597: 	<input type="hidden" name="importdetail" 
 6598: 	value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
 6599: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.supnewsyl);">$lt{'syll'}</a>
 6600: 	$help{'Syllabus'}
 6601: 	</form>
 6602: SNSFORM
 6603: 
 6604: 	my $supnewaboutmeform=(<<SNAMFORM);
 6605: 	<form action="/adm/coursedocs" method="post" name="supnewaboutme">
 6606: 	<input type="hidden" name="active" value="ff" />
 6607:         $pathitem
 6608: 	<input type="hidden" name="importdetail" 
 6609: 	value="$plainname=/adm/$udom/$uname/aboutme" />
 6610: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.supnewaboutme);">$lt{'mypi'}</a>
 6611: 	$help{'My Personal Information Page'}
 6612: 	</form>
 6613: SNAMFORM
 6614: 
 6615:         my $supwebpage;
 6616:         if ($folder =~ /^supplemental_?(\d*)$/) {
 6617:             $supwebpage = "/uploaded/$coursedom/$coursenum/supplemental/";
 6618:             if ($1) {
 6619:                 $supwebpage .= $1;
 6620:             } else {
 6621:                 $supwebpage .= 'default';
 6622:             }
 6623:             $supwebpage .= '/new.html';
 6624:         }
 6625:         my $supwebpageform =(<<SWEBFORM);
 6626:         <form action="/adm/coursedocs" method="post" name="supwebpage">
 6627:         <input type="hidden" name="active" value="cc" />
 6628:         $pathitem
 6629:         <input type="hidden" name="importdetail" value="$supwebpage" />
 6630:         <a class="LC_menubuttons_link" href="javascript:makewebpage('supp');">$lt{'webp'}</a>
 6631:         $help{'Web_Page'}
 6632:         </form>
 6633: SWEBFORM
 6634: 
 6635: 
 6636: my @specialdocs = (
 6637: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="javascript:makenew(document.supnewsyl);" />'
 6638:             =>$supnewsylform},
 6639: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makenew(document.supnewaboutme);" />'
 6640:             =>$supnewaboutmeform},
 6641:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage('."'supp'".');" />'=>$supwebpageform},
 6642: 
 6643: 		);
 6644: my @supimportdoc = (
 6645: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:toggleUpload(\'suppext\')" />'
 6646:             =>$supextform});
 6647:         if (keys(%ltitools)) {
 6648:             push(@supimportdoc,
 6649:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="javascript:toggleUpload(\'supptool\')" />'
 6650:             =>$supexttoolform});
 6651:         }
 6652:         push(@supimportdoc, 
 6653:             {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
 6654:             =>$supupdocform},
 6655:         );
 6656: 
 6657: $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
 6658: my %suporderhash = (
 6659: 		'00' => ['Supnewfolder', $supnewfolderform],
 6660:                 'ee' => ['Upload',$supupdocform],
 6661:                 'ff' => ['Other',&create_form_ul(&create_list_elements(@specialdocs))]
 6662:                 );
 6663:         if ($supplementalflag) {
 6664:            my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 6665:                                $supplementalflag,\%suporderhash,$iconpath,$pathitem,
 6666:                                \%ltitools,$canedit,$hostname);
 6667:            if ($error) {
 6668:               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 6669:            } else {
 6670:                if ($suppchanges) {
 6671:                    my %servers = &Apache::lonnet::internet_dom_servers($coursedom);
 6672:                    my @ids=&Apache::lonnet::current_machine_ids();
 6673:                    foreach my $server (keys(%servers)) {
 6674:                        next if (grep(/^\Q$server\E$/,@ids));
 6675:                        my $hashid=$coursenum.':'.$coursedom;
 6676:                        my $cachekey = &escape('suppcount').':'.&escape($hashid);
 6677:                        &Apache::lonnet::remote_devalidate_cache($server,[$cachekey]);
 6678:                    }
 6679:                    &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
 6680:                    undef($suppchanges);
 6681:                }
 6682:            }
 6683:         }
 6684:     } elsif ($supplementalflag) {
 6685:         my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 6686:                             $supplementalflag,'',$iconpath,$pathitem,'','',$hostname);
 6687:         if ($error) {
 6688:             $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 6689:         }
 6690:     }
 6691: 
 6692:     if ($needs_end) {
 6693:         $r->print(&endContentScreen());
 6694:     }
 6695: 
 6696:     if ($allowed) {
 6697: 	$r->print('
 6698: <form method="post" name="extimport" action="/adm/coursedocs">
 6699:   <input type="hidden" name="title" />
 6700:   <input type="hidden" name="url" />
 6701:   <input type="hidden" name="useform" />
 6702:   <input type="hidden" name="residx" />
 6703: </form>');
 6704:     }
 6705:   } elsif ($showdoc) {
 6706: # -------------------------------------------------------- This is showdoc mode
 6707:       $r->print("<h1>".&mt('Uploaded Document').' - '.
 6708: 		&Apache::lonnet::gettitle($r->uri).'</h1><p class="LC_warning">'.
 6709: &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
 6710:                 &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
 6711:   }
 6712:  }
 6713:  unless ($noendpage) {
 6714:      $r->print(&Apache::loncommon::end_page());
 6715:  }
 6716:  return OK;
 6717: }
 6718: 
 6719: sub embedded_form_elems {
 6720:     my ($phase,$primaryurl,$newidx) = @_;
 6721:     my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 6722:     $newidx =~s /\D+//g;
 6723:     return <<STATE;
 6724:     <input type="hidden" name="folderpath" value="$folderpath" />
 6725:     <input type="hidden" name="cmd" value="upload_embedded" />
 6726:     <input type="hidden" name="newidx" value="$newidx" />
 6727:     <input type="hidden" name="phase" value="$phase" />
 6728:     <input type="hidden" name="primaryurl" value="$primaryurl" />
 6729: STATE
 6730: }
 6731: 
 6732: sub embedded_destination {
 6733:     my $folder=$env{'form.folder'};
 6734:     my $destination = 'docs/';
 6735:     if ($folder =~ /^supplemental/) {
 6736:         $destination = 'supplemental/';
 6737:     }
 6738:     if (($folder eq 'default') || ($folder eq 'supplemental')) {
 6739:         $destination .= 'default/';
 6740:     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 6741:         $destination .=  $2.'/';
 6742:     }
 6743:     my $newidx = $env{'form.newidx'};
 6744:     $newidx =~s /\D+//g;
 6745:     if ($newidx) {
 6746:         $destination .= $newidx;
 6747:     }
 6748:     my $dir_root = '/userfiles';
 6749:     return ($destination,$dir_root);
 6750: }
 6751: 
 6752: sub return_to_editor {
 6753:     my $actionurl = '/adm/coursedocs';
 6754:     return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
 6755:            '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
 6756:            '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
 6757:            '</a></p>';
 6758: }
 6759: 
 6760: sub decompression_info {
 6761:     my ($destination,$dir_root) = &embedded_destination();
 6762:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6763:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6764:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6765:     my $container='sequence';
 6766:     my ($pathitem,$hiddenelem);
 6767:     my @hiddens = ('newidx','comment','position','folderpath','archiveurl');
 6768:     if ($env{'form.folderpath'} =~ /\:1$/) {
 6769:         $container='page';
 6770:     }
 6771:     unshift(@hiddens,$pathitem);
 6772:     foreach my $item (@hiddens) {
 6773:         if ($item eq 'newidx') {
 6774:             next if ($env{'form.'.$item} =~ /\D/);
 6775:         }
 6776:         if ($env{'form.'.$item}) {
 6777:             $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
 6778:                            &HTML::Entities::encode($env{'form.'.$item},'<>&"').'" />'."\n";
 6779:         }
 6780:     }
 6781:     return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
 6782:             $hiddenelem);
 6783: }
 6784: 
 6785: sub decompression_phase_one {
 6786:     my ($dir,$file,$warning,$error,$output);
 6787:     my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
 6788:         &decompression_info();
 6789:     if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/\E(?:docs|supplemental)/(?:default|\d+).*/([^/]+)$}) {
 6790:         $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
 6791:     } else {
 6792:         my $file = $1;
 6793:         $output =
 6794:             &Apache::loncommon::process_decompression($docudom,$docuname,$file,
 6795:                                                       $destination,$dir_root,
 6796:                                                       $hiddenelem);
 6797:         if ($env{'form.autoextract_camtasia'}) {
 6798:             $output .= &remove_archive($docudom,$docuname,$container);
 6799:         }
 6800:     }
 6801:     if ($error) {
 6802:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
 6803:                    $error.'</p>'."\n";
 6804:     }
 6805:     if ($warning) {
 6806:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
 6807:     }
 6808:     return $output;
 6809: }
 6810: 
 6811: sub decompression_phase_two {
 6812:     my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
 6813:         &decompression_info();
 6814:     my $output;
 6815:     if ($env{'form.archivedelete'}) {
 6816:         $output = &remove_archive($docudom,$docuname,$container);
 6817:     }
 6818:     $output .= 
 6819:         &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
 6820:                                                     $destination,$dir_root,$hiddenelem);
 6821:     return $output;
 6822: }
 6823: 
 6824: sub remove_archive {
 6825:     my ($docudom,$docuname,$container) = @_;
 6826:     my $map = $env{'form.folder'}.'.'.$container;
 6827:     my ($output,$delwarning,$delresult,$url);
 6828:     my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
 6829:     if ($fatal) {
 6830:         if ($container eq 'page') {
 6831:             $delwarning = &mt('An error occurred retrieving the contents of the current page.');
 6832:         } else {
 6833:             $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
 6834:         }
 6835:         $delwarning .= ' '.&mt('As a result the archive file has not been removed.');
 6836:     } else {
 6837:         my $currcmd = $env{'form.cmd'};
 6838:         my $position = $env{'form.position'};
 6839:         my $archiveidx = $position;
 6840:         if ($position > 0) {
 6841:             if (($env{'form.autoextract_camtasia'}) && (scalar(@LONCAPA::map::order) == 2)) {
 6842:                 $archiveidx = $position-1;
 6843:             }
 6844:             $env{'form.cmd'} = 'remove_'.$archiveidx;
 6845:             my ($title,$url,@rrest) =
 6846:                 split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$archiveidx]]);
 6847:             if ($url eq $env{'form.archiveurl'}) {
 6848:                 if (&handle_edit_cmd($docuname,$docudom)) {
 6849:                     ($errtext,$fatal) = &storemap($docuname,$docudom,$map,1);
 6850:                     if ($fatal) {
 6851:                         if ($container eq 'page') {
 6852:                             $delwarning = &mt('An error occurred updating the contents of the current page.');
 6853:                         } else {
 6854:                             $delwarning = &mt('An error occurred updating the contents of the current folder.');
 6855:                         }
 6856:                     } else {
 6857:                         $delresult = &mt('Archive file removed.');
 6858:                     }
 6859:                 }
 6860:             } else {
 6861:                 $delwarning .=  &mt('Archive file had unexpected item number in folder.').
 6862:                                 ' '.&mt('As a result the archive file has not been removed.');
 6863:             }
 6864:         }
 6865:         $env{'form.cmd'} = $currcmd;
 6866:     }
 6867:     if ($delwarning) {
 6868:         $output = '<p class="LC_warning">'.
 6869:                    $delwarning.
 6870:                    '</p>';
 6871:     }
 6872:     if ($delresult) {
 6873:         $output .= '<p class="LC_info">'.
 6874:                    $delresult.
 6875:                    '</p>';
 6876:     }
 6877:     return $output;
 6878: }
 6879: 
 6880: sub generate_admin_menu {
 6881:     my ($crstype,$canedit) = @_;
 6882:     my $lc_crstype = lc($crstype);
 6883:     my ($home,$other,%outhash)=&authorhosts();
 6884:     my %lt= ( # do not translate here
 6885:                                          'vc'   => 'Verify Content',
 6886:                                          'cv'   => 'Check/Set Resource Versions',
 6887:                                          'ls'   => 'List Resource Identifiers',
 6888:                                          'imse' => 'Export contents to IMS Archive',
 6889:                                          'dcd'  => "Copy $crstype Content to Authoring Space",
 6890:             );
 6891:     my ($candump,$dumpurl);
 6892:     if ($home + $other > 0) {
 6893:         $candump = 'F';
 6894:         if ($home) {
 6895:             $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
 6896:         } else {
 6897:             my @hosts;
 6898:             foreach my $aurole (keys(%outhash)) {
 6899:                 unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
 6900:                     push(@hosts,$outhash{$aurole});
 6901:                 }
 6902:             }
 6903:             if (@hosts == 1) {
 6904:                 my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
 6905:                                '&amp;role='.
 6906:                                &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
 6907:                                &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
 6908:                 $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
 6909:             } else {
 6910:                 $dumpurl = "javascript:choose_switchserver_window()";
 6911:             }
 6912:         }
 6913:     }
 6914:     my @menu=
 6915:         ({  categorytitle=>'Administration',
 6916:             items =>[
 6917:                 {   linktext   => $lt{'vc'},
 6918:                     url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
 6919:                     permission => 'F',
 6920:                     help       => 'Docs_Verify_Content',
 6921:                     icon       => 'verify.png',
 6922:                     linktitle  => 'Verify contents can be retrieved/rendered',
 6923:                 },
 6924:                 {   linktext => $lt{'cv'},
 6925:                     url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
 6926:                     permission => 'F',
 6927:                     help       => 'Docs_Check_Resource_Versions',
 6928:                     icon       => 'resversion.png',
 6929:                     linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
 6930:                 },
 6931:                 {   linktext   => $lt{'ls'},
 6932:                     url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
 6933:                     permission => 'F',
 6934:                     #help => '',
 6935:                     icon       => 'symbs.png',
 6936:                     linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
 6937:                 },
 6938:                 ]
 6939:         });
 6940:     if ($canedit) {
 6941:         push(@menu,
 6942:         {   categorytitle=>'Export',
 6943:             items =>[
 6944:                 {   linktext   => $lt{'imse'},
 6945:                     url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
 6946:                     permission => 'F',
 6947:                     help       => 'Docs_Export_Course_Docs',
 6948:                     icon       => 'imsexport.png',
 6949:                     linktitle  => $lt{'imse'},
 6950:                 },
 6951:                 {   linktext   => $lt{'dcd'},
 6952:                     url        => $dumpurl,
 6953:                     permission => $candump,
 6954:                     help       => 'Docs_Dump_Course_Docs',
 6955:                     icon       => 'dump.png',
 6956:                     linktitle  => $lt{'dcd'},
 6957:                 },
 6958:                 ]
 6959:         });
 6960:     }
 6961:     return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
 6962:            '<input type="hidden" id="dummy" />'."\n".
 6963:            &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
 6964:            '</form>';
 6965: }
 6966: 
 6967: sub generate_edit_table {
 6968:     my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile,
 6969:         $need_save,$copyfolder,$canedit) = @_;
 6970:     return unless(ref($orderhash_ref) eq 'HASH');
 6971:     my %orderhash = %{$orderhash_ref};
 6972:     my ($form, $activetab, $active, $disabled);
 6973:     if (($env{'form.active'} ne '') && ($env{'form.active'} ne '00')) {
 6974:         $activetab = $env{'form.active'};
 6975:     }
 6976:     unless ($canedit) {
 6977:         $disabled = ' disabled="disabled"';
 6978:     }
 6979:     my $backicon = $iconpath.'clickhere.gif';
 6980:     my $backtext = &mt('Exit Editor');
 6981:     $form = '<div class="LC_Box" style="margin:0;">'.
 6982:             '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
 6983:             '<li class="goback">'.
 6984:             '<a href="javascript:toContents('."'$jumpto'".');">'.
 6985:             '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
 6986:             '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n".
 6987:             '<li>'.
 6988:             '<a href="javascript:groupopen('."'$readfile'".',1);">'.
 6989:             &mt('Undo Delete').'</a></li>'."\n";
 6990:     if ($env{'form.docslog'}) {
 6991:         $form .= '<li class="active">';
 6992:     } else {
 6993:         $form .= '<li>';
 6994:     }
 6995:     $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
 6996:              &mt('History').'</a></li>'."\n";
 6997:     if ($env{'form.docslog'}) {
 6998:         $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
 6999:                  &mt('Edit').'</a></li>'."\n";
 7000:     }
 7001:     foreach my $name (reverse(sort(keys(%orderhash)))) {
 7002:         if($name ne '00'){
 7003:             if($activetab eq '' || $activetab ne $name){
 7004:                $active = '';
 7005:             }elsif($activetab eq $name){
 7006:                $active = 'class="active"';
 7007:             }
 7008:             $form .= '<li style="float:right" '.$active
 7009:                 .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
 7010:         } else {
 7011: 	    $form .= '<li style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
 7012: 
 7013: 	}
 7014:     }
 7015:     $form .= '</ul>'."\n";
 7016:     $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
 7017: 
 7018:     if ($to_show ne '') {
 7019:         my $saveform;
 7020:         if ($need_save) {
 7021:             my $button = &mt('Make changes');
 7022:             my $path;
 7023:             if ($env{'form.folderpath'}) {
 7024:                 $path =
 7025:                     &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 7026:             }
 7027:             $saveform = <<"END";
 7028: <div id="multisave" style="display:none; clear:both;" >
 7029: <form name="saveactions" method="post" action="/adm/coursedocs" onsubmit="return checkSubmits();">
 7030: <input type="hidden" name="folderpath" value="$path" />
 7031: <input type="hidden" name="symb" value="$env{'form.symb'}" />
 7032: <input type="hidden" name="allhiddenresource" value="" />
 7033: <input type="hidden" name="allencrypturl" value="" />
 7034: <input type="hidden" name="allrandompick" value="" />
 7035: <input type="hidden" name="allrandomorder" value="" />
 7036: <input type="hidden" name="changeparms" value="" />
 7037: <input type="hidden" name="multiremove" value="" />
 7038: <input type="hidden" name="multicut" value="" />
 7039: <input type="hidden" name="multicopy" value="" />
 7040: <input type="hidden" name="multichange" value="" />
 7041: <input type="hidden" name="copyfolder" value="$copyfolder" />
 7042: <input type="submit" name="savemultiples" value="$button" $disabled />
 7043: </form>
 7044: </div>
 7045: END
 7046:         }
 7047:         $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'.$saveform."\n";
 7048:     }
 7049:     foreach my $field (keys(%orderhash)){
 7050: 	if($field ne '00'){
 7051:             if($activetab eq '' || $activetab ne $field){
 7052:                 $active = 'style="display: none;float:left"';
 7053:             }elsif($activetab eq $field){
 7054:                 $active = 'style="display:block;float:left"';
 7055:             }
 7056:             $form .= '<div id="'.$field.$tid.'"'
 7057:                     .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
 7058:                     .'</div>'."\n";
 7059:         }
 7060:     }
 7061:     unless ($env{'form.docslog'}) {
 7062:         $form .= '</div></div>'."\n";
 7063:     }
 7064:     return $form;
 7065: }
 7066: 
 7067: sub editing_js {
 7068:     my ($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
 7069:         $londocroot,$canedit,$hostname,$navmapref) = @_;
 7070:     my %js_lt = &Apache::lonlocal::texthash(
 7071:                                           p_mnf => 'Name of New Folder',
 7072:                                           t_mnf => 'New Folder',
 7073:                                           p_mnp => 'Name of New Page',
 7074:                                           t_mnp => 'New Page',
 7075:                                           p_mxu => 'Title for the External Score',
 7076:                                           p_msp => 'Name of Simple Course Page',
 7077:                                           p_msb => 'Title for the Problem',
 7078:                                           p_mdb => 'Title for the Drop Box',
 7079:                                           p_mbb => 'Title for the Discussion Board',
 7080:                                           p_mwp => 'Title for Web Page',
 7081:                                           p_mnr => 'Title for the Resource',
 7082:                                           p_mab => "Enter user:domain for User's Personal Information Page",
 7083:                                           p_mab2 => 'Personal Information Page of ',
 7084:                                           p_mab_alrt1 => 'Not a valid user:domain',
 7085:                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
 7086:                                           p_chn => 'New Title',
 7087:                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
 7088:                                           p_rmr2a => 'Remove',
 7089:                                           p_rmr2b => '?',
 7090:                                           p_rmr3a => 'Remove those',
 7091:                                           p_rmr3b => 'items?',
 7092:                                           p_rmr4  => 'WARNING: Removing a resource uploaded to a course cannot be undone via "Undo Delete".',
 7093:                                           p_rmr5  => 'Push "Cancel" and then use "Cut" instead if you might need to undo this change.',
 7094:                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
 7095:                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
 7096:                                           p_ctr2a => 'Cut',
 7097:                                           p_ctr2b => '?',
 7098:                                           p_ctr3a => 'Cut those',
 7099:                                           p_ctr3b => 'items?',
 7100:                                           setal   => 'Enter a (unique) alias',
 7101:                                           delal   => 'Are you sure you want to eliminate the alias?',
 7102:                                           rpck    => 'Enter number to pick (e.g., 3)',
 7103:                                           imsfile => 'You must choose an IMS package for import',
 7104:                                           imscms  => 'You must select which Course Management System was the source of the IMS package',
 7105:                                           invurl  => 'Invalid URL',
 7106:                                           titbl   => 'Title is blank',
 7107:                                           more    => '(More ...)',
 7108:                                           less    => '(Less ...)',
 7109:                                           noor    => 'No actions selected or changes to settings specified.',
 7110:                                           noch    => 'No changes to settings specified.',
 7111:                                           noac    => 'No actions selected.',
 7112:                                           nofi    => 'No file selected',
 7113:                                           tinc    => 'Title in course',
 7114:                                           sunm    => 'Sub-directory name',
 7115:                                           edri    => 'Editing rights unavailable for your current role.',
 7116:                                         );
 7117:     &js_escape(\%js_lt);
 7118:     my $crstype = &Apache::loncommon::course_type();
 7119:     my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
 7120:     my $main_container_page;
 7121:     if (&HTML::Entities::decode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'}) =~ /\:1$/) {
 7122:         $main_container_page = 1;
 7123:     }
 7124:     my $backtourl;
 7125:     my $toplevelmain = &escape(&default_folderpath($coursenum,$coursedom,$navmapref));
 7126:     my $toplevelsupp = &supplemental_base();
 7127: 
 7128:     if ($env{'docs.exit.'.$env{'request.course.id'}} =~ /^direct_(.+)$/) {
 7129:         my $caller = $1;
 7130:         if ($caller =~ /^supplemental/) {
 7131:             $backtourl = '/adm/supplemental?folderpath='.&escape($caller);
 7132:         } else {
 7133:             my ($map,$id,$res)=&Apache::lonnet::decode_symb($caller);
 7134:             $res = &Apache::lonnet::clutter($res);
 7135:             if (&Apache::lonnet::is_on_map($res)) {
 7136:                 my ($url,$anchor);
 7137:                 if ($res =~ /^([^#]+)#([^#]+)$/) {
 7138:                     $url = $1;
 7139:                     $anchor = $2;
 7140:                     if (($caller =~ m{^([^#]+)\Q#$anchor\E$})) {
 7141:                         $caller = $1.&escape('#').$anchor;
 7142:                     }
 7143:                 } else {
 7144:                     $url = $res;
 7145:                 }
 7146:                 $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($url),'<>&"');
 7147:                 if ($backtourl =~ m{^\Q/uploaded/$coursedom/$coursenum/\Edefault_\d+\.sequence$}) {
 7148:                     $backtourl .= '?navmap=1';
 7149:                 } else {
 7150:                     $backtourl .= '?symb='.
 7151:                                   &HTML::Entities::encode($caller,'<>&"');
 7152:                 }
 7153:                 if ($backtourl =~ m{^\Q/public/$coursedom/$coursenum/syllabus\E}) {
 7154:                     if (($ENV{'SERVER_PORT'} == 443) &&
 7155:                         ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 7156:                         if ($hostname ne '') {
 7157:                             $backtourl = 'http://'.$hostname.$backtourl;
 7158:                         }
 7159:                         $backtourl .= (($backtourl =~ /\?/) ? '&amp;':'?').'usehttp=1';
 7160:                     }
 7161:                 } elsif ($backtourl =~ m{^/adm/wrapper/ext/(?!https:)}) {
 7162:                     if (($ENV{'SERVER_PORT'} == 443) && ($hostname ne '')) {
 7163:                         $backtourl = 'http://'.$hostname.$backtourl;
 7164:                     }
 7165:                 }
 7166:                 if ($anchor ne '') {
 7167:                     $backtourl .= '#'.&HTML::Entities::encode($anchor,'<>&"');
 7168:                 }
 7169:                 $backtourl = &Apache::loncommon::escape_single($backtourl);
 7170:             } else {
 7171:                 $backtourl = '/adm/navmaps';
 7172:             }
 7173:         }
 7174:     } elsif ($env{'docs.exit.'.$env{'request.course.id'}} eq '/adm/menu') {
 7175:         $backtourl = '/adm/menu';
 7176:     } elsif ($supplementalflag) {
 7177:         $backtourl = '/adm/supplemental';
 7178:     } else {
 7179:         $backtourl = '/adm/navmaps';
 7180:     }
 7181: 
 7182:     my $fieldsets = "'ext','doc'";
 7183:     if ($posslti) {
 7184:         $fieldsets .= ",'tool'";
 7185:     }
 7186:     unless ($main_container_page) {
 7187:         $fieldsets .=",'ims'";
 7188:     }
 7189:     if ($supplementalflag) {
 7190:         $fieldsets = "'suppext','suppdoc'";
 7191:         if ($posslti) {
 7192:             $fieldsets .= ",'supptool'";
 7193:         }
 7194:     }
 7195:     
 7196:     my $jsmakefunctions;
 7197:     if ($canedit) {
 7198:         $jsmakefunctions = <<ENDNEWSCRIPT;
 7199: function makenewfolder(targetform,folderseq) {
 7200:     var foldername=prompt('$js_lt{"p_mnf"}','$js_lt{"t_mnf"}');
 7201:     if (foldername) {
 7202:        targetform.importdetail.value=escape(foldername)+"="+folderseq;
 7203:         targetform.submit();
 7204:     }
 7205: }
 7206: 
 7207: function makenewpage(targetform,folderseq) {
 7208:     var pagename=prompt('$js_lt{"p_mnp"}','$js_lt{"t_mnp"}');
 7209:     if (pagename) {
 7210:         targetform.importdetail.value=escape(pagename)+"="+folderseq;
 7211:         targetform.submit();
 7212:     }
 7213: }
 7214: 
 7215: function makeexamupload() {
 7216:    var title=prompt('$js_lt{"p_mxu"}');
 7217:    if (title) {
 7218:     this.document.forms.newexamupload.importdetail.value=
 7219: 	escape(title)+'=/res/lib/templates/examupload.problem';
 7220:     this.document.forms.newexamupload.submit();
 7221:    }
 7222: }
 7223: 
 7224: function makesmppage() {
 7225:    var title=prompt('$js_lt{"p_msp"}');
 7226:    if (title) {
 7227:     this.document.forms.newsmppg.importdetail.value=
 7228: 	escape(title)+'=/adm/$udom/$uname/new/smppg';
 7229:     this.document.forms.newsmppg.submit();
 7230:    }
 7231: }
 7232: 
 7233: function makewebpage(type) {
 7234:    var title=prompt('$js_lt{"p_mwp"}');
 7235:    var formname;
 7236:    if (type == 'supp') {
 7237:        formname = this.document.forms.supwebpage;
 7238:    } else {
 7239:        formname = this.document.forms.newwebpage;
 7240:    }
 7241:    if (title) {
 7242:        var webpage = formname.importdetail.value; 
 7243:        formname.importdetail.value = escape(title)+'='+webpage;
 7244:        formname.submit();
 7245:    }
 7246: }
 7247: 
 7248: function makesmpproblem() {
 7249:    var title=prompt('$js_lt{"p_msb"}');
 7250:    if (title) {
 7251:     this.document.forms.newsmpproblem.importdetail.value=
 7252: 	escape(title)+'=/res/lib/templates/simpleproblem.problem';
 7253:     this.document.forms.newsmpproblem.submit();
 7254:    }
 7255: }
 7256: 
 7257: function makedropbox() {
 7258:    var title=prompt('$js_lt{"p_mdb"}');
 7259:    if (title) {
 7260:     this.document.forms.newdropbox.importdetail.value=
 7261:         escape(title)+'=/res/lib/templates/DropBox.problem';
 7262:     this.document.forms.newdropbox.submit();
 7263:    }
 7264: }
 7265: 
 7266: function makebulboard() {
 7267:    var title=prompt('$js_lt{"p_mbb"}');
 7268:    if (title) {
 7269:     this.document.forms.newbul.importdetail.value=
 7270: 	escape(title)+'=/adm/$udom/$uname/new/bulletinboard';
 7271:     this.document.forms.newbul.submit();
 7272:    }
 7273: }
 7274: 
 7275: function makeabout() {
 7276:    var user=prompt("$js_lt{'p_mab'}");
 7277:    if (user) {
 7278:        var comp=new Array();
 7279:        comp=user.split(':');
 7280:        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
 7281: 	   if ((comp[0]) && (comp[1])) {
 7282: 	       this.document.forms.newaboutsomeone.importdetail.value=
 7283: 		   '$js_lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
 7284:                this.document.forms.newaboutsomeone.submit();
 7285:            } else {
 7286:                alert("$js_lt{'p_mab_alrt1'}");
 7287:            }
 7288:        } else {
 7289:            alert("$js_lt{'p_mab_alrt2'}");
 7290:        }
 7291:     }
 7292: }
 7293: 
 7294: function makenew(targetform) {
 7295:     targetform.submit();
 7296: }
 7297: 
 7298: function changename(folderpath,index,oldtitle) {
 7299:     var title=prompt('$js_lt{"p_chn"}',oldtitle);
 7300:     if (title) {
 7301:         this.document.forms.renameform.markcopy.value='';
 7302:         this.document.forms.renameform.title.value=title;
 7303:         this.document.forms.renameform.cmd.value='rename_'+index;
 7304:         this.document.forms.renameform.folderpath.value=folderpath;
 7305:         this.document.forms.renameform.submit();
 7306:     }
 7307: }
 7308: 
 7309: function setalias(folderpath,index) {
 7310:     var alias = prompt('$js_lt{"setal"}');
 7311:     if ((alias != null) && (alias != '')) {
 7312:         this.document.forms.aliasform.alias.value=alias;
 7313:         this.document.forms.aliasform.cmd.value='setalias_'+index;
 7314:         this.document.forms.aliasform.folderpath.value=folderpath;
 7315:         this.document.forms.aliasform.submit();
 7316:     }
 7317: }
 7318: 
 7319: function delalias(folderpath,index) {
 7320:     if (confirm('$js_lt{"delal"}')) {
 7321:         this.document.forms.aliasform.cmd.value='delalias_'+index;
 7322:         this.document.forms.aliasform.folderpath.value=folderpath;
 7323:         this.document.forms.aliasform.submit();
 7324:     }
 7325: }
 7326: 
 7327: ENDNEWSCRIPT
 7328:     } else {
 7329:         $jsmakefunctions = <<ENDNEWSCRIPT;
 7330: 
 7331: function makenewfolder() {
 7332:     alert("$js_lt{'edri'}");
 7333: }
 7334: 
 7335: function makenewpage() {
 7336:     alert("$js_lt{'edri'}");
 7337: }
 7338: 
 7339: function makeexamupload() {
 7340:     alert("$js_lt{'edri'}");
 7341: }
 7342: 
 7343: function makesmppage() {
 7344:     alert("$js_lt{'edri'}");
 7345: }
 7346: 
 7347: function makewebpage(type) {
 7348:     alert("$js_lt{'edri'}");
 7349: }
 7350: 
 7351: function makesmpproblem() {
 7352:     alert("$js_lt{'edri'}");
 7353: }
 7354: 
 7355: function makedropbox() {
 7356:     alert("$js_lt{'edri'}");
 7357: }
 7358: 
 7359: function makebulboard() {
 7360:     alert("$js_lt{'edri'}");
 7361: }
 7362: 
 7363: function makeabout() {
 7364:     alert("$js_lt{'edri'}");
 7365: }
 7366: 
 7367: function changename() {
 7368:     alert("$js_lt{'edri'}");
 7369: }
 7370: 
 7371: function setalias() {
 7372:     alert("$js_lt{'edri'}");
 7373: }
 7374: 
 7375: function delalias() {
 7376:     alert("$js_lt{'edri'}");
 7377: }
 7378: 
 7379: function makenew() {
 7380:     alert("$js_lt{'edri'}");
 7381: }
 7382: 
 7383: function groupimport() {
 7384:     alert("$js_lt{'edri'}");
 7385: }
 7386: 
 7387: function groupsearch() {
 7388:     alert("$js_lt{'edri'}");
 7389: }
 7390: 
 7391: function groupopen(url,recover) {
 7392:    var options="scrollbars=1,resizable=1,menubar=0";
 7393:    idxflag=1;
 7394:    idx=open("/adm/groupsort?inhibitmenu=yes&mode=simple&recover="+recover+"&readfile="+url,"idxout",options);
 7395:    idx.focus();
 7396: }
 7397: 
 7398: ENDNEWSCRIPT
 7399: 
 7400:     }
 7401:     return <<ENDSCRIPT;
 7402: 
 7403: $jsmakefunctions
 7404: 
 7405: function toggleUpload(caller) {
 7406:     var blocks = Array($fieldsets);
 7407:     for (var i=0; i<blocks.length; i++) {
 7408:         var disp = 'none';
 7409:         if (caller == blocks[i]) {
 7410:             var curr = document.getElementById('upload'+caller+'form').style.display;
 7411:             if (curr == 'none') {
 7412:                 disp='block';
 7413:             }
 7414:         }
 7415:         document.getElementById('upload'+blocks[i]+'form').style.display=disp;
 7416:         if ((caller == 'tool') || (caller == 'supptool')) {
 7417:             if (disp == 'block') {
 7418:                 if (document.getElementById('LC_exttoolid')) { 
 7419:                     var toolselector = document.getElementById('LC_exttoolid'); 
 7420:                     var suppflag = 0;
 7421:                     if (caller == 'supptool') {
 7422:                         suppflag = 1;
 7423:                     }
 7424:                     currForm = document.getElementById('new'+caller);
 7425:                     updateExttool(toolselector,currForm,suppflag); 
 7426:                 }
 7427:             }
 7428:         }
 7429:     }
 7430:     resize_scrollbox('contentscroll','1','1');
 7431:     return;
 7432: }
 7433: 
 7434: function toggleMap(caller) {
 7435:     var disp = 'none';
 7436:     if (document.getElementById('importmapform')) {
 7437:         if (caller == 'map') {
 7438:             var curr = document.getElementById('importmapform').style.display;
 7439:             if (curr == 'none') {
 7440:                 disp='block';
 7441:             }
 7442:         }
 7443:         document.getElementById('importmapform').style.display=disp;
 7444:         resize_scrollbox('contentscroll','1','1');
 7445:     }
 7446:     return;
 7447: }
 7448: 
 7449: function toggleCrsRes(caller,numauthorrole,numcrsdirs) {
 7450:     var disp = 'none';
 7451:     if (document.getElementById('crsresform')) {
 7452:         if (caller == 'res') {
 7453:             var curr = document.getElementById('crsresform').style.display;
 7454:             if (curr == 'none') {
 7455:                 disp='block';
 7456:                 numauthor = parseInt(numauthorrole);
 7457:                 if (numauthor > 0) {
 7458:                     document.courseresform.authorrole.selectedIndex = 0;
 7459:                     select1priv_changed();
 7460:                     document.courseresform.authorpath.selectedIndex = 0;
 7461:                     document.courseresform.newresourceadd.selectedIndex = 0;
 7462:                     toggleNewInCourse(document.courseresform);
 7463:                     if (document.getElementById('newresource')) {
 7464:                         document.getElementById('newresource').style.display = 'none';
 7465:                     }
 7466:                 } else {
 7467:                     if (numcrsdirs) {
 7468:                         document.courseresform.authorpath.selectedIndex = 0;
 7469:                     }
 7470:                 }
 7471:                 if (document.courseresform.newresusetemp.length) {
 7472:                     document.courseresform.newresusetemp[0].checked = true;
 7473:                     toggleWithTemplate(document.courseresform);
 7474:                 }
 7475:                 document.courseresform.newresourcename.value = ''; 
 7476:             }
 7477:         }
 7478:         if (document.courseresform.newsubdir.length) {
 7479:             for (var j=0; j<document.courseresform.newsubdir.length; j++) {
 7480:                 if (document.courseresform.newsubdir[j].value == 0) {
 7481:                     document.courseresform.newsubdir[j].checked = true;
 7482:                 }
 7483:                 break;
 7484:             }
 7485:             if (document.getElementById('newsubdirname')) {
 7486:                 document.getElementById('newsubdirname').type = "hidden";
 7487:                 document.getElementById('newsubdirname').value = "";
 7488:             }
 7489:             if (document.getElementById('newsubdir')) {
 7490:                 document.getElementById('newsubdir').innerHTML = "";
 7491:             }
 7492:         }
 7493:         document.getElementById('crsresform').style.display=disp;
 7494:         resize_scrollbox('contentscroll','1','0');
 7495:     }
 7496:     return;
 7497: }
 7498: 
 7499: function toggleNewsubdir(form) {
 7500:     if (form.newsubdir.length) {
 7501:         for (var j=0; j<form.newsubdir.length; j++) {
 7502:             if (form.newsubdir[j].checked) {
 7503:                 if (document.getElementById('newsubdirname')) {
 7504:                     if (form.newsubdir[j].value == '1') {
 7505:                         document.getElementById('newsubdirname').type = "text"; 
 7506:                         if (document.getElementById('newsubdir')) {
 7507:                             document.getElementById('newsubdir').innerHTML = '<br />$js_lt{'sunm'}';
 7508:                         }
 7509:                     } else {
 7510:                         document.getElementById('newsubdirname').type = "hidden";
 7511:                         document.getElementById('newsubdirname').value = "";
 7512:                         document.getElementById('newsubdir').innerHTML = "";
 7513:                     }
 7514:                 }
 7515:                 break;
 7516:             }
 7517:         }
 7518:     }
 7519: }
 7520: 
 7521: function toggleCrsResTitle() {
 7522:     if (document.getElementById('newresource')) {
 7523:         if (document.courseresform.authorrole.options[document.courseresform.authorrole.selectedIndex].value == 'course') {
 7524:             document.getElementById('newresource').style.display = 'inline';
 7525:             document.courseresform.newresourceadd[0].checked = true;
 7526:             toggleNewInCourse(document.courseresform);
 7527:         } else {
 7528:             document.getElementById('newresource').style.display = 'none';
 7529:         }
 7530:     } 
 7531: }
 7532: 
 7533: function toggleNewInCourse(form) {
 7534:     if (form.newresourceadd.length) {
 7535:         for (var i=0; i<form.newresourceadd.length; i++) {
 7536:             if (form.newresourceadd[i].checked) {
 7537:                 if (document.getElementById('newresourcetitle')) {
 7538:                     if (form.newresourceadd[i].value == '1') {
 7539:                         document.getElementById('newresourcetitle').type = 'text';
 7540:                         if (document.getElementById('newrestitle')) {
 7541:                             document.getElementById('newrestitle').innerHTML = "<br />$js_lt{'tinc'}";
 7542:                         }
 7543:                     } else {
 7544:                         document.getElementById('newresourcetitle').type = 'hidden';
 7545:                         document.getElementById('newresourcetitle').value = '';
 7546:                         if (document.getElementById('newrestitle')) { 
 7547:                             document.getElementById('newrestitle').innerHTML = '';
 7548:                         }
 7549:                     }
 7550:                 }
 7551:                 break;
 7552:             }
 7553:         }
 7554:     }
 7555: }
 7556: 
 7557: function toggleWithTemplate(form) {
 7558:     if (form.newresusetemp.length) {
 7559:         for (var i=0; i<form.newresusetemp.length; i++) {
 7560:             if (form.newresusetemp[i].checked) {
 7561:                 if (document.getElementById('newrestemplate')) { 
 7562:                     if (form.newresusetemp[i].value == '1') {
 7563:                         document.getElementById('newrestemplate').style.display = 'inline';
 7564:                         toggleExampleText();
 7565:                     } else {
 7566:                         form.tempcategory.selectedIndex = 0;
 7567:                         select1template_changed();
 7568:                         document.getElementById('newrestemplate').style.display = 'none';
 7569:                     }
 7570:                 }
 7571:             }
 7572:         }
 7573:     }
 7574: }
 7575: 
 7576: function toggleExampleText() {
 7577:     if (document.getElementById('newresexample')) {
 7578:         var url = document.courseresform.template.options[document.courseresform.template.selectedIndex].value;
 7579:         if (url == '') {
 7580:             document.getElementById('newresexample').style.fontWeight = 'normal';
 7581:         } else {
 7582:             document.getElementById('newresexample').style.fontWeight = 'bold';
 7583:         }
 7584:     }
 7585: }
 7586: 
 7587: function getExample(width,height,scrolling,transparency) {
 7588:     var url;
 7589:     if (document.courseresform.newresusetemp.length) {
 7590:         for (var i=0; i<document.courseresform.newresusetemp.length; i++) {
 7591:             if (document.courseresform.newresusetemp[i].checked) {
 7592:                 if (document.courseresform.newresusetemp[i].value == '1') {
 7593:                     var url = document.courseresform.template.options[document.courseresform.template.selectedIndex].value;
 7594:                     if (url == '') {
 7595:                         alert('Pick a category and template');
 7596:                     } else {
 7597:                         url = url.replace("$londocroot",""); 
 7598:                         url += '?inhibitmenu=yes';
 7599:                     }
 7600:                 }
 7601:                 break;
 7602:             }
 7603:         }
 7604:     }
 7605:     if (url != '') {
 7606:         openMyModal(url,width,height,scrolling,transparency,'');
 7607:     }
 7608: }
 7609: 
 7610: function toggleImportCrsres(caller,dircount) {
 7611:     var disp = 'none';
 7612:     if (document.getElementById('importcrsresform')) {
 7613:         if (caller == 'res') {
 7614:             var numdirs = parseInt(dircount);
 7615:             var curr = document.getElementById('importcrsresform').style.display;
 7616:             if (curr == 'none') {
 7617:                 disp='block';
 7618:                 if (numdirs > 1) {
 7619:                     select1res_changed();
 7620:                 }
 7621:             }
 7622:         }
 7623:         document.getElementById('importcrsresform').style.display=disp;
 7624:         resize_scrollbox('contentscroll','1','0');
 7625:     }
 7626:     return;
 7627: }
 7628: 
 7629: function makeims(imsform) {
 7630:     if ((imsform.uploaddoc.value == '')  || (!imsform.uploaddoc.value)) {
 7631:         alert("$js_lt{'imsfile'}");
 7632:         return;
 7633:     }
 7634:     if (imsform.source.selectedIndex == 0) {
 7635:         alert("$js_lt{'imscms'}");
 7636:         return;
 7637:     }
 7638:     newWindow = window.open('', 'IMSimport',"HEIGHT=700,WIDTH=750,scrollbars=yes");
 7639:     imsform.submit();
 7640: }
 7641: 
 7642: function updatePick(targetform,index,caller) {
 7643:     var pickitem;
 7644:     var picknumitem;
 7645:     var picknumtext;
 7646:     if (index == 'all') {
 7647:         pickitem = document.getElementById('randompickall');
 7648:         picknumitem = document.getElementById('rpicknumall');
 7649:         picknumtext = document.getElementById('rpicktextall');
 7650:     } else {
 7651:         pickitem = document.getElementById('randompick_'+index);
 7652:         picknumitem = document.getElementById('rpicknum_'+index);
 7653:         picknumtext = document.getElementById('randompicknum_'+index);
 7654:     }
 7655:     if (pickitem.checked) {
 7656:         var picknum=prompt('$js_lt{"rpck"}',picknumitem.value);
 7657:         if (picknum == '' || picknum == null) {
 7658:             if (caller == 'check') {
 7659:                 pickitem.checked=false;
 7660:                 if (index == 'all') {
 7661:                     picknumtext.innerHTML = '';
 7662:                     if (caller == 'link') {
 7663:                         propagateState(targetform,'rpicknum');
 7664:                     }
 7665:                 } else {
 7666:                     checkForSubmit(targetform,'randompick','settings');
 7667:                 }
 7668:             }
 7669:         } else {
 7670:             picknum.toString();
 7671:             var regexdigit=/^\\d+\$/;
 7672:             if (regexdigit.test(picknum)) {
 7673:                 picknumitem.value = picknum;
 7674:                 if (index == 'all') {
 7675:                     picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.cumulativesettings,\\'all\\',\\'link\\');">'+picknum+'</a>';
 7676:                     if (caller == 'link') {
 7677:                         propagateState(targetform,'rpicknum');
 7678:                     }
 7679:                 } else {
 7680:                     picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+index+',\\''+index+'\\',\\'link\\');">'+picknum+'</a>';
 7681:                     checkForSubmit(targetform,'randompick','settings');
 7682:                 }
 7683:             } else {
 7684:                 if (caller == 'check') {
 7685:                     if (index == 'all') {
 7686:                         picknumtext.innerHTML = '';
 7687:                         if (caller == 'link') {
 7688:                             propagateState(targetform,'rpicknum');
 7689:                         }
 7690:                     } else {
 7691:                         pickitem.checked=false;
 7692:                         checkForSubmit(targetform,'randompick','settings');
 7693:                     }
 7694:                 }
 7695:                 return;
 7696:             }
 7697:         }
 7698:     } else {
 7699:         picknumitem.value = '';
 7700:         picknumtext.innerHTML = '';
 7701:         if (index == 'all') {
 7702:             if (caller == 'link') {
 7703:                 propagateState(targetform,'rpicknum');
 7704:             }
 7705:         } else {
 7706:             checkForSubmit(targetform,'randompick','settings');
 7707:         }
 7708:     }
 7709: }
 7710: 
 7711: function propagateState(form,param) {
 7712:     if (document.getElementById(param+'all')) {
 7713:         var setcheck = 0;
 7714:         var rpick = 0;
 7715:         if (param == 'rpicknum') {
 7716:             if (document.getElementById('randompickall')) {
 7717:                 if (document.getElementById('randompickall').checked) {
 7718:                     if (document.getElementById('rpicknumall')) {
 7719:                         rpick = document.getElementById('rpicknumall').value;
 7720:                     }
 7721:                 }
 7722:             }
 7723:         } else {
 7724:             if (document.getElementById(param+'all').checked) {
 7725:                 setcheck = 1;
 7726:             }
 7727:         }
 7728:         var allidxlist;
 7729:         if ((param == 'remove') || (param == 'cut') || (param == 'copy')) {
 7730:             if (document.getElementById('all'+param+'idx')) {
 7731:                 allidxlist = document.getElementById('all'+param+'idx').value;
 7732:             }
 7733:             var actions = new Array ('remove','cut','copy');
 7734:             for (var i=0; i<actions.length; i++) {
 7735:                 if (actions[i] != param) {
 7736:                     if (document.getElementById(actions[i]+'all')) {
 7737:                         document.getElementById(actions[i]+'all').checked = false; 
 7738:                     }
 7739:                 }
 7740:             }
 7741:         }
 7742:         if ((param == 'encrypturl') || (param == 'hiddenresource')) {
 7743:             allidxlist = form.allidx.value;
 7744:         }
 7745:         if ((param == 'randompick') || (param == 'rpicknum') || (param == 'randomorder')) {
 7746:             allidxlist = form.allmapidx.value;
 7747:         }
 7748:         if ((allidxlist != '') && (allidxlist != null)) {
 7749:             var allidxs = allidxlist.split(',');
 7750:             if (allidxs.length > 1) {
 7751:                 for (var i=0; i<allidxs.length; i++) {
 7752:                     if (document.getElementById(param+'_'+allidxs[i])) {
 7753:                         if (param == 'rpicknum') {
 7754:                             if (document.getElementById('randompick_'+allidxs[i])) {
 7755:                                 if (document.getElementById('randompick_'+allidxs[i]).checked) {
 7756:                                     document.getElementById(param+'_'+allidxs[i]).value = rpick;
 7757:                                     if (rpick > 0) {
 7758:                                         document.getElementById('randompicknum_'+allidxs[i]).innerHTML = ':&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+allidxs[i]+',\\''+allidxs[i]+'\\',\\'link\\')">'+rpick+'</a>';
 7759:                                     } else {
 7760:                                         document.getElementById('randompicknum_'+allidxs[i]).innerHTML =  '';
 7761:                                     }
 7762:                                 }
 7763:                             }
 7764:                         } else {
 7765:                             if (setcheck == 1) {
 7766:                                 document.getElementById(param+'_'+allidxs[i]).checked = true;
 7767:                             } else {
 7768:                                 document.getElementById(param+'_'+allidxs[i]).checked = false;
 7769:                                 if (param == 'randompick') {
 7770:                                     document.getElementById('randompicknum_'+allidxs[i]).innerHTML =  '';
 7771:                                 }
 7772:                             }
 7773:                         }
 7774:                     }
 7775:                 }
 7776:                 if (setcheck == 1) {
 7777:                     if ((param == 'remove') || (param == 'cut') || (param == 'copy')) {
 7778:                         var actions = new Array('copy','cut','remove');
 7779:                         for (var i=0; i<actions.length; i++) {
 7780:                             var otheractions;
 7781:                             var otheridxs;
 7782:                             if (actions[i] === param) {
 7783:                                 continue;
 7784:                             } else {
 7785:                                 if (document.getElementById('all'+actions[i]+'idx')) {
 7786:                                     otheractions = document.getElementById('all'+actions[i]+'idx').value;
 7787:                                     otheridxs = otheractions.split(',');
 7788:                                     if (otheridxs.length > 1) {
 7789:                                         for (var j=0; j<otheridxs.length; j++) {
 7790:                                             if (document.getElementById(actions[i]+'_'+otheridxs[j])) {
 7791:                                                 document.getElementById(actions[i]+'_'+otheridxs[j]).checked = false;
 7792:                                             }
 7793:                                         }
 7794:                                     }
 7795:                                 }
 7796:                             }
 7797:                         } 
 7798:                     }
 7799:                 }
 7800:             }
 7801:         }
 7802:     }
 7803:     return;
 7804: }
 7805: 
 7806: function checkForSubmit(targetform,param,context,idx,folderpath,index,oldtitle,skip_confirm,container,folder,confirm_removal) {
 7807:     var canedit = '$canedit';
 7808:     if (canedit == '') {
 7809:         alert("$js_lt{'edri'}");
 7810:         return;
 7811:     }
 7812:     var dosettings;
 7813:     var doaction;
 7814:     var control = document.togglemultsettings;
 7815:     if (context == 'actions') {
 7816:         control = document.togglemultactions;
 7817:         doaction = 1; 
 7818:     } else {
 7819:         dosettings = 1;
 7820:     }
 7821:     if (control) {
 7822:         if (control.showmultpick.length) {
 7823:             for (var i=0; i<control.showmultpick.length; i++) {
 7824:                 if (control.showmultpick[i].checked) {
 7825:                     if (control.showmultpick[i].value == 1) {
 7826:                         if (context == 'settings') {
 7827:                             dosettings = 0;
 7828:                         } else {
 7829:                             doaction = 0;
 7830:                         }
 7831:                     }
 7832:                 }
 7833:             }
 7834:         }
 7835:     }
 7836:     if (context == 'settings') {
 7837:         if (dosettings == 1) {
 7838:             targetform.changeparms.value=param;
 7839:             targetform.submit();
 7840:         }
 7841:     }
 7842:     if (context == 'actions') {
 7843:         if (doaction == 1) {
 7844:             targetform.cmd.value=param+'_'+index;
 7845:             targetform.folderpath.value=folderpath;
 7846:             targetform.markcopy.value=idx+':'+param;
 7847:             targetform.copyfolder.value=folder+'.'+container;
 7848:             if (param == 'remove') {
 7849:                 var doremove = 0;
 7850:                 if (skip_confirm) {
 7851:                     if (confirm_removal) {
 7852:                         if (confirm('$js_lt{"p_rmr4"}\\n$js_lt{"p_rmr5"}\\n\\n$js_lt{"p_rmr2a"} "'+oldtitle+'"$js_lt{"p_rmr2b"}')) {
 7853:                             doremove = 1;
 7854:                         }
 7855:                     } else {
 7856:                         doremove = 1;
 7857:                     }
 7858:                 } else {
 7859:                     if (confirm('$js_lt{"p_rmr1"}\\n\\n$js_lt{"p_rmr2a"} "'+oldtitle+'" $js_lt{"p_rmr2b"}')) {
 7860:                         doremove = 1;
 7861:                     }
 7862:                 }
 7863:                 if (doremove) {
 7864:                     targetform.markcopy.value='';
 7865:                     targetform.copyfolder.value='';
 7866:                     targetform.submit();
 7867:                 }
 7868:             }
 7869:             if (param == 'cut') {
 7870:                 if (skip_confirm || confirm('$js_lt{"p_ctr1a"}\\n$js_lt{"p_ctr1b"}\\n\\n$js_lt{"p_ctr2a"} "'+oldtitle+'" $js_lt{"p_ctr2b"}')) {
 7871:                     targetform.submit();
 7872:                     return;
 7873:                 }
 7874:             }
 7875:             if (param == 'copy') {
 7876:                 targetform.submit();
 7877:                 return;
 7878:             }
 7879:             targetform.markcopy.value='';
 7880:             targetform.copyfolder.value='';
 7881:             targetform.cmd.value='';
 7882:             targetform.folderpath.value='';
 7883:             return;
 7884:         } else {
 7885:             if (document.getElementById(param+'_'+idx)) {
 7886:                 item = document.getElementById(param+'_'+idx);
 7887:                 if (item.type == 'checkbox') {
 7888:                     if (item.checked) {
 7889:                         item.checked = false;
 7890:                     } else {
 7891:                         item.checked = true;
 7892:                         singleCheck(item,idx,param);
 7893:                     }
 7894:                 }
 7895:             }
 7896:         }
 7897:     }
 7898:     return;
 7899: }
 7900: 
 7901: function singleCheck(caller,idx,action) {
 7902:     actions = new Array('cut','copy','remove');
 7903:     if (caller.checked) {
 7904:         for (var i=0; i<actions.length; i++) {
 7905:             if (actions[i] != action) {
 7906:                 if (document.getElementById(actions[i]+'_'+idx)) {
 7907:                     if (document.getElementById(actions[i]+'_'+idx).checked) {
 7908:                         document.getElementById(actions[i]+'_'+idx).checked = false;
 7909:                     }
 7910:                 }
 7911:             }
 7912:         }
 7913:     }
 7914:     return;
 7915: }
 7916: 
 7917: function unselectInactive(nav) {
 7918: currentNav = document.getElementById(nav);
 7919: currentLis = currentNav.getElementsByTagName('LI');
 7920: for (i = 0; i < currentLis.length; i++) {
 7921:         if (currentLis[i].className == 'goback') {
 7922:             currentLis[i].className = 'goback';
 7923:         } else {
 7924: 	    if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
 7925: 		currentLis[i].className = 'right';
 7926: 	    } else {
 7927: 		currentLis[i].className = 'i';
 7928: 	    }
 7929:         }
 7930: }
 7931: }
 7932: 
 7933: function hideAll(current, nav, data) {
 7934: unselectInactive(nav);
 7935: if (current) { 
 7936:     if (current.className == 'right'){
 7937:         current.className = 'right active'
 7938:     } else {
 7939:         current.className = 'active';
 7940:     }
 7941: }
 7942: currentData = document.getElementById(data);
 7943: currentDivs = currentData.getElementsByTagName('DIV');
 7944: for (i = 0; i < currentDivs.length; i++) {
 7945: 	if(currentDivs[i].className == 'LC_ContentBox'){
 7946: 		currentDivs[i].style.display = 'none';
 7947: 	}
 7948: }
 7949: }
 7950: 
 7951: function openTabs(pageId) {
 7952: 	tabnav = document.getElementById(pageId).getElementsByTagName('UL');	
 7953: 	if(tabnav.length > 2 ){
 7954: 		currentNav = document.getElementById(tabnav[1].id);
 7955: 		currentLis = currentNav.getElementsByTagName('LI');
 7956: 		for(i = 0; i< currentLis.length; i++){
 7957: 			if(currentLis[i].className == 'active') {
 7958: 				funcString = currentLis[i].onclick.toString();
 7959: 				tab = funcString.split('"');
 7960:                                 if(tab.length < 2) {
 7961:                                    tab = funcString.split("'");
 7962:                                 }
 7963: 				currentData = document.getElementById(tab[1]);
 7964:         			currentData.style.display = 'block';
 7965: 			}	
 7966: 		}
 7967: 	}
 7968: }
 7969: 
 7970: function showPage(current, pageId, nav, data) {
 7971:         currstate = current.className;
 7972: 	hideAll(current, nav, data);
 7973: 	openTabs(pageId);
 7974: 	unselectInactive(nav);
 7975:         if ((currstate == 'active') || (currstate == 'right active')) {
 7976:             if (currstate == 'active') {
 7977: 	        current.className = '';
 7978:             } else {
 7979:                 current.className = 'right';
 7980:             }
 7981:             activeTab = ''; 
 7982:             toggleUpload();
 7983:             toggleMap();
 7984:             toggleCrsRes();
 7985:             toggleImportCrsres();
 7986:             resize_scrollbox('contentscroll','1','0');
 7987:             return;
 7988:         } else {
 7989:             current.className = 'active';
 7990:         }
 7991: 	currentData = document.getElementById(pageId);
 7992: 	currentData.style.display = 'block';
 7993:         activeTab = pageId;
 7994:         toggleUpload();
 7995:         toggleMap();
 7996:         toggleCrsRes();
 7997:         toggleImportCrsres();
 7998:         if (nav == 'mainnav') {
 7999:             var storedpath = "$docs_folderpath";
 8000:             var storedpage = "$main_container_page";
 8001:             var reg = new RegExp("^supplemental");
 8002:             if (pageId == 'mainCourseDocuments') {
 8003:                 if (storedpage == 1) {
 8004:                     document.simpleedit.folderpath.value = '';
 8005:                     document.uploaddocument.folderpath.value = '';
 8006:                 } else {
 8007:                     if (reg.test(storedpath)) {
 8008:                         document.simpleedit.folderpath.value = '$toplevelmain';
 8009:                         document.uploaddocument.folderpath.value = '$toplevelmain';
 8010:                         document.newext.folderpath.value = '$toplevelmain';
 8011:                     } else {
 8012:                         document.simpleedit.folderpath.value = storedpath;
 8013:                         document.uploaddocument.folderpath.value = storedpath;
 8014:                         document.newext.folderpath.value = storedpath;
 8015:                     }
 8016:                 }
 8017:             } else {
 8018:                 if (reg.test(storedpath)) {
 8019:                     document.simpleedit.folderpath.value = storedpath;
 8020:                     document.supuploaddocument.folderpath.value = storedpath;
 8021:                     document.supnewext.folderpath.value = storedpath;
 8022:                 } else {
 8023:                     document.simpleedit.folderpath.value = '$toplevelsupp';
 8024:                     document.supuploaddocument.folderpath.value = '$toplevelsupp';
 8025:                     document.supnewext.folderpath.value = '$toplevelsupp';
 8026:                 }
 8027:             }
 8028:         }
 8029:         resize_scrollbox('contentscroll','1','0');
 8030: 	return false;
 8031: }
 8032: 
 8033: function toContents(jumpto) {
 8034:     var newurl = '$backtourl';
 8035:     if ((newurl == '/adm/navmaps') && (jumpto != '')) {
 8036:         newurl = newurl+'?postdata='+jumpto;
 8037:     }
 8038:     location.href=newurl;
 8039: }
 8040: 
 8041: function togglePick(caller,value) {
 8042:     var disp = 'none';
 8043:     if (document.getElementById('multi'+caller)) {
 8044:         var curr = document.getElementById('multi'+caller).style.display;
 8045:         if (value == 1) {
 8046:             disp='block';
 8047:         }
 8048:         if (curr == disp) {
 8049:             return; 
 8050:         }
 8051:         document.getElementById('multi'+caller).style.display=disp;
 8052:         if (value == 1) {
 8053:             document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$js_lt{'more'}</a>'; 
 8054:         } else {
 8055:             document.getElementById('more'+caller).innerHTML = '';
 8056:         }
 8057:         if (caller == 'actions') { 
 8058:             setClass(value);
 8059:             setBoxes(value);
 8060:         }
 8061:     }
 8062:     var showButton = multiSettings();
 8063:     if (showButton != 1) {
 8064:         showButton = multiActions();
 8065:     }
 8066:     if (document.getElementById('multisave')) {
 8067:         if (showButton == 1) {
 8068:             document.getElementById('multisave').style.display='block';
 8069:         } else {
 8070:             document.getElementById('multisave').style.display='none';
 8071:         }
 8072:     }
 8073:     resize_scrollbox('contentscroll','1','1');
 8074:     return;
 8075: }
 8076: 
 8077: function toggleCheckUncheck(caller,more) {
 8078:     if (more == 1) {
 8079:         document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',0);" style="text-decoration:none;">$js_lt{'less'}</a>';
 8080:         document.getElementById('allfields'+caller).style.display='block';
 8081:     } else {
 8082:         document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$js_lt{'more'}</a>';
 8083:         document.getElementById('allfields'+caller).style.display='none';
 8084:     }
 8085:     resize_scrollbox('contentscroll','1','1');
 8086: }
 8087: 
 8088: function multiSettings() {
 8089:     var inuse = 0;
 8090:     var settingsform = document.togglemultsettings;
 8091:     if (settingsform.showmultpick.length > 1) {
 8092:         for (var i=0; i<settingsform.showmultpick.length; i++) {
 8093:             if (settingsform.showmultpick[i].checked) {
 8094:                 if (settingsform.showmultpick[i].value == 1) {
 8095:                     inuse = 1;  
 8096:                 }
 8097:             }
 8098:         }
 8099:     }
 8100:     return inuse;
 8101: }
 8102: 
 8103: function multiActions() {
 8104:     var inuse = 0;
 8105:     var actionsform = document.togglemultactions;
 8106:     if (actionsform.showmultpick.length > 1) {
 8107:         for (var i=0; i<actionsform.showmultpick.length; i++) {
 8108:             if (actionsform.showmultpick[i].checked) {
 8109:                 if (actionsform.showmultpick[i].value == 1) {
 8110:                     inuse = 1;
 8111:                 }
 8112:             }
 8113:         }
 8114:     }
 8115:     return inuse;
 8116: } 
 8117: 
 8118: function checkSubmits() {
 8119:     var numchanges = 0;
 8120:     var form = document.saveactions;
 8121:     var doactions = multiActions();
 8122:     var cutwarnings = 0;
 8123:     var remwarnings = 0;
 8124:     var removalinfo = 0;
 8125:     if (doactions == 1) {
 8126:         var remidxlist = document.cumulativeactions.allremoveidx.value;
 8127:         if ((remidxlist != '') && (remidxlist != null)) {
 8128:             var remidxs = remidxlist.split(',');
 8129:             for (var i=0; i<remidxs.length; i++) {
 8130:                 if (document.getElementById('remove_'+remidxs[i])) {
 8131:                     if (document.getElementById('remove_'+remidxs[i]).checked) {
 8132:                         form.multiremove.value += remidxs[i]+',';
 8133:                         numchanges ++;
 8134:                         if (document.getElementById('skip_remove_'+remidxs[i])) {
 8135:                             if (document.getElementById('skip_remove_'+remidxs[i]).value == 0) {
 8136:                                 remwarnings ++;
 8137:                             }
 8138:                         }
 8139:                         if (document.getElementById('confirm_removal_'+remidxs[i])) {
 8140:                             if (document.getElementById('confirm_removal_'+remidxs[i]).value == 1) {
 8141:                                 removalinfo ++;
 8142:                             }
 8143:                         }
 8144:                     }
 8145:                 }
 8146:             }
 8147:         }
 8148:         var cutidxlist = document.cumulativeactions.allcutidx.value;
 8149:         if ((cutidxlist != '') && (cutidxlist != null)) {
 8150:             var cutidxs = cutidxlist.split(',');
 8151:             for (var i=0; i<cutidxs.length; i++) {
 8152:                 if (document.getElementById('cut_'+cutidxs[i])) {
 8153:                     if (document.getElementById('cut_'+cutidxs[i]).checked == true) {
 8154:                         form.multicut.value += cutidxs[i]+',';
 8155:                         numchanges ++;
 8156:                         if (document.getElementById('skip_cut_'+cutidxs[i])) {
 8157:                             if (document.getElementById('skip_cut_'+cutidxs[i]).value == 0) {
 8158:                                 cutwarnings ++;
 8159:                             }
 8160:                         }
 8161:                     }
 8162:                 }
 8163:             }
 8164:         }
 8165:         var copyidxlist = document.cumulativeactions.allcopyidx.value;
 8166:         if ((copyidxlist != '') && (copyidxlist != null)) {
 8167:             var copyidxs = copyidxlist.split(',');
 8168:             for (var i=0; i<copyidxs.length; i++) {
 8169:                 if (document.getElementById('copy_'+copyidxs[i])) {
 8170:                     if (document.getElementById('copy_'+copyidxs[i]).checked) {
 8171:                         form.multicopy.value += copyidxs[i]+',';
 8172:                         numchanges ++;
 8173:                     }
 8174:                 }
 8175:             }
 8176:         }
 8177:         if (numchanges > 0) {
 8178:             form.multichange.value = numchanges;
 8179:         }
 8180:     }
 8181:     var dosettings = multiSettings();
 8182:     var haschanges = 0;
 8183:     if (dosettings == 1) {
 8184:         form.allencrypturl.value = '';
 8185:         form.allhiddenresource.value = '';
 8186:         form.changeparms.value = 'all';
 8187:         var patt=new RegExp(",\$");
 8188:         var allidxlist = document.cumulativesettings.allidx.value;
 8189:         if ((allidxlist != '') && (allidxlist != null)) {
 8190:             var allidxs = allidxlist.split(',');
 8191:             if (allidxs.length > 1) {
 8192:                 for (var i=0; i<allidxs.length; i++) {
 8193:                     if (document.getElementById('hiddenresource_'+allidxs[i])) {
 8194:                         if (document.getElementById('hiddenresource_'+allidxs[i]).checked) {
 8195:                             form.allhiddenresource.value += allidxs[i]+',';
 8196:                         }
 8197:                     }
 8198:                     if (document.getElementById('encrypturl_'+allidxs[i])) {
 8199:                         if (document.getElementById('encrypturl_'+allidxs[i]).checked) {
 8200:                             form.allencrypturl.value += allidxs[i]+',';
 8201:                         }
 8202:                     }
 8203:                 }
 8204:                 form.allhiddenresource.value = form.allhiddenresource.value.replace(patt,"");
 8205:                 form.allencrypturl.value = form.allencrypturl.value.replace(patt,"");
 8206:             }
 8207:         }
 8208:         form.allrandompick.value = '';
 8209:         form.allrandomorder.value = '';
 8210:         var allmapidxlist = document.cumulativesettings.allmapidx.value;
 8211:         if ((allmapidxlist != '') && (allmapidxlist != null)) {
 8212:             var allmapidxs = allmapidxlist.split(',');
 8213:             for (var i=0; i<allmapidxs.length; i++) {
 8214:                 var randompick = document.getElementById('randompick_'+allmapidxs[i]);
 8215:                 var rpicknum = document.getElementById('rpicknum_'+allmapidxs[i]);
 8216:                 var randorder = document.getElementById('randomorder_'+allmapidxs[i]);
 8217:                 if ((randompick.checked) && (rpicknum.value != '')) {
 8218:                     form.allrandompick.value += allmapidxs[i]+':'+rpicknum.value+',';
 8219:                 }
 8220:                 if (randorder.checked) {
 8221:                     form.allrandomorder.value += allmapidxs[i]+',';
 8222:                 }
 8223:             }
 8224:             form.allrandompick.value = form.allrandompick.value.replace(patt,"");
 8225:             form.allrandomorder.value = form.allrandomorder.value.replace(patt,"");
 8226:         }
 8227:         if (document.cumulativesettings.currhiddenresource.value != form.allhiddenresource.value) {
 8228:             haschanges = 1;
 8229:         }
 8230:         if (document.cumulativesettings.currencrypturl.value != form.allencrypturl.value) {
 8231:             haschanges = 1;
 8232:         }
 8233:         if (document.cumulativesettings.currrandomorder.value != form.allrandomorder.value) {
 8234:             haschanges = 1;
 8235:         }
 8236:         if (document.cumulativesettings.currrandompick.value != form.allrandompick.value) {
 8237:             haschanges = 1;
 8238:         }
 8239:     }
 8240:     if (doactions == 1) {
 8241:         if (numchanges > 0) {
 8242:             if ((cutwarnings > 0) || (remwarnings > 0) || (removalinfo > 0)) {
 8243:                 if (remwarnings > 0) {
 8244:                     if (!confirm('$js_lt{"p_rmr1"}\\n\\n$js_lt{"p_rmr3a"} '+remwarnings+' $js_lt{"p_rmr3b"}')) {
 8245:                         return false;
 8246:                     }
 8247:                 }
 8248:                 if (removalinfo > 0) {
 8249:                     if (!confirm('$js_lt{"p_rmr4"}\\n$js_lt{"p_rmr5"}\\n\\n$js_lt{"p_rmr3a"} '+removalinfo+' $js_lt{"p_rmr3b"}')) {
 8250:                         return false;
 8251:                     }
 8252:                 }
 8253:                 if (cutwarnings > 0) {
 8254:                     if (!confirm('$js_lt{"p_ctr1a"}\\n$js_lt{"p_ctr1b"}\\n\\n$js_lt{"p_ctr3a"} '+cutwarnings+' $js_lt{"p_ctr3b"}')) {
 8255:                         return false;
 8256:                     }
 8257:                 }
 8258:             }
 8259:             form.submit();
 8260:             return true;
 8261:         }
 8262:     }
 8263:     if (dosettings == 1) {
 8264:         if (haschanges == 1) {
 8265:             form.submit();
 8266:             return true;
 8267:         }
 8268:     }
 8269:     if ((dosettings == 1) && (doactions == 1)) {
 8270:         alert("$js_lt{'noor'}");
 8271:     } else {
 8272:         if (dosettings == 1) {
 8273:             alert("$js_lt{'noch'}");
 8274:         } else {
 8275:             alert("$js_lt{'noac'}");
 8276:         }
 8277:     }
 8278:     return false;
 8279: }
 8280: 
 8281: function setClass(value) {
 8282:     var cutclass = 'LC_docs_cut';
 8283:     var copyclass = 'LC_docs_copy';
 8284:     var removeclass = 'LC_docs_remove';
 8285:     var cutreg = new RegExp("\\\\b"+cutclass+"\\\\b");
 8286:     var copyreg = new RegExp("\\\\b"+copyclass+"\\\\b");
 8287:     var removereg = new RegExp("\\\\"+removeclass+"\\\\b");
 8288:     var links = document.getElementsByTagName('a');
 8289:     for (var i=0; i<links.length; i++) {
 8290:         var classes = links[i].className;
 8291:         if (cutreg.test(classes)) {
 8292:             links[i].className = cutclass;
 8293:             if (value == 1) {
 8294:                 links[i].className += " LC_menubuttons_link";
 8295:             }
 8296:         } else {
 8297:             if (copyreg.test(classes)) {
 8298:                 links[i].className = copyclass;
 8299:                 if (value == 1) {
 8300:                     links[i].className += " LC_menubuttons_link";
 8301:                 } 
 8302:             } else {
 8303:                 if (removereg.test(classes)) {
 8304:                     links[i].className = removeclass;
 8305:                     if (value == 1) {
 8306:                         links[i].className += " LC_menubuttons_link";
 8307:                     }
 8308:                 }
 8309:             }
 8310:         }
 8311:     }
 8312:     return;
 8313: }
 8314: 
 8315: function setBoxes(value) {
 8316:     var remidxlist = document.cumulativeactions.allremoveidx.value;
 8317:     if ((remidxlist != '') && (remidxlist != null)) {
 8318:         var remidxs = remidxlist.split(',');
 8319:         for (var i=0; i<remidxs.length; i++) {
 8320:             if (document.getElementById('remove_'+remidxs[i])) {
 8321:                 var item = document.getElementById('remove_'+remidxs[i]);
 8322:                 if (value == 1) {
 8323:                     item.className = 'LC_docs_remove';
 8324:                 } else {
 8325:                     item.className = 'LC_hidden';
 8326:                 }
 8327:             }
 8328:         }
 8329:     }
 8330:     var cutidxlist = document.cumulativeactions.allcutidx.value;
 8331:     if ((cutidxlist != '') && (cutidxlist != null)) {
 8332:         var cutidxs = cutidxlist.split(',');
 8333:         for (var i=0; i<cutidxs.length; i++) {
 8334:             if (document.getElementById('cut_'+cutidxs[i])) {
 8335:                 var item = document.getElementById('cut_'+cutidxs[i]);
 8336:                 if (value == 1) {
 8337:                     item.className = 'LC_docs_cut';
 8338:                 } else {
 8339:                     item.className = 'LC_hidden';
 8340:                 }
 8341:             }
 8342:         }
 8343:     }
 8344:     var copyidxlist = document.cumulativeactions.allcopyidx.value;
 8345:     if ((copyidxlist != '') && (copyidxlist != null)) {
 8346:         var copyidxs = copyidxlist.split(',');
 8347:         for (var i=0; i<copyidxs.length; i++) {
 8348:             if (document.getElementById('copy_'+copyidxs[i])) {
 8349:                 var item = document.getElementById('copy_'+copyidxs[i]);
 8350:                 if (value == 1) {
 8351:                     item.className = 'LC_docs_copy';
 8352:                 } else {
 8353:                     item.className = 'LC_hidden';
 8354:                 }
 8355:             }
 8356:         }
 8357:     }
 8358:     return;
 8359: }
 8360: 
 8361: function validImportCrsRes() {
 8362:     var path =  document.crsresimportform.coursepath.options[document.crsresimportform.coursepath.selectedIndex].value;
 8363:     var fname = document.crsresimportform.coursefile.options[document.crsresimportform.coursefile.selectedIndex].value;
 8364:     if ((fname == '') || (fname == null)) {
 8365:         alert("$js_lt{'nofi'}");
 8366:         return false;
 8367:     }
 8368:     var url = '/res/$coursedom/$coursenum/';
 8369:     if (path && path != '/') {
 8370:         url += path+'/';
 8371:     }
 8372:     if (fname != '') {
 8373:         url += fname;
 8374:     }
 8375:     var title = document.crsresimportform.crsrestitle.value;
 8376:     document.crsresimportform.importdetail.value=escape(title)+'='+escape(url);
 8377:     return true;
 8378: }
 8379: 
 8380: function validateNewRes(caller) {
 8381:     if (caller == 'single') {
 8382:         var role = document.courseresform.authorrole.options[document.courseresform.authorrole.selectedIndex].value; 
 8383:         var authorpath = document.courseresform.authorpath.options[document.courseresform.authorpath.selectedIndex].value;
 8384:         var resname = document.courseresform.newresourcename.value;
 8385:     }
 8386: }
 8387: 
 8388: ENDSCRIPT
 8389: }
 8390: 
 8391: sub history_tab_js {
 8392:     return <<"ENDHIST";
 8393: function toggleHistoryDisp(choice) {
 8394:     document.docslogform.docslog.value = choice;
 8395:     document.docslogform.submit();
 8396:     return;
 8397: }
 8398: 
 8399: ENDHIST
 8400: }
 8401: 
 8402: sub inject_data_js {
 8403:     return <<ENDINJECT;
 8404: 
 8405: function injectData(current, hiddenField, name, value) {
 8406:         currentElement = document.getElementById(hiddenField);
 8407:         currentElement.name = name;
 8408:         currentElement.value = value;
 8409:         current.submit();
 8410: }
 8411: 
 8412: ENDINJECT
 8413: }
 8414: 
 8415: sub dump_switchserver_js {
 8416:     my @hosts = @_;
 8417:     my %js_lt = &Apache::lonlocal::texthash(
 8418:         dump => 'Copying content to Authoring Space requires switching server.',
 8419:         swit => 'Switch server?',
 8420:     );
 8421:     my %html_js_lt = &Apache::lonlocal::texthash(
 8422:         swit => 'Switch server?',
 8423:         duco => 'Copying Content to Authoring Space',
 8424:         yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
 8425:         chos => 'Choose server',
 8426:     );
 8427:     &js_escape(\%js_lt);
 8428:     &html_escape(\%html_js_lt);
 8429:     &js_escape(\%html_js_lt);
 8430:     my $role = $env{'request.role'};
 8431:     my $js = <<"ENDSWJS";
 8432: <script type="text/javascript">
 8433: function write_switchserver() {
 8434:     var server;
 8435:     if (document.setserver.posshosts.length > 0) {
 8436:         for (var i=0; i<document.setserver.posshosts.length; i++) {
 8437:             if (document.setserver.posshosts[i].checked) {
 8438:                 server = document.setserver.posshosts[i].value;
 8439:             }
 8440:        }
 8441:        opener.document.location.href="/adm/switchserver?otherserver="+server+"&role=$role&origurl=/adm/coursedocs";
 8442:     }
 8443:     window.close();
 8444: }
 8445: </script>
 8446: 
 8447: ENDSWJS
 8448: 
 8449:     my $startpage = &Apache::loncommon::start_page('Choose server',$js,
 8450:                                                    {'only_body' => 1,
 8451:                                                     'js_ready'  => 1,});
 8452:     my $endpage = &Apache::loncommon::end_page({'js_ready'  => 1});
 8453: 
 8454:     my $hostpicker;
 8455:     my $count = 0;
 8456:     foreach my $host (sort(@hosts)) {
 8457:         my $checked;
 8458:         if ($count == 0) {
 8459:             $checked = ' checked="checked"';
 8460:         }
 8461:         $hostpicker .= '<label><input type="radio" name="posshosts" value="'.
 8462:                        $host.'"'.$checked.' />'.$host.'</label>&nbsp;&nbsp;';
 8463:         $count++;
 8464:     }
 8465:     
 8466:     return <<"ENDSWITCHJS";
 8467: 
 8468: function dump_needs_switchserver(url) {
 8469:     if (url!='' && url!= null) {
 8470:         if (confirm("$js_lt{'dump'}\\n$js_lt{'swit'}")) {
 8471:             go(url);
 8472:         }
 8473:     }
 8474:     return;
 8475: }
 8476: 
 8477: function choose_switchserver_window() {
 8478:     newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
 8479:     newWindow.document.open();
 8480:     newWindow.document.writeln('$startpage');
 8481:     newWindow.document.write('<h3>$html_js_lt{'duco'}<\\/h3>\\n'+
 8482:        '<p>$html_js_lt{'yone'}<\\/p>\\n'+
 8483:        '<div class="LC_left_float"><fieldset><legend>$html_js_lt{'chos'}<\\/legend>\\n'+
 8484:        '<form name="setserver" method="post" action="" \\/>\\n'+
 8485:        '$hostpicker\\n'+
 8486:        '<br \\/><br \\/>\\n'+
 8487:        '<input type="button" name="makeswitch" value="$html_js_lt{'swit'}" '+
 8488:        'onclick="write_switchserver();" \\/>\\n'+
 8489:        '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
 8490:     newWindow.document.writeln('$endpage');
 8491:     newWindow.document.close();
 8492:     newWindow.focus();
 8493: }
 8494: 
 8495: ENDSWITCHJS
 8496: }
 8497: 
 8498: sub makedocslogform {
 8499:     my ($formelems,$docslog) = @_;
 8500:     return <<"LOGSFORM";
 8501:  <form action="/adm/coursedocs" method="post" name="docslogform">
 8502:    <input type="hidden" name="docslog" value="$docslog" />
 8503:    $formelems
 8504:  </form>
 8505: LOGSFORM
 8506: }
 8507: 
 8508: sub makesimpleeditform {
 8509:     my ($formelems) = @_;
 8510:     return <<"SIMPFORM";
 8511:  <form name="simpleedit" method="post" action="/adm/coursedocs">
 8512:    <input type="hidden" name="importdetail" value="" />
 8513:    $formelems
 8514:  </form>
 8515: SIMPFORM
 8516: }
 8517: 
 8518: sub makenewproblem {
 8519:     my ($r,$coursedom,$coursenum) = @_;
 8520: # Creating a new problem
 8521:     my ($redirect,$error);
 8522:     if ($env{'form.authorrole'}) {
 8523:         my ($newsubdir,$filename);
 8524:         if ($env{'form.newsubdir'}) {
 8525:             if ($env{'form.newsubdirname'} ne '') {
 8526:                 $newsubdir = $env{'form.newsubdirname'};
 8527:             }    
 8528:         }
 8529:         if ($env{'form.newresourcename'}) {
 8530:             $filename = $env{'form.newresourcename'};
 8531:             $filename =~ s/\.(\d+)(\.\w+)$/$2/;
 8532:             $filename =~ s/`//g;
 8533:             $filename =~ s{/\.\./}{_}g;
 8534:             $filename =~ s/\.+/./g;
 8535:             $filename =~ s{/+}{_}g;
 8536:             if ($filename ne '') {
 8537:                 my ($name,$ext) = ($filename =~ /(.+)\.([^.]+)$/);
 8538:                 if (($ext) && ($ext ne '.problem')) {
 8539:                     $filename = $name.'.problem';
 8540:                 } elsif ($ext eq '') {
 8541:                     $filename .= '.problem';
 8542:                 }
 8543:                 my $docroot = $r->dir_config('lonDocRoot');
 8544:                 my @ids=&Apache::lonnet::current_machine_ids();
 8545:                 if ($env{'form.authorrole'} eq 'author') {
 8546:                     if ($env{'user.author'}) {
 8547:                         if ($env{'user.home'} && grep(/^\Q$env{'user.home'}\E$/,@ids)) {
 8548:                             my $url = "/priv/$env{'user.domain'}/$env{'user.name'}";
 8549:                             my $path = $docroot.$url;
 8550:                             my $subdir = $env{'form.authorpath'};
 8551:                             $redirect = &finishnewprob($url,$path,$subdir,$newsubdir,$filename);
 8552:                         }
 8553:                     }
 8554:                 } elsif ($env{'form.authorrole'} eq 'course') {
 8555:                     my $chome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8556:                     if ($chome && grep(/^\Q$chome\E$/,@ids)) {
 8557:                         my $url = "/priv/$coursedom/$coursenum";
 8558:                         my $path=$docroot.$url;
 8559:                         my $subdir = $env{'form.authorpath'};
 8560:                         $redirect = &finishnewprob($url,$path,$subdir,$newsubdir,$filename);
 8561:                         if ($redirect) {
 8562:                             my $rightsfile = 'default.rights';
 8563:                             my $sourcerights = "$path/$rightsfile";
 8564:                             my $targetrights = $docroot."/res/$coursedom/$coursenum/$rightsfile";
 8565:                             my $now = time;
 8566:                             if (!-e $sourcerights) {
 8567:                                 my $cid = $coursedom.'_'.$coursenum;
 8568:                                 if (open(my $fh,">$sourcerights")) {
 8569:                                     print $fh <<END;
 8570: <accessrule effect="deny" realm="" type="course" role="" />
 8571: <accessrule effect="allow" realm="$cid" type="course" role="" />
 8572: END
 8573:                                     close($fh);
 8574:                                 }
 8575:                             }
 8576:                             if (!-e "$sourcerights.meta") {
 8577:                                 if (open(my $fh,">$sourcerights.meta")) {
 8578:                                     my $author=$env{'environment.firstname'}.' '.
 8579:                                                $env{'environment.middlename'}.' '.
 8580:                                                $env{'environment.lastname'}.' '.
 8581:                                                $env{'environment.generation'};
 8582:                                     $author =~ s/\s+$//;
 8583:                                     print $fh <<"END";
 8584: 
 8585: <abstract></abstract>
 8586: <author>$author</author>
 8587: <authorspace>$coursenum:$coursedom</authorspace>
 8588: <copyright>private</copyright>
 8589: <creationdate>$now</creationdate>
 8590: <customdistributionfile></customdistributionfile>
 8591: <dependencies></dependencies>
 8592: <domain>$coursedom</domain>
 8593: <highestgradelevel>0</highestgradelevel>
 8594: <keywords></keywords>
 8595: <language>notset </language>
 8596: <lastrevisiondate>$now</lastrevisiondate>
 8597: <lowestgradelevel>0</lowestgradelevel>
 8598: <mime>rights</mime>
 8599: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
 8600: <notes></notes>
 8601: <obsolete></obsolete>
 8602: <obsoletereplacement></obsoletereplacement>
 8603: <owner>$coursenum:$coursedom</owner>
 8604: <rule>deny:::course,allow:$cid::course</rule>
 8605: <sourceavail></sourceavail>
 8606: <standards></standards>
 8607: <subject></subject>
 8608: <title></title>
 8609: END
 8610:                                         close($fh);
 8611:                                 }
 8612:                                 if ((-e $sourcerights) && (-e "$sourcerights.meta")) {
 8613:                                     if (!-e "$docroot/res/$coursedom") {
 8614:                                         mkdir("$docroot/res/$coursedom",0755);
 8615:                                     }
 8616:                                     if (!-e "$docroot/res/$coursedom/$coursenum") {
 8617:                                         mkdir("$docroot/res/$coursedom/$coursenum",0755);
 8618:                                     }
 8619:                                     if ((-e "$docroot/res/$coursedom/$coursenum") && (!-e $targetrights)) {
 8620:                                         my $nokeyref = &Apache::lonpublisher::getnokey($r->dir_config('lonIncludes'));
 8621:                                         my $output = &Apache::lonpublisher::batchpublish($r,$sourcerights,$targetrights,$nokeyref,1);
 8622:                                     }
 8623:                                 }
 8624:                             }
 8625:                             if ($env{'form.newresourceadd'}) {
 8626:                                 my $template = $env{'form.template'};
 8627:                                 my $source = $docroot.$redirect;
 8628:                                 my $target = $redirect;
 8629:                                 $target =~ s{^/priv/}{/res/};
 8630:                                 $target = $docroot.$target;
 8631:                                 if (!-e $source) {
 8632:                                     my $copyfrom; 
 8633:                                     if ($template) {
 8634:                                         my %templates;
 8635:                                         my @files = &Apache::lonhomework::get_template_list('problem');
 8636:                                         foreach my $poss (@files) {
 8637:                                             if (ref($poss) eq 'ARRAY') {
 8638:                                                 if ($template eq $poss->[0]) {
 8639:                                                     $templates{$template} = 1;
 8640:                                                     last;
 8641:                                                 }
 8642:                                             }
 8643:                                         }
 8644:                                         if ($templates{$template}) {
 8645:                                             $copyfrom = $template;
 8646:                                         }
 8647:                                     }
 8648:                                     unless ($copyfrom) {
 8649:                                         $copyfrom = $r->dir_config('lonIncludes').'/templates/blank.problem';
 8650:                                     }
 8651:                                     &File::Copy::copy($copyfrom,$source);
 8652:                                 }
 8653:                                 if (!-e "$source.meta") {
 8654:                                     my $cid = $coursedom.'_'.$coursenum;
 8655:                                     my $now = time;
 8656:                                     if (open(my $fh,">$source.meta")) {
 8657:                                         my $author=$env{'environment.firstname'}.' '.
 8658:                                                    $env{'environment.middlename'}.' '.
 8659:                                                    $env{'environment.lastname'}.' '.
 8660:                                                    $env{'environment.generation'};
 8661:                                         $author =~ s/\s+$//;
 8662:                                         my $title = $env{'form.newresourcetitle'};
 8663:                                         $title =~ s/^\s+|\s+$//g;
 8664:                                         print $fh <<END;
 8665: 
 8666: <abstract></abstract>
 8667: <author>$author</author>
 8668: <authorspace>$coursenum:$coursedom</authorspace>
 8669: <copyright>custom</copyright>
 8670: <creationdate>$now</creationdate>
 8671: <customdistributionfile>/res/$coursedom/$coursenum/default.rights</customdistributionfile>
 8672: <dependencies></dependencies>
 8673: <domain>$coursedom</domain>
 8674: <highestgradelevel>0</highestgradelevel>
 8675: <keywords></keywords>
 8676: <language>notset </language>
 8677: <lastrevisiondate>$now</lastrevisiondate>
 8678: <lowestgradelevel>0</lowestgradelevel>
 8679: <mime>problem</mime>
 8680: <modifyinguser>$coursenum:$coursedom</modifyinguser>
 8681: <notes></notes>
 8682: <obsolete></obsolete>
 8683: <obsoletereplacement></obsoletereplacement>
 8684: <owner>$coursenum:$coursedom</owner>
 8685: <sourceavail></sourceavail>
 8686: <standards></standards>
 8687: <subject></subject>
 8688: <title>$title</title>
 8689: END
 8690:                                         close($fh);
 8691:                                     }
 8692:                                 }
 8693:                             }
 8694:                         }
 8695:                     }
 8696:                 } else {
 8697:                     my ($auname,$audom,$role) = split('___',$env{'form.authorrole'});
 8698:                     my $rolehome = &Apache::lonnet::homeserver($auname,$audom);
 8699:                     if (grep(/^\Q$rolehome\E$/,@ids)) {
 8700:                         my $now = time;
 8701:                         if (exists($env{'user.role.'.$role.'./'.$audom.'/'.$auname})) {
 8702:                             my ($start,$end) = split(/\./,$env{'user.role.'.$role.'./'.$audom.'/'.$auname});
 8703:                             if (($start <= $now) && (($end == 0) || ($end >= $now))) { 
 8704:                                 my $url = "/priv/$audom/$auname";  
 8705:                                 my $path = $r->dir_config('lonDocRoot').$url;
 8706:                                 my $subdir = $env{'form.authorpath'};
 8707:                                 $redirect = &finishnewprob($url,$path,$subdir,$newsubdir,$filename);
 8708:                             }
 8709:                         }
 8710:                     }
 8711:                 }
 8712:             }
 8713:         }
 8714:     }
 8715:     return ($redirect,$error);
 8716: }
 8717: 
 8718: sub finishnewprob {
 8719:     my ($url,$path,$subdir,$newsubdir,$filename) = @_;
 8720:     unless (-d $path) {
 8721:         unless (mkdir($path,02770)) {
 8722:             return;
 8723:         }
 8724:     }
 8725:     my $redirect;
 8726:     if ($subdir ne '/') {
 8727:         $subdir = &cleandir($subdir);
 8728:         if (($subdir ne '') && (-d "$path/$subdir")) {
 8729:             $path .= "/$subdir";
 8730:             $url .= "/$subdir";
 8731:         }
 8732:     }
 8733:     my $dest;
 8734:     if ($newsubdir ne '') {
 8735:         $newsubdir = &cleandir($newsubdir);
 8736:     }
 8737:     if ($newsubdir ne '') {
 8738:         if (-d "$path/$newsubdir") {
 8739:             $dest = "$path/$newsubdir/$filename";
 8740:         } else {
 8741:             my $dirok;
 8742:             unless (-e "$path/$newsubdir") {
 8743:                 if (mkdir("$path/$newsubdir",02770)) {
 8744:                     if (chmod(02770,"$path/$newsubdir")) {
 8745:                         $dirok = 1;
 8746:                     }
 8747:                 }
 8748:             }
 8749:             if ($dirok) {
 8750:                 $dest = "$path/$newsubdir/$filename";
 8751:             }
 8752:         }
 8753:         if (($dest ne '') && (!-e $dest)) {
 8754:             $redirect = "$url/$newsubdir/$filename";
 8755:         }
 8756:     } else {
 8757:         $dest = "$path/$filename";
 8758:         if (($dest ne '') && (!-e $dest)) {
 8759:             $redirect = "$url/$filename";
 8760:         }
 8761:     }
 8762:     return $redirect;
 8763: }
 8764: 
 8765: sub cleandir {
 8766:     my ($dir) = @_;
 8767:     $dir =~ s/^\s+//;
 8768:     $dir =~ s/\s+$//;
 8769:     $dir =~ s/\.+//g;
 8770:     $dir =~ s/[\#\?&%\":]//g;
 8771:     return $dir;
 8772: }
 8773: 
 8774: 1;
 8775: __END__
 8776: 
 8777: 
 8778: =head1 NAME
 8779: 
 8780: Apache::londocs.pm
 8781: 
 8782: =head1 SYNOPSIS
 8783: 
 8784: This is part of the LearningOnline Network with CAPA project
 8785: described at http://www.lon-capa.org.
 8786: 
 8787: =head1 SUBROUTINES
 8788: 
 8789: =over
 8790: 
 8791: =item %help=()
 8792: 
 8793: Available help topics
 8794: 
 8795: =item mapread()
 8796: 
 8797: Mapread read maps into LONCAPA::map:: global arrays
 8798: @order and @resources, determines status
 8799: sets @order - pointer to resources in right order
 8800: sets @resources - array with the resources with correct idx
 8801: 
 8802: =item authorhosts()
 8803: 
 8804: Return hash with valid author names
 8805: 
 8806: =item clean()
 8807: 
 8808: =item dumpcourse()
 8809: 
 8810:     Actually dump course
 8811: 
 8812: =item group_import()
 8813: 
 8814:     Imports the given (name, url) resources into the course
 8815:     coursenum, coursedom, and folder must precede the list
 8816: 
 8817: =item breadcrumbs()
 8818: 
 8819: =item log_docs()
 8820: 
 8821: =item docs_change_log()
 8822: 
 8823: =item update_paste_buffer()
 8824: 
 8825: =item print_paste_buffer()
 8826: 
 8827: =item do_paste_from_buffer()
 8828: 
 8829: =item do_buffer_empty() 
 8830: 
 8831: =item clear_from_buffer()
 8832: 
 8833: =item get_newmap_url()
 8834: 
 8835: =item dbcopy()
 8836: 
 8837: =item uniqueness_check()
 8838: 
 8839: =item contained_map_check()
 8840: 
 8841: =item url_paste_fixups()
 8842: 
 8843: =item apply_fixups()
 8844: 
 8845: =item copy_dependencies()
 8846: 
 8847: =item update_parameter()
 8848: 
 8849: =item handle_edit_cmd()
 8850: 
 8851: =item editor()
 8852: 
 8853: =item process_file_upload()
 8854: 
 8855: =item process_secondary_uploads()
 8856: 
 8857: =item is_supplemental_title()
 8858: 
 8859: =item entryline()
 8860: 
 8861: =item tiehash()
 8862: 
 8863: =item untiehash()
 8864: 
 8865: =item checkonthis()
 8866: 
 8867: check on this
 8868: 
 8869: =item verifycontent()
 8870: 
 8871: Verify Content
 8872: 
 8873: =item devalidateversioncache() 
 8874: 
 8875: =item checkversions()
 8876: 
 8877: Check Versions
 8878: 
 8879: =item mark_hash_old()
 8880: 
 8881: =item is_hash_old()
 8882: 
 8883: =item changewarning()
 8884: 
 8885: =item init_breadcrumbs()
 8886: 
 8887: Breadcrumbs for special functions
 8888: 
 8889: =item create_list_elements()
 8890: 
 8891: =item create_form_ul()
 8892: 
 8893: =item startContentScreen() 
 8894: 
 8895: =item endContentScreen()
 8896: 
 8897: =item supplemental_base()
 8898: 
 8899: =item embedded_form_elems()
 8900: 
 8901: =item embedded_destination()
 8902: 
 8903: =item return_to_editor()
 8904: 
 8905: =item decompression_info()
 8906: 
 8907: =item decompression_phase_one()
 8908: 
 8909: =item decompression_phase_two()
 8910: 
 8911: =item remove_archive()
 8912: 
 8913: =item generate_admin_menu()
 8914: 
 8915: =item generate_edit_table()
 8916: 
 8917: =item editing_js()
 8918: 
 8919: =item history_tab_js()
 8920: 
 8921: =item inject_data_js()
 8922: 
 8923: =item dump_switchserver_js()
 8924: 
 8925: =item resize_scrollbox_js()
 8926: 
 8927: =item makedocslogform()
 8928: 
 8929: =item makesimpleeditform()
 8930: 
 8931: =back
 8932: 
 8933: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>