File:  [LON-CAPA] / loncom / interface / londocs.pm
Revision 1.484.2.93.2.10: download - view: text, annotated - select for diffs
Fri Jan 20 16:55:44 2023 UTC (17 months, 1 week ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.484.2.93: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.682, 1.683, 1.684, 1.685, 1.686, 1.687, 1.688

    1: # The LearningOnline Network
    2: # Documents
    3: #
    4: # $Id: londocs.pm,v 1.484.2.93.2.10 2023/01/20 16:55:44 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::loncourserespicker();
   47: use HTML::Entities;
   48: use HTML::TokeParser;
   49: use GDBM_File;
   50: use File::MMagic;
   51: use Apache::lonlocal;
   52: use Cwd;
   53: use LONCAPA qw(:DEFAULT :match);
   54: 
   55: my $iconpath;
   56: 
   57: my %hash;
   58: 
   59: my $hashtied;
   60: my %alreadyseen=();
   61: 
   62: my $hadchanges;
   63: my $suppchanges;
   64: 
   65: 
   66: my %help=();
   67: 
   68: 
   69: sub mapread {
   70:     my ($coursenum,$coursedom,$map)=@_;
   71:     return
   72:       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   73: 			     $map);
   74: }
   75: 
   76: sub storemap {
   77:     my ($coursenum,$coursedom,$map,$contentchg)=@_;
   78:     my $report;
   79:     if (($contentchg) && ($map =~ /^default/)) {
   80:        $report = 1;
   81:     }
   82:     my ($outtext,$errtext)=
   83:       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   84: 			      $map,1,$report);
   85:     if ($errtext) { return ($errtext,2); }
   86: 
   87:     if ($map =~ /^default/) {
   88:         $hadchanges=1;
   89:     } elsif ($contentchg) {
   90:         $suppchanges=1;
   91:     }
   92:     return ($errtext,0);
   93: }
   94: 
   95: 
   96: 
   97: sub authorhosts {
   98:     my %outhash=();
   99:     my $home=0;
  100:     my $other=0;
  101:     foreach my $key (keys(%env)) {
  102: 	if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
  103: 	    my $role=$1;
  104: 	    my $realm=$2;
  105: 	    my ($start,$end)=split(/\./,$env{$key});
  106: 	    if (($start) && ($start>time)) { next; }
  107: 	    if (($end) && (time>$end)) { next; }
  108: 	    my ($ca,$cd);
  109: 	    if ($1 eq 'au') {
  110: 		$ca=$env{'user.name'};
  111: 		$cd=$env{'user.domain'};
  112: 	    } else {
  113: 		($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  114: 	    }
  115: 	    my $allowed=0;
  116: 	    my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  117: 	    my @ids=&Apache::lonnet::current_machine_ids();
  118: 	    foreach my $id (@ids) {
  119:                 if ($id eq $myhome) {
  120:                     $allowed=1;
  121:                     last;
  122:                 }
  123:             }
  124: 	    if ($allowed) {
  125: 		$home++;
  126: 		$outhash{'home_'.$ca.':'.$cd}=1;
  127: 	    } else {
  128: 		$outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
  129: 		$other++;
  130: 	    }
  131: 	}
  132:     }
  133:     return ($home,$other,%outhash);
  134: }
  135: 
  136: 
  137: sub clean {
  138:     my ($title)=@_;
  139:     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
  140:     return $title;
  141: }
  142: 
  143: sub default_folderpath {
  144:     my ($coursenum,$coursedom,$navmapref) = @_;
  145:     return unless ($coursenum && $coursedom && ref($navmapref));
  146: # Check if entire course is hidden and/or encrypted
  147:     my ($hiddenmap,$encryptmap,$folderpath,$hiddentop);
  148:     my $toplevel = "uploaded/$coursedom/$coursenum/default.sequence";
  149:     unless (ref($$navmapref)) {
  150:         $$navmapref = Apache::lonnavmaps::navmap->new();
  151:     }
  152:     if (ref($$navmapref)) {
  153:         if (lc($$navmapref->get_mapparam(undef,$toplevel,"0.hiddenresource")) eq 'yes') {
  154:             my $filterFunc = sub { my $res = shift; return (!$res->randomout() && !$res->is_map()) };
  155:             my @resources = $$navmapref->retrieveResources($toplevel,$filterFunc,1,1);
  156:             unless (@resources) {
  157:                 $hiddenmap = 1;
  158:                 unless ($env{'request.role.adv'}) {
  159:                     $hiddentop = 1;
  160:                     if ($env{'form.folder'}) {
  161:                         undef($env{'form.folder'});
  162:                     }
  163:                 }
  164:             }
  165:         }
  166:         if (lc($$navmapref->get_mapparam(undef,$toplevel,"0.encrypturl")) eq 'yes') {
  167:             $encryptmap = 1;
  168:         }
  169:     }
  170:     unless ($hiddentop) {
  171:         $folderpath='default&'.&escape(&mt('Main Content')).
  172:                     '::'.$hiddenmap.':'.$encryptmap.'::';
  173:     }
  174:     if (wantarray) {
  175:         return ($folderpath,$hiddentop);
  176:     } else {
  177:         return $folderpath;
  178:     }
  179: }
  180: 
  181: sub validate_supppath {
  182:     my ($coursenum,$coursedom) = @_;
  183:     my $backto;
  184:     if ($env{'form.supppath'} ne '') {
  185:         my @items = split(/\&/,$env{'form.supppath'});
  186:         my ($badpath,$got_supp,$supppath,%supphidden,%suppids);
  187:         for (my $i=0; $i<@items; $i++) {
  188:             my $odd = $i%2;
  189:             if ((!$odd) && ($items[$i] !~ /^supplemental(|_\d+)$/)) {
  190:                 $badpath = 1;
  191:                 last;
  192:             } elsif ($odd) {
  193:                 my $suffix;
  194:                 my $idx = $i-1;
  195:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
  196:                     $backto .= '&'.$1;
  197:                 } elsif ($items[$idx] eq 'supplemental') {
  198:                     $backto .= '&'.$items[$i];
  199:                 } else {
  200:                     $backto .= '&'.$items[$i];
  201:                     my $is_hidden;
  202:                     unless ($got_supp) {
  203:                         my ($supplemental) = &Apache::loncommon::get_supplemental($coursenum,$coursedom);
  204:                         if (ref($supplemental) eq 'HASH') {
  205:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
  206:                                 %supphidden = %{$supplemental->{'hidden'}};
  207:                             }
  208:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
  209:                                 %suppids = %{$supplemental->{'ids'}};
  210:                             }
  211:                         }
  212:                         $got_supp = 1;
  213:                     }
  214:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
  215:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
  216:                         if ($supphidden{$mapid}) {
  217:                             $is_hidden = 1;
  218:                         }
  219:                     }
  220:                     $suffix = '::'.$is_hidden.':::';
  221:                 }
  222:                 $supppath .= '&'.$items[$i].$suffix;
  223:             } else {
  224:                 $supppath .= '&'.$items[$i];
  225:                 $backto .= '&'.$items[$i];
  226:             }
  227:         }
  228:         if ($badpath) {
  229:             delete($env{'form.supppath'});
  230:         } else {
  231:             $supppath =~ s/^\&//;
  232:             $backto =~ s/^\&//;
  233:             $env{'form.supppath'} = $supppath;
  234:         }
  235:     }
  236:     return $backto;
  237: }
  238: 
  239: sub dumpcourse {
  240:     my ($r) = @_;
  241:     my $crstype = &Apache::loncommon::course_type();
  242:     my ($starthash,$js);
  243:     unless (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  244:         $js = <<"ENDJS";
  245: <script type="text/javascript">
  246: // <![CDATA[
  247: 
  248: function hide_searching() {
  249:     if (document.getElementById('searching')) {
  250:         document.getElementById('searching').style.display = 'none';
  251:     }
  252:     return;
  253: }
  254: 
  255: // ]]>
  256: </script>
  257: ENDJS
  258:         $starthash = {
  259:                          add_entries => {'onload' => "hide_searching();"},
  260:                      };
  261:     }
  262:     $r->print(&Apache::loncommon::start_page('Copy '.$crstype.' Content to Authoring Space',$js,$starthash)."\n".
  263:               &Apache::lonhtmlcommon::breadcrumbs('Copy '.$crstype.' Content to Authoring Space')."\n");
  264:     $r->print(&startContentScreen('tools'));
  265:     my ($home,$other,%outhash)=&authorhosts();
  266:     unless ($home) {
  267:         $r->print(&endContentScreen());
  268:         return '';
  269:     }
  270:     my $origcrsid=$env{'request.course.id'};
  271:     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
  272:     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  273: # Do the dumping
  274: 	unless ($outhash{'home_'.$env{'form.authorspace'}}) {
  275:             $r->print(&endContentScreen());
  276:             return '';
  277:         }
  278: 	my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  279: 	$r->print('<h3>'.&mt('Copying Files').'</h3>');
  280: 	my $title=$env{'form.authorfolder'};
  281: 	$title=&clean($title);
  282:         my ($navmap,$errormsg) =
  283:             &Apache::loncourserespicker::get_navmap_object($crstype,'dumpdocs');
  284:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  285:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  286:         my (%maps,%resources,%titles);
  287:         if (!ref($navmap)) {
  288:             $r->print($errormsg.
  289:                       &endContentScreen());
  290:             return '';
  291:         } else {
  292:             &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
  293:                                                                    'dumpdocs',$cdom,$cnum);
  294:         }
  295:         my @todump = &Apache::loncommon::get_env_multiple('form.archive');
  296:         my (%tocopy,%replacehash,%lookup,%deps,%display,%result,%depresult,%simpleproblems,%simplepages,
  297:             %newcontent,%has_simpleprobs);
  298:         foreach my $item (sort {$a <=> $b} (@todump)) {
  299:             my $name = $env{'form.namefor_'.$item};
  300:             if ($resources{$item}) {
  301:                 my ($map,$id,$res) = &Apache::lonnet::decode_symb($resources{$item});
  302:                 if ($res =~ m{^uploaded/$cdom/$cnum/\E((?:docs|supplemental)/.+)$}) {
  303:                     $tocopy{$1} = $name;
  304:                     $display{$item} = $1;
  305:                     $lookup{$1} = $item;
  306:                 } elsif ($res eq 'lib/templates/simpleproblem.problem') {
  307:                     $simpleproblems{$item} = {
  308:                                                 symb => $resources{$item},
  309:                                                 name => $name,
  310:                                              };
  311:                     $display{$item} = 'simpleproblem_'.$name;
  312:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(.+)$}) {
  313:                         $has_simpleprobs{$1}{$id} = $item;
  314:                     }
  315:                 } elsif ($res =~ m{^adm/$match_domain/$match_username/(\d+)/smppg}) {
  316:                     my $marker = $1;
  317:                     my $db_name = &Apache::lonsimplepage::get_db_name($res,$marker,$cdom,$cnum);
  318:                     $simplepages{$item} = {
  319:                                             res    => $res,
  320:                                             title  => $titles{$item},
  321:                                             db     => $db_name,
  322:                                             marker => $marker,
  323:                                             symb   => $resources{$item},
  324:                                             name   => $name,
  325:                                           };
  326:                     $display{$item} = '/'.$res;
  327:                 }
  328:             } elsif ($maps{$item}) {
  329:                 if ($maps{$item} =~ m{^\Quploaded/$cdom/$cnum/\E((?:default|supplemental)_\d+\.(?:sequence|page))$}) {
  330:                     $tocopy{$1} = $name;
  331:                     $display{$item} = $1;
  332:                     $lookup{$1} = $item;
  333:                 }
  334:             } else {
  335:                 next;
  336:             }
  337:         }
  338: 	my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  339: 	$crs=~s/\_/\//g;
  340:         my $mm = new File::MMagic;
  341:         my $prefix = "/uploaded/$cdom/$cnum/";
  342:         %replacehash = %tocopy;
  343:         foreach my $item (sort(keys(%simpleproblems))) {
  344:             my $content = &Apache::imsexport::simpleproblem($simpleproblems{$item}{'symb'});
  345:             $newcontent{$display{$item}} = $content;
  346:         }
  347:         my $gateway = Apache::lonhtmlgateway->new('web');
  348:         foreach my $item (sort(keys(%simplepages))) {
  349:             if (ref($simplepages{$item}) eq 'HASH') {
  350:                 my $pagetitle = $simplepages{$item}{'title'};
  351:                 my %fields = &Apache::lonnet::dump($simplepages{$item}{'db'},$cdom,$cnum);
  352:                 my %contents;
  353:                 foreach my $field (keys(%fields)) {
  354:                     if ($field =~ /^(?:aaa|bbb|ccc)_(\w+)$/) {
  355:                         my $name = $1;
  356:                         my $msg = $fields{$field};
  357:                         if ($name eq 'webreferences') {
  358:                             if ($msg =~ m{^https?://}) {
  359:                                 $contents{$name} = '<a href="'.$msg.'"><tt>'.$msg.'</tt></a>';
  360:                             }
  361:                         } else {
  362:                             $msg = &Encode::decode('utf8',$msg);
  363:                             $msg = $gateway->process_outgoing_html($msg,1);
  364:                             $contents{$name} = $msg;
  365:                         }
  366:                     } elsif ($field eq 'uploaded.photourl') {
  367:                         my $marker = $simplepages{$item}{marker};
  368:                         if ($fields{$field} =~ m{^\Q$prefix\E(simplepage/$marker/.+)$}) {
  369:                             my $filepath = $1;
  370:                             my ($relpath,$fname) = ($filepath =~ m{^(.+/)([^/]+)$});
  371:                             if ($fname ne '') {
  372:                                 $fname=~s/\.(\w+)$//;
  373:                                 my $ext=$1;
  374:                                 $fname = &clean($fname);
  375:                                 $fname.='.'.$ext;
  376:                                 $contents{image} = '<img src="'.$relpath.$fname.'" alt="Image" />';
  377:                                 $replacehash{$filepath} = $relpath.$fname;
  378:                                 $deps{$item}{$filepath} = 1;
  379:                             }
  380:                         }
  381:                     }
  382:                 }
  383:                 $replacehash{'/'.$simplepages{$item}{'res'}} = $simplepages{$item}{'name'};
  384:                 $lookup{'/'.$simplepages{$item}{'res'}} = $item;
  385:                 my $content = '
  386: <html>
  387: <head>
  388: <title>'.$pagetitle.'</title>
  389: </head>
  390: <body bgcolor="#ffffff">';
  391:                 if ($contents{title}) {
  392:                     $content .= "\n".'<h2>'.$contents{title}.'</h2>';
  393:                 }
  394:                 if ($contents{image}) {
  395:                     $content .= "\n".$contents{image};
  396:                 }
  397:                 if ($contents{content}) {
  398:                     $content .= '
  399: <div class="LC_Box">
  400: <h4 class="LC_hcell">'.&mt('Content').'</h4>'.
  401: $contents{content}.'
  402: </div>';
  403:                 }
  404:                 if ($contents{webreferences}) {
  405:                     $content .= '
  406: <div class="LC_Box">
  407: <h4 class="LC_hcell">'.&mt('Web References').'</h4>'.
  408: $contents{webreferences}.'
  409: </div>';
  410:                 }
  411:                 $content .= '
  412: </body>
  413: </html>
  414: ';
  415:                 $newcontent{'/'.$simplepages{$item}{res}} = $content;
  416:             }
  417:         }
  418:         foreach my $item (keys(%tocopy)) {
  419:             unless ($item=~/\.(sequence|page)$/) {
  420:                 my $currurlpath = $prefix.$item;
  421:                 my $currdirpath = &Apache::lonnet::filelocation('',$currurlpath);
  422:                 &recurse_html($mm,$prefix,$currdirpath,$currurlpath,$item,$lookup{$item},\%replacehash,\%deps);
  423:             }
  424:         }
  425:         foreach my $num (sort {$a <=> $b} (@todump)) {
  426:             my $src = $display{$num};
  427:             next if ($src eq '');
  428:             my @needcopy = ();
  429:             if ($replacehash{$src}) {
  430:                 push(@needcopy,$src);
  431:                 if (ref($deps{$num}) eq 'HASH') {
  432:                     foreach my $dep (sort(keys(%{$deps{$num}}))) {
  433:                         if ($replacehash{$dep}) {
  434:                             push(@needcopy,$dep);
  435:                         }
  436:                     }
  437:                 }
  438:             } elsif ($src =~ /^simpleproblem_/) {
  439:                 push(@needcopy,$src);
  440:             }
  441:             next if (@needcopy == 0);
  442:             my ($result,$depresult);
  443:             for (my $i=0; $i<@needcopy; $i++) {
  444:                 my $item = $needcopy[$i];
  445:                 my $newfilename;
  446:                 if ($simpleproblems{$num}) {
  447:                     $newfilename=$title.'/'.$simpleproblems{$num}{'name'};
  448:                 } else {
  449:                     $newfilename=$title.'/'.$replacehash{$item};
  450:                 }
  451:                 $newfilename=~s/\.(\w+)$//;
  452:                my $ext=$1;
  453:                 $newfilename=&clean($newfilename);
  454:                 $newfilename.='.'.$ext;
  455:                 my ($newrelpath) = ($newfilename =~ m{^\Q$title/\E(.+)$});
  456:                 if ($newrelpath ne $replacehash{$item}) {
  457:                     $replacehash{$item} = $newrelpath;
  458:                 }
  459:                 my @dirs=split(/\//,$newfilename);
  460:                 my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
  461:                 my $makepath=$path;
  462:                 my $fail;
  463:                 my $origin;
  464:                 for (my $i=0;$i<$#dirs;$i++) {
  465:                     $makepath.='/'.$dirs[$i];
  466:                     unless (-e $makepath) {
  467:                         unless(mkdir($makepath,0755)) {
  468:                             $fail = &mt('Directory creation failed.');
  469:                         }
  470:                     }
  471:                 }
  472:                 if ($i == 0) {
  473:                     $result = '<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ';
  474:                 } else {
  475:                     $depresult .= '<li><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt> '.
  476:                                   '<span class="LC_fontsize_small" style="font-weight: bold;">'.
  477:                                   &mt('(dependency)').'</span>: ';
  478:                 }
  479:                 if (-e $path.'/'.$newfilename) {
  480:                     $fail = &mt('Destination already exists -- not overwriting.');
  481:                 } else {
  482:                     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
  483:                         if (($item =~ m{^/adm/$match_domain/$match_username/\d+/smppg}) ||
  484:                             ($item =~ /^simpleproblem_/)) {
  485:                             print $fh $newcontent{$item};
  486:                         } else {
  487:                             my $fileloc = &Apache::lonnet::filelocation('',$prefix.$item);
  488:                             if (-e $fileloc) {
  489:                                 if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  490:                                     if ((($1 eq 'sequence') || ($1 eq 'page')) &&
  491:                                         (ref($has_simpleprobs{$item}) eq 'HASH')) {
  492:                                         my %changes = %{$has_simpleprobs{$item}};
  493:                                         my $content = &Apache::lonclonecourse::rewritefile(
  494:                      &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  495:                                                       (%replacehash,$crs => '')
  496:                                                                                           );
  497:                                         my $updatedcontent = '';
  498:                                         my $parser = HTML::TokeParser->new(\$content);
  499:                                         $parser->attr_encoded(1);
  500:                                         while (my $token = $parser->get_token) {
  501:                                             if ($token->[0] eq 'S') {
  502:                                                 if (($token->[1] eq 'resource') &&
  503:                                                     ($token->[2]->{'src'} eq '/res/lib/templates/simpleproblem.problem') &&
  504:                                                     ($changes{$token->[2]->{'id'}})) {
  505:                                                     my $id = $token->[2]->{'id'};
  506:                                                     $updatedcontent .= '<'.$token->[1];
  507:                                                     foreach my $attrib (@{$token->[3]}) {
  508:                                                        next unless ($attrib =~ /^(src|type|title|id)$/);
  509:                                                         if ($attrib eq 'src') {
  510:                                                             my ($file) = ($display{$changes{$id}} =~ /^\Qsimpleproblem_\E(.+)$/);
  511:                                                             if ($file) {
  512:                                                                 $updatedcontent .= ' '.$attrib.'="'.$file.'"';
  513:                                                             } else {
  514:                                                                 $updatedcontent .= ' '.$attrib.'="'.$token->[2]->{$attrib}.'"';
  515:                                                             }
  516:                                                         } else {
  517:                                                             $updatedcontent .= ' '.$attrib.'="'.$token->[2]->{$attrib}.'"';
  518:                                                         }
  519:                                                     }
  520:                                                     $updatedcontent .= ' />'."\n";
  521:                                                 } else {
  522:                                                     $updatedcontent .= $token->[4]."\n";
  523:                                                 }
  524:                                              } else {
  525:                                                  $updatedcontent .= $token->[2];
  526:                                              }
  527:                                          }
  528:                                          print $fh $updatedcontent;
  529:                                     } else {
  530:                                         print $fh &Apache::lonclonecourse::rewritefile(
  531:                      &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  532:                                                       (%replacehash,$crs => '')
  533:                                                                                       );
  534:                                     }
  535:                                 } else {
  536:                                     print $fh
  537:                                         &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  538:                                 }
  539:                             } else {
  540:                                 $fail = &mt('Source does not exist.');
  541:                             }
  542:                         }
  543:                         $fh->close();
  544:                     } else {
  545:                         $fail = &mt('Could not write to destination.');
  546:                     }
  547:                 }
  548:                 my $text;
  549:                 if ($fail) {
  550:                     $text = '<span class="LC_error">'.&mt('fail').('&nbsp;'x3).$fail.'</span>';
  551:                 } else {
  552:                     $text = '<span class="LC_success">'.&mt('ok').'</span>';
  553:                 }
  554:                 if ($i == 0) {
  555:                     $result .= $text;
  556:                 } else {
  557:                     $depresult .= $text.'</li>';
  558:                 }
  559:             }
  560:             $r->print($result);
  561:             if ($depresult) {
  562:                 $r->print('<ul>'.$depresult.'</ul>');
  563:             }
  564:         }
  565:     } else {
  566:         my ($navmap,$errormsg) =
  567:             &Apache::loncourserespicker::get_navmap_object($crstype,'dumpdocs');
  568:         if (!ref($navmap)) {
  569:             $r->print($errormsg);
  570:         } else {
  571:             $r->print('<div id="searching">'.&mt('Searching ...').'</div>');
  572:             $r->rflush();
  573:             my ($preamble,$formname);
  574:             $formname = 'dumpdoc';
  575:             unless ($home==1) {
  576:                 $preamble = '<div class="LC_left_float">'.
  577:                             '<fieldset><legend>'.
  578:                             &mt('Select the Authoring Space').
  579:                             '</legend><select name="authorspace">';
  580:             }
  581:             my @orderspaces = ();
  582:             foreach my $key (sort(keys(%outhash))) {
  583:                 if ($key=~/^home_(.+)$/) {
  584:                     if ($1 eq $env{'user.name'}.':'.$env{'user.domain'}) {
  585:                         unshift(@orderspaces,$1);
  586:                     } else {
  587:                         push(@orderspaces,$1);
  588:                     }
  589:                 }
  590:             }
  591:             if ($home>1) {
  592:                 $preamble .= '<option value="" selected="selected">'.&mt('Select').'</option>';
  593:             }
  594:             foreach my $user (@orderspaces) {
  595:                 if ($home==1) {
  596:                     $preamble .= '<input type="hidden" name="authorspace" value="'.$user.'" />';
  597:                 } else {
  598:                     $preamble .= '<option value="'.$user.'">'.$user.' - '.
  599:                                  &Apache::loncommon::plainname(split(/\:/,$user)).'</option>';
  600:                 }
  601:             }
  602:             unless ($home==1) {
  603:                 $preamble .= '</select></fieldset></div>'."\n";
  604:             }
  605:             my $title=$origcrsdata{'description'};
  606:             $title=~s/[\/\s]+/\_/gs;
  607:             $title=&clean($title);
  608:             $preamble .= '<div class="LC_left_float">'.
  609:                          '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
  610:                          '<input type="text" size="50" name="authorfolder" value="'.
  611:                          $title.'" />'.
  612:                          '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>'."\n";
  613:             my %uploadedfiles;
  614:             &tiehash();
  615:             foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  616:                 my ($ext)=($file=~/\.(\w+)$/);
  617: # FIXME Check supplemental here
  618:                 my $title=$hash{'title_'.$hash{
  619:                                 'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
  620:                 if (!$title) {
  621:                     $title=$file;
  622:                 } else {
  623:                     $title=~s|/|_|g;
  624:                 }
  625:                 $title=~s/\.(\w+)$//;
  626:                 $title=&clean($title);
  627:                 $title.='.'.$ext;
  628: #           $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
  629:                 $uploadedfiles{$file} = $title;
  630:             }
  631:             &untiehash();
  632:             $r->print(&Apache::loncourserespicker::create_picker($navmap,'dumpdocs',$formname,$crstype,undef,
  633:                                                                  undef,undef,$preamble,$home,\%uploadedfiles));
  634:         }
  635:     }
  636:     $r->print(&endContentScreen());
  637: }
  638: 
  639: sub recurse_html {
  640:     my ($mm,$prefix,$currdirpath,$currurlpath,$container,$item,$replacehash,$deps) = @_;
  641:     return unless ((ref($replacehash) eq 'HASH') && (ref($deps) eq 'HASH'));
  642:     my (%allfiles,%codebase);
  643:     if (&Apache::lonnet::extract_embedded_items($currdirpath,\%allfiles,\%codebase) eq 'ok') {
  644:         if (keys(%allfiles)) {
  645:             foreach my $dependency (keys(%allfiles)) {
  646:                 next if (($dependency =~ m{^/(res|adm)/}) || ($dependency =~ m{^https?://}));
  647:                 my ($depurl,$relfile,$newcontainer);
  648:                 if ($dependency =~ m{^/}) {
  649:                     if ($dependency =~ m{^\Q$currurlpath/\E(.+)$}) {
  650:                         $relfile = $1;
  651:                         if ($dependency =~ m{^\Q$prefix\E(.+)$}) {
  652:                             $newcontainer = $1;
  653:                             next if ($replacehash->{$newcontainer});
  654:                         }
  655:                         $depurl = $dependency;
  656:                     } else {
  657:                         next;
  658:                     }
  659:                 } else {
  660:                     $relfile = $dependency;
  661:                     $depurl = $currurlpath;
  662:                     $depurl =~ s{[^/]+$}{}; 
  663:                     $depurl .= $dependency;
  664:                     ($newcontainer) = ($depurl =~ m{^\Q$prefix\E(.+)$});
  665:                 }
  666:                 next if ($relfile eq '');
  667:                 my $newname = $replacehash->{$container};
  668:                 $newname =~ s{[^/]+$}{};
  669:                 $replacehash->{$newcontainer} = $newname.$relfile;
  670:                 $deps->{$item}{$newcontainer} = 1;
  671:                 my ($newurlpath) = ($depurl =~ m{^(.*)/[^/]+$});
  672:                 my $depfile = &Apache::lonnet::filelocation('',$depurl);
  673:                 my $type = $mm->checktype_filename($depfile);
  674:                 if ($type eq 'text/html') {
  675:                     &recurse_html($mm,$prefix,$depfile,$newurlpath,$newcontainer,$item,$replacehash,$deps);
  676:                 }
  677:             }
  678:         }
  679:     }
  680:     return;
  681: }
  682: 
  683: sub group_import {
  684:     my ($coursenum, $coursedom, $folder, $container, $caller, $ltitoolsref, @files) = @_;
  685:     my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
  686:         %removeparam,$importuploaded,$fixuperrors);
  687:     $allmaps = {};
  688:     while (@files) {
  689: 	my ($name, $url, $residx) = @{ shift(@files) };
  690:         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
  691: 	     && ($caller eq 'londocs')
  692: 	     && (!&Apache::lonnet::stat_file($url))) {
  693: 
  694:             my $errtext = '';
  695:             my $fatal = 0;
  696:             my $newmapstr = '<map>'."\n".
  697:                             '<resource id="1" src="" type="start"></resource>'."\n".
  698:                             '<link from="1" to="2" index="1"></link>'."\n".
  699:                             '<resource id="2" src="" type="finish"></resource>'."\n".
  700:                             '</map>';
  701:             $env{'form.output'}=$newmapstr;
  702:             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
  703:                                                 'output',$1.$2);
  704:             if ($result !~ m{^/uploaded/}) {
  705:                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
  706:                 $fatal = 2;
  707:             }
  708:             if ($fatal) {
  709:                 return ($errtext,$fatal);
  710:             }
  711:         }
  712: 	if ($url) {
  713:             if ($url =~ m{^(/adm/$coursedom/$coursenum/(\d+)/ext\.tool)\:?(.*)$}) {
  714:                 $url = $1;
  715:                 my $marker = $2;
  716:                 my $info = $3;
  717:                 my ($toolid,%toolhash,%toolsettings);
  718:                 my @extras = ('linktext','explanation','crslabel','crstitle','crsappend');
  719:                 my @toolinfo = split(/:/,$info);
  720:                 if ($residx) {
  721:                     %toolsettings=&Apache::lonnet::dump('exttool_'.$marker,$coursedom,$coursenum);
  722:                     $toolid = $toolsettings{'id'};
  723:                 } else {
  724:                     $toolid = shift(@toolinfo);
  725:                 }
  726:                 $toolid =~ s/\D//g;
  727:                 ($toolhash{'target'},$toolhash{'width'},$toolhash{'height'},
  728:                  $toolhash{'linktext'},$toolhash{'explanation'},
  729:                  $toolhash{'crslabel'},$toolhash{'crstitle'},$toolhash{'crsappend'}) = @toolinfo;
  730:                 foreach my $item (@extras) {
  731:                     $toolhash{$item} = &unescape($toolhash{$item});
  732:                 }
  733:                 if (ref($ltitoolsref) eq 'HASH') {
  734:                     my @deleted;
  735:                     if (ref($ltitoolsref->{$toolid}) eq 'HASH') {
  736:                         $toolhash{'id'} = $toolid;
  737:                         if (($toolhash{'target'} eq 'iframe') || ($toolhash{'target'} eq 'tab') ||
  738:                             ($toolhash{'target'} eq 'window')) {
  739:                             if ($toolhash{'target'} eq 'window') {
  740:                                 foreach my $item ('width','height') {
  741:                                     $toolhash{$item} =~ s/^\s+//;
  742:                                     $toolhash{$item} =~ s/\s+$//;
  743:                                     if ($toolhash{$item} =~ /\D/) {
  744:                                         delete($toolhash{$item});
  745:                                         if ($residx) {
  746:                                             if ($toolsettings{$item}) {
  747:                                                 push(@deleted,$item);
  748:                                             }
  749:                                         }
  750:                                     }
  751:                                 }
  752:                             }
  753:                         } elsif ($residx) {
  754:                             $toolhash{'target'} = $toolsettings{'target'};
  755:                             if ($toolhash{'target'} eq 'window') {
  756:                                 foreach my $item ('width','height') {
  757:                                     $toolhash{$item} = $toolsettings{$item};
  758:                                 }
  759:                             }
  760:                         } elsif (ref($ltitoolsref->{$toolid}->{'display'}) eq 'HASH') {
  761:                             $toolhash{'target'} = $ltitoolsref->{$toolid}->{'display'}->{'target'};
  762:                             if ($toolhash{'target'} eq 'window') {
  763:                                 $toolhash{'width'} = $ltitoolsref->{$toolid}->{'display'}->{'width'};
  764:                                 $toolhash{'height'} = $ltitoolsref->{$toolid}->{'display'}->{'height'};
  765:                             }
  766:                         }
  767:                         if ($toolhash{'target'} eq 'iframe') {
  768:                             foreach my $item ('width','height','linktext','explanation') {
  769:                                 delete($toolhash{$item});
  770:                                 if ($residx) {
  771:                                     if ($toolsettings{$item}) {
  772:                                         push(@deleted,$item);
  773:                                     }
  774:                                 }
  775:                             }
  776:                         } elsif ($toolhash{'target'} eq 'tab') {
  777:                             foreach my $item ('width','height') {
  778:                                 delete($toolhash{$item});
  779:                                 if ($residx) {
  780:                                     if ($toolsettings{$item}) {
  781:                                         push(@deleted,$item);
  782:                                     }
  783:                                 }
  784:                             }
  785:                         }
  786:                         if (ref($ltitoolsref->{$toolid}->{'crsconf'}) eq 'HASH') {
  787:                             foreach my $item ('label','title','linktext','explanation') {
  788:                                 my $crsitem;
  789:                                 if (($item eq 'label') || ($item eq 'title')) {
  790:                                     $crsitem = 'crs'.$item;
  791:                                 } else {
  792:                                     $crsitem = $item;
  793:                                 }
  794:                                 if ($ltitoolsref->{$toolid}->{'crsconf'}->{$item}) {
  795:                                     $toolhash{$crsitem} =~ s/^\s+//;
  796:                                     $toolhash{$crsitem} =~ s/\s+$//;
  797:                                     if ($toolhash{$crsitem} eq '') {
  798:                                         delete($toolhash{$crsitem});
  799:                                     }
  800:                                 } else {
  801:                                     delete($toolhash{$crsitem});
  802:                                 }
  803:                                 if (($residx) && (exists($toolsettings{$crsitem}))) {
  804:                                     unless (exists($toolhash{$crsitem})) {
  805:                                         push(@deleted,$crsitem);
  806:                                     }
  807:                                 }
  808:                             }
  809:                         }
  810:                         my $putres = &Apache::lonnet::put('exttool_'.$marker,\%toolhash,$coursedom,$coursenum);
  811:                         if ($putres eq 'ok') {
  812:                             if (@deleted) {
  813:                                 &Apache::lonnet::del('exttool_'.$marker,\@deleted,$coursedom,$coursenum);
  814:                             }
  815:                         } else {
  816:                             return (&mt('Failed to save update to external tool.'),1);
  817:                         }
  818:                     }
  819:                 }
  820:             }
  821:             if (($caller eq 'londocs') &&
  822:                 ($folder =~ /^default/)) {
  823:                 if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
  824:                     my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
  825:                     my $cid = $coursedom.'_'.$coursenum;
  826:                     $allmaps =
  827:                         &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
  828:                                                              $chome,$cid);
  829:                     $donechk = 1;
  830:                 }
  831:                 if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
  832:                     &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
  833:                                          \%removeparam,\%addedmaps,\%hierarchy,\%titles,$allmaps);
  834:                     $importuploaded = 1;
  835:                 } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
  836:                     next if ($allmaps->{$url});
  837:                 }
  838:             }
  839: 	    if (!$residx
  840: 		|| defined($LONCAPA::map::zombies[$residx])) {
  841: 		$residx = &LONCAPA::map::getresidx($url,$residx);
  842: 		push(@LONCAPA::map::order, $residx);
  843: 	    }
  844: 	    my $ext = 'false';
  845: 	    if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
  846:             if ($url =~ m{^/uploaded/$coursedom/$coursenum/((?:docs|supplemental)/(?:default|\d+))/new\.html$}) {
  847:                 my $filepath = $1;
  848:                 my $fname;
  849:                 if ($name eq '') {
  850:                     $name = &mt('Web Page');
  851:                     $fname = 'web';
  852:                 } else {
  853:                     $fname = $name;
  854:                     $fname=&Apache::lonnet::clean_filename($fname);
  855:                     if ($fname eq '') {
  856:                         $fname = 'web';
  857:                     } elsif (length($fname) > 15) {
  858:                         $fname = substr($fname,0,14);
  859:                     }
  860:                 }
  861:                 my $title = &Apache::loncommon::cleanup_html($name);
  862:                 my $initialtext = &mt('Replace with your own content.');
  863:                 my $newhtml = <<END;
  864: <html>
  865: <head>
  866: <title>$title</title>
  867: </head>
  868: <body bgcolor="#ffffff">
  869: $initialtext
  870: </body>
  871: </html>
  872: END
  873:                 $env{'form.output'}=$newhtml;
  874:                 my $result =
  875:                     &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
  876:                                                           'output',
  877:                                                           "$filepath/$residx/$fname.html");
  878:                 if ($result =~ m{^/uploaded/}) {
  879:                     $url = $result;
  880:                     if ($filepath =~ /^supplemental/) {
  881:                         $name = time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  882:                                 $env{'user.domain'}.'___&&&___'.$name;
  883:                     }
  884:                 } else {
  885:                     return (&mt('Failed to save new web page.'),1);
  886:                 }
  887:             }
  888:             $name = &LONCAPA::map::qtunescape($name);
  889:             $url  = &LONCAPA::map::qtunescape($url);
  890: 	    $LONCAPA::map::resources[$residx] =
  891: 		join(':', ($name, $url, $ext, 'normal', 'res'));
  892: 	}
  893:     }
  894:     if ($importuploaded) {
  895:         my %import_errors;
  896:         my %updated = (
  897:                           removefrommap => \%removefrommap,
  898:                           removeparam   => \%removeparam,
  899:                       );
  900:         my ($result,$msgsarray,$lockerror) =
  901:             &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
  902:         if (keys(%import_errors) > 0) {
  903:             $fixuperrors =
  904:                 '<p span class="LC_warning">'."\n".
  905:                 &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".
  906:                 '<ul>'."\n";
  907:             foreach my $key (sort(keys(%import_errors))) {
  908:                 $fixuperrors .= '<li>'.$key.'</li>'."\n";
  909:             }
  910:             $fixuperrors .= '</ul></p>'."\n";
  911:         }
  912:         if (ref($msgsarray) eq 'ARRAY') {
  913:             if (@{$msgsarray} > 0) {
  914:                 $fixuperrors .= '<p class="LC_info">'.
  915:                                 join('<br />',@{$msgsarray}).
  916:                                 '</p>';
  917:             }
  918:         }
  919:         if ($lockerror) {
  920:             $fixuperrors .= '<p class="LC_error">'.
  921:                             $lockerror.
  922:                             '</p>';
  923:         }
  924:     }
  925:     my ($errtext,$fatal) =
  926:         &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
  927:     unless ($fatal) {
  928:         if ($folder =~ /^supplemental/) {
  929:             my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  930:                                             $folder.'.'.$container);
  931:         }
  932:     }
  933:     return ($errtext,$fatal,$fixuperrors);
  934: }
  935: 
  936: sub log_docs {
  937:     return &Apache::lonnet::write_log('course','docslog',@_);
  938: }
  939: 
  940: {
  941:     my @oldresources=();
  942:     my @oldorder=();
  943:     my $parmidx;
  944:     my %parmaction=();
  945:     my %parmvalue=();
  946:     my $changedflag;
  947: 
  948:     sub snapshotbefore {
  949:         @oldresources=@LONCAPA::map::resources;
  950:         @oldorder=@LONCAPA::map::order;
  951:         $parmidx=undef;
  952:         %parmaction=();
  953:         %parmvalue=();
  954:         $changedflag=0;
  955:     }
  956: 
  957:     sub remember_parms {
  958:         my ($idx,$parameter,$action,$value)=@_;
  959:         $parmidx=$idx;
  960:         $parmaction{$parameter}=$action;
  961:         $parmvalue{$parameter}=$value;
  962:         $changedflag=1;
  963:     }
  964: 
  965:     sub log_differences {
  966:         my ($plain)=@_;
  967:         my %storehash=('folder' => $plain,
  968:                        'currentfolder' => $env{'form.folder'});
  969:         if ($parmidx) {
  970:            $storehash{'parameter_res'}=$oldresources[$parmidx];
  971:            foreach my $parm (keys(%parmaction)) {
  972:               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
  973:               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
  974:            }
  975:         }
  976:         my $maxidx=$#oldresources;
  977:         if ($#LONCAPA::map::resources>$#oldresources) {
  978:            $maxidx=$#LONCAPA::map::resources;
  979:         }
  980:         for (my $idx=0; $idx<=$maxidx; $idx++) {
  981:            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
  982:               $storehash{'before_resources_'.$idx}=$oldresources[$idx];
  983:               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
  984:               $changedflag=1;
  985:            }
  986:            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
  987:               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
  988:               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  989:               $changedflag=1;
  990:            }
  991:         }
  992: 	$storehash{'maxidx'}=$maxidx;
  993:         if ($changedflag) { &log_docs(\%storehash); }
  994:     }
  995: }
  996: 
  997: sub docs_change_log {
  998:     my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath,$canedit)=@_;
  999:     my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 1000:     my $navmap;   
 1001:     my $js = '<script type="text/javascript">'."\n".
 1002:              '// <![CDATA['."\n".
 1003:              &Apache::loncommon::display_filter_js('docslog')."\n".
 1004:              &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag,
 1005:                          $coursedom,$coursenum,'',$canedit,'',\$navmap)."\n".
 1006:              &history_tab_js()."\n".
 1007:              &Apache::lonratedt::editscript('simple')."\n".
 1008:              '// ]]>'."\n".
 1009:              '</script>'."\n";
 1010:     $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
 1011:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
 1012:     $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
 1013:     my %orderhash;
 1014:     my $container='sequence';
 1015:     my $pathitem;
 1016:     if ($env{'form.folderpath'} =~ /\:1$/) {
 1017:         $container='page';
 1018:     }
 1019:     my $folderpath=$env{'form.folderpath'};
 1020:     if ($folderpath eq '') {
 1021:         $folderpath = &default_folderpath($coursenum,$coursedom,\$navmap);
 1022:     }
 1023:     undef($navmap);
 1024:     $pathitem = '<input type="hidden" name="folderpath" value="'.
 1025:                 &HTML::Entities::encode($folderpath,'<>&"').'" />';
 1026:     my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
 1027:     my $jumpto = $readfile;
 1028:     $jumpto =~ s{^/}{};
 1029:     my $tid = 1;
 1030:     if ($supplementalflag) {
 1031:         $tid = 2;
 1032:     }
 1033:     my ($breadcrumbtrail) = 
 1034:         &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 1035:     $r->print($breadcrumbtrail.
 1036:               &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
 1037:               $readfile));
 1038:     my %docslog=&Apache::lonnet::dump('nohist_docslog',
 1039:                                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 1040:                                       $env{'course.'.$env{'request.course.id'}.'.num'});
 1041: 
 1042:     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 1043: 
 1044:     my %saveable_parameters = ('show' => 'scalar',);
 1045:     &Apache::loncommon::store_course_settings('docs_log',
 1046:                                               \%saveable_parameters);
 1047:     &Apache::loncommon::restore_course_settings('docs_log',
 1048:                                                 \%saveable_parameters);
 1049:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1050: # FIXME: internationalization seems wrong here
 1051:     my %lt=('hiddenresource' => 'Resources hidden',
 1052: 	    'encrypturl'     => 'URL hidden',
 1053: 	    'randompick'     => 'Randomly pick',
 1054: 	    'randomorder'    => 'Randomly ordered',
 1055: 	    'set'            => 'set to',
 1056: 	    'del'            => 'deleted');
 1057:     my $filter = &Apache::loncommon::display_filter('docslog')."\n".
 1058:                  $pathitem."\n".
 1059:                  '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
 1060:                  ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
 1061:     $r->print('<div class="LC_left_float">'.
 1062:               '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
 1063:               &makedocslogform($filter,1).
 1064:               '</fieldset></div><br clear="all" />');
 1065:     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
 1066:               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
 1067:               &mt('After').'</th>'.
 1068:               &Apache::loncommon::end_data_table_header_row());
 1069:     my $shown=0;
 1070:     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
 1071: 	if ($env{'form.displayfilter'} eq 'currentfolder') {
 1072: 	    if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
 1073: 	}
 1074:         my @changes=keys(%{$docslog{$id}{'logentry'}});
 1075:         if ($env{'form.displayfilter'} eq 'containing') {
 1076: 	    my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
 1077: 		&Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
 1078: 	    foreach my $key (@changes) {
 1079: 		$wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
 1080: 	    }
 1081: 	    if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
 1082: 	}
 1083:         my $count = 0;
 1084:         my $time =
 1085:             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
 1086:         my $plainname =
 1087:             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
 1088:                                           $docslog{$id}{'exe_udom'});
 1089:         my $about_me_link =
 1090:             &Apache::loncommon::aboutmewrapper($plainname,
 1091:                                                $docslog{$id}{'exe_uname'},
 1092:                                                $docslog{$id}{'exe_udom'});
 1093:         my $send_msg_link='';
 1094:         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
 1095:              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
 1096:             $send_msg_link ='<br />'.
 1097:                 &Apache::loncommon::messagewrapper(&mt('Send message'),
 1098:                                                    $docslog{$id}{'exe_uname'},
 1099:                                                    $docslog{$id}{'exe_udom'});
 1100:         }
 1101:         $r->print(&Apache::loncommon::start_data_table_row());
 1102:         $r->print('<td>'.$time.'</td>
 1103:                        <td>'.$about_me_link.
 1104:                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.
 1105:                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
 1106:                   $send_msg_link.'</td><td>'.
 1107:                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
 1108:         my $is_supp = 0; 
 1109:         if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
 1110:             $is_supp = 1;
 1111:         }
 1112: # Before
 1113: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1114: 	    my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
 1115: 	    my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
 1116: 	    if ($oldname ne $newname) {
 1117:                 my $shown = &LONCAPA::map::qtescape($oldname);
 1118:                 if ($is_supp) {
 1119:                     $shown = &Apache::loncommon::parse_supplemental_title($shown);
 1120:                 }
 1121:                 $r->print($shown);
 1122: 	    }
 1123: 	}
 1124: 	$r->print('<ul>');
 1125: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1126:             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
 1127:                 my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
 1128:                 if ($is_supp) {
 1129:                     $shown = &Apache::loncommon::parse_supplemental_title($shown);
 1130:                 }
 1131: 		$r->print('<li>'.$shown.'</li>');
 1132: 	    }
 1133: 	}
 1134: 	$r->print('</ul>');
 1135: # After
 1136:         $r->print('</td><td>');
 1137: 
 1138: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1139: 	    my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
 1140: 	    my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
 1141: 	    if ($oldname ne '' && $oldname ne $newname) {
 1142:                 my $shown = &LONCAPA::map::qtescape($newname);
 1143:                 if ($is_supp) {
 1144:                     $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
 1145:                 }
 1146:                 $r->print($shown);
 1147: 	    }
 1148: 	}
 1149: 	$r->print('<ul>');
 1150: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1151:             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
 1152:                 my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
 1153:                 if ($is_supp) {
 1154:                     $shown = &Apache::loncommon::parse_supplemental_title($shown);
 1155:                 }
 1156:                 $r->print('<li>'.$shown.'</li>');
 1157: 	    }
 1158: 	}
 1159: 	$r->print('</ul>');
 1160: 	if ($docslog{$id}{'logentry'}{'parameter_res'}) {
 1161:             my ($title,$url) = split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'},3);
 1162:             if ($title eq '') {
 1163:                 ($title) = ($url =~ m{/([^/]+)$});
 1164:             }
 1165:             $r->print(&LONCAPA::map::qtescape($title).':<ul>');
 1166: 	    foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
 1167: 		if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
 1168: # FIXME: internationalization seems wrong here
 1169: 		    $r->print('<li>'.
 1170: 			      &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
 1171: 				  $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
 1172: 			      .'</li>');
 1173: 		}
 1174: 	    }
 1175: 	    $r->print('</ul>');
 1176: 	}
 1177: # End
 1178:         $r->print('</td>'.&Apache::loncommon::end_data_table_row());
 1179:         $shown++;
 1180:         if (!($env{'form.show'} eq &mt('all')
 1181:               || $shown<=$env{'form.show'})) { last; }
 1182:     }
 1183:     $r->print(&Apache::loncommon::end_data_table()."\n".
 1184:               &makesimpleeditform($pathitem)."\n".
 1185:               '</div></div>');
 1186:     $r->print(&endContentScreen());
 1187: }
 1188: 
 1189: sub update_paste_buffer {
 1190:     my ($coursenum,$coursedom,$folder) = @_;
 1191:     my (@possibles,%removals,%cuts,$output);
 1192:     if ($env{'form.multiremove'}) {
 1193:         $env{'form.multiremove'} =~ s/,$//;
 1194:         map { $removals{$_} = 1; } split(/,/,$env{'form.multiremove'});
 1195:     }
 1196:     if (($env{'form.multicopy'}) || ($env{'form.multicut'})) {
 1197:         if ($env{'form.multicut'}) {
 1198:             $env{'form.multicut'} =~ s/,$//;
 1199:             foreach my $item (split(/,/,$env{'form.multicut'})) {
 1200:                 unless ($removals{$item}) {
 1201:                     $cuts{$item} = 1;
 1202:                     push(@possibles,$item.':cut');
 1203:                 }
 1204:             }
 1205:         }
 1206:         if ($env{'form.multicopy'}) {
 1207:             $env{'form.multicopy'} =~ s/,$//;
 1208:             foreach my $item (split(/,/,$env{'form.multicopy'})) {
 1209:                 unless ($removals{$item} || $cuts{$item}) {
 1210:                     push(@possibles,$item.':copy'); 
 1211:                 }
 1212:             }
 1213:         }
 1214:     } elsif ($env{'form.markcopy'}) {
 1215:         @possibles = split(/,/,$env{'form.markcopy'});
 1216:     }
 1217: 
 1218:     return if (@possibles == 0);
 1219:     return if (!defined($env{'form.copyfolder'}));
 1220: 
 1221:     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 1222: 				    $env{'form.copyfolder'});
 1223:     return if ($fatal);
 1224: 
 1225:     my %curr_groups = &Apache::longroup::coursegroups();
 1226: 
 1227: # Retrieve current paste buffer suffixes.
 1228:     my @currpaste = split(/,/,$env{'docs.markedcopies'});
 1229:     my (%pasteurls,@newpaste);
 1230: 
 1231: # Construct identifiers for current contents of user's paste buffer
 1232:     if (@currpaste) {
 1233:         foreach my $suffix (@currpaste) {
 1234:             my $cid = $env{'docs.markedcopy_crs_'.$suffix};
 1235:             my $url = $env{'docs.markedcopy_url_'.$suffix};
 1236:             my $mapidx = $env{'docs.markedcopy_map_'.$suffix};
 1237:             if (($cid =~ /^$match_domain(?:_)$match_courseid$/) &&
 1238:                 ($url ne '')) {
 1239:                 if ($url eq '/res/lib/templates/simpleproblem.problem') {
 1240:                     $pasteurls{$cid.'_'.$mapidx} = 1;
 1241:                 } elsif ($url =~ m{^/res/$match_domain/$match_username/}) {
 1242:                     $pasteurls{$url} = 1;
 1243:                 } else {
 1244:                     $pasteurls{$cid.'_'.$url} = 1;
 1245:                 }
 1246:             }
 1247:         }
 1248:     }
 1249: 
 1250: # Mark items for copying (skip any items already in user's paste buffer)
 1251:     my %addtoenv;
 1252: 
 1253:     my @pathitems = split(/\&/,$env{'form.folderpath'});
 1254:     my @folderconf = split(/\:/,$pathitems[-1]);
 1255:     my $ispage = $folderconf[5];
 1256: 
 1257:     foreach my $item (@possibles) {
 1258:         my ($orderidx,$cmd) = split(/:/,$item);
 1259:         next if ($orderidx =~ /\D/);
 1260:         next unless (($cmd eq 'cut') || ($cmd eq 'copy') || ($cmd eq 'remove'));
 1261:         my $mapidx = $folder.':'.$orderidx.':'.$ispage;
 1262:         my ($title,$url)=split(':',$LONCAPA::map::resources[$orderidx]);
 1263:         my %denied = &action_restrictions($coursenum,$coursedom,
 1264:                                           &LONCAPA::map::qtescape($url),
 1265:                                           $env{'form.folderpath'},\%curr_groups);
 1266:         next if ($denied{'copy'});
 1267:         $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 1268:         if ($url eq '/res/lib/templates/simpleproblem.problem') {
 1269:             next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$mapidx}));
 1270:         } elsif ($url =~ m{^/res/$match_domain/$match_username/}) {
 1271:             next if (exists($pasteurls{$url}));
 1272:         } else {
 1273:             next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$url}));
 1274:         }
 1275:         my ($suffix,$errortxt,$locknotfreed) =
 1276:             &new_timebased_suffix($env{'user.domain'},$env{'user.name'},'paste');
 1277:         if ($suffix ne '') {
 1278:             push(@newpaste,$suffix);
 1279:         } else {
 1280:             if ($locknotfreed) {
 1281:                 return $locknotfreed;
 1282:             }
 1283:         }
 1284:         if (&is_supplemental_title($title)) {
 1285:             &Apache::lonnet::appenv({'docs.markedcopy_supplemental_'.$suffix => $title});
 1286: 	    ($title) = &Apache::loncommon::parse_supplemental_title($title);
 1287:         }
 1288: 
 1289:         $addtoenv{'docs.markedcopy_title_'.$suffix} = $title,
 1290:         $addtoenv{'docs.markedcopy_url_'.$suffix}   = $url,
 1291:         $addtoenv{'docs.markedcopy_cmd_'.$suffix}   = $cmd,
 1292:         $addtoenv{'docs.markedcopy_crs_'.$suffix}   = $env{'request.course.id'};
 1293:         $addtoenv{'docs.markedcopy_map_'.$suffix}   = $mapidx;
 1294:         if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
 1295:             my $prefix = $1;
 1296:             my $subdir =$2;
 1297:             if ($subdir eq '') {
 1298:                 $subdir = $prefix;
 1299:             }
 1300:             my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
 1301:             &contained_map_check($url,$folder,$coursenum,$coursedom,\%removefrommap,
 1302:                                  \%removeparam,\%addedmaps,\%hierarchy,\%titles,\%allmaps);
 1303:             if (ref($hierarchy{$url}) eq 'HASH') {
 1304:                 my ($nested,$nestednames);
 1305:                 &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
 1306:                 $nested =~ s/\&$//;
 1307:                 $nestednames =~ s/\Q___&&&___\E$//;
 1308:                 if ($nested ne '') {
 1309:                     $addtoenv{'docs.markedcopy_nested_'.$suffix} = $nested;
 1310:                 }
 1311:                 if ($nestednames ne '') {
 1312:                     $addtoenv{'docs.markedcopy_nestednames_'.$suffix} = $nestednames;
 1313:                 }
 1314:             }
 1315:         }
 1316:         if ($locknotfreed) {
 1317:             $output = $locknotfreed;
 1318:             last;
 1319:         }
 1320:     }
 1321:     if (@newpaste) {
 1322:         $addtoenv{'docs.markedcopies'} = join(',',(@currpaste,@newpaste));
 1323:     }
 1324:     &Apache::lonnet::appenv(\%addtoenv);
 1325:     delete($env{'form.markcopy'});
 1326:     return $output;
 1327: }
 1328: 
 1329: sub recurse_uploaded_maps {
 1330:     my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
 1331:     if (ref($hierarchy->{$url}) eq 'HASH') {
 1332:         my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
 1333:         my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
 1334:         my (@uploaded,@names,%shorter);
 1335:         for (my $i=0; $i<@maps; $i++) {
 1336:             my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
 1337:             if ($inner ne '') {
 1338:                 push(@uploaded,$inner);
 1339:                 push(@names,&escape($titles[$i]));
 1340:                 $shorter{$maps[$i]} = $inner;
 1341:             }
 1342:         }
 1343:         $$nestref .= "$dir:".join(',',@uploaded).'&';
 1344:         $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
 1345:         foreach my $map (@maps) {
 1346:             if ($shorter{$map} ne '') {
 1347:                 &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
 1348:             }
 1349:         }
 1350:     }
 1351:     return;
 1352: }
 1353: 
 1354: sub print_paste_buffer {
 1355:     my ($r,$container,$folder,$coursedom,$coursenum) = @_;
 1356:     return if (!defined($env{'docs.markedcopies'}));
 1357: 
 1358:     unless (($env{'form.pastemarked'}) || ($env{'form.clearmarked'})) {
 1359:         return if ($env{'docs.markedcopies'} eq '');
 1360:     }
 1361: 
 1362:     my @currpaste = split(/,/,$env{'docs.markedcopies'});
 1363:     my ($pasteitems,@pasteable);
 1364:     my $clipboardcount = 0;
 1365: 
 1366: # Construct identifiers for current contents of user's paste buffer
 1367:     foreach my $suffix (@currpaste) {
 1368:         next if ($suffix =~ /\D/);
 1369:         my $cid = $env{'docs.markedcopy_crs_'.$suffix};
 1370:         my $url = $env{'docs.markedcopy_url_'.$suffix};
 1371:         my $mapidx = $env{'docs.markedcopy_map_'.$suffix}; 
 1372:         if (($cid =~ /^$match_domain\_$match_courseid$/) &&
 1373:             ($url ne '')) {
 1374:             $clipboardcount ++;
 1375:             my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent,
 1376:                 $canpaste,$nopaste,$othercrs,$areachange,$is_exttool);
 1377:             my $extension = (split(/\./,$env{'docs.markedcopy_url_'.$suffix}))[-1];
 1378:             if ($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
 1379:                 $is_external = 1;
 1380:             } elsif ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
 1381:                 $is_exttool = 1;
 1382:             }
 1383:             if ($folder =~ /^supplemental/) {
 1384:                 $canpaste = &supp_pasteable($env{'docs.markedcopy_url_'.$suffix});
 1385:                 unless ($canpaste) {
 1386:                     $nopaste = &mt('Paste into Supplemental Content unavailable.');
 1387:                 }
 1388:             } else {
 1389:                 $canpaste = 1;
 1390:             }
 1391:             if ($canpaste) {
 1392:                 if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
 1393:                     my $srcdom = $1;
 1394:                     my $srcnum = $2;
 1395:                     my $rem = $3;
 1396:                     if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
 1397:                         $othercourse = 1;
 1398:                         if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
 1399:                             $othercrs = '<br />'.&mt('(from another course)');
 1400:                         } else {
 1401:                             $canpaste = 0;
 1402:                             $nopaste = &mt('Paste from another course unavailable.'); 
 1403:                         }
 1404:                     }
 1405:                     if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
 1406:                         my $prefix = $1;
 1407:                         $parent = $2;
 1408:                         if ($folder !~ /^\Q$prefix\E/) {
 1409:                             $areachange = 1;
 1410:                         }
 1411:                         $is_uploaded_map = 1;
 1412:                     }
 1413:                 } elsif (($url =~ m{^/res/lib/templates/\w+\.problem$}) ||
 1414:                          ($url =~ m{^/adm/($match_domain)/($match_username)/\d+/(bulletinboard|smppg|ext\.tool)$})) {
 1415:                     if ($cid ne $env{'request.course.id'}) {
 1416:                         my ($srcdom,$srcnum) = split(/_/,$cid);
 1417:                         if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
 1418:                             if (($is_exttool) && ($srcdom ne $coursedom)) {
 1419:                                 $canpaste = 0;
 1420:                                 $nopaste = &mt('Paste from another domain unavailable.');
 1421:                             } else {
 1422:                                 $othercrs = '<br />'.&mt('(from another course)');
 1423:                             }
 1424:                         } else {
 1425:                             $canpaste = 0;
 1426:                             $nopaste = &mt('Paste from another course unavailable.');
 1427:                         }
 1428:                     }
 1429:                 }
 1430:                 if ($canpaste) {
 1431:                     push(@pasteable,$suffix);
 1432:                 }
 1433:             }
 1434:             my $buffer;
 1435:             if ($is_external) {
 1436:                 $buffer = &mt('External Resource').': '.
 1437:                     &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
 1438:                     &LONCAPA::map::qtescape($url).')';
 1439:             } elsif ($is_exttool) {
 1440:                 $buffer = &mt('External Tool').': '.
 1441:                     &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
 1442:             } else {
 1443:                 my $icon = &Apache::loncommon::icon($extension);
 1444:                 if ($extension eq 'sequence' &&
 1445:                     $url =~ m{/default_\d+\.sequence$}x) {
 1446:                     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
 1447:                     $icon .= '/navmap.folder.closed.gif';
 1448:                 }
 1449:                 my $title = $env{'docs.markedcopy_title_'.$suffix};
 1450:                 if ($title eq '') {
 1451:                     ($title) = ($url =~ m{/([^/]+)$});
 1452:                 }
 1453:                 $buffer = '<img src="'.$icon.'" alt="" class="LC_icon" />'.
 1454:                           ': '.
 1455:                           &Apache::loncommon::parse_supplemental_title(
 1456:                              &LONCAPA::map::qtescape($title));
 1457:             }
 1458:             $pasteitems .= '<div class="LC_left_float">';
 1459:             my ($options,$onclick);
 1460:             if (($canpaste) && (!$areachange) && (!$othercourse) &&
 1461:                 ($env{'docs.markedcopy_cmd_'.$suffix} eq 'cut')) {
 1462:                 if (($is_uploaded_map) ||
 1463:                     ($url =~ /(bulletinboard|smppg)$/) ||
 1464:                     ($url =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
 1465:                     $options = &paste_options($suffix,$is_uploaded_map,$parent);
 1466:                     $onclick= 'onclick="showOptions(this,'."'$suffix'".');" ';
 1467:                 }
 1468:             }
 1469:             $pasteitems .= '<label><input type="checkbox" name="pasting" id="pasting_'.$suffix.'" value="'.$suffix.'" '.$onclick.'/>'.$buffer.'</label>';
 1470:             if ($nopaste) {
 1471:                  $pasteitems .= ' <span class="LC_cusr_emph">'.$nopaste.'</span>';   
 1472:             } else {
 1473:                 if ($othercrs) {
 1474:                     $pasteitems .= $othercrs;
 1475:                 }
 1476:                 if ($options) {
 1477:                     $pasteitems .= $options;
 1478:                 }
 1479:             }
 1480:             $pasteitems .= '</div>';
 1481:         }
 1482:     }
 1483:     if ($pasteitems eq '') {
 1484:         &Apache::lonnet::delenv('docs.markedcopies');
 1485:     }
 1486:     my ($pasteform,$form_start,$buttons,$form_end);
 1487:     if ($pasteitems) {
 1488:         $pasteitems .= '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1489:         $form_start = '<form name="pasteform" action="/adm/coursedocs" method="post" onsubmit="return validateClipboard();">';
 1490:         if (@pasteable) {
 1491:             my $value = &mt('Paste to current folder');
 1492:             if ($container eq 'page') {
 1493:                 $value = &mt('Paste to current page');
 1494:             }
 1495:             $buttons = '<input type="submit" name="pastemarked" value="'.$value.'" />'.('&nbsp;'x2);
 1496:         }
 1497:         $buttons .= '<input type="submit" name="clearmarked" value="'.&mt('Remove from clipboard').'" />'.('&nbsp;'x2);
 1498:         if ($clipboardcount > 1) {
 1499:             $buttons .=
 1500:                 '<span style="text-decoration:line-through">'.('&nbsp;'x20).'</span>'.('&nbsp;'x2).
 1501:                 '<input type="button" name="checkallclip" value="'.&mt('Check all').'" style="height:20px;" onclick="checkClipboard();" />'.
 1502:                 ('&nbsp;'x2).
 1503:                 '<input type="button" name="uncheckallclip" value="'.&mt('Uncheck all').'" style="height:20px;" onclick="uncheckClipboard();" />'.
 1504:                 ('&nbsp;'x2);
 1505:         }
 1506:         $form_end = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />'.
 1507:                     '</form>';
 1508:     } else {
 1509:         $pasteitems = &mt('Clipboard is empty');
 1510:     }
 1511:     $r->print($form_start
 1512:              .'<fieldset>'
 1513:              .'<legend>'.&mt('Clipboard').('&nbsp;' x2).$buttons.'</legend>'
 1514:              .$pasteitems
 1515:              .'</fieldset>'
 1516:              .$form_end);
 1517: }
 1518: 
 1519: sub paste_options {
 1520:     my ($suffix,$is_uploaded_map,$parent) = @_;
 1521:     my ($copytext,$movetext);
 1522:     if ($is_uploaded_map) {
 1523:         $copytext = &mt('Copy to new folder');
 1524:         $movetext = &mt('Move old');
 1525:     } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /bulletinboard$/) {
 1526:         $copytext = &mt('Copy to new board');
 1527:         $movetext = &mt('Move (not posts)');
 1528:     } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /smppg$/) {
 1529:         $copytext = &mt('Copy to new page');
 1530:         $movetext = &mt('Move');
 1531:     } else {
 1532:         $copytext = &mt('Copy to new file');
 1533:         $movetext = &mt('Move');
 1534:     }
 1535:     my $output = '<br />'.
 1536:                  '<span id="pasteoptionstext_'.$suffix.'" class="LC_fontsize_small LC_nobreak"></span>'.
 1537:                  '<div id="pasteoptions_'.$suffix.'" class="LC_dccid" style="display:none;"><span class="LC_nobreak">'.('&nbsp;'x 4).
 1538:                  '<label>'.
 1539:                  '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="new" checked="checked" />'.
 1540:                  $copytext.'</label></span>'.('&nbsp;'x2).' '.
 1541:                  '<span class="LC_nobreak"><label>'.
 1542:                  '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="move" />'.
 1543:                  $movetext.'</label></span>';
 1544:     if (($is_uploaded_map) && ($env{'docs.markedcopy_nested_'.$suffix})) {
 1545:         $output .= '<br /><fieldset><legend>'.&mt('Folder to paste contains sub-folders').
 1546:                    '</legend><table border="0">';
 1547:         my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
 1548:         my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames_'.$suffix});
 1549:         my $lastdir = $parent;
 1550:         my %depths = (
 1551:                        $lastdir => 0,
 1552:                      );
 1553:         my (%display,%deps);
 1554:         for (my $i=0; $i<@pastemaps; $i++) {
 1555:             ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
 1556:             my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
 1557:             my @subfolders = split(/,/,$subfolderstr);
 1558:             $deps{$lastdir} = \@subfolders;
 1559:             my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
 1560:             my $depth = $depths{$lastdir} + 1;
 1561:             my $offset = int($depth * 4);
 1562:             my $indent = ('&nbsp;' x $offset);
 1563:             for (my $j=0; $j<@subfolders; $j++) {
 1564:                 $depths{$subfolders[$j]} = $depth;
 1565:                 $display{$subfolders[$j]} =
 1566:                     '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
 1567:                     '<td><label>'.
 1568:                     '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
 1569:                     '<label>'.
 1570:                     '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="move" />'.
 1571:                     &mt('Move old').'</label>'.
 1572:                     '</td></tr>';
 1573:              }
 1574:         }
 1575:         &recurse_print(\$output,$parent,\%deps,\%display);
 1576:         $output .= '</table></fieldset>';
 1577:     }
 1578:     $output .= '</div>';
 1579:     return $output;
 1580: }
 1581: 
 1582: sub recurse_print {
 1583:     my ($outputref,$dir,$deps,$display) = @_;
 1584:     $$outputref .= $display->{$dir}."\n";
 1585:     if (ref($deps->{$dir}) eq 'ARRAY') {
 1586:         foreach my $subdir (@{$deps->{$dir}}) {
 1587:             &recurse_print($outputref,$subdir,$deps,$display);
 1588:         }
 1589:     }
 1590: }
 1591: 
 1592: sub supp_pasteable {
 1593:     my ($url) = @_;
 1594:     if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
 1595:         (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
 1596:         ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
 1597:         ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
 1598:         ($url =~ m{^/public/$match_domain/$match_courseid/syllabus}) ||
 1599:         ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$})) {
 1600:         return 1;
 1601:     }
 1602:     return;
 1603: }
 1604: 
 1605: sub paste_popup_js {
 1606:     my %html_js_lt = &Apache::lonlocal::texthash(
 1607:                                           show => 'Show Options',
 1608:                                           hide => 'Hide Options',
 1609:                                         );
 1610:     my %js_lt = &Apache::lonlocal::texthash(
 1611:                                           none => 'No items selected from clipboard.',
 1612:                                         );
 1613:     &html_escape(\%html_js_lt);
 1614:     &js_escape(\%html_js_lt);
 1615:     &js_escape(\%js_lt);
 1616:     return <<"END";
 1617: 
 1618: function showPasteOptions(suffix) {
 1619:     document.getElementById('pasteoptions_'+suffix).style.display='block';
 1620:     document.getElementById('pasteoptionstext_'+suffix).innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:hidePasteOptions(\\''+suffix+'\\');" class="LC_menubuttons_link">$html_js_lt{'hide'}</a>';
 1621:     return;
 1622: }
 1623: 
 1624: function hidePasteOptions(suffix) {
 1625:     document.getElementById('pasteoptions_'+suffix).style.display='none';
 1626:     document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$html_js_lt{'show'}</a>';
 1627:     return;
 1628: }
 1629: 
 1630: function showOptions(caller,suffix) {
 1631:     if (document.getElementById('pasteoptionstext_'+suffix)) {
 1632:         if (caller.checked) {
 1633:             document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$html_js_lt{'show'}</a>';
 1634:         } else {
 1635:             document.getElementById('pasteoptionstext_'+suffix).innerHTML ='';
 1636:         }
 1637:         if (document.getElementById('pasteoptions_'+suffix)) {
 1638:             document.getElementById('pasteoptions_'+suffix).style.display='none';
 1639:         }
 1640:     }
 1641:     return;
 1642: }
 1643: 
 1644: function validateClipboard() {
 1645:     var numchk = 0;
 1646:     if (document.pasteform.pasting.length > 1) {
 1647:         for (var i=0; i<document.pasteform.pasting.length; i++) {
 1648:             if (document.pasteform.pasting[i].checked) {
 1649:                 numchk ++;
 1650:             }
 1651:         }
 1652:     } else {
 1653:         if (document.pasteform.pasting.type == 'checkbox') {
 1654:             if (document.pasteform.pasting.checked) {
 1655:                 numchk ++; 
 1656:             } 
 1657:         }
 1658:     }
 1659:     if (numchk > 0) { 
 1660:         return true;
 1661:     } else {
 1662:         alert("$js_lt{'none'}");
 1663:         return false;
 1664:     }
 1665: }
 1666: 
 1667: function checkClipboard() {
 1668:     if (document.pasteform.pasting.length > 1) {
 1669:         for (var i=0; i<document.pasteform.pasting.length; i++) {
 1670:             document.pasteform.pasting[i].checked = true;
 1671:         }
 1672:     }
 1673:     return;
 1674: }
 1675: 
 1676: function uncheckClipboard() {
 1677:     if (document.pasteform.pasting.length >1) {
 1678:         for (var i=0; i<document.pasteform.pasting.length; i++) {
 1679:             document.pasteform.pasting[i].checked = false;
 1680:         }
 1681:     }
 1682:     return;
 1683: }
 1684: 
 1685: END
 1686: 
 1687: }
 1688: 
 1689: sub do_paste_from_buffer {
 1690:     my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
 1691: 
 1692: # Array of items in paste buffer
 1693:     my (@currpaste,%pastebuffer,%allerrors);
 1694:     @currpaste = split(/,/,$env{'docs.markedcopies'});
 1695: 
 1696: # Early out if paste buffer is empty
 1697:     if (@currpaste == 0) {
 1698:         return ();
 1699:     } 
 1700:     map { $pastebuffer{$_} = 1; } @currpaste;
 1701: 
 1702: # Array of items selected items to paste
 1703:     my @reqpaste = &Apache::loncommon::get_env_multiple('form.pasting');
 1704: 
 1705: # Early out if nothing selected to paste
 1706:     if (@reqpaste == 0) {
 1707:         return();
 1708:     }
 1709:     my @topaste;
 1710:     foreach my $suffix (@reqpaste) {
 1711:         next if ($suffix =~ /\D/);
 1712:         next unless (exists($pastebuffer{$suffix}));
 1713:         push(@topaste,$suffix);
 1714:     }
 1715: 
 1716: # Early out if nothing available to paste
 1717:     if (@topaste == 0) {
 1718:         return();
 1719:     }
 1720: 
 1721:     my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%notindom,%duplicate,
 1722:         %prefixchg,%srcdom,%srcnum,%srcmapidx,%marktomove,$save_err,$lockerrors,$allresult);
 1723: 
 1724:     foreach my $suffix (@topaste) {
 1725:         my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
 1726:         my $cid=&LONCAPA::map::qtescape($env{'docs.markedcopy_crs_'.$suffix});
 1727:         my $mapidx=&LONCAPA::map::qtescape($env{'docs.markedcopy_map_'.$suffix});  
 1728: # Supplemental content may only include certain types of content
 1729: # Early out if pasted content is not supported in Supplemental area
 1730:         if ($folder =~ /^supplemental/) {
 1731:             unless (&supp_pasteable($url)) {
 1732:                 $notinsupp{$suffix} = 1;
 1733:                 next;
 1734:             }
 1735:         }
 1736:         if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/}) {
 1737:             my $srcd = $1;
 1738:             my $srcn = $2;
 1739: # When paste buffer was populated using an active role in a different course
 1740: # check for mdc privilege in the course from which the resource was pasted
 1741:             if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
 1742:                 unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
 1743:                     $notincrs{$suffix} = 1;
 1744:                     next;
 1745:                 }
 1746:             }
 1747:             $srcdom{$suffix} = $srcd;
 1748:             $srcnum{$suffix} = $srcn;
 1749:         } elsif ($url =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
 1750:             my ($srcd,$srcn) = split(/_/,$cid);
 1751: # When paste buffer was populated using an active role in a different course
 1752: # check for mdc privilege in the course from which the resource was pasted
 1753:             if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
 1754:                 unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
 1755:                     $notincrs{$suffix} = 1;
 1756:                     next;
 1757:                 }
 1758:             }
 1759: # When buffer was populated using an active role in a different course
 1760: # disallow pasting of External Tool if course is in a different domain.
 1761:             if ($srcd ne $coursedom) {
 1762:                 $notindom{$suffix} = 1;
 1763:                 next;
 1764:             }
 1765:             $srcdom{$suffix} = $srcd;
 1766:             $srcnum{$suffix} = $srcn;
 1767:         } elsif (($url =~ m{^/res/lib/templates/\w+\.problem$}) ||
 1768:                  ($url =~ m{^/adm/$match_domain/$match_username/\d+/(bulletinboard|smppg)$})) {
 1769:             my ($srcd,$srcn) = split(/_/,$cid);
 1770: # When paste buffer was populated using an active role in a different course
 1771: # check for mdc privilege in the course from which the resource was pasted
 1772:             if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
 1773:                 unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
 1774:                     $notincrs{$suffix} = 1;
 1775:                     next;
 1776:                 }
 1777:             }
 1778:             $srcdom{$suffix} = $srcd;
 1779:             $srcnum{$suffix} = $srcn;
 1780:         }
 1781:         $srcmapidx{$suffix} = $mapidx; 
 1782:         push(@dopaste,$suffix);
 1783:         if ($url=~/\.(page|sequence)$/) {
 1784:             $is_map{$suffix} = 1; 
 1785:         }
 1786: 
 1787:         if ($url =~ m{^/uploaded/$match_domain/$match_courseid/([^/]+)}) {
 1788:             my $oldprefix = $1;
 1789: # When pasting content from Main Content to Supplemental Content and vice versa 
 1790: # URLs will contain different paths (which depend on whether pasted item is
 1791: # a folder/page or a document).   
 1792:             if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
 1793:                 $prefixchg{$suffix} = 'docstosupp';
 1794:             } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
 1795:                 $prefixchg{$suffix} = 'supptodocs';
 1796:             }
 1797: 
 1798: # If pasting an uploaded map, get list of contained uploaded maps.
 1799:             if ($env{'docs.markedcopy_nested_'.$suffix}) {
 1800:                 my @nested;
 1801:                 my ($type) = ($oldprefix =~ /^(default|supplemental)/);
 1802:                 my @items = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
 1803:                 my @deps = map { /\d+:([\d,]+$)/ } @items;
 1804:                 foreach my $dep (@deps) {
 1805:                     if ($dep =~ /,/) {
 1806:                         push(@nested,split(/,/,$dep));
 1807:                     } else {
 1808:                         push(@nested,$dep);
 1809:                     }
 1810:                 }
 1811:                 foreach my $item (@nested) {
 1812:                     if ($env{'form.docs.markedcopy_'.$suffix.'_'.$item} eq 'move') {
 1813:                         push(@{$marktomove{$suffix}},$type.'_'.$item);
 1814:                     }
 1815:                 }
 1816:             }
 1817:         }
 1818:     }
 1819: 
 1820: # Early out if nothing available to paste
 1821:     if (@dopaste == 0) {
 1822:         return ();
 1823:     }
 1824: 
 1825: # Populate message hash and hashes used for main content <=> supplemental content
 1826: # changes    
 1827: 
 1828:     %msgs = &Apache::lonlocal::texthash (
 1829:                 notinsupp => 'Paste failed: content type is not supported within Supplemental Content',
 1830:                 notincrs  => 'Paste failed: Item is from a different course which you do not have rights to edit.',
 1831:                 notindom  => 'Paste failed: Item is an external tool from a course in a different donain.',
 1832:                 duplicate => 'Paste failed: only one instance of a particular published sequence or page is allowed within each course.',
 1833:             );
 1834: 
 1835:     %before = (
 1836:                  docstosupp => {
 1837:                                    map => 'default',
 1838:                                    doc => 'docs',
 1839:                                },
 1840:                  supptodocs => {
 1841:                                    map => 'supplemental',
 1842:                                    doc => 'supplemental',
 1843:                                },
 1844:               );
 1845: 
 1846:     %after = (
 1847:                  docstosupp => {
 1848:                                    map => 'supplemental',
 1849:                                    doc => 'supplemental'
 1850:                                },
 1851:                  supptodocs => {
 1852:                                    map => 'default',
 1853:                                    doc => 'docs',
 1854:                                },
 1855:              );
 1856: 
 1857: # Retrieve information about all course maps in main content area 
 1858: 
 1859:     my $allmaps = {};
 1860:     my (@toclear,%mapurls,%lockerrs,%msgerrs,%results,$donechk);
 1861: 
 1862: # Loop over the items to paste
 1863:     foreach my $suffix (@dopaste) {
 1864: # Maps need to be copied first
 1865:         my (%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
 1866:             %dbcopies,%zombies,%params,%docmoves,%mapmoves,%mapchanges,%newsubdir,
 1867:             %newurls,%tomove,%resdatacopy);
 1868:         if (ref($marktomove{$suffix}) eq 'ARRAY') {
 1869:             map { $tomove{$_} = 1; } @{$marktomove{$suffix}};
 1870:         }
 1871:         my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
 1872:         my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
 1873:         my $cid=&LONCAPA::map::qtescape($env{'docs.markedcopy_crs_'.$suffix});
 1874:         my $oldurl = $url;
 1875:         if ($is_map{$suffix}) {
 1876: # If pasting a map, check if map contains other maps
 1877:             my (%hierarchy,%titles);
 1878:             if (($folder =~ /^default/) && (!$donechk)) {
 1879:                 $allmaps =
 1880:                     &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
 1881:                                                          $env{"course.$env{'request.course.id'}.home"},
 1882:                                                          $env{'request.course.id'});
 1883:                 $donechk = 1; 
 1884:             }
 1885:             &contained_map_check($url,$folder,$coursenum,$coursedom,
 1886:                                  \%removefrommap,\%removeparam,\%addedmaps,
 1887:                                  \%hierarchy,\%titles,$allmaps);
 1888:             if ($url=~ m{^/uploaded/}) {
 1889:                 my $newurl;
 1890:                 unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
 1891:                     ($newurl,my $error) = 
 1892:                         &get_newmap_url($url,$folder,$prefixchg{$suffix},$coursedom,
 1893:                                         $coursenum,$srcdom{$suffix},$srcnum{$suffix},
 1894:                                         \$title,$allmaps,\%newurls);
 1895:                     if ($error) {
 1896:                         $allerrors{$suffix} = $error;
 1897:                         next;
 1898:                     }
 1899:                     if ($newurl ne '') {
 1900:                         if ($newurl ne $url) {
 1901:                             if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
 1902:                                 $newsubdir{$url} = $1;
 1903:                             }
 1904:                             $mapchanges{$url} = 1;
 1905:                         }
 1906:                     }
 1907:                 }
 1908:                 if (($srcdom{$suffix} ne $coursedom) ||
 1909:                     ($srcnum{$suffix} ne $coursenum) ||
 1910:                     ($prefixchg{$suffix}) || (($newurl ne '') && ($newurl ne $url))) {
 1911:                     unless (&url_paste_fixups($url,$folder,$prefixchg{$suffix},
 1912:                                               $coursedom,$coursenum,$srcdom{$suffix},
 1913:                                               $srcnum{$suffix},$allmaps,\%rewrites,
 1914:                                               \%retitles,\%copies,\%dbcopies,
 1915:                                               \%zombies,\%params,\%mapmoves,
 1916:                                               \%mapchanges,\%tomove,\%newsubdir,
 1917:                                               \%newurls,\%resdatacopy)) {
 1918:                         $mapmoves{$url} = 1;
 1919:                     }
 1920:                     $url = $newurl;
 1921:                 } elsif ($env{'docs.markedcopy_nested_'.$suffix}) {
 1922:                     &url_paste_fixups($url,$folder,$prefixchg{$suffix},$coursedom,
 1923:                                       $coursenum,$srcdom{$suffix},$srcnum{$suffix},
 1924:                                       $allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
 1925:                                       \%zombies,\%params,\%mapmoves,\%mapchanges,
 1926:                                       \%tomove,\%newsubdir,\%newurls,\%resdatacopy); 
 1927:                 }
 1928:             } elsif ($url=~m {^/res/}) {
 1929: # published map can only exist once, so remove from paste buffer when done
 1930:                 push(@toclear,$suffix);
 1931: # if pasting published map (main content area only) check map not already in course
 1932:                 if ($folder =~ /^default/) {
 1933:                     if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
 1934:                         $duplicate{$suffix} = 1; 
 1935:                         next;
 1936:                     }
 1937:                 }
 1938:             }
 1939:         }
 1940:         if ($url=~ m{/(bulletinboard|smppg|ext\.tool)$}) {
 1941:             my $prefix = $1;
 1942:             my $fromothercrs;
 1943:             #need to copy the db contents to a new one, unless this is a move.
 1944:             my %info = (
 1945:                          src  => $url,
 1946:                          cdom => $coursedom,
 1947:                          cnum => $coursenum,
 1948:                        );
 1949:             if (($srcdom{$suffix} =~ /^$match_domain$/) && ($srcnum{$suffix} =~ /^$match_courseid$/)) {
 1950:                 unless (($srcdom{$suffix} eq $coursedom) && ($srcnum{$suffix} eq $coursenum)) {
 1951:                     $fromothercrs = 1;
 1952:                     $info{'cdom'} = $srcdom{$suffix};
 1953:                     $info{'cnum'} = $srcnum{$suffix};
 1954:                 }
 1955:             }
 1956:             unless (($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') && (!$fromothercrs)) {
 1957:                 my (%lockerr,$msg); 
 1958:                 my ($newurl,$result,$errtext) =
 1959:                     &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
 1960:                 if ($result eq 'ok') {
 1961:                     $url = $newurl;
 1962:                     $title=&mt('Copy of').' '.$title;
 1963:                 } else {
 1964:                     if ($prefix eq 'smppg') {
 1965:                         $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
 1966:                     } elsif ($prefix eq 'bulletinboard') {
 1967:                         $msg = &mt('Paste failed: An error occurred when copying the discussion board.').' '.$errtext;
 1968:                     } elsif ($prefix eq 'ext.tool') {
 1969:                         $msg = &mt('Paste failed: An error occurred when copying the external tool.').' '.$errtext;
 1970:                     }
 1971:                     $results{$suffix} = $result;
 1972:                     $msgerrs{$suffix} = $msg;
 1973:                     $lockerrs{$suffix} = $lockerr{$prefix}; 
 1974:                     next;
 1975: 	        }
 1976:                 if ($lockerr{$prefix}) {
 1977:                     $lockerrs{$suffix} = $lockerr{$prefix};
 1978:                 }
 1979:             }
 1980:         }
 1981:         $title = &LONCAPA::map::qtunescape($title);
 1982:         my $ext='false';
 1983:         if ($url=~m{^http(|s)://}) { $ext='true'; }
 1984:         if ($env{'docs.markedcopy_supplemental_'.$suffix}) {
 1985:             if ($folder !~ /^supplemental/) {
 1986:                 (undef,undef,$title) =
 1987:                     &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental_'.$suffix});
 1988:             }
 1989:         } else {
 1990:             if ($folder=~/^supplemental/) {
 1991:                 $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 1992:                        $env{'user.domain'}.'___&&&___'.$title;
 1993:             }
 1994:         }
 1995: 
 1996: # For uploaded files (excluding pages/sequences) path in copied file is changed
 1997: # if paste is from Main to Supplemental (or vice versa), or if pasting between
 1998: # courses.
 1999: 
 2000:         unless ($is_map{$suffix}) {
 2001:             my $newidx;
 2002: # Now insert the URL at the bottom
 2003:             $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
 2004:             if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
 2005:                 my $relpath = $1;
 2006:                 if ($relpath ne '') {
 2007:                     my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
 2008:                     my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
 2009:                     my $newprefix = $newloc;
 2010:                     if ($newloc eq 'default') {
 2011:                         $newprefix = 'docs';
 2012:                     }
 2013:                     if ($newdocsdir eq '') {
 2014:                         $newdocsdir = 'default';
 2015:                     }
 2016:                     if (($prefixchg{$suffix}) ||
 2017:                         ($srcdom{$suffix} ne $coursedom) || 
 2018:                         ($srcnum{$suffix} ne $coursenum) ||
 2019:                         ($env{'form.docs.markedcopy_options_'.$suffix} ne 'move')) {
 2020:                         my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
 2021:                         $url =
 2022:                             &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
 2023:                                                                &Apache::lonnet::getfile($oldurl));
 2024:                         if ($url eq '/adm/notfound.html') {
 2025:                             $msgs{$suffix} = &mt('Paste failed: an error occurred saving the file.');
 2026:                             next;
 2027:                         } else {
 2028:                             my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
 2029:                             $newsubpath =~ s{/+$}{/};
 2030:                             $docmoves{$oldurl} = $newsubpath;
 2031:                         }
 2032:                     }
 2033:                 }
 2034:             } elsif ($url =~ m{^/res/lib/templates/(\w+)\.problem$}) {
 2035:                 my $template = $1;
 2036:                 if ($newidx) {
 2037:                     &copy_templated_files($url,$srcdom{$suffix},$srcnum{$suffix},$srcmapidx{$suffix},
 2038:                                           $coursedom,$coursenum,$template,$newidx,"$folder.$container");
 2039:                 }
 2040:             }
 2041:             $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
 2042:                                               ':'.$ext.':normal:res';
 2043:             push(@LONCAPA::map::order,$newidx);
 2044: # Store the result
 2045:             my ($errtext,$fatal) =
 2046:                 &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 2047:             if ($fatal) {
 2048:                 $save_err .= $errtext;
 2049:                 $allresult = 'fail';
 2050:             }
 2051:         }
 2052: 
 2053: # Apply any changes to maps, or copy dependencies for uploaded HTML pages, or update 
 2054: # resourcedata for simpleproblems copied from another course
 2055:         unless ($allresult eq 'fail') {
 2056:             my %updated = (
 2057:                             rewrites      => \%rewrites,
 2058:                             zombies       => \%zombies,
 2059:                             removefrommap => \%removefrommap,
 2060:                             removeparam   => \%removeparam,
 2061:                             dbcopies      => \%dbcopies,
 2062:                             resdatacopy   => \%resdatacopy,
 2063:                             retitles      => \%retitles,
 2064:                           );
 2065:             my %info = (
 2066:                            newsubdir => \%newsubdir,
 2067:                            params    => \%params,
 2068:                        );
 2069:             if ($prefixchg{$suffix}) {
 2070:                 $info{'before'} = $before{$prefixchg{$suffix}};
 2071:                 $info{'after'} = $after{$prefixchg{$suffix}};
 2072:             }
 2073:             my %moves = (
 2074:                            copies   => \%copies,
 2075:                            docmoves => \%docmoves,
 2076:                            mapmoves => \%mapmoves,
 2077:                         );
 2078:             (my $result,$msgs{$suffix},my $lockerror) =
 2079:                 &apply_fixups($folder,$is_map{$suffix},$coursedom,$coursenum,$errors,
 2080:                               \%updated,\%info,\%moves,$prefixchg{$suffix},$oldurl,
 2081:                               $url,'paste');
 2082:             $lockerrors .= $lockerror;
 2083:             if ($result eq 'ok') {
 2084:                 if ($is_map{$suffix}) {
 2085:                     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 2086:                                                     $folder.'.'.$container);
 2087:                     if ($fatal) {
 2088:                         $allresult = 'failread';
 2089:                     } else {
 2090:                         if ($#LONCAPA::map::order<1) {
 2091:                             my $idx=&LONCAPA::map::getresidx();
 2092:                             if ($idx<=0) { $idx=1; }
 2093:                             $LONCAPA::map::order[0]=$idx;
 2094:                             $LONCAPA::map::resources[$idx]='';
 2095:                         }
 2096:                         my $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
 2097:                         $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
 2098:                                                           ':'.$ext.':normal:res';
 2099:                         push(@LONCAPA::map::order,$newidx);
 2100: 
 2101: # Store the result
 2102:                         my ($errtext,$fatal) = 
 2103:                             &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 2104:                         if ($fatal) {
 2105:                             $save_err .= $errtext;
 2106:                             $allresult = 'failstore';
 2107:                         }
 2108:                     } 
 2109:                 }
 2110:                 if ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
 2111:                      push(@toclear,$suffix);
 2112:                 }
 2113:             }
 2114:         }
 2115:     }
 2116:     &clear_from_buffer(\@toclear,\@currpaste);
 2117:     my $msgsarray;
 2118:     foreach my $suffix (keys(%msgs)) {
 2119:          if (ref($msgs{$suffix}) eq 'ARRAY') {
 2120:              $msgsarray .= join(',',@{$msgs{$suffix}});
 2121:          }
 2122:     }
 2123:     return ($allresult,$save_err,$msgsarray,$lockerrors);
 2124: }
 2125: 
 2126: sub do_buffer_empty {
 2127:     my @currpaste = split(/,/,$env{'docs.markedcopies'});
 2128:     if (@currpaste == 0) {
 2129:         return &mt('Clipboard is already empty');
 2130:     }
 2131:     my @toclear = &Apache::loncommon::get_env_multiple('form.pasting');
 2132:     if (@toclear == 0) {
 2133:         return &mt('Nothing selected to clear from clipboard');
 2134:     }
 2135:     my $numdel = &clear_from_buffer(\@toclear,\@currpaste);
 2136:     if ($numdel) {
 2137:         return &mt('[quant,_1,item] cleared from clipboard',$numdel);
 2138:     } else {
 2139:         return &mt('Clipboard unchanged');
 2140:     }
 2141:     return;
 2142: }
 2143: 
 2144: sub clear_from_buffer {
 2145:     my ($toclear,$currpaste) = @_;
 2146:     return unless ((ref($toclear) eq 'ARRAY') && (ref($currpaste) eq 'ARRAY'));
 2147:     my %pastebuffer;
 2148:     map { $pastebuffer{$_} = 1; } @{$currpaste};
 2149:     my $numdel = 0;
 2150:     foreach my $suffix (@{$toclear}) {
 2151:         next if ($suffix =~ /\D/);
 2152:         next unless (exists($pastebuffer{$suffix}));
 2153:         my $regexp = 'docs.markedcopy_[a-z]+_'.$suffix;
 2154:         if (&Apache::lonnet::delenv($regexp,1) eq 'ok') {
 2155:             delete($pastebuffer{$suffix});
 2156:             $numdel ++;
 2157:         }
 2158:     }
 2159:     my $newbuffer = join(',',sort(keys(%pastebuffer)));
 2160:     &Apache::lonnet::appenv({'docs.markedcopies' => $newbuffer});
 2161:     return $numdel;
 2162: }
 2163: 
 2164: sub get_newmap_url {
 2165:     my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
 2166:         $titleref,$allmaps,$newurls) = @_;
 2167:     my $newurl;
 2168:     if ($url=~ m{^/uploaded/}) {
 2169:         $$titleref=&mt('Copy of').' '.$$titleref;
 2170:     }
 2171:     my $now = time;
 2172:     my $suffix=$$.int(rand(100)).$now;
 2173:     my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
 2174:     if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
 2175:         my $path = $1;
 2176:         my $prefix = $2;
 2177:         my $ancestor = $3;
 2178:         if (length($ancestor) > 10) {
 2179:             $ancestor = substr($ancestor,-10,10);
 2180:         }
 2181:         my $newid;
 2182:         if ($prefixchg) {
 2183:             if ($folder =~ /^supplemental/) {
 2184:                 $prefix =~ s/^default/supplemental/;
 2185:             } else {
 2186:                 $prefix =~ s/^supplemental/default/;
 2187:             }
 2188:         }
 2189:         if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
 2190:             $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
 2191:         } else {
 2192:             $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
 2193:         }
 2194:         my $counter = 0;
 2195:         my $is_unique = &uniqueness_check($newurl);
 2196:         if ($folder =~ /^default/) {
 2197:             if ($allmaps->{$newurl}) {
 2198:                 $is_unique = 0;
 2199:             }
 2200:         }
 2201:         while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
 2202:             $counter ++;
 2203:             $suffix ++;
 2204:             if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
 2205:                 $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
 2206:             } else {
 2207:                 $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
 2208:             }
 2209:             $is_unique = &uniqueness_check($newurl);
 2210:         }
 2211:         if ($is_unique) {
 2212:             $newurls->{$newurl} = 1;
 2213:         } else {
 2214:             if ($url=~/\.page$/) {
 2215:                 return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
 2216:             } else {
 2217:                 return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
 2218:             }
 2219:         }
 2220:     }
 2221:     return ($newurl);
 2222: }
 2223: 
 2224: sub dbcopy {
 2225:     my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
 2226:     my ($url,$result,$errtext);
 2227:     if (ref($dbref) eq 'HASH') {
 2228:         $url = $dbref->{'src'};
 2229:         if ($url =~ m{/(smppg|bulletinboard|ext\.tool)$}) {
 2230:             my $prefix = $1;
 2231:             if ($prefix eq 'ext.tool') {
 2232:                 $prefix = 'exttool';
 2233:             }
 2234:             if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
 2235:                 ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
 2236:                 my $db_name;
 2237:                 my $marker = (split(m{/},$url))[4];
 2238:                 $marker=~s/\D//g;
 2239:                 if ($dbref->{'src'} =~ m{/smppg$}) {
 2240:                     $db_name =
 2241:                         &Apache::lonsimplepage::get_db_name($url,$marker,
 2242:                                                             $dbref->{'cdom'},
 2243:                                                             $dbref->{'cnum'});
 2244:                 } elsif ($dbref->{'src'} =~ m{/ext\.tool$}) {
 2245:                     $db_name = 'exttool_'.$marker;
 2246:                 } else {
 2247:                     $db_name = 'bulletinpage_'.$marker;
 2248:                 }
 2249:                 my ($suffix,$freedlock,$error) =
 2250:                     &Apache::lonnet::get_timebased_id($prefix,'num','templated',
 2251:                                                       $coursedom,$coursenum,
 2252:                                                       'concat');
 2253:                 if (!$suffix) {
 2254:                     if ($prefix eq 'smppg') {
 2255:                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
 2256:                     } elsif ($prefix eq 'exttool') {
 2257:                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying an external tool [_1].',$url);
 2258:                     } else {
 2259:                         $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a discussion board [_1].',$url);
 2260:                     }
 2261:                     if ($error) {
 2262:                         $errtext .= '<br />'.$error;
 2263:                     }
 2264:                 } else {
 2265:                     #need to copy the db contents to a new one.
 2266:                     my %contents=&Apache::lonnet::dump($db_name,
 2267:                                                        $dbref->{'cdom'},
 2268:                                                        $dbref->{'cnum'});
 2269:                     if (exists($contents{'uploaded.photourl'})) {
 2270:                         my $photo = $contents{'uploaded.photourl'};
 2271:                         my ($subdir,$fname) =
 2272:                             ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
 2273:                         my $newphoto;
 2274:                         if ($fname ne '') {
 2275:                             my $content = &Apache::lonnet::getfile($photo);
 2276:                             unless ($content eq '-1') {
 2277:                                 $env{'form.'.$suffix.'.photourl'} = $content;
 2278:                                 $newphoto =
 2279:                                     &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
 2280:                                 delete($env{'form.'.$suffix.'.photourl'});
 2281:                             }
 2282:                         }
 2283:                         if ($newphoto =~ m{^/uploaded/}) {
 2284:                             $contents{'uploaded.photourl'} = $newphoto;
 2285:                         }
 2286:                     }
 2287:                     $db_name =~ s{_\d*$ }{_$suffix}x;
 2288:                     $result=&Apache::lonnet::put($db_name,\%contents,
 2289:                                                  $coursedom,$coursenum);
 2290:                     if ($result eq 'ok') {
 2291:                         $url =~ s{/(\d*)/(smppg|bulletinboard|ext\.tool)$}{/$suffix/$2}x;
 2292:                     }
 2293:                 }
 2294:                 if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
 2295:                     $lockerrorsref->{$prefix} =
 2296:                         '<div class="LC_error">'.
 2297:                         &mt('There was a problem removing a lockfile.');
 2298:                     if ($prefix eq 'smppg') {
 2299:                         $lockerrorsref->{$prefix} .=
 2300:                             ' '.&mt('This will prevent creation of additional simple pages in this course.');
 2301:                     } elsif ($prefix eq 'exttool') {
 2302:                         $lockerrorsref->{$prefix} .=
 2303:                             ' '.&mt('This will prevent addition of more external tools to this course.');
 2304:                     } else {
 2305:                         $lockerrorsref->{$prefix} .= ' '.&mt('This will prevent creation of additional discussion boards in this course.');
 2306:                     }
 2307:                     $lockerrorsref->{$prefix} .= ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
 2308:                                                      '<a href="/adm/helpdesk" target="_helpdesk">','</a>').
 2309:                                                  '</div>';
 2310:                 }
 2311:             }
 2312:         } elsif ($url =~ m{/syllabus$}) {
 2313:             if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
 2314:                 ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
 2315:                 if (($dbref->{'cdom'} ne $coursedom) ||
 2316:                     ($dbref->{'cnum'} ne $coursenum)) {
 2317:                     my %contents=&Apache::lonnet::dump('syllabus',
 2318:                                                        $dbref->{'cdom'},
 2319:                                                        $dbref->{'cnum'});
 2320:                     $result=&Apache::lonnet::put('syllabus',\%contents,
 2321:                                                  $coursedom,$coursenum);
 2322:                 }
 2323:             }
 2324:         }
 2325:     }
 2326:     return ($url,$result,$errtext);
 2327: }
 2328: 
 2329: sub copy_templated_files {
 2330:     my ($srcurl,$srcdom,$srcnum,$srcmapinfo,$coursedom,$coursenum,$template,$newidx,$newmapname) = @_;
 2331:     my ($srcfolder,$srcid,$srcwaspage) = split(/:/,$srcmapinfo);
 2332:     my $srccontainer = 'sequence';
 2333:     if ($srcwaspage) {
 2334:         $srccontainer = 'page';
 2335:     }
 2336:     my $srcsymb = "uploaded/$srcdom/$srcnum/$srcfolder.$srccontainer".
 2337:                   '___'.$srcid.'___'.&Apache::lonnet::declutter($srcurl);
 2338:     my $srcprefix = $srcdom.'_'.$srcnum.'.'.$srcsymb;
 2339:     my %srcparms=&Apache::lonnet::dump('resourcedata',$srcdom,$srcnum,$srcprefix);
 2340:     my $newsymb = "uploaded/$coursedom/$coursenum/$newmapname".'___'.$newidx.'___lib/templates/'.
 2341:                   $template.'.problem';
 2342:     my $newprefix = $coursedom.'_'.$coursenum.'.'.$newsymb;
 2343:     if ($template eq 'simpleproblem') {
 2344:         $srcprefix .= '.0.';
 2345:         my $weightprefix = $newprefix;
 2346:         $newprefix .= '.0.';
 2347:         my @simpleprobqtypes = qw(radio option string essay numerical);
 2348:         my $qtype=$srcparms{$srcprefix.'questiontype'};
 2349:         if (grep(/^\Q$qtype\E$/,@simpleprobqtypes)) {
 2350:             my %newdata = (
 2351:                 $newprefix.'questiontype' => $qtype,
 2352:             );
 2353:             foreach my $type (@simpleprobqtypes) {
 2354:                 if ($type eq $qtype) {
 2355:                     $newdata{"$weightprefix.$type.weight"}=1;
 2356:                 } else {
 2357:                     $newdata{"$weightprefix.$type.weight"}=0;
 2358:                 }
 2359:             }
 2360:             $newdata{$newprefix.'hiddenparts'} = '!'.$qtype;
 2361:             $newdata{$newprefix.'questiontext'} = $srcparms{$srcprefix.'questiontext'};
 2362:             $newdata{$newprefix.'hinttext'} = $srcparms{$srcprefix.'hinttext'};
 2363:             if ($qtype eq 'numerical') {
 2364:                 $newdata{$newprefix.'numericalscript'} = $srcparms{$srcprefix.'numericalscript'};
 2365:                 $newdata{$newprefix.'numericalanswer'} = $srcparms{$srcprefix.'numericalanswer'};
 2366:                 $newdata{$newprefix.'numericaltolerance'} = $srcparms{$srcprefix.'numericaltolerance'};
 2367:                 $newdata{$newprefix.'numericalsigfigs'} = $srcparms{$srcprefix.'numericalsigfigs'};
 2368:             } elsif (($qtype eq 'option') || ($qtype eq 'radio')) {
 2369:                 my $maxfoils=$srcparms{$srcprefix.'maxfoils'};
 2370:                 unless (defined($maxfoils)) { $maxfoils=10; }
 2371:                     unless ($maxfoils=~/^\d+$/) { $maxfoils=10; }
 2372:                         if ($maxfoils<=0) { $maxfoils=10; }
 2373:                             my $randomize=$srcparms{$srcprefix.'randomize'};
 2374:                             unless (defined($randomize)) { $randomize='yes'; }
 2375:                             unless ($randomize eq 'no') { $randomize='yes'; }
 2376:                             $newdata{$newprefix.'maxfoils'} = $maxfoils;
 2377:                             $newdata{$newprefix.'randomize'} = $randomize;
 2378:                             if ($qtype eq 'option') {
 2379:                                 $newdata{$newprefix.'options'} = $srcparms{$srcprefix.'options'};
 2380:                             }
 2381:                             for (my $i=1; $i<=10; $i++) {
 2382:                                 $newdata{$newprefix.'value'.$i} = $srcparms{$srcprefix.'value'.$i};
 2383:                                 $newdata{$newprefix.'position'.$i} = $srcparms{$srcprefix.'position'.$i};
 2384:                                 $newdata{$newprefix.'text'.$i} = $srcparms{$srcprefix.'text'.$i};
 2385:                             }
 2386: 
 2387:             } elsif (($qtype eq 'option') || ($qtype eq 'radio')) {
 2388:                 my $maxfoils=$srcparms{$srcprefix.'maxfoils'};
 2389:                 unless (defined($maxfoils)) { $maxfoils=10; }
 2390:                 unless ($maxfoils=~/^\d+$/) { $maxfoils=10; }
 2391:                 if ($maxfoils<=0) { $maxfoils=10; }
 2392:                 my $randomize=$srcparms{$srcprefix.'randomize'};
 2393:                 unless (defined($randomize)) { $randomize='yes'; }
 2394:                 unless ($randomize eq 'no') { $randomize='yes'; }
 2395:                 $newdata{$newprefix.'maxfoils'} = $maxfoils;
 2396:                 $newdata{$newprefix.'randomize'} = $randomize;
 2397:                 if ($qtype eq 'option') {
 2398:                     $newdata{$newprefix.'options'} = $srcparms{$srcprefix.'options'};
 2399:                 }
 2400:                 for (my $i=1; $i<=10; $i++) {
 2401:                     $newdata{$newprefix.'value'.$i} = $srcparms{$srcprefix.'value'.$i};
 2402:                     $newdata{$newprefix.'position'.$i} = $srcparms{$srcprefix.'position'.$i};
 2403:                     $newdata{$newprefix.'text'.$i} = $srcparms{$srcprefix.'text'.$i};
 2404:                 }
 2405:             } elsif ($qtype eq 'string') {
 2406:                 $newdata{$newprefix.'stringanswer'} = $srcparms{$srcprefix.'stringanswer'};
 2407:                 $newdata{$newprefix.'stringtype'} = $srcparms{$srcprefix.'stringtype'};
 2408:             }
 2409:             if (keys(%newdata)) {
 2410:                 my $putres = &Apache::lonnet::cput('resourcedata',\%newdata,$coursedom,
 2411:                                                    $coursenum);
 2412:                 if ($putres eq 'ok') {
 2413:                     &Apache::lonnet::devalidatecourseresdata($coursenum,$coursedom);
 2414:                 }
 2415:             }
 2416:         }
 2417:     }
 2418: }
 2419: 
 2420: sub uniqueness_check {
 2421:     my ($newurl) = @_;
 2422:     my $unique = 1;
 2423:     foreach my $res (@LONCAPA::map::order) {
 2424:         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 2425:         $url=&LONCAPA::map::qtescape($url);
 2426:         if ($newurl eq $url) {
 2427:             $unique = 0;
 2428:             last;
 2429:         }
 2430:     }
 2431:     return $unique;
 2432: }
 2433: 
 2434: sub contained_map_check {
 2435:     my ($url,$folder,$coursenum,$coursedom,$removefrommap,$removeparam,$addedmaps,
 2436:         $hierarchy,$titles,$allmaps) = @_;
 2437:     my $content = &Apache::lonnet::getfile($url);
 2438:     unless ($content eq '-1') {
 2439:         my $parser = HTML::TokeParser->new(\$content);
 2440:         $parser->attr_encoded(1);
 2441:         while (my $token = $parser->get_token) {
 2442:             next if ($token->[0] ne 'S');
 2443:             if ($token->[1] eq 'resource') {
 2444:                 next if ($token->[2]->{'type'} eq 'zombie');
 2445:                 my $ressrc = $token->[2]->{'src'};
 2446:                 if ($folder =~ /^supplemental/) {
 2447:                     unless (&supp_pasteable($ressrc)) {
 2448:                         $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 2449:                         next;
 2450:                     }
 2451:                 }
 2452:                 if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
 2453:                     if ($1 eq 'uploaded') {
 2454:                         $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
 2455:                         $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
 2456:                     } else {
 2457:                         if ($allmaps->{$ressrc}) {
 2458:                             $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 2459:                         } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
 2460:                             $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 2461:                         } else {
 2462:                             $addedmaps->{$ressrc} = [$url];
 2463:                         }
 2464:                     }
 2465:                     &contained_map_check($ressrc,$folder,$coursenum,$coursedom,
 2466:                                          $removefrommap,$removeparam,
 2467:                                          $addedmaps,$hierarchy,$titles,$allmaps);
 2468:                 }
 2469:             } elsif ($token->[1] eq 'param') {
 2470:                 if ($folder =~ /^supplemental/) {
 2471:                     if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
 2472:                         push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
 2473:                     } else {
 2474:                         $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
 2475:                     }
 2476:                 }
 2477:             }
 2478:         }
 2479:     }
 2480:     return;
 2481: }
 2482: 
 2483: sub url_paste_fixups {
 2484:     my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
 2485:         $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
 2486:         $mapchanges,$tomove,$newsubdir,$newurls,$resdatacopy) = @_;
 2487:     my $checktitle;
 2488:     if (($prefixchg) &&
 2489:         ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
 2490:         $checktitle = 1;
 2491:     }
 2492:     my $skip;
 2493:     if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
 2494:         my $mapid = $1.$2;
 2495:         if ($tomove->{$mapid}) {
 2496:             $skip = 1;
 2497:         }
 2498:     }
 2499:     my $file = &Apache::lonnet::getfile($oldurl);
 2500:     return if ($file eq '-1');
 2501:     my $parser = HTML::TokeParser->new(\$file);
 2502:     $parser->attr_encoded(1);
 2503:     my $changed = 0;
 2504:     while (my $token = $parser->get_token) {
 2505:         next if ($token->[0] ne 'S');
 2506:         if ($token->[1] eq 'resource') {
 2507:             my $ressrc = $token->[2]->{'src'};
 2508:             next if ($ressrc eq '');
 2509:             my $id = $token->[2]->{'id'};
 2510:             my $title = $token->[2]->{'title'};
 2511:             if ($checktitle) {
 2512:                 if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
 2513:                     $retitles->{$oldurl}{$id} = $ressrc;
 2514:                 }
 2515:             }
 2516:             next if ($token->[2]->{'type'} eq 'external');
 2517:             if ($token->[2]->{'type'} eq 'zombie') {
 2518:                 next if ($skip);
 2519:                 $zombies->{$oldurl}{$id} = $ressrc;
 2520:                 $changed = 1;
 2521:             } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
 2522:                 my $srcdom = $1;
 2523:                 my $srcnum = $2;
 2524:                 my $rem = $3;
 2525:                 my $newurl;
 2526:                 my $mapname;
 2527:                 if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
 2528:                     my $prefix = $1;
 2529:                     $mapname = $prefix.$2;
 2530:                     if ($tomove->{$mapname}) {
 2531:                         &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
 2532:                                           $srcdom,$srcnum,$allmaps,$rewrites,
 2533:                                           $retitles,$copies,$dbcopies,$zombies,
 2534:                                           $params,$mapmoves,$mapchanges,$tomove,
 2535:                                           $newsubdir,$newurls,$resdatacopy);
 2536:                         next;
 2537:                     } else {
 2538:                         ($newurl,my $error) =
 2539:                             &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
 2540:                                             $srcdom,$srcnum,\$title,$allmaps,$newurls);
 2541:                         if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
 2542:                             $newsubdir->{$ressrc} = $1;
 2543:                         }
 2544:                         if ($error) {
 2545:                             next;
 2546:                         }
 2547:                     }
 2548:                 }
 2549:                 if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
 2550:                     ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
 2551:                    
 2552:                     if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
 2553:                         $rewrites->{$oldurl}{$id} = $ressrc;
 2554:                         $mapchanges->{$ressrc} = 1;
 2555:                         unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
 2556:                                                   $cnum,$srcdom,$srcnum,$allmaps,
 2557:                                                   $rewrites,$retitles,$copies,$dbcopies,
 2558:                                                   $zombies,$params,$mapmoves,$mapchanges,
 2559:                                                   $tomove,$newsubdir,$newurls,$resdatacopy)) {
 2560:                             $mapmoves->{$ressrc} = 1;
 2561:                         }
 2562:                         $changed = 1;
 2563:                     } else {
 2564:                         $rewrites->{$oldurl}{$id} = $ressrc;
 2565:                         $copies->{$oldurl}{$ressrc} = $id;
 2566:                         $changed = 1;
 2567:                     }
 2568:                 }
 2569:             } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
 2570:                 next if ($skip);
 2571:                 my $srcdom = $1;
 2572:                 my $srcnum = $2;
 2573:                 if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
 2574:                     $rewrites->{$oldurl}{$id} = $ressrc;
 2575:                     $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
 2576:                     $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
 2577:                     $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
 2578:                     $changed = 1;
 2579:                 }
 2580:             } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
 2581:                 if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
 2582:                     ($env{'form.docs.markedcopy_options'} ne 'move')) {
 2583:                     $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
 2584:                     $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
 2585:                     $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
 2586:                     $changed = 1;
 2587:                 }
 2588:             } elsif ($ressrc eq '/res/lib/templates/simpleproblem.problem') {
 2589:                 if (($fromcdom ne $cdom) || ($fromcnum ne $cnum)) {
 2590:                     $resdatacopy->{$oldurl}{$id}{'src'} = $ressrc;
 2591:                     $resdatacopy->{$oldurl}{$id}{'cdom'} = $fromcdom;
 2592:                     $resdatacopy->{$oldurl}{$id}{'cnum'} = $fromcnum;
 2593:                 }
 2594:             } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
 2595:                 next if ($skip);
 2596:                 my $srcdom = $1;
 2597:                 my $srcnum = $2;
 2598:                 if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
 2599:                     $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
 2600:                     $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
 2601:                     $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
 2602:                     $changed = 1;
 2603:                 }
 2604:             }
 2605:         } elsif ($token->[1] eq 'param') {
 2606:             next if ($skip);
 2607:             my $to = $token->[2]->{'to'}; 
 2608:             if ($to ne '') {
 2609:                 if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
 2610:                     push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
 2611:                 } else {
 2612:                     @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
 2613:                 }
 2614:             }
 2615:         }
 2616:     }
 2617:     return $changed;
 2618: }
 2619: 
 2620: sub apply_fixups {
 2621:     my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
 2622:         $oldurl,$url,$caller) = @_;
 2623:     my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
 2624:         %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
 2625:         %resdatacopy,%lockerrors,$lockmsg);
 2626:     if (ref($updated) eq 'HASH') {
 2627:         if (ref($updated->{'rewrites'}) eq 'HASH') {
 2628:             %rewrites = %{$updated->{'rewrites'}};
 2629:         }
 2630:         if (ref($updated->{'zombies'}) eq 'HASH') {
 2631:             %zombies = %{$updated->{'zombies'}};
 2632:         }
 2633:         if (ref($updated->{'removefrommap'}) eq 'HASH') {
 2634:             %removefrommap = %{$updated->{'removefrommap'}};
 2635:         }
 2636:         if (ref($updated->{'removeparam'}) eq 'HASH') {
 2637:             %removeparam = %{$updated->{'removeparam'}};
 2638:         }
 2639:         if (ref($updated->{'dbcopies'}) eq 'HASH') {
 2640:             %dbcopies = %{$updated->{'dbcopies'}};
 2641:         }
 2642:         if (ref($updated->{'retitles'}) eq 'HASH') {
 2643:             %retitles = %{$updated->{'retitles'}};
 2644:         }
 2645:         if (ref($updated->{'resdatacopy'}) eq 'HASH') {
 2646:             %resdatacopy = %{$updated->{'resdatacopy'}};
 2647:         }
 2648:     }
 2649:     if (ref($info) eq 'HASH') {
 2650:         if (ref($info->{'newsubdir'}) eq 'HASH') {
 2651:             %newsubdir = %{$info->{'newsubdir'}};
 2652:         }
 2653:         if (ref($info->{'params'}) eq 'HASH') {
 2654:             %params = %{$info->{'params'}};
 2655:         }
 2656:         if (ref($info->{'before'}) eq 'HASH') {
 2657:             %before = %{$info->{'before'}};
 2658:         }
 2659:         if (ref($info->{'after'}) eq 'HASH') {
 2660:             %after = %{$info->{'after'}};
 2661:         }
 2662:     }
 2663:     if (ref($moves) eq 'HASH') {
 2664:         if (ref($moves->{'copies'}) eq 'HASH') {
 2665:             %copies = %{$moves->{'copies'}};
 2666:         }
 2667:         if (ref($moves->{'docmoves'}) eq 'HASH') {
 2668:             %docmoves = %{$moves->{'docmoves'}};
 2669:         }
 2670:         if (ref($moves->{'mapmoves'}) eq 'HASH') {
 2671:             %mapmoves = %{$moves->{'mapmoves'}};
 2672:         }
 2673:     }
 2674:     foreach my $key (keys(%copies),keys(%docmoves)) {
 2675:         my @allcopies;
 2676:         if (exists($copies{$key})) {
 2677:             if (ref($copies{$key}) eq 'HASH') {
 2678:                 my %added;
 2679:                 foreach my $innerkey (keys(%{$copies{$key}})) {
 2680:                     if (($innerkey ne '') && (!$added{$innerkey})) {
 2681:                         push(@allcopies,$innerkey);
 2682:                         $added{$innerkey} = 1;
 2683:                     }
 2684:                 }
 2685:                 undef(%added);
 2686:             }
 2687:         }
 2688:         if ($key eq $oldurl) {
 2689:             if ((exists($docmoves{$key}))) {
 2690:                 unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
 2691:                     push(@allcopies,$oldurl);
 2692:                 }
 2693:             }
 2694:         }
 2695:         if (@allcopies > 0) {
 2696:             foreach my $item (@allcopies) {
 2697:                 my ($relpath,$oldsubdir,$fname) = 
 2698:                     ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
 2699:                 if ($fname ne '') {
 2700:                     my $content = &Apache::lonnet::getfile($item);
 2701:                     unless ($content eq '-1') {
 2702:                         my $storefn;
 2703:                         if (($key eq $oldurl) && (exists($docmoves{$key}))) {
 2704:                             $storefn = $docmoves{$key};
 2705:                         } else {
 2706:                             $storefn = $relpath;
 2707:                             $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
 2708:                             if ($prefixchg && $before{'doc'} && $after{'doc'}) {
 2709:                                 $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
 2710:                             }
 2711:                             if ($newsubdir{$key}) {
 2712:                                 $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
 2713:                             }
 2714:                         }
 2715:                         &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
 2716:                         my $copyurl = 
 2717:                             &Apache::lonclonecourse::writefile($env{'request.course.id'},
 2718:                                                                $storefn.$fname,$content);
 2719:                         if ($copyurl eq '/adm/notfound.html') {
 2720:                             if (exists($docmoves{$oldurl})) {
 2721:                                 return &mt('Paste failed: an error occurred copying the file.');
 2722:                             } elsif (ref($errors) eq 'HASH') {
 2723:                                 $errors->{$item} = 1;
 2724:                             }
 2725:                         }
 2726:                     }
 2727:                 }
 2728:             }
 2729:         }
 2730:     }
 2731:     foreach my $key (keys(%mapmoves)) {
 2732:         my $storefn=$key;
 2733:         $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 2734:         if ($prefixchg && $before{'map'} && $after{'map'}) {
 2735:             $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
 2736:         }
 2737:         if ($newsubdir{$key}) {
 2738:             $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
 2739:         }
 2740:         my $mapcontent = &Apache::lonnet::getfile($key);
 2741:         if (($mapcontent eq '-1') && ($before{'map'} eq 'supplemental') &&
 2742:             ($after{'map'} eq 'default') &&
 2743:             ($key =~ m{^/uploaded/$match_domain/$match_courseid/supplemental_\d+\.sequence$})) {
 2744:             $mapcontent = '<map>'."\n".
 2745:                           '<resource id="1" src="" type="start" />'."\n".
 2746:                           '<link from="1" to="2" index="1" />'."\n".
 2747:                           '<resource id="2" src="" type="finish" />'."\n".
 2748:                           '</map>';
 2749:         }
 2750:         if ($mapcontent eq '-1') {
 2751:             if (ref($errors) eq 'HASH') {
 2752:                 $errors->{$key} = 1;
 2753:             }
 2754:         } else {
 2755:             my $newmap =
 2756:                 &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
 2757:                                                    $mapcontent);
 2758:             if ($newmap eq '/adm/notfound.html') {
 2759:                 if (ref($errors) eq 'HASH') {
 2760:                     $errors->{$key} = 1;
 2761:                 }
 2762:             }
 2763:         }
 2764:     }
 2765:     my %updates;
 2766:     if ($is_map) {
 2767:         if (ref($updated) eq 'HASH') {
 2768:             foreach my $type (keys(%{$updated})) {
 2769:                 if (ref($updated->{$type}) eq 'HASH') {
 2770:                     foreach my $key (keys(%{$updated->{$type}})) {
 2771:                         $updates{$key} = 1;
 2772:                     }
 2773:                 }
 2774:             }
 2775:         }
 2776:         foreach my $key (keys(%updates)) {
 2777:             my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
 2778:             if (ref($rewrites{$key}) eq 'HASH') {
 2779:                 %torewrite = %{$rewrites{$key}};
 2780:             }
 2781:             if (ref($retitles{$key}) eq 'HASH') {
 2782:                 %toretitle = %{$retitles{$key}};
 2783:             }
 2784:             if (ref($removefrommap{$key}) eq 'HASH') {
 2785:                 %toremove = %{$removefrommap{$key}};
 2786:             }
 2787:             if (ref($removeparam{$key}) eq 'HASH') {
 2788:                 %remparam = %{$removeparam{$key}};
 2789:             }
 2790:             if (ref($zombies{$key}) eq 'HASH') {
 2791:                 %zombie = %{$zombies{$key}};
 2792:             }
 2793:             if (ref($dbcopies{$key}) eq 'HASH') {
 2794:                 foreach my $idx (keys(%{$dbcopies{$key}})) {
 2795:                     if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
 2796:                         my ($newurl,$result,$errtext) =
 2797:                             &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
 2798:                         if ($result eq 'ok') {
 2799:                             $newdb{$idx} = $newurl;
 2800:                         } elsif (ref($errors) eq 'HASH') {
 2801:                             $errors->{$key} = 1;
 2802:                         }
 2803:                         push(@msgs,$errtext);
 2804:                     }
 2805:                 }
 2806:             }
 2807:             if (ref($resdatacopy{$key}) eq 'HASH') {
 2808:                 my ($gotnewmapname,$newmapname,$srcfolder,$srccontainer);
 2809:                 foreach my $idx (keys(%{$resdatacopy{$key}})) {
 2810:                     if (ref($resdatacopy{$key}{$idx}) eq 'HASH') {
 2811:                         my $srcurl = $resdatacopy{$key}{$idx}{'src'};
 2812:                         if ($srcurl =~ m{^/res/lib/templates/(\w+)\.problem$}) {
 2813:                             my $template = $1;
 2814:                             if (($resdatacopy{$key}{$idx}{'cdom'} =~ /^$match_domain$/) &&
 2815:                                 ($resdatacopy{$key}{$idx}{'cnum'} =~ /^$match_courseid$/)) {
 2816:                                 my $srcdom = $resdatacopy{$key}{$idx}{'cdom'};
 2817:                                 my $srcnum = $resdatacopy{$key}{$idx}{'cnum'};
 2818:                                 unless ($gotnewmapname) {
 2819:                                     ($newmapname) = ($key =~ m{/([^/]+)$});
 2820:                                     ($srcfolder,$srccontainer) = split(/\./,$newmapname);
 2821:                                     if ($newsubdir{$key}) {
 2822:                                         $newmapname =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
 2823:                                     }
 2824:                                     $gotnewmapname = 1;
 2825:                                 }
 2826:                                 my $srcmapinfo = $srcfolder.':'.$idx;
 2827:                                 if ($srccontainer eq 'page') {
 2828:                                     $srcmapinfo .= ':1';
 2829:                                 }
 2830:                                 &copy_templated_files($srcurl,$srcdom,$srcnum,$srcmapinfo,$cdom,
 2831:                                                       $cnum,$template,$idx,$newmapname);
 2832:                             }
 2833:                         }
 2834:                     }
 2835:                 }
 2836:             }
 2837:             if (ref($params{$key}) eq 'HASH') {
 2838:                 %currparam = %{$params{$key}};
 2839:             }
 2840:             my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
 2841:             if ($fatal) {
 2842:                 return ($errtext);
 2843:             }
 2844:             for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
 2845:                 if (defined($LONCAPA::map::zombies[$i])) {
 2846:                     my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
 2847:                     if ($zombie{$i} eq $src) {
 2848:                         undef($LONCAPA::map::zombies[$i]);
 2849:                     }
 2850:                 }
 2851:             }
 2852:             my $total = scalar(@LONCAPA::map::order) - 1;
 2853:             for (my $i=$total; $i>=0; $i--) {
 2854:                 my $idx = $LONCAPA::map::order[$i];
 2855:                 if (defined($LONCAPA::map::resources[$idx])) {
 2856:                     my $changed;
 2857:                     my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
 2858:                     if ((exists($toremove{$idx})) && 
 2859:                         ($toremove{$idx} eq &LONCAPA::map::qtescape($src))) {
 2860:                         splice(@LONCAPA::map::order,$i,1);
 2861:                         if (ref($currparam{$idx}) eq 'ARRAY') {
 2862:                             foreach my $name (@{$currparam{$idx}}) {
 2863:                                 &LONCAPA::map::delparameter($idx,$name);
 2864:                             }
 2865:                         }
 2866:                         next;
 2867:                     }
 2868:                     my $origsrc = $src;
 2869:                     if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
 2870:                         if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
 2871:                             $changed = 1;
 2872:                         }
 2873:                     }
 2874:                     if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
 2875:                         $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
 2876:                         if ($origsrc =~ m{^/uploaded/}) {
 2877:                             if ($prefixchg && $before{'map'} && $after{'map'}) {
 2878:                                 if ($src =~ /\.(page|sequence)$/) {
 2879:                                     $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
 2880:                                 } else {
 2881:                                     $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
 2882:                                 }
 2883:                             }
 2884:                             if ($origsrc =~ /\.(page|sequence)$/) {
 2885:                                 if ($newsubdir{$origsrc}) {
 2886:                                     $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
 2887:                                 }
 2888:                             } elsif ($newsubdir{$key}) {
 2889:                                 $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
 2890:                             }
 2891:                         }
 2892:                         $changed = 1;
 2893:                     } elsif ($newdb{$idx} ne '') {
 2894:                         $src = $newdb{$idx};
 2895:                         $changed = 1;
 2896:                     }
 2897:                     if ($changed) {
 2898:                         $LONCAPA::map::resources[$idx] = join(':',($title,&LONCAPA::map::qtunescape($src),$ext,$type));
 2899:                     }
 2900:                 }
 2901:             }
 2902:             foreach my $idx (keys(%remparam)) {
 2903:                 if (ref($remparam{$idx}) eq 'ARRAY') {
 2904:                     foreach my $name (@{$remparam{$idx}}) {   
 2905:                         &LONCAPA::map::delparameter($idx,$name);
 2906:                     }
 2907:                 }
 2908:             }
 2909:             if (values(%lockerrors) > 0) {
 2910:                 $lockmsg = join('<br />',values(%lockerrors));
 2911:             }
 2912:             my $storefn;
 2913:             if ($key eq $oldurl) {
 2914:                 $storefn = $url;
 2915:                 $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 2916:             } else {
 2917:                 $storefn = $key;
 2918:                 $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 2919:                 if ($prefixchg && $before{'map'} && $after{'map'}) {
 2920:                     $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
 2921:                 }
 2922:                 if ($newsubdir{$key}) {
 2923:                     $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
 2924:                 }
 2925:             }
 2926:             my $report;
 2927:             if ($folder !~ /^supplemental/) {
 2928:                 $report = 1;
 2929:             }
 2930:             (my $outtext,$errtext) =
 2931:                 &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
 2932:             if ($errtext) {
 2933:                 if ($caller eq 'paste') {
 2934:                     return (&mt('Paste failed: an error occurred saving the folder or page.'));
 2935:                 }
 2936:             }
 2937:         }
 2938:     }
 2939:     return ('ok',\@msgs,$lockmsg);
 2940: }
 2941: 
 2942: sub copy_dependencies {
 2943:     my ($item,$storefn,$relpath,$errors,$contentref) = @_;
 2944:     my $content;
 2945:     if (ref($contentref)) {
 2946:         $content = $$contentref;
 2947:     } else {
 2948:         $content = &Apache::lonnet::getfile($item);
 2949:     }
 2950:     unless ($content eq '-1') {
 2951:         my $mm = new File::MMagic;
 2952:         my $mimetype = $mm->checktype_contents($content);
 2953:         if ($mimetype eq 'text/html') {
 2954:             my (%allfiles,%codebase,$state);
 2955:             my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
 2956:             if ($res eq 'ok') {
 2957:                 my ($numexisting,$numpathchanges,$existing);
 2958:                 (undef,$numexisting,$numpathchanges,$existing) =
 2959:                     &Apache::loncommon::ask_for_embedded_content(
 2960:                         '/adm/coursedocs',$state,\%allfiles,\%codebase,
 2961:                         {'error_on_invalid_names'   => 1,
 2962:                          'ignore_remote_references' => 1,
 2963:                          'docs_url'                 => $item,
 2964:                          'context'                  => 'paste'});
 2965:                 if ($numexisting > 0) {
 2966:                     if (ref($existing) eq 'HASH') {
 2967:                         foreach my $dep (keys(%{$existing})) {
 2968:                             my $depfile = $dep;
 2969:                             unless ($depfile =~ m{^\Q$relpath\E}) {
 2970:                                 $depfile = $relpath.$dep;
 2971:                             }
 2972:                             my $depcontent = &Apache::lonnet::getfile($depfile);
 2973:                             unless ($depcontent eq '-1') {
 2974:                                 my $storedep = $dep;
 2975:                                 $storedep =~ s{^\Q$relpath\E}{};
 2976:                                 my $dep_url =
 2977:                                     &Apache::lonclonecourse::writefile(
 2978:                                         $env{'request.course.id'},
 2979:                                         $storefn.$storedep,$depcontent);
 2980:                                 if ($dep_url eq '/adm/notfound.html') {
 2981:                                     if (ref($errors) eq 'HASH') {
 2982:                                         $errors->{$depfile} = 1;
 2983:                                     }
 2984:                                 } else {
 2985:                                     &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
 2986:                                 }
 2987:                             }
 2988:                         }
 2989:                     }
 2990:                 }
 2991:             }
 2992:         }
 2993:     }
 2994:     return;
 2995: }
 2996: 
 2997: my %parameter_type = ( 'randompick'     => 'int_pos',
 2998: 		       'hiddenresource' => 'string_yesno',
 2999: 		       'encrypturl'     => 'string_yesno',
 3000: 		       'randomorder'    => 'string_yesno',);
 3001: my $valid_parameters_re = join('|',keys(%parameter_type));
 3002: # set parameters
 3003: sub update_parameter {
 3004:     if ($env{'form.changeparms'} eq 'all') {
 3005:         my (@allidx,@allmapidx,%allchecked,%currchecked);
 3006:         %allchecked = (
 3007:                          'hiddenresource' => {},
 3008:                          'encrypturl'     => {},
 3009:                          'randompick'     => {},
 3010:                          'randomorder'    => {},
 3011:                       );
 3012:         foreach my $which (keys(%allchecked)) {
 3013:             $env{'form.all'.$which} =~ s/,$//;
 3014:             if ($which eq 'randompick') {
 3015:                 foreach my $item (split(/,/,$env{'form.all'.$which})) {
 3016:                     my ($res,$value) = split(/:/,$item);
 3017:                     if ($value =~ /^\d+$/) {
 3018:                         $allchecked{$which}{$res} = $value;
 3019:                     }
 3020:                 }
 3021:             } else {
 3022:                 if ($env{'form.all'.$which}) {
 3023:                     map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.all'.$which});
 3024:                 }
 3025:             }
 3026:         }
 3027:         my $haschanges = 0;
 3028:         foreach my $res (@LONCAPA::map::order) {
 3029:             my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 3030:             $name=&LONCAPA::map::qtescape($name);
 3031:             $url=&LONCAPA::map::qtescape($url);
 3032:             next unless $url;
 3033:             my $is_map;
 3034:             if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
 3035:                 $is_map = 1;
 3036:             }
 3037:             foreach my $which (keys(%allchecked)) {
 3038:                 if (($which eq 'randompick' || $which eq 'randomorder')) {
 3039:                     next if (!$is_map);
 3040:                 }
 3041:                 my $oldvalue = 0;
 3042:                 my $newvalue = 0;
 3043:                 if ($allchecked{$which}{$res}) {
 3044:                     $newvalue = $allchecked{$which}{$res};
 3045:                 }
 3046:                 my $current = (&LONCAPA::map::getparameter($res,'parameter_'.$which))[0];
 3047:                 if ($which eq 'randompick') {
 3048:                     if ($current =~ /^(\d+)$/) {
 3049:                         $oldvalue = $1;
 3050:                     }
 3051:                 } else {
 3052:                     if ($current =~ /^yes$/i) {
 3053:                         $oldvalue = 1;
 3054:                     }
 3055:                 }
 3056:                 if ($oldvalue ne $newvalue) {
 3057:                     $haschanges = 1;
 3058:                     if ($newvalue) {
 3059:                         my $storeval = 'yes';
 3060:                         if ($which eq 'randompick') {
 3061:                             $storeval = $newvalue;
 3062:                         }
 3063:                         &LONCAPA::map::storeparameter($res,'parameter_'.$which,
 3064:                                                       $storeval,
 3065:                                                       $parameter_type{$which});
 3066:                         &remember_parms($res,$which,'set',$storeval);
 3067:                     } elsif ($oldvalue) {
 3068:                         &LONCAPA::map::delparameter($res,'parameter_'.$which);
 3069:                         &remember_parms($res,$which,'del');
 3070:                     }
 3071:                 }
 3072:             }
 3073:         }
 3074:         return $haschanges;
 3075:     } else {
 3076:         my $haschanges = 0;
 3077:         return $haschanges if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
 3078: 
 3079:         my $which = $env{'form.changeparms'};
 3080:         my $idx = $env{'form.setparms'};
 3081:         my $oldvalue = 0;
 3082:         my $newvalue = 0;
 3083:         my $current = (&LONCAPA::map::getparameter($idx,'parameter_'.$which))[0];
 3084:         if ($which eq 'randompick') {
 3085:             if ($current =~ /^(\d+)$/) {
 3086:                 $oldvalue = $1;
 3087:             }
 3088:         } elsif ($current =~ /^yes$/i) {
 3089:             $oldvalue = 1;
 3090:         }
 3091:         if ($env{'form.'.$which.'_'.$idx}) {
 3092:             $newvalue = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
 3093:                                                  : 1;
 3094:         }
 3095:         if ($oldvalue ne $newvalue) {
 3096:             $haschanges = 1;
 3097:             if ($newvalue) {
 3098:                 my $storeval = 'yes';
 3099:                 if ($which eq 'randompick') {
 3100:                     $storeval = $newvalue;
 3101:                 }
 3102:                 &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $storeval,
 3103:                                               $parameter_type{$which});
 3104:                 &remember_parms($idx,$which,'set',$storeval);
 3105:             } else {
 3106:                 &LONCAPA::map::delparameter($idx,'parameter_'.$which);
 3107:                 &remember_parms($idx,$which,'del');
 3108:             }
 3109:         }
 3110:         return $haschanges;
 3111:     }
 3112:     return;
 3113: }
 3114: 
 3115: sub handle_edit_cmd {
 3116:     my ($coursenum,$coursedom) =@_;
 3117:     if ($env{'form.cmd'} eq '') {
 3118:         return 0;
 3119:     }
 3120:     my ($cmd,$idx)=split('_',$env{'form.cmd'});
 3121: 
 3122:     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
 3123:     my ($title, $url, @rrest) = split(':', $ratstr);
 3124: 
 3125:     if ($cmd eq 'remove') {
 3126: 	if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 3127: 	    ($url!~/$LONCAPA::assess_page_seq_re/)) {
 3128: 	    &Apache::lonnet::removeuploadedurl($url);
 3129: 	} else {
 3130: 	    &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 3131: 	}
 3132: 	splice(@LONCAPA::map::order, $idx, 1);
 3133: 
 3134:     } elsif ($cmd eq 'cut') {
 3135: 	&LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 3136: 	splice(@LONCAPA::map::order, $idx, 1);
 3137: 
 3138:     } elsif ($cmd eq 'up'
 3139: 	     && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
 3140: 	@LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
 3141: 
 3142:     } elsif ($cmd eq 'down'
 3143: 	     && defined($LONCAPA::map::order[$idx+1])) {
 3144: 	@LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
 3145: 
 3146:     } elsif ($cmd eq 'rename') {
 3147: 	my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
 3148: 	if ($comment=~/\S/) {
 3149: 	    $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
 3150: 		$comment.':'.join(':', $url, @rrest);
 3151: 	}
 3152: # Devalidate title cache
 3153: 	my $renamed_url=&LONCAPA::map::qtescape($url);
 3154: 	&Apache::lonnet::devalidate_title_cache($renamed_url);
 3155: 
 3156:     } else {
 3157: 	return 0;
 3158:     }
 3159:     return 1;
 3160: }
 3161: 
 3162: sub editor {
 3163:     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 3164:         $supplementalflag,$orderhash,$iconpath,$pathitem,$ltitoolsref,
 3165:         $canedit,$hostname,$navmapref,$hiddentop)=@_;
 3166:     my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
 3167:     if ($allowed) {
 3168:         (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
 3169:          $is_random_order,$container) =
 3170:             &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 3171:         $r->print($breadcrumbtrail);
 3172:     } elsif ($env{'form.folderpath'} =~ /\:1$/) {
 3173:         $container = 'page'; 
 3174:     } else {
 3175:         $container = 'sequence';
 3176:     }
 3177: 
 3178:     my $jumpto;
 3179: 
 3180:     unless ($supplementalflag) {
 3181:         $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
 3182:     }
 3183: 
 3184:     unless ($allowed) {
 3185:         $randompick = -1;
 3186:     }
 3187: 
 3188:     my ($errtext,$fatal);
 3189:     if (($folder eq '') && (!$supplementalflag)) {
 3190:         if (@LONCAPA::map::order) {
 3191:             undef(@LONCAPA::map::order);
 3192:             undef(@LONCAPA::map::resources);
 3193:             undef(@LONCAPA::map::resparms);
 3194:             undef(@LONCAPA::map::zombies);
 3195:         }
 3196:         $folder = 'default';
 3197:         $container = 'sequence';
 3198:     } else {
 3199:         ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 3200:                                      $folder.'.'.$container);
 3201:         return $errtext if ($fatal);
 3202:     }
 3203: 
 3204:     if ($#LONCAPA::map::order<1) {
 3205: 	my $idx=&LONCAPA::map::getresidx();
 3206: 	if ($idx<=0) { $idx=1; }
 3207:        	$LONCAPA::map::order[0]=$idx;
 3208:         $LONCAPA::map::resources[$idx]='';
 3209:     }
 3210: 
 3211: # ------------------------------------------------------------ Process commands
 3212: 
 3213: # ---------------- if they are for this folder and user allowed to make changes
 3214:     if (($allowed && $canedit) && ($env{'form.folder'} eq $folder)) {
 3215: # set parameters and change order
 3216: 	&snapshotbefore();
 3217: 
 3218: 	if (&update_parameter()) {
 3219: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 3220: 	    return $errtext if ($fatal);
 3221: 	}
 3222: 
 3223: 	if ($env{'form.newpos'} && $env{'form.currentpos'}) {
 3224: # change order
 3225: 	    my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
 3226: 	    splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
 3227: 
 3228: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 3229: 	    return $errtext if ($fatal);
 3230: 	}
 3231: 
 3232: 	if ($env{'form.pastemarked'}) {
 3233:             my %paste_errors;
 3234:             my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
 3235:                 &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
 3236:                                       \%paste_errors);
 3237:             if (ref($pastemsgarray) eq 'ARRAY') {
 3238:                 if (@{$pastemsgarray} > 0) {
 3239:                     $r->print('<p class="LC_info">'.
 3240:                               join('<br />',@{$pastemsgarray}).
 3241:                               '</p>');
 3242:                 }
 3243:             }
 3244:             if ($lockerror) {
 3245:                 $r->print('<p class="LC_error">'.
 3246:                           $lockerror.
 3247:                           '</p>');
 3248:             }
 3249:             if ($save_error ne '') {
 3250:                 return $save_error; 
 3251:             }
 3252:             if ($paste_res) {
 3253:                 my %errortext = &Apache::lonlocal::texthash (
 3254:                                     fail      => 'Storage of folder contents failed',
 3255:                                     failread  => 'Reading folder contents failed',
 3256:                                     failstore => 'Storage of folder contents failed',
 3257:                                 );
 3258:                 if ($errortext{$paste_res}) {
 3259:                     $r->print('<p class="LC_error">'.$errortext{$paste_res}.'</p>');
 3260:                 }
 3261:             }
 3262:             if (keys(%paste_errors) > 0) {
 3263:                 $r->print('<p class="LC_warning">'."\n".
 3264:                           &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".
 3265:                           '<ul>'."\n");
 3266:                 foreach my $key (sort(keys(%paste_errors))) {
 3267:                     $r->print('<li>'.$key.'</li>'."\n");
 3268:                 }
 3269:                 $r->print('</ul></p>'."\n");
 3270:             }
 3271: 	} elsif ($env{'form.clearmarked'}) {
 3272:             my $output = &do_buffer_empty();
 3273:             if ($output) {
 3274:                 $r->print('<p class="LC_info">'.$output.'</p>');
 3275:             }
 3276:         }
 3277: 
 3278: 	$r->print($upload_output);
 3279: 
 3280: # Rename, cut, copy or remove a single resource
 3281: 	if (&handle_edit_cmd($coursenum,$coursedom)) {
 3282:             my $contentchg;
 3283:             if ($env{'form.cmd'} =~ m{^(remove|cut)_}) {
 3284:                 $contentchg = 1;
 3285:             }
 3286: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
 3287: 	    return $errtext if ($fatal);
 3288: 	}
 3289: 
 3290: # Cut, copy and/or remove multiple resources
 3291:         if ($env{'form.multichange'}) {
 3292:             my %allchecked = (
 3293:                                cut     => {},
 3294:                                remove  => {},
 3295:                              );
 3296:             my $needsupdate;
 3297:             foreach my $which (keys(%allchecked)) {
 3298:                 $env{'form.multi'.$which} =~ s/,$//;
 3299:                 if ($env{'form.multi'.$which}) {
 3300:                     map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.multi'.$which});
 3301:                     if (ref($allchecked{$which}) eq 'HASH') {
 3302:                         $needsupdate += scalar(keys(%{$allchecked{$which}}));
 3303:                     }
 3304:                 }
 3305:             }
 3306:             if ($needsupdate) {
 3307:                 my $haschanges = 0;
 3308:                 my %curr_groups = &Apache::longroup::coursegroups();
 3309:                 my $total = scalar(@LONCAPA::map::order) - 1; 
 3310:                 for (my $i=$total; $i>=0; $i--) {
 3311:                     my $res = $LONCAPA::map::order[$i];
 3312:                     my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 3313:                     $name=&LONCAPA::map::qtescape($name);
 3314:                     $url=&LONCAPA::map::qtescape($url);
 3315:                     next unless $url;
 3316:                     my %denied =
 3317:                         &action_restrictions($coursenum,$coursedom,$url,
 3318:                                              $env{'form.folderpath'},\%curr_groups);
 3319:                     foreach my $which (keys(%allchecked)) {
 3320:                         next if ($denied{$which});
 3321:                         next unless ($allchecked{$which}{$res});
 3322:                         if ($which eq 'remove') {
 3323:                             if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 3324:                                 ($url!~/$LONCAPA::assess_page_seq_re/)) {
 3325:                                 &Apache::lonnet::removeuploadedurl($url);
 3326:                             } else {
 3327:                                 &LONCAPA::map::makezombie($res);
 3328:                             }
 3329:                             splice(@LONCAPA::map::order,$i,1);
 3330:                             $haschanges ++;
 3331:                         } elsif ($which eq 'cut') {
 3332:                             &LONCAPA::map::makezombie($res);
 3333:                             splice(@LONCAPA::map::order,$i,1);
 3334:                             $haschanges ++;
 3335:                         }
 3336:                     }
 3337:                 }
 3338:                 if ($haschanges) {
 3339:                     ($errtext,$fatal) = 
 3340:                         &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 3341:                     return $errtext if ($fatal);
 3342:                 }
 3343:             }
 3344:         }
 3345: 
 3346: # Group import/search
 3347: 	if ($env{'form.importdetail'}) {
 3348: 	    my @imports;
 3349: 	    foreach my $item (split(/\&/,$env{'form.importdetail'})) {
 3350: 		if (defined($item)) {
 3351: 		    my ($name,$url,$residx)=
 3352: 			map { &unescape($_); } split(/\=/,$item);
 3353:                     if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
 3354:                         my ($suffix,$errortxt,$locknotfreed) =
 3355:                             &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
 3356:                         if ($locknotfreed) {
 3357:                             $r->print($locknotfreed);
 3358:                         }
 3359:                         if ($suffix) {
 3360:                             $url =~ s/_new\./_$suffix./; 
 3361:                         } else {
 3362:                             return $errortxt;
 3363:                         }
 3364:                     } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
 3365:                         my $type = $1;
 3366:                         my ($suffix,$errortxt,$locknotfreed) =
 3367:                             &new_timebased_suffix($coursedom,$coursenum,$type);
 3368:                         if ($locknotfreed) {
 3369:                             $r->print($locknotfreed);
 3370:                         }
 3371:                         if ($suffix) {
 3372:                             $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
 3373:                         } else {
 3374:                             return $errortxt;
 3375:                         }
 3376:                     } elsif ($url =~ m{^/adm/$coursedom/$coursenum/new/ext\.tool}) {
 3377:                         my ($suffix,$errortxt,$locknotfreed) =
 3378:                             &new_timebased_suffix($coursedom,$coursenum,'exttool');
 3379:                         if ($locknotfreed) {
 3380:                             $r->print($locknotfreed);
 3381:                         }
 3382:                         if ($suffix) {
 3383:                             $url =~ s{^(/adm/$coursedom/$coursenum)/new}{$1/$suffix};
 3384:                         } else {
 3385:                             return $errortxt;
 3386:                         }
 3387:                     } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
 3388:                         if ($supplementalflag) {
 3389:                             next unless ($1 eq 'supplemental');
 3390:                             if ($folder eq 'supplemental') {
 3391:                                 next unless ($2 eq 'default');
 3392:                             } else {
 3393:                                 next unless ($folder eq 'supplemental_'.$2);
 3394:                             }
 3395:                         } else {
 3396:                             next unless ($1 eq 'docs');
 3397:                             if ($folder eq 'default') {
 3398:                                 next unless ($2 eq 'default');
 3399:                             } else {
 3400:                                 next unless ($folder eq 'default_'.$2);
 3401:                             }
 3402:                         }
 3403:                     }
 3404: 		    push(@imports, [$name, $url, $residx]);
 3405: 		}
 3406: 	    }
 3407:             ($errtext,$fatal,my $fixuperrors) =
 3408:                 &group_import($coursenum, $coursedom, $folder,$container,
 3409:                               'londocs',$ltitoolsref,@imports);
 3410: 	    return $errtext if ($fatal);
 3411:             if ($fixuperrors) {
 3412:                 $r->print($fixuperrors);
 3413:             }
 3414: 	}
 3415: # Loading a complete map
 3416: 	if ($env{'form.loadmap'}) {
 3417: 	    if ($env{'form.importmap'}=~/\w/) {
 3418: 		foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
 3419: 		    my ($title,$url,$ext,$type)=split(/\:/,$res);
 3420: 		    my $idx=&LONCAPA::map::getresidx($url);
 3421: 		    $LONCAPA::map::resources[$idx]=$res;
 3422: 		    $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
 3423: 		}
 3424: 		($errtext,$fatal)=&storemap($coursenum,$coursedom,
 3425: 					    $folder.'.'.$container,1);
 3426: 		return $errtext if ($fatal);
 3427: 	    } else {
 3428: 		$r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
 3429: 
 3430: 	    }
 3431: 	}
 3432: 	&log_differences($plain);
 3433:     }
 3434: # ---------------------------------------------------------------- End commands
 3435: # ---------------------------------------------------------------- Print screen
 3436:     my $idx=0;
 3437:     my $shown=0;
 3438:     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
 3439: 	$r->print('<div class="LC_Box">'.
 3440:           '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
 3441: 		  ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
 3442: 		  ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
 3443: 		  ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
 3444: 		  ($is_random_order?'<li>'.&mt('random order').'</li>':'').
 3445: 		  '</ol>');
 3446:         if ($randompick>=0) {
 3447:             $r->print('<p class="LC_warning">'
 3448:                  .&mt('Caution: this folder is set to randomly pick a subset'
 3449:                      .' of resources. Adding or removing resources from this'
 3450:                      .' folder will change the set of resources that the'
 3451:                      .' students see, resulting in spurious or missing credit'
 3452:                      .' for completed problems, not limited to ones you'
 3453:                      .' modify. Do not modify the contents of this folder if'
 3454:                      .' it is in active student use.')
 3455:                  .'</p>'
 3456:             );
 3457:         }
 3458:         if ($is_random_order) {
 3459:             $r->print('<p class="LC_warning">'
 3460:                  .&mt('Caution: this folder is set to randomly order its'
 3461:                      .' contents. Adding or removing resources from this folder'
 3462:                      .' will change the order of resources shown.')
 3463:                  .'</p>'
 3464:             );
 3465:         }
 3466:         $r->print('</div>');
 3467:     }
 3468: 
 3469:     if ((!$allowed) && ($folder =~ /^supplemental_\d+$/)) {
 3470:         my ($supplemental) = &Apache::loncommon::get_supplemental($coursenum,$coursedom);
 3471:         if (ref($supplemental) eq 'HASH') {
 3472:             if ((ref($supplemental->{'hidden'}) eq 'HASH') &&
 3473:                 (ref($supplemental->{'ids'}) eq 'HASH')) {
 3474:                 if (ref($supplemental->{'ids'}->{"/uploaded/$coursedom/$coursenum/$folder.$container"}) eq 'ARRAY') {
 3475:                     my $mapnum = $supplemental->{'ids'}->{"/uploaded/$coursedom/$coursenum/$folder.$container"}->[0];
 3476:                     if ($supplemental->{'hidden'}->{$mapnum}) {
 3477:                         $ishidden = 1;
 3478:                     }
 3479:                 }
 3480:             }
 3481:         }
 3482:     }
 3483: 
 3484:     my ($to_show,$output,@allidx,@allmapidx,%filters,%lists,%curr_groups);
 3485:     %filters =  (
 3486:                   canremove      => [],
 3487:                   cancut         => [],
 3488:                   cancopy        => [],
 3489:                   hiddenresource => [],
 3490:                   encrypturl     => [],
 3491:                   randomorder    => [],
 3492:                   randompick     => [],
 3493:                 );
 3494:     %curr_groups = &Apache::longroup::coursegroups();
 3495:     &Apache::loncommon::start_data_table_count(); #setup a row counter 
 3496:     foreach my $res (@LONCAPA::map::order) {
 3497:         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 3498:         $name=&LONCAPA::map::qtescape($name);
 3499:         $url=&LONCAPA::map::qtescape($url);
 3500:         unless ($name) {  $name=(split(/\//,$url))[-1]; }
 3501:         unless ($name) { $idx++; next; }
 3502:         push(@allidx,$res);
 3503:         if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
 3504:             push(@allmapidx,$res);
 3505:         }
 3506: 
 3507:         if (($supplementalflag) && (!$allowed) && (!$env{'request.role.adv'})) {
 3508:             if (($ishidden) || ((&LONCAPA::map::getparameter($res,'parameter_hiddenresource'))[0]=~/^yes$/i)) {
 3509:                 $idx++;
 3510:                 next;
 3511:             }
 3512:         }
 3513:         $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
 3514:                               $coursenum,$coursedom,$crstype,
 3515:                               $pathitem,$supplementalflag,$container,
 3516:                               \%filters,\%curr_groups,$ltitoolsref,$canedit,
 3517:                               $isencrypted,$ishidden,$navmapref,$hostname);
 3518:         $idx++;
 3519:         $shown++;
 3520:     }
 3521:     &Apache::loncommon::end_data_table_count();
 3522: 
 3523:     my $need_save;
 3524:     if ($allowed || ($supplementalflag && $folder eq 'supplemental')) {
 3525:         my $toolslink;
 3526:         if ($allowed || $canedit) {
 3527:             my $helpitem = 'Navigation_Screen';
 3528:             if (!$allowed) {
 3529:                 $helpitem = 'Supplemental_Navigation';
 3530:             }
 3531:             $toolslink = '<table><tr><td>'
 3532:                        .&Apache::loncommon::help_open_menu('Navigation Screen',
 3533:                                                            $helpitem,undef,'RAT')
 3534:                        .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
 3535:                        .'<td align="left"><ul id="LC_toolbar">'
 3536:                        .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
 3537:                        .'id="LC_content_toolbar_edittoplevel" '
 3538:                        .'class="LC_toolbarItem" '
 3539:                        .'title="'.&mt('Supplemental Content Editor').'">'
 3540:                        .'</a></li></ul></td></tr></table><br />';
 3541:         }
 3542:         if ($shown) {
 3543:             if ($allowed) {
 3544:                 $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
 3545:                           .&Apache::loncommon::start_data_table(undef,'contentlist')
 3546:                           .&Apache::loncommon::start_data_table_header_row()
 3547:                           .'<th colspan="2">'.&mt('Move').'</th>'
 3548:                           .'<th colspan="2">'.&mt('Actions').'</th>'
 3549:                           .'<th>'.&mt('Document').'</th>'
 3550:                           .'<th colspan="2">'.&mt('Settings').'</th>'
 3551:                           .&Apache::loncommon::end_data_table_header_row();
 3552:                 if ($folder !~ /^supplemental/) {
 3553:                     $lists{'canhide'} = join(',',@allidx);
 3554:                     $lists{'canrandomlyorder'} = join(',',@allmapidx);
 3555:                     my @possfilters = ('canremove','cancut','cancopy','hiddenresource','encrypturl',
 3556:                                        'randomorder','randompick');
 3557:                     foreach my $item (@possfilters) {
 3558:                         if (ref($filters{$item}) eq 'ARRAY') {
 3559:                             if (@{$filters{$item}} > 0) {
 3560:                                 $lists{$item} = join(',',@{$filters{$item}});
 3561:                             }
 3562:                         }
 3563:                     }
 3564:                     if (@allidx > 0) {
 3565:                         my $path;
 3566:                         if ($env{'form.folderpath'}) {
 3567:                             $path =
 3568:                                 &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 3569:                         }
 3570:                         if (@allidx > 1) {
 3571:                             $to_show .=
 3572:                                 &Apache::loncommon::continue_data_table_row().
 3573:                                 '<td colspan="2">&nbsp;</td>'.
 3574:                                 '<td>'.
 3575:                                 &multiple_check_form('actions',\%lists,$canedit).
 3576:                                 '</td>'.
 3577:                                 '<td>&nbsp;</td>'.
 3578:                                 '<td>&nbsp;</td>'.
 3579:                                 '<td colspan="2">'.
 3580:                                 &multiple_check_form('settings',\%lists,$canedit).
 3581:                                 '</td>'.
 3582:                                 &Apache::loncommon::end_data_table_row();
 3583:                              $need_save = 1;
 3584:                         }
 3585:                     }
 3586:                 }
 3587:                 $to_show .= $output.' '
 3588:                            .&Apache::loncommon::end_data_table()
 3589:                            .'<br style="line-height:2px;" />'
 3590:                            .&Apache::loncommon::end_scrollbox();
 3591:             } else {
 3592:                 $to_show .= $toolslink
 3593:                            .&Apache::loncommon::start_data_table('LC_tableOfContent')
 3594:                            .$output.' '
 3595:                            .&Apache::loncommon::end_data_table();
 3596:             }
 3597:         } else {
 3598:             if (!$allowed) {
 3599:                 $to_show .= $toolslink;
 3600:             }
 3601:             my $noresmsg;
 3602:             if ($allowed && $hiddentop && !$supplementalflag) {
 3603:                 $noresmsg = &mt('Main Content Hidden');
 3604:             } else {
 3605:                 $noresmsg = &mt('Currently empty');
 3606:             }
 3607:             $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
 3608:                        .'<div class="LC_info" id="contentlist">'
 3609:                        .$noresmsg
 3610:                        .'</div>'
 3611:                        .&Apache::loncommon::end_scrollbox();
 3612:         }
 3613:     } else {
 3614:         if ($shown) {
 3615:             $to_show = '<div>'
 3616:                       .&Apache::loncommon::start_data_table('LC_tableOfContent')
 3617:                       .$output
 3618:                       .&Apache::loncommon::end_data_table()
 3619:                       .'</div>';
 3620:         } else {
 3621:             $to_show = '<div class="LC_info" id="contentlist">'
 3622:                       .&mt('Currently empty')
 3623:                       .'</div>'
 3624:         }
 3625:     }
 3626:     my $tid = 1;
 3627:     if ($supplementalflag) {
 3628:         $tid = 2;
 3629:     }
 3630:     if ($allowed) {
 3631:         my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
 3632:         $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,
 3633:                                        $jumpto,$readfile,$need_save,"$folder.$container",$canedit));
 3634:         if ($canedit) {
 3635:             &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
 3636:         }
 3637:     } else {
 3638:         $r->print($to_show);
 3639:     }
 3640:     return;
 3641: }
 3642: 
 3643: sub multiple_check_form {
 3644:     my ($caller,$listsref,$canedit) = @_;
 3645:     return unless (ref($listsref) eq 'HASH');
 3646:     my $disabled;
 3647:     unless ($canedit) {
 3648:         $disabled = 'disabled="disabled"';
 3649:     }
 3650:     my $output =
 3651:     '<form action="/adm/coursedocs" method="post" name="togglemult'.$caller.'">'.
 3652:     '<span class="LC_nobreak" style="font-size:x-small;font-weight:bold;">'.
 3653:     '<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>'.
 3654:     '<div id="multi'.$caller.'" style="display:none;margin:0;padding:0;border:0">'.
 3655:     '<form action="/adm/coursedocs" method="post" name="cumulative'.$caller.'">'."\n".
 3656:     '<fieldset id="allfields'.$caller.'" style="display:none"><legend style="font-size:x-small;">'.&mt('check/uncheck all').'</legend>'."\n";
 3657:     if ($caller eq 'settings') {
 3658:         $output .= 
 3659:             '<table><tr>'.
 3660:             '<td class="LC_docs_entry_parameter">'.
 3661:             '<span class="LC_nobreak"><label>'.
 3662:             '<input type="checkbox" name="hiddenresourceall" id="hiddenresourceall" onclick="propagateState(this.form,'."'hiddenresource'".')"'.$disabled.' />'.&mt('Hidden').
 3663:             '</label></span></td>'.
 3664:             '<td class="LC_docs_entry_parameter">'.
 3665:             '<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="" />'.
 3666:             '</span></td>'.
 3667:             '</tr>'."\n".
 3668:             '<tr>'.
 3669:             '<td class="LC_docs_entry_parameter">'.
 3670:             '<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').
 3671:             '</label></span>'.
 3672:             '</td></tr></table>'."\n";
 3673:     } else {
 3674:         $output .=
 3675:             '<table><tr>'.
 3676:             '<td class="LC_docs_entry_parameter">'.
 3677:             '<span class="LC_nobreak LC_docs_remove">'.
 3678:             '<label><input type="checkbox" name="removeall" id="removeall" onclick="propagateState(this.form,'."'remove'".')"'.$disabled.' />'.&mt('Remove').
 3679:             '</label></span></td>'.
 3680:             '<td class="LC_docs_entry_parameter">'.
 3681:             '<span class="LC_nobreak LC_docs_cut">'.
 3682:             '<label><input type="checkbox" name="cut" id="cutall" onclick="propagateState(this.form,'."'cut'".');"'.$disabled.' />'.&mt('Cut').
 3683:             '</label></span></td>'."\n".
 3684:             '<td class="LC_docs_entry_parameter">'.
 3685:             '<span class="LC_nobreak LC_docs_copy">'.
 3686:             '<label><input type="checkbox" name="copyall" id="copyall" onclick="propagateState(this.form,'."'copy'".')"'.$disabled.' />'.&mt('Copy').
 3687:             '</label></span></td>'.
 3688:             '</tr></table>'."\n";
 3689:     }
 3690:     $output .= 
 3691:         '</fieldset>'.
 3692:         '<input type="hidden" name="allidx" value="'.$listsref->{'canhide'}.'" />';
 3693:     if ($caller eq 'settings') {
 3694:         $output .= 
 3695:         '<input type="hidden" name="allmapidx" value="'.$listsref->{'canrandomlyorder'}.'" />'."\n".
 3696:         '<input type="hidden" name="currhiddenresource" value="'.$listsref->{'hiddenresource'}.'" />'."\n".
 3697:         '<input type="hidden" name="currencrypturl" value="'.$listsref->{'encrypturl'}.'" />'."\n".
 3698:         '<input type="hidden" name="currrandomorder" value="'.$listsref->{'randomorder'}.'" />'."\n".
 3699:         '<input type="hidden" name="currrandompick" value="'.$listsref->{'randompick'}.'" />'."\n";
 3700:     } elsif ($caller eq 'actions') {
 3701:         $output .=
 3702:         '<input type="hidden" name="allremoveidx" id="allremoveidx" value="'.$listsref->{'canremove'}.'" />'.
 3703:         '<input type="hidden" name="allcutidx" id="allcutidx" value="'.$listsref->{'cancut'}.'" />'.
 3704:         '<input type="hidden" name="allcopyidx" id="allcopyidx" value="'.$listsref->{'cancopy'}.'" />';
 3705:     }
 3706:     $output .= 
 3707:         '</form>'.
 3708:         '</div>';
 3709:     return $output;
 3710: }
 3711: 
 3712: sub process_file_upload {
 3713:     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd,$crstype) = @_;
 3714: # upload a file, if present
 3715:     my $filesize = length($env{'form.uploaddoc'});
 3716:     if (!$filesize) {
 3717:         $$upload_output = '<div class="LC_error">'.
 3718:                            &mt('Unable to upload [_1]. (size = [_2] bytes)',
 3719:                           '<span class="LC_filename">'.$env{'form.uploaddoc.filename'}.'</span>',
 3720:                           $filesize).'<br />'.
 3721:                           &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
 3722:                           '</div>';
 3723:         return;
 3724:     }
 3725:     my $quotatype = 'unofficial';
 3726:     if ($crstype eq 'Community') {
 3727:         $quotatype = 'community';
 3728:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.coursecode'}) {
 3729:         $quotatype = 'official';
 3730:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.textbook'}) {
 3731:         $quotatype = 'textbook';
 3732:     }
 3733:     if (&Apache::loncommon::get_user_quota($coursenum,$coursedom,'course',$quotatype)) {
 3734:         $filesize = int($filesize/1000); #expressed in kb
 3735:         $$upload_output = &Apache::loncommon::excess_filesize_warning($coursenum,$coursedom,'course',
 3736:                                                                       $env{'form.uploaddoc.filename'},$filesize,
 3737:                                                                       'upload',$quotatype);
 3738:         return if ($$upload_output);
 3739:     }
 3740:     my ($parseaction,$showupload,$nextphase,$mimetype);
 3741:     if ($env{'form.parserflag'}) {
 3742:         $parseaction = 'parse';
 3743:     }
 3744:     my $folder=$env{'form.folder'};
 3745:     if ($folder eq '') {
 3746:         $folder='default';
 3747:     }
 3748:     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
 3749:         my $errtext='';
 3750:         my $fatal=0;
 3751:         my $container='sequence';
 3752:         if ($env{'form.folderpath'} =~ /:1$/) {
 3753:             $container='page';
 3754:         }
 3755:         ($errtext,$fatal)=
 3756:             &mapread($coursenum,$coursedom,$folder.'.'.$container);
 3757:         if ($#LONCAPA::map::order<1) {
 3758:             $LONCAPA::map::order[0]=1;
 3759:             $LONCAPA::map::resources[1]='';
 3760:         }
 3761:         my $destination = 'docs/';
 3762:         if ($folder =~ /^supplemental/) {
 3763:             $destination = 'supplemental/';
 3764:         }
 3765:         if (($folder eq 'default') || ($folder eq 'supplemental')) {
 3766:             $destination .= 'default/';
 3767:         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 3768:             $destination .=  $2.'/';
 3769:         }
 3770:         if ($fatal) {
 3771:             $$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>';
 3772:             return;
 3773:         }
 3774: # this is for a course, not a user, so set context to coursedoc.
 3775:         my $newidx=&LONCAPA::map::getresidx();
 3776:         $destination .= $newidx;
 3777:         my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
 3778: 						$parseaction,$allfiles,
 3779: 						$codebase,undef,undef,undef,undef,
 3780:                                                 undef,undef,\$mimetype);
 3781:         if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
 3782:             my $stored = $1;
 3783:             $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 3784:                           $stored.'</span>').'</p>';
 3785:         } else {
 3786:             my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
 3787:             
 3788:             $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
 3789:             return;
 3790:         }
 3791:         my $ext='false';
 3792:         if ($url=~m{^http://}) { $ext='true'; }
 3793: 	$url     = &LONCAPA::map::qtunescape($url);
 3794:         my $comment=$env{'form.comment'};
 3795: 	$comment = &LONCAPA::map::qtunescape($comment);
 3796:         if ($folder=~/^supplemental/) {
 3797:               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 3798:                   $env{'user.domain'}.'___&&&___'.$comment;
 3799:         }
 3800: 
 3801:         $LONCAPA::map::resources[$newidx]=
 3802: 	    $comment.':'.$url.':'.$ext.':normal:res';
 3803:         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
 3804:         ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 3805: 				    $folder.'.'.$container,1);
 3806:         if ($fatal) {
 3807:             $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
 3808:             return;
 3809:         } else {
 3810:             if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
 3811:                 $$upload_output = $showupload;
 3812:                 my $total_embedded = scalar(keys(%{$allfiles}));
 3813:                 if ($total_embedded > 0) {
 3814:                     my $uploadphase = 'upload_embedded';
 3815:                     my $primaryurl = &HTML::Entities::encode($url,'<>&"');
 3816: 		    my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
 3817:                     my ($embedded,$num) = 
 3818:                         &Apache::loncommon::ask_for_embedded_content(
 3819:                             '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
 3820:                     if ($embedded) {
 3821:                         if ($num) {
 3822:                             $$upload_output .=
 3823: 			         '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
 3824:                             $nextphase = $uploadphase;
 3825:                         } else {
 3826:                             $$upload_output .= $embedded;
 3827:                         }
 3828:                     } else {
 3829:                         $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
 3830:                     }
 3831:                 } else {
 3832:                     $$upload_output .= &mt('No embedded items identified').'<br />';
 3833:                 }
 3834:                 $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
 3835:             } elsif ((&Apache::loncommon::is_archive_file($mimetype)) &&
 3836:                      ($env{'form.uploaddoc.filename'} =~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i)) {
 3837:                 $nextphase = 'decompress_uploaded';
 3838:                 my $position = scalar(@LONCAPA::map::order)-1;
 3839:                 my $noextract = &return_to_editor();
 3840:                 my $archiveurl = &HTML::Entities::encode($url,'<>&"');
 3841:                 my %archiveitems = (
 3842:                     folderpath => $env{'form.folderpath'},
 3843:                     cmd        => $nextphase,
 3844:                     newidx     => $newidx,
 3845:                     position   => $position,
 3846:                     phase      => $nextphase,
 3847:                     comment    => $comment,
 3848:                 );
 3849:                 my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
 3850:                 my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
 3851:                 $$upload_output = $showupload.
 3852:                                   &Apache::loncommon::decompress_form($mimetype,
 3853:                                       $archiveurl,'/adm/coursedocs',$noextract,
 3854:                                       \%archiveitems,\@current);
 3855:             }
 3856:         }
 3857:     }
 3858:     return $nextphase;
 3859: }
 3860: 
 3861: sub get_dir_list {
 3862:     my ($url,$coursenum,$coursedom,$newidx) = @_;
 3863:     my ($destination,$dir_root) = &embedded_destination();
 3864:     my ($dirlistref,$listerror) =  
 3865:         &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
 3866:     my @dir_lines;
 3867:     my $dirptr=16384;
 3868:     if (ref($dirlistref) eq 'ARRAY') {
 3869:         foreach my $dir_line (sort
 3870:                           {
 3871:                               my ($afile)=split('&',$a,2);
 3872:                               my ($bfile)=split('&',$b,2);
 3873:                               return (lc($afile) cmp lc($bfile));
 3874:                           } (@{$dirlistref})) {
 3875:             my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
 3876:             $filename =~ s/\s+$//;
 3877:             next if ($filename =~ /^\.\.?$/); 
 3878:             my $isdir = 0;
 3879:             if ($dirptr&$testdir) {
 3880:                 $isdir = 1;
 3881:             }
 3882:             push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
 3883:         }
 3884:     }
 3885:     return @dir_lines;
 3886: }
 3887: 
 3888: sub is_supplemental_title {
 3889:     my ($title) = @_;
 3890:     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
 3891: }
 3892: 
 3893: # --------------------------------------------------------------- An entry line
 3894: 
 3895: sub entryline {
 3896:     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
 3897:         $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups,
 3898:         $ltitoolsref,$canedit,$isencrypted,$ishidden,$navmapref,$hostname)=@_;
 3899:     my ($foldertitle,$renametitle,$oldtitle,$encodedtitle);
 3900:     if (&is_supplemental_title($title)) {
 3901: 	($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
 3902:         $encodedtitle=$title;
 3903:     } else {
 3904: 	$title=&HTML::Entities::encode($title,'"<>&\'');
 3905:         $encodedtitle=$title;
 3906: 	$renametitle=$title;
 3907: 	$foldertitle=$title;
 3908:     }
 3909: 
 3910:     my ($disabled,$readonly,$js_lt);
 3911:     unless ($canedit) {
 3912:         $disabled = 'disabled="disabled"';
 3913:         $readonly = 1;
 3914:     }
 3915: 
 3916:     my $orderidx=$LONCAPA::map::order[$index];
 3917: 
 3918:     $renametitle=~s/\\/\\\\/g;
 3919:     $renametitle=~s/\&quot\;/\\\"/g;
 3920:     $renametitle=~s/"/%22/g;
 3921:     $renametitle=~s/ /%20/g;
 3922:     $oldtitle = $renametitle;
 3923:     $renametitle=~s/\&#39\;/\\\'/g;
 3924:     my $line=&Apache::loncommon::start_data_table_row();
 3925:     my ($form_start,$form_end,$form_common,$form_param);
 3926: # Edit commands
 3927:     my ($esc_path, $path, $symb, $shownsymb);
 3928:     if ($env{'form.folderpath'}) {
 3929: 	$esc_path=&escape($env{'form.folderpath'});
 3930: 	$path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 3931: 	# $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 3932:     }
 3933:     my $isexternal;
 3934:     if ($residx) {
 3935:         my $currurl = $url;
 3936:         $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
 3937:         if ($currurl =~ m{^/adm/wrapper/ext/}) {
 3938:             $isexternal = 1;
 3939:         }
 3940:         if (!$supplementalflag) {
 3941:             my $path = 'uploaded/'.
 3942:                        $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 3943:                        $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 3944:             $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
 3945:                                                  $residx,
 3946:                                                  &Apache::lonnet::declutter($currurl));
 3947:         }
 3948:     }
 3949:     my ($renamelink,%lt,$ishash);
 3950:     if (ref($filtersref) eq 'HASH') {
 3951:         $ishash = 1;
 3952:     }
 3953: 
 3954:     if ($allowed) {
 3955:         $form_start = '
 3956:    <form action="/adm/coursedocs" method="post">
 3957: ';
 3958:         $form_common=(<<END);
 3959:    <input type="hidden" name="folderpath" value="$path" />
 3960:    <input type="hidden" name="symb" value="$symb" />
 3961: END
 3962:         $form_param=(<<END);
 3963:    <input type="hidden" name="setparms" value="$orderidx" />
 3964:    <input type="hidden" name="changeparms" value="0" />
 3965: END
 3966:         $form_end = '</form>';
 3967: 
 3968: 	my $incindex=$index+1;
 3969: 	my $selectbox='';
 3970: 	if (($#LONCAPA::map::order>0) &&
 3971: 	    ((split(/\:/,
 3972: 	     $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
 3973: 	     ne '') &&
 3974: 	    ((split(/\:/,
 3975: 	     $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
 3976: 	     ne '')) {
 3977: 	    $selectbox=
 3978: 		'<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
 3979: 		'<select name="newpos" onchange="this.form.submit()"'.$disabled.'>';
 3980: 	    for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
 3981: 		if ($i==$incindex) {
 3982: 		    $selectbox.='<option value="" selected="selected">('.$i.')</option>';
 3983: 		} else {
 3984: 		    $selectbox.='<option value="'.$i.'">'.$i.'</option>';
 3985: 		}
 3986: 	    }
 3987: 	    $selectbox.='</select>';
 3988: 	}
 3989: 	%lt=&Apache::lonlocal::texthash(
 3990:                 'up' => 'Move Up',
 3991: 		'dw' => 'Move Down',
 3992: 		'rm' => 'Remove',
 3993:                 'ct' => 'Cut',
 3994: 		'rn' => 'Rename',
 3995: 		'cp' => 'Copy',
 3996:                 'ex' => 'External Resource',
 3997:                 'et' => 'External Tool',
 3998:                 'ed' => 'Edit',
 3999:                 'pr' => 'Preview',
 4000:                 'sv' => 'Save',
 4001:                 'ul' => 'URL',
 4002:                 'ti' => 'Title',
 4003:                 'er' => 'Editing rights unavailable for your current role.',  
 4004:                 );
 4005: 	my %denied = &action_restrictions($coursenum,$coursedom,$url,
 4006:                                           $env{'form.folderpath'},
 4007:                                           $currgroups);
 4008:         my ($copylink,$cutlink,$removelink);
 4009: 	my $skip_confirm = 0;
 4010:         my $confirm_removal = 0;
 4011: 	if ( $folder =~ /^supplemental/
 4012: 	     || ($url =~ m{( /smppg$
 4013: 			    |/syllabus$
 4014: 			    |/aboutme$
 4015: 			    |/navmaps$
 4016: 			    |/bulletinboard$
 4017:                             |/ext\.tool$
 4018: 			    |\.html$)}x)
 4019:              || $isexternal) {
 4020: 	    $skip_confirm = 1;
 4021: 	}
 4022:         if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 4023:             ($url!~/$LONCAPA::assess_page_seq_re/)) {
 4024:             $confirm_removal = 1;
 4025:         }
 4026: 
 4027: 	if ($denied{'copy'}) {
 4028:             $copylink=(<<ENDCOPY)
 4029: <span style="visibility: hidden;">$lt{'cp'}</span>
 4030: ENDCOPY
 4031:         } else {
 4032:             my $formname = 'edit_copy_'.$orderidx;
 4033:             my $js = "javascript:checkForSubmit(document.forms.renameform,'copy','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 4034: 	    $copylink=(<<ENDCOPY);
 4035: <form name="$formname" method="post" action="/adm/coursedocs">
 4036: $form_common
 4037: <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>
 4038: $form_end
 4039: ENDCOPY
 4040:             if (($ishash) && (ref($filtersref->{'cancopy'}) eq 'ARRAY')) {
 4041:                 push(@{$filtersref->{'cancopy'}},$orderidx);
 4042:             }
 4043:         }
 4044: 	if ($denied{'cut'}) {
 4045:             $cutlink=(<<ENDCUT);
 4046: <span style="visibility: hidden;">$lt{'ct'}</span>
 4047: ENDCUT
 4048:         } else {
 4049:             my $formname = 'edit_cut_'.$orderidx;
 4050:             my $js = "javascript:checkForSubmit(document.forms.renameform,'cut','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 4051: 	    $cutlink=(<<ENDCUT);
 4052: <form name="$formname" method="post" action="/adm/coursedocs">
 4053: $form_common
 4054: <input type="hidden" name="skip_$orderidx" id="skip_cut_$orderidx" value="$skip_confirm" />
 4055: <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>
 4056: $form_end
 4057: ENDCUT
 4058:             if (($ishash) && (ref($filtersref->{'cancut'}) eq 'ARRAY')) {
 4059:                 push(@{$filtersref->{'cancut'}},$orderidx);
 4060:             }
 4061:         }
 4062:         if ($denied{'remove'}) {
 4063:             $removelink=(<<ENDREM);
 4064: <span style="visibility: hidden;">$lt{'rm'}</a>
 4065: ENDREM
 4066:         } else {
 4067:             my $formname = 'edit_remove_'.$orderidx;
 4068:             my $js = "javascript:checkForSubmit(document.forms.renameform,'remove','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder',$confirm_removal);";
 4069:             $removelink=(<<ENDREM);
 4070: <form name="$formname" method="post" action="/adm/coursedocs">
 4071: $form_common
 4072: <input type="hidden" name="skip_$orderidx" id="skip_remove_$orderidx" value="$skip_confirm" />
 4073: <input type="hidden" name="confirm_rem_$orderidx" id="confirm_removal_$orderidx" value="$confirm_removal" />
 4074: <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>
 4075: $form_end
 4076: ENDREM
 4077:             if (($ishash) && (ref($filtersref->{'canremove'}) eq 'ARRAY')) {
 4078:                 push(@{$filtersref->{'canremove'}},$orderidx);
 4079:             }
 4080:         }
 4081:         $renamelink=(<<ENDREN);
 4082: <a href='javascript:changename("$esc_path","$index","$oldtitle");' class="LC_docs_rename">$lt{'rn'}</a>
 4083: ENDREN
 4084:         my ($uplink,$downlink);
 4085:         if ($canedit) {
 4086:             $uplink = "/adm/coursedocs?cmd=up_$index&amp;folderpath=$esc_path&amp;symb=$symb";
 4087:             $downlink = "/adm/coursedocs?cmd=down_$index&amp;folderpath=$esc_path&amp;symb=$symb";
 4088:         } else {
 4089:             $uplink = "javascript:alert('".&js_escape($lt{'er'})."');";
 4090:             $downlink = $uplink;
 4091:         }
 4092: 	$line.=(<<END);
 4093: <td>
 4094: <div class="LC_docs_entry_move">
 4095:   <a href="$uplink">
 4096:     <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
 4097:   </a>
 4098: </div>
 4099: <div class="LC_docs_entry_move">
 4100:   <a href="$downlink">
 4101:     <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
 4102:   </a>
 4103: </div>
 4104: </td>
 4105: <td>
 4106:    $form_start
 4107:    $form_param
 4108:    $form_common
 4109:    $selectbox
 4110:    $form_end
 4111: </td>
 4112: <td class="LC_docs_entry_commands LC_nobreak">
 4113: $removelink
 4114: $cutlink
 4115: $copylink
 4116: </td>
 4117: END
 4118:     }
 4119: # Figure out what kind of a resource this is
 4120:     my ($extension)=($url=~/\.(\w+)$/);
 4121:     my $uploaded=($url=~/^\/*uploaded\//);
 4122:     my $icon=&Apache::loncommon::icon($url);
 4123:     my $isfolder;
 4124:     my $ispage;
 4125:     my $containerarg;
 4126:     my $folderurl;
 4127:     my $plainurl;
 4128:     if ($uploaded) {
 4129:         if (($extension eq 'sequence') || ($extension eq 'page')) {
 4130:             $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
 4131:             $containerarg = $1;
 4132: 	    if ($extension eq 'sequence') {
 4133: 	        $icon=$iconpath.'navmap.folder.closed.gif';
 4134:                 $isfolder=1;
 4135:             } else {
 4136:                 $icon=$iconpath.'page.gif';
 4137:                 $ispage=1;
 4138:             }
 4139:             $folderurl = &Apache::lonnet::declutter($url);
 4140:             if ($allowed) {
 4141:                 $url='/adm/coursedocs?';
 4142:             } else {
 4143:                 $url='/adm/supplemental?';
 4144:             }
 4145: 	} else {
 4146:             $plainurl = $url;
 4147: 	}
 4148:     }
 4149: 
 4150:     my ($editlink,$extresform,$anchor,$hiddenres,$nomodal);
 4151:     my $orig_url = $url;
 4152:     $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 4153:     if ($container eq 'page') {
 4154:         $url=~s{^http(|s)(&colon;|:)//}{/ext/};
 4155:     } else {
 4156:         $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
 4157:     }
 4158:     if (!$supplementalflag && $residx && $symb) {
 4159:         if ((!$isfolder) && (!$ispage)) {
 4160: 	    (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4161:             if (($url =~ m{^ext/}) && ($container eq 'page')) {
 4162:                 $url=&Apache::lonnet::clutter_with_no_wrapper($url);
 4163:             } else {
 4164:                 $url=&Apache::lonnet::clutter($url);
 4165:             }
 4166: 	    if ($url=~/^\/*uploaded\//) {
 4167: 	        $url=~/\.(\w+)$/;
 4168: 	        my $embstyle=&Apache::loncommon::fileembstyle($1);
 4169: 	        if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
 4170: 		    $url='/adm/wrapper'.$url;
 4171: 	        } elsif ($embstyle eq 'ssi') {
 4172: 		    #do nothing with these
 4173: 	        } elsif ($url!~/\.(sequence|page)$/) {
 4174: 		    $url='/adm/coursedocs/showdoc'.$url;
 4175: 	        }
 4176:             } elsif ($url=~m{^(|/adm/wrapper)/ext/([^#]+)}) {
 4177:                 my $wrapped = $1;
 4178:                 my $exturl = $2;
 4179:                 if (($wrapped eq '') && ($container ne 'page')) {
 4180:                     $url='/adm/wrapper'.$url;
 4181:                 }
 4182:                 if (($ENV{'SERVER_PORT'} == 443) && ($exturl !~ /^https:/)) {
 4183:                     $nomodal = 1;
 4184:                 }
 4185:             } elsif ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
 4186:                 $url='/adm/wrapper'.$url;
 4187:             } elsif ($url eq "/public/$coursedom/$coursenum/syllabus") {
 4188:                 if (($ENV{'SERVER_PORT'} == 443) &&
 4189:                     ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 4190:                     unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
 4191:                         $url .= '?usehttp=1';
 4192:                     }
 4193:                     $nomodal = 1;
 4194:                 }
 4195: 	    }
 4196:             my ($checkencrypt,$shownurl);
 4197:             if (!$env{'request.role.adv'}) {
 4198:                 if (((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i) ||
 4199:                     ($isencrypted) || (&Apache::lonnet::EXT('resource.0.encrypturl',$symb) =~ /^yes$/i)) {
 4200:                     $checkencrypt = 1;
 4201:                 } elsif (ref($navmapref)) {
 4202:                     unless (ref($$navmapref)) {
 4203:                         $$navmapref = Apache::lonnavmaps::navmap->new();
 4204:                     }
 4205:                     if (ref($$navmapref)) {
 4206:                         if (lc($$navmapref->get_mapparam($symb,undef,"0.encrypturl")) eq 'yes') {
 4207:                             $checkencrypt = 1;
 4208:                         }
 4209:                     }
 4210:                 }
 4211:             }
 4212:             if ($checkencrypt) {
 4213:                 my $currenc = $env{'request.enc'};
 4214:                 $env{'request.enc'} = 1;
 4215:                 $shownsymb = &Apache::lonenc::encrypted($symb);
 4216:                 $shownurl = &Apache::lonenc::encrypted($url);
 4217:                 if (&Apache::lonnet::symbverify($symb,$url)) {
 4218:                     $url = $shownurl;
 4219:                 } else {
 4220:                     $url = '';
 4221:                 }
 4222:                 $env{'request.enc'} = $currenc;
 4223:             } elsif (&Apache::lonnet::symbverify($symb,$url)) {
 4224:                 $shownsymb = $symb;
 4225:                 if ($isexternal) {
 4226:                     $url =~ s/\#[^#]+$//;
 4227:                     if ($container eq 'page') {
 4228:                         $url = &Apache::lonnet::clutter($url);
 4229:                     }
 4230:                 }
 4231:                 $shownurl = $url;
 4232:             }
 4233:             unless ($env{'request.role.adv'}) {
 4234:                 if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4235:                     $url = '';
 4236:                 }
 4237:                 if (&Apache::lonnet::EXT('resource.0.hiddenresource',$symb) =~ /^yes$/i) {
 4238:                     $url = '';
 4239:                     $hiddenres = 1;
 4240:                 }
 4241:             }
 4242:             if ($url ne '') {
 4243:                 $url = $shownurl.(($shownurl=~/\?/)?'&':'?').'symb='.&escape($shownsymb);
 4244:             }
 4245: 	}
 4246:     } elsif ($supplementalflag) {
 4247:         if ($isexternal) {
 4248:             if ($url =~ /^([^#]+)#([^#]+)$/) {
 4249:                 $url = $1;
 4250:                 $anchor = $2;
 4251:                 if (($url =~ m{^(|/adm/wrapper)/ext/(?!https:)}) && ($ENV{'SERVER_PORT'} == 443)) {
 4252:                     unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
 4253:                         if ($hostname ne '') {
 4254:                             $url = 'http://'.$hostname.$url;
 4255:                         }
 4256:                         $url .= (($url =~ /\?/) ? '&amp;':'?').'usehttp=1';
 4257:                     }
 4258:                     $nomodal = 1;
 4259:                 }
 4260:             }
 4261:         } elsif ($url =~ m{^\Q/public/$coursedom/$coursenum/syllabus\E}) {
 4262:             if (($ENV{'SERVER_PORT'} == 443) &&
 4263:                 ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 4264:                 unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
 4265:                     if ($hostname ne '') {
 4266:                         $url = 'http://'.$hostname.$url;
 4267:                     }
 4268:                     $url .= (($url =~ /\?/) ? '&amp;':'?').'usehttp=1';
 4269:                 }
 4270:                 $nomodal = 1;
 4271:             }
 4272:         } elsif (($uploaded) && (!$allowed) && ($url ne '/adm/supplemental?')) {
 4273:             my $embstyle=&Apache::loncommon::fileembstyle($extension);
 4274:             unless ($embstyle eq 'ssi') {
 4275:                 if (($embstyle eq 'img')
 4276:                  || ($embstyle eq 'emb')
 4277:                  || ($embstyle eq 'wrp')) {
 4278:                     $url='/adm/wrapper'.$url;
 4279:                 } elsif ($url !~ /\.(sequence|page)$/) {
 4280:                     $url='/adm/coursedocs/showdoc'.$url;
 4281:                 }
 4282:             }
 4283:         }
 4284:         unless ($allowed && $env{'request.role.adv'}) {
 4285:             if ($ishidden || (&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4286:                 $hiddenres = 1;
 4287:             }
 4288:         }
 4289:     }
 4290:     my ($rand_pick_text,$rand_order_text,$hiddenfolder);
 4291:     my $filterFunc = sub { my $res = shift; return (!$res->randomout() && !$res->is_map()) };
 4292:     if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
 4293: 	my $foldername=&escape($foldertitle);
 4294: 	my $folderpath=$env{'form.folderpath'};
 4295: 	if ($folderpath) { $folderpath.='&' };
 4296:         if (!$allowed && $supplementalflag) {
 4297:             $folderpath.=$containerarg.'&'.$foldername;
 4298:             $url.='folderpath='.&escape($folderpath);
 4299:             if ($ishidden || (&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4300:                 $hiddenfolder = 1;
 4301:             }
 4302:         } else {
 4303:             my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
 4304:                                                         'parameter_randompick'))[0];
 4305:             my $randorder = ((&LONCAPA::map::getparameter($orderidx,
 4306:                                               'parameter_randomorder'))[0]=~/^yes$/i);
 4307:             my $hiddenmap = ((&LONCAPA::map::getparameter($orderidx,
 4308:                                               'parameter_hiddenresource'))[0]=~/^yes$/i);
 4309:             my $encryptmap = ((&LONCAPA::map::getparameter($orderidx,
 4310:                                               'parameter_encrypturl'))[0]=~/^yes$/i);
 4311:             unless ($hiddenmap) {
 4312:                 if (ref($navmapref)) {
 4313:                     unless (ref($$navmapref)) {
 4314:                         $$navmapref = Apache::lonnavmaps::navmap->new();
 4315:                     }
 4316:                     if (ref($$navmapref)) {
 4317:                         if (lc($$navmapref->get_mapparam(undef,$folderurl,"0.hiddenresource")) eq 'yes') {
 4318:                             my @resources = $$navmapref->retrieveResources($folderurl,$filterFunc,1,1);
 4319:                             unless (@resources) {
 4320:                                 $hiddenmap = 1;
 4321:                                 unless ($env{'request.role.adv'}) {
 4322:                                     $url = '';
 4323:                                     $hiddenfolder = 1;
 4324:                                 }
 4325:                             }
 4326:                         }
 4327:                     }
 4328:                 }
 4329:             }
 4330:             unless ($encryptmap) {
 4331:                 if ((ref($navmapref)) && (ref($$navmapref))) {
 4332:                     if (lc($$navmapref->get_mapparam(undef,$folderurl,"0.encrypturl")) eq 'yes') {
 4333:                         $encryptmap = 1;
 4334:                     }
 4335:                 }
 4336:             }
 4337: 
 4338: # Append randompick number, hidden, and encrypted with ":" to foldername,
 4339: # so it gets transferred between levels
 4340:             $folderpath.=$containerarg.'&'.$foldername.
 4341:                          ':'.$rpicknum.':'.$hiddenmap.':'.$encryptmap.':'.$randorder.':'.$ispage;
 4342:             unless ($url eq '') {
 4343:                 $url.='folderpath='.&escape($folderpath);
 4344:             }
 4345:             my $rpckchk;
 4346:             if ($rpicknum) {
 4347:                 $rpckchk = ' checked="checked"';
 4348:                 if (($ishash) && (ref($filtersref->{'randompick'}) eq 'ARRAY')) {
 4349:                     push(@{$filtersref->{'randompick'}},$orderidx.':'.$rpicknum);
 4350:                 }
 4351:             }
 4352:             my $formname = 'edit_randompick_'.$orderidx;
 4353: 	    $rand_pick_text = 
 4354: '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
 4355: $form_param."\n".
 4356: $form_common."\n".
 4357: '<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.'">';
 4358:             if ($rpicknum ne '') {
 4359:                 $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
 4360:             }
 4361:             $rand_pick_text .= '</span></span>'.
 4362:                                $form_end;
 4363:             my $ro_set;
 4364:             if ($randorder) {
 4365:                 $ro_set = 'checked="checked"';
 4366:                 if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
 4367:                     push(@{$filtersref->{'randomorder'}},$orderidx);
 4368:                 }
 4369:             }
 4370:             $formname = 'edit_rorder_'.$orderidx;
 4371: 	    $rand_order_text = 
 4372: '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
 4373: $form_param."\n".
 4374: $form_common."\n".
 4375: '<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>'.
 4376: $form_end;
 4377:         }
 4378:     } elsif ($supplementalflag && !$allowed) {
 4379:         my $isexttool;
 4380:         if ($url=~m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
 4381:             $url='/adm/wrapper'.$url;
 4382:             $isexttool = 1;
 4383:         }
 4384:         $url .= ($url =~ /\?/) ? '&amp;':'?';
 4385:         $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
 4386:         if ($title) {
 4387:             $url .= '&amp;title='.$encodedtitle;
 4388:         }
 4389:         if ((($isexternal) || ($isexttool)) && $orderidx) {
 4390:             $url .= '&amp;idx='.$orderidx;
 4391:         }
 4392:         if ($anchor ne '') {
 4393:             $url .= '&amp;anchor='.&HTML::Entities::encode($anchor,'"<>&');
 4394:         }
 4395:     }
 4396:     my ($tdalign,$tdwidth);
 4397:     if ($allowed) {
 4398:         my $fileloc = 
 4399:             &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
 4400:         if ($isexternal) {
 4401:             ($editlink,$extresform) = 
 4402:                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
 4403:                                                      undef,undef,undef,undef,undef,undef,
 4404:                                                      undef,$disabled);
 4405:         } elsif ($orig_url =~ m{^/adm/$coursedom/$coursenum/\d+/ext\.tool$}) {
 4406:             ($editlink,$extresform) =
 4407:                 &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem,
 4408:                                                      undef,undef,undef,'tool',$coursedom,
 4409:                                                      $coursenum,$ltitoolsref,$disabled);
 4410:         } elsif (!$isfolder && !$ispage) {
 4411:             my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
 4412:                 &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
 4413:             if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
 4414:                 my $suppanchor;
 4415:                 if ($supplementalflag) {
 4416:                     $suppanchor = $anchor;
 4417:                 }
 4418:                 my $jscall = 
 4419:                     &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
 4420:                                                             $switchserver,
 4421:                                                             $forceedit,
 4422:                                                             undef,$symb,$shownsymb,
 4423:                                                             &escape($env{'form.folderpath'}),
 4424:                                                             $renametitle,$hostname,
 4425:                                                             '','',1,$suppanchor);
 4426:                 if ($jscall) {
 4427:                     $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
 4428:                                 $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
 4429:                 }
 4430:             }
 4431:         }
 4432:         $tdalign = ' align="right" valign="top"';
 4433:         $tdwidth = ' width="80%"';
 4434:     }
 4435:     my $reinit;
 4436:     if ($crstype eq 'Community') {
 4437:         $reinit = &mt('(re-initialize community to access)');
 4438:     } else {
 4439:         $reinit = &mt('(re-initialize course to access)');
 4440:     }
 4441:     $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
 4442:     my ($link,$nolink);
 4443:     if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 4444:         if ($allowed && !$env{'request.role.adv'} && !$isfolder && !$ispage) {
 4445:             if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4446:                 $nolink = 1;
 4447:             }
 4448:         }
 4449:         if ($nolink) {
 4450:             $line .= '<img src="'.$icon.'" alt="" class="LC_icon" /></a>';
 4451:         } else {
 4452:             $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
 4453:         }
 4454:     } elsif ($url) {
 4455:        if ($anchor ne '') {
 4456:            if ($supplementalflag) {
 4457:                $anchor = '&amp;anchor='.&HTML::Entities::encode($anchor,'"<>&');
 4458:            } else {
 4459:                $anchor = '#'.&HTML::Entities::encode($anchor,'"<>&');
 4460:            }
 4461:        }
 4462:        if ((!$supplementalflag) && ($nomodal) && ($hostname ne '')) {
 4463:            $link = 'http://'.$hostname.$url;
 4464:        } else {
 4465:            $link = $url;
 4466:        }
 4467:        $link = &js_escape($link.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes'.$anchor);
 4468:        if ($allowed && !$env{'request.role.adv'} && !$isfolder && !$ispage && !$uploaded) {
 4469:            if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4470:                $nolink = 1;
 4471:            }
 4472:        }
 4473:        if ($nolink) {
 4474:            $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
 4475:        } elsif ($nomodal) {
 4476:            $line.='<a href="#" onclick="javascript:window.open('."'$link','syllabuspreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1')".'; return false;" />'.
 4477:                   '<img src="'.$icon.'" alt="" class="LC_icon" border="0" /></a>';
 4478:        } else {
 4479:            $line.=&Apache::loncommon::modal_link($link,
 4480:                                                  '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
 4481:        }
 4482:     } else {
 4483:        $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
 4484:     }
 4485:     $line.='</span></td><td'.$tdwidth.'>';
 4486:     if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 4487:        if ($nolink) {
 4488:            $line.=$title;
 4489:        } else {
 4490:            $line.='<a href="'.$url.'">'.$title.'</a>';
 4491:        }
 4492:        if (!$allowed && $supplementalflag && $canedit && $isfolder) {
 4493:            my $editicon = &Apache::loncommon::lonhttpdurl('/res/adm/pages').'/editmap.png';
 4494:            my $editurl = $url;
 4495:            $editurl =~ s{^\Q/adm/supplemental?\E}{/adm/coursedocs?command=direct&amp;forcesupplement=1&amp;};
 4496:            $line .= '&nbsp;'.'<a href="'.$editurl.'">'.
 4497:                     '<img src="'.$editicon.'" alt="'.&mt('Edit Content').'" title="'.&mt('Edit Content').'" />'.
 4498:                     '</a>';
 4499:        }
 4500:        if ((($hiddenfolder) || ($hiddenres)) && (!$allowed) && ($supplementalflag))  {
 4501:            $line.= ' <span class="LC_warning">('.&mt('hidden').')</span> ';
 4502:        }
 4503:     } elsif ($url) {
 4504:        if ($nolink) {
 4505:            $line.=$title;
 4506:        } elsif ($nomodal) {
 4507:            $line.='<a href="#" onclick="javascript:window.open('."'$link','syllabuspreview','height=400,width=500,scrollbars=1,resizable=1,menubar=0,location=1')".'; return false;" />'.
 4508:                   $title.'</a>';
 4509:        } else {
 4510:            $line.=&Apache::loncommon::modal_link($link,$title,600,500);
 4511:        }
 4512:     } elsif (($hiddenfolder) || ($hiddenres)) {
 4513:        $line.=$title.' <span class="LC_warning LC_docs_reinit_warn">('.&mt('Hidden').')</span>';
 4514:     } else {
 4515:        $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
 4516:     }
 4517:     $line.="$extresform</td>";
 4518:     $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
 4519:     $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
 4520:     if ($uploaded && $url && !$isfolder && !$ispage) {
 4521:         if (($plainurl ne '') && ($env{'request.role.adv'} || $allowed || !$hiddenres)) {
 4522:             &Apache::lonnet::allowuploaded('/adm/coursedoc',$plainurl);
 4523:         }
 4524:     }
 4525:     if ($allowed) {
 4526:         my %lt=&Apache::lonlocal::texthash(
 4527:                               'hd' => 'Hidden',
 4528:                               'ec' => 'URL hidden');
 4529:         my ($enctext,$hidtext,$formhidden,$formurlhidden);
 4530:         if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 4531:             $hidtext = ' checked="checked"';
 4532:             if (($ishash) && (ref($filtersref->{'hiddenresource'}) eq 'ARRAY')) {
 4533:                 push(@{$filtersref->{'hiddenresource'}},$orderidx);
 4534:             }
 4535:         }
 4536:         $formhidden = 'edit_hiddenresource_'.$orderidx;
 4537:         $line.=(<<ENDPARMS);
 4538:   <td class="LC_docs_entry_parameter">
 4539:     <form action="/adm/coursedocs" method="post" name="$formhidden">
 4540:     $form_param
 4541:     $form_common
 4542:     <label><input type="checkbox" name="hiddenresource_$orderidx" id="hiddenresource_$orderidx" onclick="checkForSubmit(this.form,'hiddenresource','settings');" $hidtext $disabled /> $lt{'hd'}</label>
 4543:     $form_end
 4544: ENDPARMS
 4545:         if ($folder =~/^supplemental/) {
 4546:             $line.= "\n    <td>";
 4547:         } else {
 4548:             if ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i) {
 4549:                 $enctext = ' checked="checked"';
 4550:                 if (($ishash) && (ref($filtersref->{'encrypturl'}) eq 'ARRAY')) {
 4551:                     push(@{$filtersref->{'encrypturl'}},$orderidx);
 4552:                 }
 4553:             }
 4554:             $formurlhidden = 'edit_encrypturl_'.$orderidx;
 4555: 	    $line.=(<<ENDPARMS);
 4556:     <br />
 4557:     <form action="/adm/coursedocs" method="post" name="$formurlhidden">
 4558:     $form_param
 4559:     $form_common
 4560:     <label><input type="checkbox" name="encrypturl_$orderidx" id="encrypturl_$orderidx" onclick="checkForSubmit(this.form,'encrypturl','settings');" $enctext $disabled /> $lt{'ec'}</label>
 4561:     $form_end
 4562:   </td>
 4563:   <td class="LC_docs_entry_parameter">$rand_pick_text<br />
 4564:                                       $rand_order_text</td>
 4565: ENDPARMS
 4566:         }
 4567:     }
 4568:     $line.=&Apache::loncommon::end_data_table_row();
 4569:     return $line;
 4570: }
 4571: 
 4572: sub action_restrictions {
 4573:     my ($cnum,$cdom,$url,$folderpath,$currgroups) = @_;
 4574:     my %denied = (
 4575:                    cut    => 0,
 4576:                    copy   => 0,
 4577:                    remove => 0,
 4578:                  );
 4579:     if ($url=~ m{^/res/.+\.(page|sequence)$}) {
 4580:         # no copy for published maps
 4581:         $denied{'copy'} = 1;
 4582:     } elsif ($url=~m{^/res/lib/templates/([^/]+)\.problem$}) {
 4583:         unless ($1 eq 'simpleproblem') {
 4584:             $denied{'copy'} = 1;
 4585:         }
 4586:         $denied{'cut'} = 1;
 4587:     } elsif ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
 4588:         if ($folderpath =~ /^default&[^\&]+$/) {
 4589:             if ((ref($currgroups) eq 'HASH') && (keys(%{$currgroups}) > 0)) {
 4590:                 $denied{'remove'} = 1;
 4591:             }
 4592:             $denied{'cut'} = 1;
 4593:             $denied{'copy'} = 1;
 4594:         }
 4595:     } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
 4596:         my $group = $1;
 4597:         if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
 4598:             if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
 4599:                 $denied{'remove'} = 1;
 4600:             }
 4601:         }
 4602:         $denied{'cut'} = 1;
 4603:         $denied{'copy'} = 1;
 4604:     } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
 4605:         my $group = $1;
 4606:         if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
 4607:             if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
 4608:                 my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
 4609:                 if (keys(%groupsettings) > 0) {
 4610:                     $denied{'remove'} = 1;
 4611:                 }
 4612:                 $denied{'cut'} = 1;
 4613:                 $denied{'copy'} = 1;
 4614:             }
 4615:         }
 4616:     } elsif ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
 4617:         my $group = $1;
 4618:         if ($url =~ /group_boards_\Q$group\E/) {
 4619:             if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
 4620:                 my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
 4621:                 if (keys(%groupsettings) > 0) {
 4622:                     if (ref($groupsettings{'functions'}) eq 'HASH') {
 4623:                         if ($groupsettings{'functions'}{'discussion'} eq 'on') {
 4624:                             $denied{'remove'} = 1;
 4625:                         }
 4626:                     }
 4627:                 }
 4628:                 $denied{'cut'} = 1;
 4629:                 $denied{'copy'} = 1;
 4630:             }
 4631:         }
 4632:     }
 4633:     return %denied;
 4634: }
 4635: 
 4636: sub new_timebased_suffix {
 4637:     my ($dom,$num,$type,$area,$container) = @_;
 4638:     my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
 4639:     if ($type eq 'paste') {
 4640:         $prefix = $type;
 4641:         $namespace = 'courseeditor';
 4642:         $idtype = 'addcode';
 4643:     } elsif ($type eq 'map') {
 4644:         $prefix = 'docs';
 4645:         if ($area eq 'supplemental') {
 4646:             $prefix = 'supp';
 4647:         }
 4648:         $prefix .= $container;
 4649:         $namespace = 'uploadedmaps';
 4650:     } else {
 4651:         $prefix = $type;
 4652:         $namespace = 'templated';
 4653:     }
 4654:     my ($suffix,$freedlock,$error) =
 4655:         &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,$dom,$num,$idtype);
 4656:     if (!$suffix) {
 4657:         if ($type eq 'paste') {
 4658:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix when adding to the paste buffer.');
 4659:         } elsif ($type eq 'map') {
 4660:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
 4661:         } elsif ($type eq 'smppg') {
 4662:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
 4663:         } elsif ($type eq 'exttool') {
 4664:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new external tool.');
 4665:         } else {
 4666:             $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new discussion board.');
 4667:         }
 4668:         if ($error) {
 4669:             $errtext .= '<br />'.$error;
 4670:         }
 4671:     }
 4672:     if ($freedlock ne 'ok') {
 4673:         $locknotfreed =
 4674:             '<div class="LC_error">'.
 4675:             &mt('There was a problem removing a lockfile.').' ';
 4676:         if ($type eq 'paste') {
 4677:             if ($freedlock eq 'nolock') {
 4678:                 $locknotfreed =
 4679:                     '<div class="LC_error">'.
 4680:                     &mt('A lockfile was not released when you added content to the clipboard earlier in this session.').' '.
 4681: 
 4682:                     &mt('As a result addition of items to the clipboard will be unavailable until your next log-in.');
 4683:             } else {
 4684:                 $locknotfreed .=
 4685:                     &mt('This will prevent addition of items to the clipboard until your next log-in.');
 4686:             }
 4687:         } elsif ($type eq 'map') {
 4688:             $locknotfreed .=
 4689:                 &mt('This will prevent creation of additional folders or composite pages in this course.');
 4690:         } elsif ($type eq 'smppg') {
 4691:             $locknotfreed .=
 4692:                 &mt('This will prevent creation of additional simple pages in this course.');
 4693:         } elsif ($type eq 'exttool') {
 4694:             $locknotfreed .=
 4695:                 &mt('This will prevent creation of additional external tools in this course.');
 4696:         } else {
 4697:             $locknotfreed .=
 4698:                 &mt('This will prevent creation of additional discussion boards in this course.');
 4699:         }
 4700:         unless ($type eq 'paste') {
 4701:             $locknotfreed .=
 4702:                 ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
 4703:                         '<a href="/adm/helpdesk" target="_helpdesk">','</a>');
 4704:         }
 4705:         $locknotfreed .= '</div>';
 4706:     }
 4707:     return ($suffix,$errtext,$locknotfreed);
 4708: }
 4709: 
 4710: =pod
 4711: 
 4712: =item tiehash()
 4713: 
 4714: tie the hash
 4715: 
 4716: =cut
 4717: 
 4718: sub tiehash {
 4719:     my ($mode)=@_;
 4720:     $hashtied=0;
 4721:     if ($env{'request.course.fn'}) {
 4722: 	if ($mode eq 'write') {
 4723: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 4724: 		    &GDBM_WRCREAT(),0640)) {
 4725:                 $hashtied=2;
 4726: 	    }
 4727: 	} else {
 4728: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 4729: 		    &GDBM_READER(),0640)) {
 4730:                 $hashtied=1;
 4731: 	    }
 4732: 	}
 4733:     }
 4734: }
 4735: 
 4736: sub untiehash {
 4737:     if ($hashtied) { untie %hash; }
 4738:     $hashtied=0;
 4739:     return OK;
 4740: }
 4741: 
 4742: 
 4743: 
 4744: 
 4745: sub checkonthis {
 4746:     my ($r,$url,$level,$title,$checkstale)=@_;
 4747:     $url=&unescape($url);
 4748:     $alreadyseen{$url}=1;
 4749:     $r->rflush();
 4750:     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 4751:        $r->print("\n<br />");
 4752:        if ($level==0) {
 4753:            $r->print("<br />");
 4754:        }
 4755:        for (my $i=0;$i<=$level*5;$i++) {
 4756:            $r->print('&nbsp;');
 4757:        }
 4758:        $r->print('<a href="'.$url.'" target="cat">'.
 4759: 		 ($title?$title:$url).'</a> ');
 4760:        if ($url=~/^\/res\//) {
 4761:           my $updated;
 4762:           if (($checkstale) && ($url !~ m{^/res/lib/templates/}) &&
 4763:               ($url !~ /\.\d+\.\w+$/)) {
 4764:               $updated = &Apache::lonnet::remove_stale_resfile($url);
 4765:           }
 4766: 	  my $result=&Apache::lonnet::repcopy(
 4767:                               &Apache::lonnet::filelocation('',$url));
 4768:           if ($result eq 'ok') {
 4769:              $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 4770:              if ($updated) {
 4771:                  $r->print('<br />');
 4772:                  for (my $i=0;$i<=$level*5;$i++) {
 4773:                      $r->print('&nbsp;');
 4774:                  }
 4775:                  $r->print('- '.&mt('Outdated copy removed'));
 4776:              }
 4777:              $r->rflush();
 4778:              &Apache::lonnet::countacc($url);
 4779:              $url=~/\.(\w+)$/;
 4780:              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 4781: 		 $r->print('<br />');
 4782:                  $r->rflush();
 4783:                  for (my $i=0;$i<=$level*5;$i++) {
 4784:                      $r->print('&nbsp;');
 4785:                  }
 4786:                  $r->print('- '.&mt('Rendering:').' ');
 4787: 		 my ($errorcount,$warningcount)=split(/:/,
 4788: 	       &Apache::lonnet::ssi_body($url,
 4789: 			       ('grade_target'=>'web',
 4790: 				'return_only_error_and_warning_counts' => 1)));
 4791:                  if (($errorcount) ||
 4792:                      ($warningcount)) {
 4793: 		     if ($errorcount) {
 4794:                         $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
 4795:                           &mt('[quant,_1,error]',$errorcount).'</span>');
 4796:                      }
 4797: 		     if ($warningcount) {
 4798:                         $r->print('<span class="LC_warning">'.
 4799:                           &mt('[quant,_1,warning]',$warningcount).'</span>');
 4800:                      }
 4801:                  } else {
 4802:                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 4803:                  }
 4804:                  $r->rflush();
 4805:              }
 4806: 	     my $dependencies=
 4807:                 &Apache::lonnet::metadata($url,'dependencies');
 4808:              foreach my $dep (split(/\,/,$dependencies)) {
 4809: 		 if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 4810:                     &checkonthis($r,$dep,$level+1,'',$checkstale);
 4811:                  }
 4812:              }
 4813:           } elsif ($result eq 'unavailable') {
 4814:              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 4815:           } elsif ($result eq 'not_found') {
 4816: 	      unless ($url=~/\$/) {
 4817: 		  $r->print('<span class="LC_error">'.&mt('not found').'</span>');
 4818: 	      } else {
 4819: 		  $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
 4820: 	      }
 4821:           } else {
 4822:              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
 4823:           }
 4824:           if (($updated) && ($result ne 'ok')) {
 4825:               $r->print('<br />'.&mt('Outdated copy removed'));
 4826:           }
 4827:        }
 4828:     }
 4829: }
 4830: 
 4831: 
 4832: 
 4833: =pod
 4834: 
 4835: =item list_symbs()
 4836: 
 4837: List Content Identifiers
 4838: 
 4839: =cut
 4840: 
 4841: sub list_symbs {
 4842:     my ($r) = @_;
 4843: 
 4844:     my $crstype = &Apache::loncommon::course_type();
 4845:     $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
 4846:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
 4847:     $r->print(&startContentScreen('tools'));
 4848:     my $navmap = Apache::lonnavmaps::navmap->new();
 4849:     if (!defined($navmap)) {
 4850:         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
 4851:                   '<div class="LC_error">'.
 4852:                   &mt('Unable to retrieve information about course contents').
 4853:                   '</div>');
 4854:         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
 4855:     } else {
 4856:         $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
 4857:                   &Apache::loncommon::start_data_table().
 4858:                   &Apache::loncommon::start_data_table_header_row().
 4859:                   '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
 4860:                   &Apache::loncommon::end_data_table_header_row()."\n");
 4861:         my $count;
 4862:         foreach my $res ($navmap->retrieveResources()) {
 4863:             $r->print(&Apache::loncommon::start_data_table_row().
 4864:                       '<td>'.$res->compTitle().'</td>'.
 4865:                       '<td>'.$res->symb().'</td>'.
 4866:                       &Apache::loncommon::end_data_table_row());
 4867:             $count ++;
 4868:         }
 4869:         if (!$count) {
 4870:             $r->print(&Apache::loncommon::start_data_table_row().
 4871:                       '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
 4872:                       &Apache::loncommon::end_data_table_row()); 
 4873:         }
 4874:         $r->print(&Apache::loncommon::end_data_table());
 4875:     }
 4876:     $r->print(&endContentScreen());
 4877: }
 4878: 
 4879: sub short_urls {
 4880:     my ($r,$canedit) = @_;
 4881:     my $crstype = &Apache::loncommon::course_type();
 4882:     my $formname = 'shortenurl';
 4883:     $r->print(&Apache::loncommon::start_page('Display/Set Shortened URLs'));
 4884:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Shortened URLs'));
 4885:     $r->print(&startContentScreen('tools'));
 4886:     my ($navmap,$errormsg) =
 4887:         &Apache::loncourserespicker::get_navmap_object($crstype,'shorturls');
 4888:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4889:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4890:     my (%maps,%resources,%titles);
 4891:     if (!ref($navmap)) {
 4892:         $r->print($errormsg.
 4893:                   &endContentScreen());
 4894:         return '';
 4895:     } else {
 4896:         $r->print('<h4 class="LC_info">'.&mt('Tiny URLs for deep-linking into course').'</h4>'."\n");
 4897:         $r->rflush();
 4898:         my $readonly;
 4899:         if ($canedit) {
 4900:             my ($numnew,$errors) = &Apache::loncommon::get_requested_shorturls($cdom,$cnum,$navmap);
 4901:             if ($numnew) {
 4902:                 $r->print('<p class="LC_info">'.&mt('Created [quant,_1,URL]',$numnew).'</p>');
 4903:             }
 4904:             if ((ref($errors) eq 'ARRAY') && (@{$errors} > 0)) {
 4905:                 $r->print(&mt('The following errors occurred when processing your request to create shortened URLs:').'<br /><ul>');
 4906:                 foreach my $error (@{$errors}) {
 4907:                     $r->print('<li>'.$error.'</li>');
 4908:                 }
 4909:                 $r->print('</ul><br />');
 4910:             }
 4911:         } else {
 4912:             $readonly = 1;
 4913:         }
 4914:         my %currtiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
 4915:         $r->print(&Apache::loncourserespicker::create_picker($navmap,'shorturls',$formname,$crstype,undef,
 4916:                                                              undef,undef,undef,undef,undef,\%currtiny,$readonly));
 4917:     }
 4918:     $r->print(&endContentScreen());
 4919: }
 4920: 
 4921: sub contentverifyform {
 4922:     my ($r) = @_;
 4923:     my $crstype = &Apache::loncommon::course_type();
 4924:     $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
 4925:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
 4926:     $r->print(&startContentScreen('tools'));
 4927:     $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>');
 4928:     $r->print('<form method="post" action="/adm/coursedocs"><p>'.
 4929:               &mt('Include a check if files copied from elsewhere are up to date (will increase verification time)?').
 4930:               '&nbsp;<span class="LC_nobreak">'.
 4931:               '<label><input type="radio" name="checkstale" value="0" checked="checked" />'.
 4932:               &mt('No').'</label>'.('&nbsp;'x2).
 4933:               '<label><input type="radio" name="checkstale" value="1" />'.
 4934:               &mt('Yes').'</label></span></p><p>'.
 4935:               '<input type="submit" value="'.&mt('Verify Content').' "/>'.
 4936:               '<input type="hidden" value="1" name="tools" />'.
 4937:               '<input type="hidden" value="1" name="verify" /></p></form>');
 4938:     $r->print(&endContentScreen());
 4939:     return;
 4940: }
 4941: 
 4942: sub verifycontent {
 4943:     my ($r,$checkstale) = @_;
 4944:     my $crstype = &Apache::loncommon::course_type();
 4945:     $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
 4946:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
 4947:     $r->print(&startContentScreen('tools'));
 4948:     $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
 4949:    $hashtied=0;
 4950:    undef %alreadyseen;
 4951:    %alreadyseen=();
 4952:    &tiehash();
 4953:    
 4954:    foreach my $key (keys(%hash)) {
 4955:        if ($hash{$key}=~/\.(page|sequence)$/) {
 4956: 	   if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
 4957: 	       $r->print('<hr /><span class="LC_error">'.
 4958: 			 &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
 4959: 			 &unescape($hash{$key}).'</span><br />'.
 4960: 			 &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
 4961: 	   }
 4962:        }
 4963:        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 4964:            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1},$checkstale);
 4965:        }
 4966:    }
 4967:    &untiehash();
 4968:    $r->print('<p class="LC_success">'.&mt('Done').'</p>');
 4969:     $r->print(&endContentScreen());
 4970: }
 4971: 
 4972: 
 4973: sub devalidateversioncache {
 4974:     my $src=shift;
 4975:     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
 4976: 					  &Apache::lonnet::clutter($src));
 4977: }
 4978: 
 4979: sub checkversions {
 4980:     my ($r,$canedit) = @_;
 4981:     my $crstype = &Apache::loncommon::course_type();
 4982:     $r->print(&Apache::loncommon::start_page("Check $crstype Resource Versions"));
 4983:     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Resource Versions"));
 4984:     $r->print(&startContentScreen('tools'));
 4985: 
 4986:     my $header='';
 4987:     my $startsel='';
 4988:     my $monthsel='';
 4989:     my $weeksel='';
 4990:     my $daysel='';
 4991:     my $allsel='';
 4992:     my %changes=();
 4993:     my $starttime=0;
 4994:     my $haschanged=0;
 4995:     my %setversions=&Apache::lonnet::dump('resourceversions',
 4996: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 4997: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 4998: 
 4999:     $hashtied=0;
 5000:     &tiehash();
 5001:     if ($canedit) {
 5002:         my %newsetversions=();
 5003:         if ($env{'form.setmostrecent'}) {
 5004: 	    $haschanged=1;
 5005: 	    foreach my $key (keys(%hash)) {
 5006: 	        if ($key=~/^ids\_(\/res\/.+)$/) {
 5007: 		    $newsetversions{$1}='mostrecent';
 5008:                     &devalidateversioncache($1);
 5009: 	        }
 5010: 	    }
 5011:         } elsif ($env{'form.setcurrent'}) {
 5012: 	    $haschanged=1;
 5013: 	    foreach my $key (keys(%hash)) {
 5014: 	        if ($key=~/^ids\_(\/res\/.+)$/) {
 5015: 		    my $getvers=&Apache::lonnet::getversion($1);
 5016: 		    if ($getvers>0) {
 5017: 		        $newsetversions{$1}=$getvers;
 5018: 		        &devalidateversioncache($1);
 5019: 		    }
 5020: 	        }
 5021: 	    }
 5022:         } elsif ($env{'form.setversions'}) {
 5023: 	    $haschanged=1;
 5024: 	    foreach my $key (keys(%env)) {
 5025: 	        if ($key=~/^form\.set_version_(.+)$/) {
 5026: 		    my $src=$1;
 5027: 		    if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
 5028: 		        $newsetversions{$src}=$env{$key};
 5029: 		        &devalidateversioncache($src);
 5030: 		    }
 5031: 	        }
 5032: 	    }
 5033:         }
 5034:         if ($haschanged) {
 5035:             if (&Apache::lonnet::put('resourceversions',\%newsetversions,
 5036: 			      $env{'course.'.$env{'request.course.id'}.'.domain'},
 5037: 			      $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 5038: 	        $r->print(&Apache::loncommon::confirmwrapper(
 5039:                     &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
 5040: 	    } else {
 5041: 	        $r->print(&Apache::loncommon::confirmwrapper(
 5042:                     &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
 5043: 	    }
 5044: 	    &mark_hash_old();
 5045:         }
 5046:         &changewarning($r,'');
 5047:     }
 5048:     if ($env{'form.timerange'} eq 'all') {
 5049: # show all documents
 5050: 	$header=&mt('All content in '.$crstype);
 5051: 	$allsel=' selected="selected"';
 5052: 	foreach my $key (keys(%hash)) {
 5053: 	    if ($key=~/^ids\_(\/res\/.+)$/) {
 5054: 		my $src=$1;
 5055: 		$changes{$src}=1;
 5056: 	    }
 5057: 	}
 5058:     } else {
 5059: # show documents which changed
 5060: 	%changes=&Apache::lonnet::dump
 5061: 	 ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
 5062:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 5063: 	my $firstkey=(keys(%changes))[0];
 5064: 	unless ($firstkey=~/^error\:/) {
 5065: 	    unless ($env{'form.timerange'}) {
 5066: 		$env{'form.timerange'}=604800;
 5067: 	    }
 5068: 	    my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 5069: 		.&mt('seconds');
 5070: 	    if ($env{'form.timerange'}==-1) {
 5071: 		$seltext='since start of course';
 5072: 		$startsel=' selected="selected"';
 5073: 		$env{'form.timerange'}=time;
 5074: 	    }
 5075: 	    $starttime=time-$env{'form.timerange'};
 5076: 	    if ($env{'form.timerange'}==2592000) {
 5077: 		$seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 5078: 		$monthsel=' selected="selected"';
 5079: 	    } elsif ($env{'form.timerange'}==604800) {
 5080: 		$seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 5081: 		$weeksel=' selected="selected"';
 5082: 	    } elsif ($env{'form.timerange'}==86400) {
 5083: 		$seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 5084: 		$daysel=' selected="selected"';
 5085: 	    }
 5086: 	    $header=&mt('Content changed').' '.$seltext;
 5087: 	} else {
 5088: 	    $header=&mt('No content modifications yet.');
 5089: 	}
 5090:     }
 5091:     %setversions=&Apache::lonnet::dump('resourceversions',
 5092: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 5093: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 5094:     my %lt=&Apache::lonlocal::texthash
 5095: 	      ('st' => 'Version changes since start of '.$crstype,
 5096: 	       'lm' => 'Version changes since last Month',
 5097: 	       'lw' => 'Version changes since last Week',
 5098: 	       'sy' => 'Version changes since Yesterday',
 5099:                'al' => 'All Resources (possibly large output)',
 5100:                'cd' => 'Change display', 
 5101: 	       'sd' => 'Display',
 5102: 	       'fi' => 'File',
 5103: 	       'md' => 'Modification Date',
 5104:                'mr' => 'Most recently published Version',
 5105: 	       've' => 'Version used in '.$crstype,
 5106:                'vu' => 'Set Version to be used in '.$crstype,
 5107: 'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
 5108: 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 5109: 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 5110: 	       'di' => 'Differences',
 5111: 	       'save' => 'Save changes',
 5112:                'vers' => 'Version choice(s) for specific resources', 
 5113: 	       'act' => 'Actions');
 5114:     my ($disabled,$readonly);
 5115:     unless ($canedit) {
 5116:         $disabled = 'disabled="disabled"';
 5117:         $readonly = 1;
 5118:     }
 5119:     $r->print(<<ENDHEADERS);
 5120: <h4 class="LC_info">$header</h4>
 5121: <form action="/adm/coursedocs" method="post">
 5122: <input type="hidden" name="versions" value="1" />
 5123: <div class="LC_left_float">
 5124: <fieldset>
 5125: <legend>$lt{'cd'}</legend>
 5126: <select name="timerange">
 5127: <option value='all'$allsel>$lt{'al'}</option>
 5128: <option value="-1"$startsel>$lt{'st'}</option>
 5129: <option value="2592000"$monthsel>$lt{'lm'}</option>
 5130: <option value="604800"$weeksel>$lt{'lw'}</option>
 5131: <option value="86400"$daysel>$lt{'sy'}</option>
 5132: </select>
 5133: <input type="submit" name="display" value="$lt{'sd'}" />
 5134: </fieldset>
 5135: </div>
 5136: <div class="LC_left_float">
 5137: <fieldset>
 5138: <legend>$lt{'act'}</legend>
 5139: $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" $disabled /><br />
 5140: $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" $disabled />
 5141: </fieldset>
 5142: </div>
 5143: <br clear="all" />
 5144: <hr />
 5145: <h4>$lt{'vers'}</h4>
 5146: ENDHEADERS
 5147:     #number of columns for version history
 5148:     my %changedbytime;
 5149:     foreach my $key (keys(%changes)) {
 5150:         #excludes not versionable problems from resource version history:
 5151:         next if ($key =~ /^\/res\/lib\/templates/);
 5152:         my $chg;
 5153:         if ($env{'form.timerange'} eq 'all') {
 5154:             my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
 5155:             $chg = &Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate');
 5156:         } else {
 5157:             $chg = $changes{$key};
 5158:             next if ($chg < $starttime);
 5159:         }
 5160:         push(@{$changedbytime{$chg}},$key);
 5161:     }
 5162:     if (keys(%changedbytime) == 0) {
 5163:         &untiehash();
 5164:         $r->print(&mt('No content changes in imported content in specified time frame').
 5165:                   &endContentScreen());
 5166:         return;
 5167:     }
 5168:     $r->print(
 5169:         '<input type="submit" name="setversions" value="'.$lt{'save'}.'"'.$disabled.' />'.
 5170:         &Apache::loncommon::start_data_table().
 5171:         &Apache::loncommon::start_data_table_header_row().
 5172:         '<th>'.&mt('Resources').'</th>'.
 5173:         "<th>$lt{'mr'}</th>".
 5174:         "<th>$lt{'ve'}</th>".
 5175:         "<th>$lt{'vu'}</th>".
 5176:         '<th>'.&mt('History').'</th>'.
 5177:         &Apache::loncommon::end_data_table_header_row()
 5178:     );
 5179:     foreach my $chg (sort {$b <=> $a } keys(%changedbytime)) {
 5180:         foreach my $key (sort(@{$changedbytime{$chg}})) {
 5181:             my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
 5182:             my $currentversion=&Apache::lonnet::getversion($key);
 5183:             if ($currentversion<0) {
 5184:                 $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
 5185:             }
 5186:             my $linkurl=&Apache::lonnet::clutter($key);
 5187:             $r->print(
 5188:                 &Apache::loncommon::start_data_table_row().
 5189:                 '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
 5190:                 '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
 5191:                 '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
 5192:                 &Apache::lonlocal::locallocaltime($chg).')</span></td>'.
 5193:                 '<td align="right">'
 5194:             );
 5195:             # Used in course
 5196:             my $usedversion=$hash{'version_'.$linkurl};
 5197:             if (($usedversion) && ($usedversion ne 'mostrecent')) {
 5198:                 if ($usedversion != $currentversion) {
 5199:                     $r->print('<span class="LC_warning">'.$usedversion.'</span>');
 5200:                 } else {
 5201:                     $r->print($usedversion);
 5202:                 }
 5203:             } else {
 5204:                 $r->print($currentversion);
 5205:             }
 5206:             $r->print('</td><td title="'.$lt{'vu'}.'">');
 5207:             # Set version
 5208:             $r->print(&Apache::loncommon::select_form(
 5209:                       $setversions{$linkurl},
 5210:                       'set_version_'.$linkurl,
 5211:                       {'select_form_order' => ['',1..$currentversion,'mostrecent'],
 5212:                        '' => '',
 5213:                        'mostrecent' => &mt('most recent'),
 5214:                        map {$_,$_} (1..$currentversion)},'',$readonly));
 5215:             my $lastold=1;
 5216:             for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
 5217:                 my $url=$root.'.'.$prevvers.'.'.$extension;
 5218:                 if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
 5219:                     $lastold=$prevvers;
 5220:                 }
 5221:             }
 5222:             $r->print('</td>');
 5223:             # List all available versions
 5224:             $r->print('<td valign="top"><span class="LC_fontsize_medium">');
 5225:             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
 5226:                 my $url=$root.'.'.$prevvers.'.'.$extension;
 5227:                 $r->print(
 5228:                     '<span class="LC_nobreak">'
 5229:                    .'<a href="'.&Apache::lonnet::clutter($url).'">'
 5230:                    .&mt('Version [_1]',$prevvers).'</a>'
 5231:                    .' ('.&Apache::lonlocal::locallocaltime(
 5232:                          &Apache::lonnet::metadata($url,'lastrevisiondate'))
 5233:                    .')');
 5234:                 if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
 5235:                     $r->print(
 5236:                         ' <a href="/adm/diff?filename='.
 5237:                         &Apache::lonnet::clutter($root.'.'.$extension).
 5238:                         &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
 5239:                         '" target="diffs">'.&mt('Diffs').'</a>');
 5240:                 }
 5241:                 $r->print('</span><br />');
 5242:             }
 5243:             $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
 5244:         }
 5245:     }
 5246:     $r->print(
 5247:         &Apache::loncommon::end_data_table().
 5248:         '<input type="submit" name="setversions" value="'.$lt{'save'}.'"'.$disabled.' />'.
 5249:         '</form>'
 5250:     );
 5251: 
 5252:     &untiehash();
 5253:     $r->print(&endContentScreen());
 5254:     return;
 5255: }
 5256: 
 5257: sub mark_hash_old {
 5258:     my $retie_hash=0;
 5259:     if ($hashtied) {
 5260: 	$retie_hash=1;
 5261: 	&untiehash();
 5262:     }
 5263:     &tiehash('write');
 5264:     $hash{'old'}=1;
 5265:     &untiehash();
 5266:     if ($retie_hash) { &tiehash(); }
 5267: }
 5268: 
 5269: sub is_hash_old {
 5270:     my $untie_hash=0;
 5271:     if (!$hashtied) {
 5272: 	$untie_hash=1;
 5273: 	&tiehash();
 5274:     }
 5275:     my $return=$hash{'old'};
 5276:     if ($untie_hash) { &untiehash(); }
 5277:     return $return;
 5278: }
 5279: 
 5280: sub changewarning {
 5281:     my ($r,$postexec,$message,$url)=@_;
 5282:     if (!&is_hash_old()) { return; }
 5283:     my $pathvar='folderpath';
 5284:     my $path=&escape($env{'form.folderpath'});
 5285:     if (!defined($url)) {
 5286: 	$url='/adm/coursedocs?'.$pathvar.'='.$path;
 5287:     }
 5288:     my $course_type = &Apache::loncommon::course_type();
 5289:     if (!defined($message)) {
 5290: 	$message='Changes will become active for your current session after [_1], or the next time you log in.';
 5291:     }
 5292:     $r->print("\n\n".
 5293: '<script type="text/javascript">'."\n".
 5294: '// <![CDATA['."\n".
 5295: 'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
 5296: '// ]]>'."\n".
 5297: '</script>'."\n".
 5298: '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 5299: '<input type="hidden" name="orgurl" value="'.$url.
 5300: '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
 5301: &mt($message,' <input type="hidden" name="'.
 5302:     $env{'request.role'}.'" value="1" /><input type="button" value="'.
 5303:     &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
 5304: $help{'Caching'}.'</p></form>'."\n\n");
 5305: }
 5306: 
 5307: 
 5308: sub init_breadcrumbs {
 5309:     my ($form,$text,$help)=@_;
 5310:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5311:     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
 5312: 					    text=>&Apache::loncommon::course_type().' Editor',
 5313: 					    faq=>273,
 5314: 					    bug=>'Instructor Interface',
 5315:                                             help => $help});
 5316:     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
 5317: 					    text=>$text,
 5318: 					    faq=>273,
 5319: 					    bug=>'Instructor Interface'});
 5320: }
 5321: 
 5322: # subroutine to list form elements
 5323: sub create_list_elements {
 5324:    my @formarr = @_;
 5325:    my $list = '';
 5326:    foreach my $button (@formarr){
 5327:         foreach my $picture (keys(%{$button})) {
 5328:             $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
 5329:         }
 5330:    }
 5331:    return $list;
 5332: }
 5333: 
 5334: # subroutine to create ul from list elements
 5335: sub create_form_ul {
 5336:    my $list = shift;
 5337:    my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
 5338:    return $ul;
 5339: }
 5340: 
 5341: #
 5342: # Start tabs
 5343: #
 5344: 
 5345: sub startContentScreen {
 5346:     my ($mode) = @_;
 5347:     my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
 5348:     if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
 5349:         $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";
 5350:         $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";
 5351:         $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
 5352:     } else {
 5353:         $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";
 5354:         $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
 5355:         $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";
 5356:                    '><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>';
 5357:     }
 5358:     $output .= "\n".'</ul>'."\n";
 5359:     $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
 5360:                '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
 5361:                '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
 5362:     return $output;
 5363: }
 5364: 
 5365: #
 5366: # End tabs
 5367: #
 5368: 
 5369: sub endContentScreen {
 5370:     return '</div></div></div>';
 5371: }
 5372: 
 5373: sub supplemental_base {
 5374:     return 'supplemental&'.&escape(&mt('Supplemental Content'));
 5375: }
 5376: 
 5377: sub handler {
 5378:     my $r = shift;
 5379:     &Apache::loncommon::content_type($r,'text/html');
 5380:     $r->send_http_header;
 5381:     return OK if $r->header_only;
 5382: 
 5383: # get course data
 5384:     my $crstype = &Apache::loncommon::course_type();
 5385:     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 5386:     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5387: 
 5388: # graphics settings
 5389:     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
 5390: 
 5391: #
 5392: # --------------------------------------------- Initialize help topics for this
 5393:     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
 5394: 	               'Adding_External_Resource','Adding_External_Tool',
 5395:                        'Navigate_Content','Adding_Folders','Docs_Overview',
 5396: 	               'Load_Map','Supplemental','Score_Upload_Form', 
 5397: 	               'Adding_Pages','Importing_LON-CAPA_Resource',
 5398: 	               'Importing_IMS_Course','Uploading_From_Harddrive',
 5399:                        'Course_Roster','Web_Page','Dropbox','Simple_Problem') {
 5400: 	$help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 5401:     }
 5402:     # Composite help files
 5403:     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 5404: 		    'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 5405:     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 5406: 		    'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 5407:     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 5408: 		    'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 5409:     $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
 5410: 		  'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 5411:     $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 5412:     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 5413:  
 5414:     my ($allowed,$canedit,$canview,$disabled);
 5415: # does this user have privileges to modify content.
 5416:     if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 5417: # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
 5418:         unless ($r->uri eq '/adm/supplemental') {
 5419:             $allowed = 1;
 5420:         }
 5421:         $canedit = 1;
 5422:         $canview = 1;
 5423:     } elsif (&Apache::lonnet::allowed('cev',$env{'request.course.id'})) {
 5424: # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
 5425:         unless ($r->uri eq '/adm/supplemental') {
 5426:             $allowed = 1;
 5427:         }
 5428:         $canview = 1;
 5429:     }
 5430:     unless ($canedit) {
 5431:         $disabled = ' disabled="disabled"';
 5432:     }
 5433:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
 5434:     if ($env{'form.inhibitmenu'}) {
 5435:         unless ($env{'form.inhibitmenu'} eq 'yes') {
 5436:             delete($env{'form.inhibitmenu'});
 5437:         }
 5438:     }
 5439: 
 5440:   if ($allowed && $env{'form.verify'}) {
 5441:       &init_breadcrumbs('verify','Verify Content','Docs_Verify_Content');
 5442:       if (!$canedit) {
 5443:           &verifycontent($r);
 5444:       } elsif (($env{'form.checkstale'} ne '') && ($env{'form.checkstale'} =~ /^\d$/)) {
 5445:           &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1&verify=1&checkstale=$env{'form.checkstale'}",
 5446:                                                   text=>'Results',
 5447:                                                   faq=>273,
 5448:                                                   bug=>'Instructor Interface'});
 5449:           &verifycontent($r,$env{'form.checkstale'});
 5450:       } else {
 5451:           &contentverifyform($r);
 5452:       }
 5453:   } elsif ($allowed && $env{'form.listsymbs'}) {
 5454:       &init_breadcrumbs('listsymbs','List Content IDs');
 5455:       &list_symbs($r);
 5456:   } elsif ($allowed && $env{'form.shorturls'}) {
 5457:       &init_breadcrumbs('shorturls','Set/Display Shortened URLs','Docs_Short_URLs');
 5458:       &short_urls($r,$canedit);
 5459:   } elsif ($allowed && $env{'form.docslog'}) {
 5460:       &init_breadcrumbs('docslog','Show Log');
 5461:       my $folder = $env{'form.folder'};
 5462:       if ($folder eq '') {
 5463:           $folder='default';
 5464:       }
 5465:       &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath,$canedit);
 5466:   } elsif ($allowed && $env{'form.versions'}) {
 5467:       &init_breadcrumbs('versions','Check/Set Resource Versions','Docs_Check_Resource_Versions');
 5468:       &checkversions($r,$canedit);
 5469:   } elsif ($canedit && $env{'form.dumpcourse'}) {
 5470:       &init_breadcrumbs('dumpcourse','Copy '.&Apache::loncommon::course_type().' Content to Authoring Space');
 5471:       &dumpcourse($r);
 5472:   } elsif ($allowed && $env{'form.exportcourse'}) {
 5473:       &init_breadcrumbs('exportcourse','IMS Export');
 5474:       &Apache::imsexport::exportcourse($r);
 5475:   } else {
 5476: #
 5477: # Done catching special calls
 5478: # The whole rest is for course and supplemental documents and utilities menu
 5479: # Get the parameters that may be needed
 5480: #
 5481:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5482:                                             ['folderpath','title',
 5483:                                              'forcesupplement','forcestandard',
 5484:                                              'tools','symb','command','supppath']);
 5485: 
 5486:     foreach my $item ('forcesupplement','forcestandard','tools') {
 5487:         next if ($env{'form.'.$item} eq '');
 5488:         unless ($env{'form.'.$item} eq '1') {
 5489:             delete($env{'form.'.$item});
 5490:         }
 5491:     }
 5492: 
 5493:     if ($env{'form.command'}) {
 5494:         unless ($env{'form.command'} =~ /^(direct|directnav|editdocs|editsupp|contents|home)$/) {
 5495:             delete($env{'form.command'});
 5496:         }
 5497:     }
 5498: 
 5499:     if ($env{'form.symb'}) {
 5500:         my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
 5501:         unless (($id =~ /^\d+$/) && (&Apache::lonnet::is_on_map($resurl))) {
 5502:             delete($env{'form.symb'});
 5503:         }
 5504:     }
 5505: 
 5506: # standard=1: this is a "new-style" course with an uploaded map as top level
 5507: # standard=2: this is a "old-style" course, and there is nothing we can do
 5508: 
 5509:     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 5510: 
 5511: # Decide whether this should display supplemental or main content or utilities
 5512: # supplementalflag=1: show supplemental documents
 5513: # supplementalflag=0: show standard documents
 5514: # toolsflag=1: show utilities
 5515: 
 5516:     my $unesc_folderpath = &unescape($env{'form.folderpath'});
 5517:     my $supplementalflag=($unesc_folderpath=~/^supplemental/);
 5518:     if (($unesc_folderpath=~/^default/) || ($unesc_folderpath eq "")) {
 5519:        $supplementalflag=0;
 5520:     }
 5521:     if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 5522:     if ($env{'form.forcestandard'})   { $supplementalflag=0; }
 5523:     unless ($allowed) { $supplementalflag=1; }
 5524:     unless ($standard) { $supplementalflag=1; }
 5525:     my $toolsflag=0;
 5526:     if ($env{'form.tools'}) { $toolsflag=1; }
 5527: 
 5528:     if ($env{'form.folderpath'} ne '') {
 5529:         &Apache::loncommon::validate_folderpath($supplementalflag,$allowed,$coursenum,$coursedom);
 5530:     }
 5531: 
 5532:     my $backto_supppath;
 5533:     if ($env{'form.supppath'} ne '') {
 5534:         if ($supplementalflag && $allowed) {
 5535:             $backto_supppath = &validate_supppath($coursenum,$coursedom);
 5536:         }
 5537:     }
 5538: 
 5539:     my $script='';
 5540:     my $showdoc=0;
 5541:     my $addentries = {};
 5542:     my $container;
 5543:     my $containertag;
 5544:     my $pathitem;
 5545:     my %ltitools;
 5546:     my $hiddentop;
 5547:     my $navmap;
 5548:     my $filterFunc = sub { my $res = shift; return (!$res->randomout() && !$res->is_map()) };
 5549: 
 5550: # Do we directly jump somewhere?
 5551:    if (($env{'form.command'} eq 'direct') || ($env{'form.command'} eq 'directnav')) {
 5552:        if ($env{'form.symb'} ne '') {
 5553:            $env{'form.folderpath'}=
 5554:                &Apache::loncommon::symb_to_docspath($env{'form.symb'},\$navmap);
 5555:            &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
 5556:                $env{'form.command'}.'_'.$env{'form.symb'}});
 5557:        } elsif (($env{'form.supppath'} ne '') && $supplementalflag && $allowed) {
 5558:            $env{'form.folderpath'}=$env{'form.supppath'};
 5559:            &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
 5560:                $env{'form.command'}.'_'.$backto_supppath});
 5561:        }
 5562:    } elsif ($env{'form.command'} eq 'editdocs') {
 5563:        $env{'form.folderpath'} = &default_folderpath($coursenum,$coursedom,\$navmap);
 5564:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => $env{'form.command'}});
 5565:    } elsif ($env{'form.command'} eq 'editsupp') {
 5566:        $env{'form.folderpath'} = &supplemental_base();
 5567:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/supplemental'});
 5568:    } elsif ($env{'form.command'} eq 'contents') {
 5569:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/navmaps'});
 5570:    } elsif ($env{'form.command'} eq 'home') {
 5571:        &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/menu'});
 5572:    }
 5573: 
 5574: 
 5575: # Where do we store these for when we come back?
 5576:     my $stored_folderpath='docs_folderpath';
 5577:     if ($supplementalflag) {
 5578:        $stored_folderpath='docs_sup_folderpath';
 5579:     }
 5580: 
 5581: # No folderpath, and in edit mode, see if we have something stored
 5582:     if ((!$env{'form.folderpath'}) && $allowed) {
 5583:         &Apache::loncommon::restore_course_settings($stored_folderpath,
 5584:                                           {'folderpath' => 'scalar'});
 5585: 
 5586:         if (&unescape($env{'form.folderpath'}) =~ m{^(default|supplemental)&}) {
 5587:             if ($supplementalflag) {
 5588:                 undef($env{'form.folderpath'}) if ($1 eq 'default');
 5589:             } else {
 5590:                 undef($env{'form.folderpath'}) if ($1 eq 'supplemental');
 5591:             }
 5592:         } else {
 5593:             undef($env{'form.folderpath'});
 5594:         }
 5595:         if ($env{'form.folderpath'} ne '') {
 5596:             &Apache::loncommon::validate_folderpath($supplementalflag,$allowed,$coursenum,$coursedom);
 5597:         }
 5598:     }
 5599:    
 5600: # If we are not allowed to make changes, all we can see are supplemental docs
 5601:     if (!$allowed) {
 5602:         unless ($env{'form.folderpath'} =~ /^supplemental/) {
 5603:             $env{'form.folderpath'} = &supplemental_base();
 5604:         }
 5605:     }
 5606: # Make the zeroth entry in supplemental docs page paths, so we can get to top level
 5607:     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 5608:         $env{'form.folderpath'} = &supplemental_base()
 5609:                                   .'&'.
 5610:                                   $env{'form.folderpath'};
 5611:     }
 5612: # If allowed and user's role is not advanced check folderpath is not hidden
 5613:     my $hidden_and_empty;
 5614:     if (($allowed) && (!$env{'request.role.adv'}) && ($env{'form.folderpath'} ne '')) {
 5615:         my ($folderurl,$foldername,$hiddenfolder);
 5616:         my @pathitems = split(/\&/,$env{'form.folderpath'});
 5617:         my $folder = $pathitems[-2];
 5618:         if ($folder eq '') {
 5619:             undef($env{'form.folderpath'});
 5620:         } else {
 5621:             $folderurl = "uploaded/$coursedom/$coursenum/$folder";
 5622:             if ((split(/\:/,$pathitems[-1]))[5]) {
 5623:                 $folderurl .= '.page';
 5624:             } else {
 5625:                 $folderurl .= '.sequence';
 5626:             }
 5627:             if ($supplementalflag) {
 5628:                 ($foldername,$hiddenfolder) = ($pathitems[-1] =~ /^([^:]*)::(|1):::$/);
 5629:                 $foldername = &HTML::Entities::decode(&unescape($foldername));
 5630:                 my ($supplemental) = &Apache::loncommon::get_supplemental($coursenum,$coursedom);
 5631:                 if (ref($supplemental) eq 'HASH') {
 5632:                     my ($suppmap,$suppmapnum);
 5633:                     if ($folder eq 'supplemental') {
 5634:                         $suppmap = 'default';
 5635:                         $suppmapnum = 0;
 5636:                     } elsif ($folder =~ /^supplemental_(\d+)$/) {
 5637:                         $suppmap = $1;
 5638:                         $suppmapnum = $suppmap;
 5639:                     }
 5640:                     if ($hiddenfolder) {
 5641:                         my $hascontent;
 5642:                         foreach my $key (reverse(sort(keys(%{$supplemental->{'ids'}})))) {
 5643:                             if ($key =~ m{^\Q/uploaded/$coursedom/$coursenum/supplemental/$suppmap/\E}) {
 5644:                                 $hascontent = 1;
 5645:                             } elsif (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
 5646:                                 foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
 5647:                                     if ($id =~ /^$suppmapnum\:/) {
 5648:                                         $hascontent = 1;
 5649:                                         last;
 5650:                                     }
 5651:                                 }
 5652:                             }
 5653:                             last if ($hascontent);
 5654:                         }
 5655:                         unless ($hascontent) {
 5656:                             if ($foldername ne '') {
 5657:                                 $hidden_and_empty = $foldername;
 5658:                             } else {
 5659:                                 $hidden_and_empty = $folder;
 5660:                             }
 5661:                         }
 5662:                     }
 5663:                 }
 5664:             } else {
 5665:                 unless (ref($navmap)) {
 5666:                     $navmap = Apache::lonnavmaps::navmap->new();
 5667:                 }
 5668:                 ($foldername,$hiddenfolder) = ($pathitems[-1] =~ /^([^:]*):|\d+:|1:(|1):|1:|1$/);
 5669:                 $foldername = &HTML::Entities::decode(&unescape($foldername));
 5670:                 if (ref($navmap)) {
 5671:                     if ($hiddenfolder ||
 5672:                         (lc($navmap->get_mapparam(undef,$folderurl,"0.hiddenresource")) eq 'yes')) {
 5673:                         my @resources = $navmap->retrieveResources($folderurl,$filterFunc,1,1);
 5674:                         unless (@resources) {
 5675:                             if ($foldername ne '') {
 5676:                                 $hidden_and_empty = $foldername;
 5677:                             } else {
 5678:                                 $hidden_and_empty = $folder;
 5679:                             }
 5680:                         }
 5681:                     }
 5682:                 }
 5683:             }
 5684:             if ($hidden_and_empty ne '') {
 5685:                 splice(@pathitems,-2);
 5686:                 if (@pathitems) {
 5687:                     $env{'form.folderpath'} = join('&',@pathitems);
 5688:                 } else {
 5689:                     undef($env{'form.folderpath'});
 5690:                 }
 5691:             }
 5692:         }
 5693:     }
 5694: 
 5695: # If after all of this, we still don't have any paths, make them
 5696:     unless ($env{'form.folderpath'}) {
 5697:        if ($supplementalflag) {
 5698:           $env{'form.folderpath'}=&supplemental_base();
 5699:        } elsif ($allowed) {
 5700:           ($env{'form.folderpath'},$hiddentop) = &default_folderpath($coursenum,$coursedom,\$navmap);
 5701:        }
 5702:     }
 5703: 
 5704: # Store this
 5705:     unless ($toolsflag) {
 5706:         if (($allowed) && ($env{'form.folderpath'} ne '')) {
 5707:             &Apache::loncommon::store_course_settings($stored_folderpath,
 5708:                                                       {'folderpath' => 'scalar'});
 5709:         }
 5710:         my $folderpath;
 5711:         if ($env{'form.folderpath'}) {
 5712:             $folderpath = $env{'form.folderpath'};
 5713: 	    my (@folders)=split('&',$env{'form.folderpath'});
 5714: 	    $env{'form.foldername'}=&unescape(pop(@folders));
 5715:             if ($env{'form.foldername'} =~ /\:1$/) {
 5716:                 $container = 'page';
 5717:             } else {
 5718:                 $container = 'sequence';
 5719:             }
 5720: 	    $env{'form.folder'}=pop(@folders);
 5721:         } else {
 5722:             if ($env{'form.folder'} eq '' ||
 5723:                 $env{'form.folder'} eq 'supplemental') {
 5724:                 if ($env{'form.folder'} eq 'supplemental') {
 5725:                     $folderpath=&supplemental_base();
 5726:                 } elsif (!$hiddentop) {
 5727:                     $folderpath='default&'.
 5728:                                  &escape(&mt('Main Content').':::::');
 5729:                 }
 5730:             }
 5731:         }
 5732:         $containertag = '<input type="hidden" name="folderpath" value="" />';
 5733:         $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
 5734:         if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 5735:            $showdoc='/'.$1;
 5736:         }
 5737:         if ($showdoc) { # got called in sequence from course
 5738: 	    $allowed=0; 
 5739:         } else {
 5740:             if ($canedit) {
 5741:                 &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
 5742:                 $script=&Apache::lonratedt::editscript('simple');
 5743:             }
 5744:         }
 5745:     }
 5746: 
 5747: # get personal data
 5748:     my $uname=$env{'user.name'};
 5749:     my $udom=$env{'user.domain'};
 5750:     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 5751: 
 5752:     if ($allowed) {
 5753:         if ($toolsflag) {
 5754:             $script .= &inject_data_js();
 5755:             my ($home,$other,%outhash)=&authorhosts();
 5756:             if (!$home && $other) {
 5757:                 my @hosts;
 5758:                 foreach my $aurole (keys(%outhash)) {
 5759:                     unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
 5760:                         push(@hosts,$outhash{$aurole});
 5761:                     }
 5762:                 }
 5763:                 $script .= &dump_switchserver_js(@hosts); 
 5764:             }
 5765:         } else {
 5766:             my $tid = 1;
 5767:             my @tabids;
 5768:             if ($supplementalflag) {
 5769:                 @tabids = ('002','ee2','ff2');
 5770:                 $tid = 2;
 5771:             } else {
 5772:                 @tabids = ('aa1','bb1','cc1','ff1');
 5773:                 unless ($env{'form.folderpath'} =~ /\:1$/) {
 5774:                     unshift(@tabids,'001');
 5775:                     push(@tabids,('dd1','ee1'));
 5776:                 }
 5777:             }
 5778:             my $tabidstr = join("','",@tabids);
 5779:             %ltitools = &Apache::lonnet::get_domain_lti($coursedom,'consumer');
 5780:             my $posslti = keys(%ltitools);
 5781:             my $hostname = $r->hostname();
 5782:             $script .= &editing_js($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
 5783:                                    $canedit,$hostname,\$navmap).
 5784:                        &history_tab_js().
 5785:                        &inject_data_js().
 5786:                        &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr,$tid).
 5787:                        &Apache::lonextresedit::extedit_javascript(\%ltitools);
 5788:             my $onload = "javascript:resize_scrollbox('contentscroll','1','1');";
 5789:             if ($hidden_and_empty ne '') {
 5790:                 my $alert = &mt("Additional privileges required to edit empty and hidden folder: '[_1]'",
 5791:                                 $hidden_and_empty);
 5792:                 $onload .= "javascript:alert('".&js_escape($alert)."');";
 5793:             }
 5794:             $addentries = {
 5795:                             onload => $onload,
 5796:                           };
 5797:         }
 5798:         $script .= &paste_popup_js(); 
 5799:         my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
 5800:                              &mt('Switch server?');
 5801:         
 5802: 
 5803:     }
 5804: # -------------------------------------------------------------------- Body tag
 5805:     $script = '<script type="text/javascript">'."\n"
 5806:               .'// <![CDATA['."\n"
 5807:               .$script."\n"
 5808:               .'// ]]>'."\n"
 5809:               .'</script>'."\n"
 5810:               .'<script type="text/javascript" src="/res/adm/includes/file_upload.js"></script>'."\n";
 5811: 
 5812:     # Breadcrumbs
 5813:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5814: 
 5815:     if ($showdoc) {
 5816:         my $args;
 5817:         if ($supplementalflag) {
 5818:             my $title = &HTML::Entities::encode($env{'form.title'},'\'"<>&');
 5819:             my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype,undef,$title,1);
 5820:             $args = {'bread_crumbs' => $brcrum};
 5821:         } else {
 5822:             $args = {'force_register' => $showdoc};
 5823:         }
 5824:         $r->print(&Apache::loncommon::start_page("$crstype documents",undef,$args));
 5825:     } elsif ($toolsflag) {
 5826:         my ($breadtext,$breadtitle);
 5827:         $breadtext = "$crstype Editor";
 5828:         if ($canedit) {
 5829:             $breadtitle = 'Editing '.$crstype.' Contents';
 5830:         } else {
 5831:             $breadtext .= ' (View-only mode)';
 5832:             $breadtitle = 'Viewing '.$crstype.' Contents';
 5833:         }
 5834:         &Apache::lonhtmlcommon::add_breadcrumb({
 5835:             href=>"/adm/coursedocs",text=>$breadtext});
 5836:         $r->print(&Apache::loncommon::start_page("$crstype Contents", $script)
 5837:                  .&Apache::loncommon::help_open_menu('','',273,'RAT')
 5838:                  .&Apache::lonhtmlcommon::breadcrumbs(
 5839:                      $breadtitle)
 5840:                  );
 5841:     } elsif ($r->uri eq '/adm/supplemental') {
 5842:         unless ($env{'request.role.adv'}) {
 5843:             unless (&Apache::lonnet::has_unhidden_suppfiles($coursenum,$coursedom)) {
 5844:                 $r->internal_redirect('/adm/navmaps');
 5845:                 return OK;
 5846:             }
 5847:         }
 5848:         my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype);
 5849:         $r->print(&Apache::loncommon::start_page("Supplemental $crstype Content",undef,
 5850:                                                 {'bread_crumbs' => $brcrum,}));
 5851:     } else {
 5852:         my ($breadtext,$breadtitle,$helpitem);
 5853:         $breadtext = "$crstype Editor";
 5854:         if ($canedit) {
 5855:             $breadtitle = 'Editing '.$crstype.' Contents';
 5856:             $helpitem = 'Docs_Adding_Course_Doc';
 5857:         } else {
 5858:             $breadtext .= ' (View-only mode)';
 5859:             $breadtitle = 'Viewing '.$crstype.' Contents';
 5860:             $helpitem = 'Docs_Viewing_Course_Doc';
 5861:         }
 5862:         &Apache::lonhtmlcommon::add_breadcrumb({
 5863:             href=>"/adm/coursedocs",text=>$breadtext});
 5864:         $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
 5865:                                                  {'add_entries'    => $addentries}
 5866:                                                 )
 5867:                  .&Apache::loncommon::help_open_menu('','',273,'RAT')
 5868:                  .&Apache::lonhtmlcommon::breadcrumbs(
 5869:                      $breadtitle,
 5870:                      $helpitem)
 5871:         );
 5872:     }
 5873: 
 5874:   my %allfiles = ();
 5875:   my %codebase = ();
 5876:   my ($upload_result,$upload_output,$uploadphase);
 5877:   if ($canedit) {
 5878:       undef($suppchanges);
 5879:       if (($env{'form.uploaddoc.filename'}) &&
 5880: 	  ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 5881:           my $context = $1; 
 5882:           # Process file upload - phase one - upload and parse primary file.
 5883: 	  undef($hadchanges);
 5884:           $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
 5885:                                               \%allfiles,\%codebase,$context,$crstype);
 5886:           undef($navmap);
 5887: 	  if ($hadchanges) {
 5888: 	      &mark_hash_old();
 5889: 	  }
 5890:           if ($suppchanges) {
 5891:               &Apache::lonnet::update_supp_caches($coursedom,$coursenum);
 5892:               undef($suppchanges);
 5893:           }
 5894:           $r->print($upload_output);
 5895:       } elsif ($env{'form.phase'} eq 'upload_embedded') {
 5896:           # Process file upload - phase two - upload embedded objects 
 5897:           $uploadphase = 'check_embedded';
 5898:           my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
 5899:           my $state = &embedded_form_elems($uploadphase,$primaryurl,
 5900:                                            $env{'form.newidx'});
 5901:           my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5902:           my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5903:           my ($destination,$dir_root) = &embedded_destination();
 5904:           my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
 5905:           my $actionurl = '/adm/coursedocs';
 5906:           my ($result,$flag) = 
 5907:               &Apache::loncommon::upload_embedded('coursedoc',$destination,
 5908:                   $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
 5909:                   $actionurl);
 5910:           $r->print($result.&return_to_editor());
 5911:       } elsif ($env{'form.phase'} eq 'check_embedded') {
 5912:           # Process file upload - phase three - modify references in HTML file
 5913:           $uploadphase = 'modified_orightml';
 5914:           my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5915:           my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5916:           my ($destination,$dir_root) = &embedded_destination();
 5917:           my $result = 
 5918:               &Apache::loncommon::modify_html_refs('coursedoc',$destination,
 5919:                                                    $docuname,$docudom,undef,
 5920:                                                    $dir_root);
 5921:           $r->print($result.&return_to_editor());   
 5922:       } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
 5923:           $uploadphase = 'decompress_phase_one';
 5924:           $r->print(&decompression_phase_one().
 5925:                     &return_to_editor());
 5926:       } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
 5927:           $uploadphase = 'decompress_phase_two';
 5928:           $r->print(&decompression_phase_two().
 5929:                     &return_to_editor());
 5930:       }
 5931:   }
 5932: 
 5933:   if ($allowed && $toolsflag) {
 5934:       $r->print(&startContentScreen('tools'));
 5935:       $r->print(&generate_admin_menu($crstype,$canedit));
 5936:       $r->print(&endContentScreen());
 5937:   } elsif ((!$showdoc) && (!$uploadphase)) {
 5938: # -----------------------------------------------------------------------------
 5939:        my %lt=&Apache::lonlocal::texthash(
 5940: 		'copm' => 'All documents out of a published map into this folder',
 5941:                 'upfi' => 'Upload File',
 5942:                 'upld' => 'Upload Content',
 5943:                 'srch' => 'Search',
 5944:                 'impo' => 'Import',
 5945: 		'lnks' => 'Import from Stored Links',
 5946:                 'impm' => 'Import from Assembled Map',
 5947:                 'extr' => 'External Resource',
 5948:                 'extt' => 'External Tool',
 5949:                 'selm' => 'Select Map',
 5950:                 'load' => 'Load Map',
 5951:                 'newf' => 'New Folder',
 5952:                 'newp' => 'New Composite Page',
 5953:                 'syll' => 'Syllabus',
 5954:                 'navc' => 'Table of Contents',
 5955:                 'sipa' => 'Simple Course Page',
 5956:                 'sipr' => 'Simple Problem',
 5957:                 'webp' => 'Blank Web Page (editable)',
 5958:                 'drbx' => 'Drop Box',
 5959:                 'scuf' => 'External Scores (handgrade, upload, clicker)',
 5960:                 'bull' => 'Discussion Board',
 5961:                 'mypi' => 'My Personal Information Page',
 5962:                 'grpo' => 'Group Portfolio',
 5963:                 'rost' => 'Course Roster',
 5964:                 'abou' => 'Personal Information Page for a User',
 5965:                 'imsf' => 'IMS Upload',
 5966:                 'imsl' => 'Upload IMS package',
 5967:                 'cms'  => 'Origin of IMS package',
 5968:                 'se'   => 'Select',
 5969:                 'file' =>  'File',
 5970:                 'title' => 'Title',
 5971:                 'comment' => 'Comment',
 5972:                 'parse' => 'Upload embedded images/multimedia files if HTML file',
 5973:                 'bb5'      => 'Blackboard 5',
 5974:                 'bb6'      => 'Blackboard 6',
 5975:                 'angel5'   => 'ANGEL 5.5',
 5976:                 'webctce4' => 'WebCT 4 Campus Edition',
 5977:                 'er' => 'Editing rights unavailable for your current role.',
 5978:         );
 5979: # -----------------------------------------------------------------------------
 5980:     # Calculate free quota space for a user or course. A javascript function checks
 5981:     # file size to determine if upload should be allowed.
 5982:     my $quotatype = 'unofficial';
 5983:     if ($crstype eq 'Community') {
 5984:         $quotatype = 'community';
 5985:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.coursecode'}) {
 5986:         $quotatype = 'official';
 5987:     } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.textbook'}) {
 5988:         $quotatype = 'textbook';
 5989:     }
 5990:     my $disk_quota = &Apache::loncommon::get_user_quota($coursenum,$coursedom,
 5991:                      'course',$quotatype); # expressed in MB
 5992:     my $current_disk_usage = 0;
 5993:     foreach my $subdir ('docs','supplemental') {
 5994:         $current_disk_usage += &Apache::lonnet::diskusage($coursedom,$coursenum,
 5995:                                "userfiles/$subdir",1); # expressed in kB
 5996:     }
 5997:     my $free_space = 1024 * ((1024 * $disk_quota) - $current_disk_usage);
 5998:     my $usage = $current_disk_usage/1024; # in MB
 5999:     my $quota = $disk_quota;
 6000:     my $percent;
 6001:     if ($disk_quota == 0) {
 6002:         $percent = 100.0;
 6003:     } else {
 6004:         $percent = 100*($usage/$disk_quota);
 6005:     }
 6006:     $usage = sprintf("%.2f",$usage);
 6007:     $quota = sprintf("%.2f",$quota);
 6008:     $percent = sprintf("%.0f",$percent);
 6009:     my $quotainfo = '<p>'.&mt('Currently using [_1] of the [_2] available.',
 6010:                               $percent.'%',$quota.' MB').'</p>';
 6011: 
 6012: 	my $fileupload=(<<FIUP);
 6013:         $quotainfo
 6014: 	$lt{'file'}:<br />
 6015: 	<input type="file" name="uploaddoc" class="LC_flUpload" size="40" $disabled />
 6016:         <input type="hidden" id="LC_free_space" value="$free_space" />
 6017: FIUP
 6018: 
 6019: 	my $checkbox=(<<CHBO);
 6020: 	<!-- <label>$lt{'parse'}?
 6021: 	<input type="checkbox" name="parserflag" />
 6022: 	</label> -->
 6023: 	<label>
 6024: 	<input type="checkbox" name="parserflag" checked="checked" $disabled /> $lt{'parse'}
 6025: 	</label>
 6026: CHBO
 6027:         my $imsfolder = $env{'form.folder'};
 6028:         if ($imsfolder eq '') {
 6029:             $imsfolder = 'default';  
 6030:         }
 6031:         my $imspform=(<<IMSFORM);
 6032:         <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
 6033:         $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
 6034:         <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
 6035:         <fieldset id="uploadimsform" style="display: none;">
 6036:         <legend>$lt{'imsf'}</legend>
 6037:         $fileupload
 6038:         <br />
 6039:         <p>
 6040:         $lt{'cms'}:&nbsp; 
 6041:         <select name="source" $disabled>
 6042:         <option value="-1" selected="selected">$lt{'se'}</option>
 6043:         <option value="bb5">$lt{'bb5'}</option>
 6044:         <option value="bb6">$lt{'bb6'}</option>
 6045:         <option value="angel5">$lt{'angel5'}</option>
 6046:         <option value="webctce4">$lt{'webctce4'}</option>
 6047:         </select>
 6048:         <input type="hidden" name="folder" value="$imsfolder" />
 6049:         </p>
 6050:         <input type="hidden" name="phase" value="one" />
 6051:         <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" $disabled />
 6052:         </fieldset>
 6053:         </form>
 6054: IMSFORM
 6055: 
 6056: 	my $fileuploadform=(<<FUFORM);
 6057:         <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
 6058:         $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
 6059:         <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 6060:         <fieldset id="uploaddocform" style="display: none;">
 6061:         <legend>$lt{'upfi'}</legend>
 6062: 	<input type="hidden" name="active" value="aa" />
 6063: 	$fileupload
 6064: 	<br />
 6065: 	$lt{'title'}:<br />
 6066: 	<input type="text" size="60" name="comment" $disabled />
 6067: 	$pathitem
 6068: 	<input type="hidden" name="cmd" value="upload_default" />
 6069: 	<br />
 6070: 	<span class="LC_nobreak" style="float:left">
 6071: 	$checkbox
 6072: 	</span>
 6073:         <br clear="all" />
 6074:         <input type="submit" value="$lt{'upld'}" $disabled />
 6075:         </fieldset>
 6076:         </form>
 6077: FUFORM
 6078: 
 6079:         my $mapimportjs;
 6080:         if ($canedit) {
 6081:             $mapimportjs = "javascript:openbrowser('mapimportform','importmap','sequence,page','');";
 6082:         } else {
 6083:             $mapimportjs = "javascript:alert('".&js_escape($lt{'er'})."');";
 6084:         }
 6085: 	my $importpubform=(<<SEDFFORM);
 6086:         <a class="LC_menubuttons_link" href="javascript:toggleMap('map');">
 6087:         $lt{'impm'}</a>$help{'Load_Map'}
 6088: 	<form action="/adm/coursedocs" method="post" name="mapimportform">
 6089:         <fieldset id="importmapform" style="display: none;">
 6090:         <legend>$lt{'impm'}</legend>
 6091: 	<input type="hidden" name="active" value="bb" />
 6092:         $lt{'copm'}<br />
 6093:         <span class="LC_nobreak">
 6094:         <input type="text" name="importmap" size="40" value="" 
 6095:         onfocus="this.blur();$mapimportjs" $disabled />
 6096:         &nbsp;<a href="$mapimportjs">$lt{'selm'}</a></span><br />
 6097:         <input type="submit" name="loadmap" value="$lt{'load'}" $disabled />
 6098:         </fieldset>
 6099:         </form>
 6100: 
 6101: SEDFFORM
 6102: 
 6103:         my $fromstoredjs;
 6104:         if ($canedit) {
 6105:             $fromstoredjs = 'open_StoredLinks_Import()';
 6106:         } else {
 6107:             $fromstoredjs = "alert('".&js_escape($lt{'er'})."')";
 6108:         }
 6109: 
 6110: 	my @importpubforma = (
 6111: 	{ '<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>" },
 6112: 	{ '<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'}" },
 6113: 	{ '<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>' },
 6114:         { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/sequence.png" alt="'.$lt{impm}.'" onclick="javascript:toggleMap(\'map\');" />' => $importpubform }
 6115: 	);
 6116: 	$importpubform = &create_form_ul(&create_list_elements(@importpubforma));
 6117:         my $extresourcesform =
 6118:             &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
 6119:                                                  $help{'Adding_External_Resource'},
 6120:                                                  undef,undef,undef,undef,undef,undef,$disabled);
 6121:         my $exttoolform =
 6122:             &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
 6123:                                                  $help{'Adding_External_Tool'},undef,
 6124:                                                  undef,'tool',$coursedom,$coursenum,
 6125:                                                  \%ltitools,$disabled);
 6126:     if ($allowed) {
 6127:         my $folder = $env{'form.folder'};
 6128:         if ($folder eq '') {
 6129:             $folder='default';
 6130:         }
 6131:         if ($canedit) {
 6132: 	    my $output = &update_paste_buffer($coursenum,$coursedom,$folder);
 6133:             if ($output) {
 6134:                 $r->print($output);
 6135:             }
 6136:         }
 6137: 	$r->print(<<HIDDENFORM);
 6138: 	<form name="renameform" method="post" action="/adm/coursedocs">
 6139:    <input type="hidden" name="title" />
 6140:    <input type="hidden" name="cmd" />
 6141:    <input type="hidden" name="markcopy" />
 6142:    <input type="hidden" name="copyfolder" />
 6143:    $containertag
 6144:  </form>
 6145: 
 6146: HIDDENFORM
 6147:         $r->print(&makesimpleeditform($pathitem)."\n".
 6148:                   &makedocslogform($pathitem."\n".
 6149:                                    '<input type="hidden" name="folder" value="'.
 6150:                                    $env{'form.folder'}.'" />'."\n"));
 6151:     }
 6152: 
 6153: # Generate the tabs
 6154:     my ($mode,$needs_end);
 6155:     if (($supplementalflag) && (!$allowed)) {
 6156:         my @folders = split('&',$env{'form.folderpath'});
 6157:         unless (@folders > 2) {
 6158:             &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
 6159:             $needs_end = 1;
 6160:         }
 6161:     } else {
 6162:         $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
 6163:         $needs_end = 1;
 6164:     }
 6165: 
 6166: #
 6167: 
 6168:     my $savefolderpath;
 6169:     my $hostname = $r->hostname();
 6170: 
 6171:     if ($allowed) {
 6172:        my $folder=$env{'form.folder'};
 6173:        if ((($folder eq '') && (!$hiddentop)) || ($supplementalflag)) {
 6174:            $folder='default';
 6175: 	   $savefolderpath = $env{'form.folderpath'};
 6176: 	   $env{'form.folderpath'}='default&'.&escape(&mt('Main Content'));
 6177:            $pathitem = '<input type="hidden" name="folderpath" value="'.
 6178: 	       &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 6179:        }
 6180:        my $postexec='';
 6181:        if ($folder eq 'default') {
 6182:            $r->print('<script type="text/javascript">'."\n"
 6183:                     .'// <![CDATA['."\n"
 6184:                     .'this.window.name="loncapaclient";'."\n"
 6185:                     .'// ]]>'."\n"
 6186:                     .'</script>'."\n"
 6187:        );
 6188:        } else {
 6189:            #$postexec='self.close();';
 6190:        }
 6191:        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.sequence';
 6192:        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.page';
 6193: 	my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 6194: 
 6195: 	my $newnavform=(<<NNFORM);
 6196: 	<form action="/adm/coursedocs" method="post" name="newnav">
 6197: 	<input type="hidden" name="active" value="ee" />
 6198: 	$pathitem
 6199: 	<input type="hidden" name="importdetail" 
 6200: 	value="$lt{'navc'}=/adm/navmaps" />
 6201: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newnav);">$lt{'navc'}</a>
 6202: 	$help{'Navigate_Content'}
 6203: 	</form>
 6204: NNFORM
 6205: 	my $newsmppageform=(<<NSPFORM);
 6206: 	<form action="/adm/coursedocs" method="post" name="newsmppg">
 6207: 	<input type="hidden" name="active" value="ee" />
 6208: 	$pathitem
 6209: 	<input type="hidden" name="importdetail" value="" />
 6210: 	<a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
 6211: 	$help{'Simple Page'}
 6212: 	</form>
 6213: NSPFORM
 6214: 
 6215: 	my $newsmpproblemform=(<<NSPROBFORM);
 6216: 	<form action="/adm/coursedocs" method="post" name="newsmpproblem">
 6217: 	<input type="hidden" name="active" value="cc" />
 6218: 	$pathitem
 6219: 	<input type="hidden" name="importdetail" value="" />
 6220: 	<a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
 6221: 	$help{'Simple_Problem'}
 6222: 	</form>
 6223: 
 6224: NSPROBFORM
 6225: 
 6226: 	my $newdropboxform=(<<NDBFORM);
 6227: 	<form action="/adm/coursedocs" method="post" name="newdropbox">
 6228: 	<input type="hidden" name="active" value="cc" />
 6229: 	$pathitem
 6230: 	<input type="hidden" name="importdetail" value="" />
 6231: 	<a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
 6232:         $help{'Dropbox'}
 6233: 	</form>
 6234: NDBFORM
 6235: 
 6236: 	my $newexuploadform=(<<NEXUFORM);
 6237: 	<form action="/adm/coursedocs" method="post" name="newexamupload">
 6238: 	<input type="hidden" name="active" value="cc" />
 6239: 	$pathitem
 6240: 	<input type="hidden" name="importdetail" value="" />
 6241: 	<a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
 6242: 	$help{'Score_Upload_Form'}
 6243: 	</form>
 6244: NEXUFORM
 6245: 
 6246: 	my $newbulform=(<<NBFORM);
 6247: 	<form action="/adm/coursedocs" method="post" name="newbul">
 6248: 	<input type="hidden" name="active" value="dd" />
 6249: 	$pathitem
 6250: 	<input type="hidden" name="importdetail" value="" />
 6251: 	<a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
 6252: 	$help{'Bulletin Board'}
 6253: 	</form>
 6254: NBFORM
 6255: 
 6256: 	my $newaboutmeform=(<<NAMFORM);
 6257: 	<form action="/adm/coursedocs" method="post" name="newaboutme">
 6258: 	<input type="hidden" name="active" value="dd" />
 6259: 	$pathitem
 6260: 	<input type="hidden" name="importdetail" 
 6261: 	value="$plainname=/adm/$udom/$uname/aboutme" />
 6262: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newaboutme);">$lt{'mypi'}</a>
 6263: 	$help{'My Personal Information Page'}
 6264: 	</form>
 6265: NAMFORM
 6266: 
 6267: 	my $newaboutsomeoneform=(<<NASOFORM);
 6268: 	<form action="/adm/coursedocs" method="post" name="newaboutsomeone">
 6269: 	<input type="hidden" name="active" value="dd" />
 6270: 	$pathitem
 6271: 	<input type="hidden" name="importdetail" value="" />
 6272: 	<a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
 6273: 	</form>
 6274: NASOFORM
 6275: 
 6276: 	my $newrosterform=(<<NROSTFORM);
 6277: 	<form action="/adm/coursedocs" method="post" name="newroster">
 6278: 	<input type="hidden" name="active" value="dd" />
 6279: 	$pathitem
 6280: 	<input type="hidden" name="importdetail" 
 6281: 	value="$lt{'rost'}=/adm/viewclasslist" />
 6282: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newroster);">$lt{'rost'}</a>
 6283: 	$help{'Course_Roster'}
 6284: 	</form>
 6285: NROSTFORM
 6286: 
 6287:         my $newwebpage;
 6288:         if ($folder =~ /^default_?(\d*)$/) {
 6289:             $newwebpage = "/uploaded/$coursedom/$coursenum/docs/";
 6290:             if ($1) {
 6291:                 $newwebpage .= $1;
 6292:             } else {
 6293:                 $newwebpage .= 'default';
 6294:             }
 6295:             $newwebpage .= '/new.html';
 6296:         }
 6297:         my $newwebpageform =(<<NWEBFORM);
 6298:         <form action="/adm/coursedocs" method="post" name="newwebpage">
 6299:         <input type="hidden" name="active" value="ee" />
 6300:         $pathitem
 6301:         <input type="hidden" name="importdetail" value="$newwebpage" />
 6302:         <a class="LC_menubuttons_link" href="javascript:makewebpage();">$lt{'webp'}</a>
 6303:         $help{'Web_Page'}
 6304:         </form>
 6305: NWEBFORM
 6306:  
 6307: 
 6308: my $specialdocumentsform;
 6309: my @specialdocumentsforma;
 6310: my $gradingform;
 6311: my @gradingforma;
 6312: my $communityform;
 6313: my @communityforma;
 6314: my $newfolderform;
 6315: my $newfolderb;
 6316: 
 6317: 	my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 6318: 	
 6319: 	my $newpageform=(<<NPFORM);
 6320: 	<form action="/adm/coursedocs" method="post" name="newpage">
 6321: 	<input type="hidden" name="folderpath" value="$path" />
 6322: 	<input type="hidden" name="importdetail" value="" />
 6323: 	<input type="hidden" name="active" value="ee" />
 6324: 	<a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
 6325: 	$help{'Adding_Pages'}
 6326: 	</form>
 6327: NPFORM
 6328: 
 6329: 
 6330: 	$newfolderform=(<<NFFORM);
 6331: 	<form action="/adm/coursedocs" method="post" name="newfolder">
 6332: 	$pathitem
 6333: 	<input type="hidden" name="importdetail" value="" />
 6334: 	<input type="hidden" name="active" value="" />
 6335: 	<a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
 6336: 	</form>
 6337: NFFORM
 6338: 
 6339: 	my $newsylform=(<<NSYLFORM);
 6340: 	<form action="/adm/coursedocs" method="post" name="newsyl">
 6341: 	<input type="hidden" name="active" value="ee" />
 6342: 	$pathitem
 6343: 	<input type="hidden" name="importdetail" 
 6344: 	value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
 6345: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newsyl);">$lt{'syll'}</a>
 6346: 	$help{'Syllabus'}
 6347: 
 6348: 	</form>
 6349: NSYLFORM
 6350: 
 6351: 	my $newgroupfileform=(<<NGFFORM);
 6352: 	<form action="/adm/coursedocs" method="post" name="newgroupfiles">
 6353: 	<input type="hidden" name="active" value="dd" />
 6354: 	$pathitem
 6355: 	<input type="hidden" name="importdetail"
 6356: 	value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
 6357: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.newgroupfiles);">$lt{'grpo'}</a>
 6358: 	$help{'Group Portfolio'}
 6359: 	</form>
 6360: NGFFORM
 6361:         if ($container eq 'page') {
 6362:             @specialdocumentsforma=(
 6363:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage();" />'=>$newwebpageform},
 6364:             );
 6365:         } else {
 6366: 	    @specialdocumentsforma=(
 6367: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
 6368: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="javascript:makenew(document.newsyl);" />'=>$newsylform},
 6369: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="javascript:makenew(document.newnav);" />'=>$newnavform},
 6370:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
 6371:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage();" />'=>$newwebpageform},
 6372:             );
 6373:         }
 6374:         $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
 6375: 
 6376: 
 6377:         my @importdoc = (
 6378:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform}
 6379:         );
 6380:         if (keys(%ltitools)) {
 6381:             push(@importdoc,
 6382:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="toggleUpload(\'tool\');" />'=>$exttoolform},
 6383:         );
 6384:         }
 6385:         unless ($container eq 'page') {
 6386:             push(@importdoc,
 6387:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform}
 6388:             );
 6389:         }
 6390:         push(@importdoc,
 6391:             {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'doc\');" />'=>$fileuploadform}
 6392:         );
 6393:         $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc));
 6394: 
 6395:         @gradingforma=(
 6396:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
 6397:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
 6398:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
 6399: 
 6400:         );
 6401:         $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
 6402: 
 6403:         @communityforma=(
 6404:        {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
 6405:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
 6406:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
 6407:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="javascript:makenew(document.newroster);" />'=>$newrosterform},
 6408:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="javascript:makenew(document.newgroupfiles);" />'=>$newgroupfileform},
 6409:         );
 6410:         $communityform = &create_form_ul(&create_list_elements(@communityforma));
 6411: 
 6412: my %orderhash = (
 6413:                 'aa' => ['Upload',$fileuploadform],
 6414:                 'bb' => ['Import',$importpubform],
 6415:                 'cc' => ['Grading',$gradingform],
 6416:                 'ee' => ['Other',$specialdocumentsform],
 6417:                 );
 6418: unless ($container eq 'page') {
 6419:     $orderhash{'00'} = ['Newfolder',$newfolderform];
 6420:     $orderhash{'dd'} = ['Collaboration',$communityform];
 6421: }
 6422: 
 6423:  $hadchanges=0;
 6424:        unless (($supplementalflag || $toolsflag)) {
 6425:           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 6426:                               $supplementalflag,\%orderhash,$iconpath,$pathitem,
 6427:                               \%ltitools,$canedit,$hostname,\$navmap,$hiddentop);
 6428:           undef($navmap);
 6429:           if ($error) {
 6430:              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 6431:           }
 6432:           if ($hadchanges) {
 6433:              unless (&is_hash_old()) {
 6434:                  &mark_hash_old();
 6435:              }
 6436:           }
 6437: 
 6438:           &changewarning($r,'');
 6439:         }
 6440:     }
 6441: 
 6442: # Supplemental documents start here
 6443: 
 6444:        my $folder=$env{'form.folder'};
 6445:        unless ($supplementalflag) {
 6446: 	   $folder='supplemental';
 6447:        }
 6448:        if (($folder eq 'supplemental') &&
 6449: 	   (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
 6450:           $env{'form.folderpath'} = &supplemental_base();
 6451:        } elsif ($allowed) {
 6452: 	  $env{'form.folderpath'} = $savefolderpath;
 6453:        }
 6454:        $pathitem = '<input type="hidden" name="folderpath" value="'.
 6455:                     &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 6456:        if ($allowed) {
 6457: 	   my $folderseq=
 6458: 	       '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_new.sequence';
 6459: 
 6460: 	my $supupdocform=(<<SUPDOCFORM);
 6461:         <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppdoc');">
 6462:         $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
 6463: 	<form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
 6464:         <fieldset id="uploadsuppdocform" style="display: none;">
 6465:         <legend>$lt{'upfi'}</legend>
 6466: 	<input type="hidden" name="active" value="ee" />	
 6467: 	$fileupload
 6468: 	<br />
 6469: 	<br />
 6470: 	<span class="LC_nobreak">
 6471: 	$checkbox
 6472: 	</span>
 6473: 	<br /><br />
 6474: 	$lt{'comment'}:<br />
 6475: 	<textarea cols="50" rows="4" name="comment"></textarea>
 6476: 	<br />
 6477: 	$pathitem
 6478: 	<input type="hidden" name="cmd" value="upload_supplemental" />
 6479:         <input type='submit' value="$lt{'upld'}" />
 6480:         </form>
 6481: SUPDOCFORM
 6482: 
 6483: 	my $supnewfolderform=(<<SNFFORM);
 6484: 	<form action="/adm/coursedocs" method="post" name="supnewfolder">
 6485: 	<input type="hidden" name="active" value="" />
 6486:         $pathitem
 6487: 	<input type="hidden" name="importdetail" value="" />
 6488: 	<a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
 6489: 	$help{'Adding_Folders'}
 6490: 	</form>
 6491: SNFFORM
 6492: 	
 6493:         my $supextform =
 6494:             &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
 6495:                                                  $help{'Adding_External_Resource'},
 6496:                                                  undef,undef,$disabled);
 6497:         my $supexttoolform =
 6498:             &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
 6499:                                                  $help{'Adding_External_Tool'},
 6500:                                                  undef,undef,'tool',$coursedom,
 6501:                                                  $coursenum,\%ltitools,$disabled);
 6502: 
 6503: 	my $supnewsylform=(<<SNSFORM);
 6504: 	<form action="/adm/coursedocs" method="post" name="supnewsyl">
 6505: 	<input type="hidden" name="active" value="ff" />
 6506:         $pathitem
 6507: 	<input type="hidden" name="importdetail" 
 6508: 	value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
 6509: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.supnewsyl);">$lt{'syll'}</a>
 6510: 	$help{'Syllabus'}
 6511: 	</form>
 6512: SNSFORM
 6513: 
 6514: 	my $supnewaboutmeform=(<<SNAMFORM);
 6515: 	<form action="/adm/coursedocs" method="post" name="supnewaboutme">
 6516: 	<input type="hidden" name="active" value="ff" />
 6517:         $pathitem
 6518: 	<input type="hidden" name="importdetail" 
 6519: 	value="$plainname=/adm/$udom/$uname/aboutme" />
 6520: 	<a class="LC_menubuttons_link" href="javascript:makenew(document.supnewaboutme);">$lt{'mypi'}</a>
 6521: 	$help{'My Personal Information Page'}
 6522: 	</form>
 6523: SNAMFORM
 6524: 
 6525:         my $supwebpage;
 6526:         if ($folder =~ /^supplemental_?(\d*)$/) {
 6527:             $supwebpage = "/uploaded/$coursedom/$coursenum/supplemental/";
 6528:             if ($1) {
 6529:                 $supwebpage .= $1;
 6530:             } else {
 6531:                 $supwebpage .= 'default';
 6532:             }
 6533:             $supwebpage .= '/new.html';
 6534:         }
 6535:         my $supwebpageform =(<<SWEBFORM);
 6536:         <form action="/adm/coursedocs" method="post" name="supwebpage">
 6537:         <input type="hidden" name="active" value="cc" />
 6538:         $pathitem
 6539:         <input type="hidden" name="importdetail" value="$supwebpage" />
 6540:         <a class="LC_menubuttons_link" href="javascript:makewebpage('supp');">$lt{'webp'}</a>
 6541:         $help{'Web_Page'}
 6542:         </form>
 6543: SWEBFORM
 6544: 
 6545: 
 6546: my @specialdocs = (
 6547: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="javascript:makenew(document.supnewsyl);" />'
 6548:             =>$supnewsylform},
 6549: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makenew(document.supnewaboutme);" />'
 6550:             =>$supnewaboutmeform},
 6551:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage('."'supp'".');" />'=>$supwebpageform},
 6552: 
 6553: 		);
 6554: my @supimportdoc = (
 6555: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:toggleUpload(\'suppext\')" />'
 6556:             =>$supextform});
 6557:         if (keys(%ltitools)) {
 6558:             push(@supimportdoc,
 6559:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/exttool.png" alt="'.$lt{extt}.'" onclick="javascript:toggleUpload(\'supptool\')" />'
 6560:             =>$supexttoolform});
 6561:         }
 6562:         push(@supimportdoc,
 6563:                 {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
 6564:             =>$supupdocform},
 6565:         );
 6566: 
 6567: $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
 6568: my %suporderhash = (
 6569: 		'00' => ['Supnewfolder', $supnewfolderform],
 6570:                 'ee' => ['Upload',$supupdocform],
 6571:                 'ff' => ['Other',&create_form_ul(&create_list_elements(@specialdocs))]
 6572:                 );
 6573:         if ($supplementalflag) {
 6574:             $suppchanges = 0;
 6575:             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 6576:                                 $supplementalflag,\%suporderhash,$iconpath,$pathitem,
 6577:                                 \%ltitools,$canedit,$hostname);
 6578:             if ($error) {
 6579:                 $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 6580:             }
 6581:             if ($suppchanges) {
 6582:                 &Apache::lonnet::update_supp_caches($coursedom,$coursenum);
 6583:                 undef($suppchanges);
 6584:             }
 6585:         }
 6586:     } elsif ($supplementalflag) {
 6587:         my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 6588:                             $supplementalflag,'',$iconpath,$pathitem,'',$canedit,
 6589:                             $hostname);
 6590:         if ($error) {
 6591:             $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 6592:         }
 6593:     }
 6594: 
 6595:     if ($needs_end) {
 6596:         $r->print(&endContentScreen());
 6597:     }
 6598: 
 6599:     if ($allowed) {
 6600: 	$r->print('
 6601: <form method="post" name="extimport" action="/adm/coursedocs">
 6602:   <input type="hidden" name="title" />
 6603:   <input type="hidden" name="url" />
 6604:   <input type="hidden" name="useform" />
 6605:   <input type="hidden" name="residx" />
 6606: </form>');
 6607:     }
 6608:   } elsif ($showdoc) {
 6609: # -------------------------------------------------------- This is showdoc mode
 6610:       $r->print("<h1>".&mt('Uploaded Document').' - '.
 6611: 		&Apache::lonnet::gettitle($r->uri).'</h1><p class="LC_warning">'.
 6612: &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
 6613:                 &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
 6614:   }
 6615:  }
 6616:  $r->print(&Apache::loncommon::end_page());
 6617:  return OK;
 6618: }
 6619: 
 6620: sub embedded_form_elems {
 6621:     my ($phase,$primaryurl,$newidx) = @_;
 6622:     my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 6623:     $newidx =~s /\D+//g;
 6624:     return <<STATE;
 6625:     <input type="hidden" name="folderpath" value="$folderpath" />
 6626:     <input type="hidden" name="cmd" value="upload_embedded" />
 6627:     <input type="hidden" name="newidx" value="$newidx" />
 6628:     <input type="hidden" name="phase" value="$phase" />
 6629:     <input type="hidden" name="primaryurl" value="$primaryurl" />
 6630: STATE
 6631: }
 6632: 
 6633: sub embedded_destination {
 6634:     my $folder=$env{'form.folder'};
 6635:     my $destination = 'docs/';
 6636:     if ($folder =~ /^supplemental/) {
 6637:         $destination = 'supplemental/';
 6638:     }
 6639:     if (($folder eq 'default') || ($folder eq 'supplemental')) {
 6640:         $destination .= 'default/';
 6641:     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 6642:         $destination .=  $2.'/';
 6643:     }
 6644:     my $newidx = $env{'form.newidx'};
 6645:     $newidx =~s /\D+//g;
 6646:     if ($newidx) {
 6647:         $destination .= $newidx;
 6648:     }
 6649:     my $dir_root = '/userfiles';
 6650:     return ($destination,$dir_root);
 6651: }
 6652: 
 6653: sub return_to_editor {
 6654:     my $actionurl = '/adm/coursedocs';
 6655:     return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
 6656:            '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
 6657:            '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
 6658:            '</a></p>';
 6659: }
 6660: 
 6661: sub decompression_info {
 6662:     my ($destination,$dir_root) = &embedded_destination();
 6663:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6664:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6665:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6666:     my $container='sequence';
 6667:     my ($pathitem,$hiddenelem);
 6668:     my @hiddens = ('newidx','comment','position','folderpath','archiveurl');
 6669:     if ($env{'form.folderpath'} =~ /\:1$/) {
 6670:         $container='page';
 6671:     }
 6672:     unshift(@hiddens,$pathitem);
 6673:     foreach my $item (@hiddens) {
 6674:         if ($item eq 'newidx') {
 6675:             next if ($env{'form.'.$item} =~ /\D/);
 6676:         }
 6677:         if ($env{'form.'.$item}) {
 6678:             $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
 6679:                            &HTML::Entities::encode($env{'form.'.$item},'<>&"').'" />'."\n";
 6680:         }
 6681:     }
 6682:     return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
 6683:             $hiddenelem);
 6684: }
 6685: 
 6686: sub decompression_phase_one {
 6687:     my ($dir,$file,$warning,$error,$output);
 6688:     my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
 6689:         &decompression_info();
 6690:     if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/\E(?:docs|supplemental)/(?:default|\d+).*/([^/]+)$}) {
 6691:         $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
 6692:     } else {
 6693:         my $file = $1;
 6694:         $output = 
 6695:             &Apache::loncommon::process_decompression($docudom,$docuname,$file,
 6696:                                                       $destination,$dir_root,
 6697:                                                       $hiddenelem);
 6698:         if ($env{'form.autoextract_camtasia'}) {
 6699:             $output .= &remove_archive($docudom,$docuname,$container);
 6700:         }
 6701:     }
 6702:     if ($error) {
 6703:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
 6704:                    $error.'</p>'."\n";
 6705:     }
 6706:     if ($warning) {
 6707:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
 6708:     }
 6709:     return $output;
 6710: }
 6711: 
 6712: sub decompression_phase_two {
 6713:     my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
 6714:         &decompression_info();
 6715:     my $output;
 6716:     if ($env{'form.archivedelete'}) {
 6717:         $output = &remove_archive($docudom,$docuname,$container);
 6718:     }
 6719:     $output .= 
 6720:         &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
 6721:                                                     $destination,$dir_root,$hiddenelem);
 6722:     return $output;
 6723: }
 6724: 
 6725: sub remove_archive {
 6726:     my ($docudom,$docuname,$container) = @_;
 6727:     my $map = $env{'form.folder'}.'.'.$container;
 6728:     my ($output,$delwarning,$delresult,$url);
 6729:     my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
 6730:     if ($fatal) {
 6731:         if ($container eq 'page') {
 6732:             $delwarning = &mt('An error occurred retrieving the contents of the current page.');
 6733:         } else {
 6734:             $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
 6735:         }
 6736:         $delwarning .= ' '.&mt('As a result the archive file has not been removed.');
 6737:     } else {
 6738:         my $currcmd = $env{'form.cmd'};
 6739:         my $position = $env{'form.position'};
 6740:         my $archiveidx = $position;
 6741:         if ($position > 0) {
 6742:             if (($env{'form.autoextract_camtasia'}) && (scalar(@LONCAPA::map::order) == 2)) {
 6743:                 $archiveidx = $position-1;
 6744:             }
 6745:             $env{'form.cmd'} = 'remove_'.$archiveidx;
 6746:             my ($title,$url,@rrest) =
 6747:                 split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$archiveidx]]);
 6748:             if ($url eq $env{'form.archiveurl'}) {
 6749:                 if (&handle_edit_cmd($docuname,$docudom)) {
 6750:                     ($errtext,$fatal) = &storemap($docuname,$docudom,$map,1);
 6751:                     if ($suppchanges) {
 6752:                         &Apache::lonnet::update_supp_caches($docudom,$docuname);
 6753:                         undef($suppchanges);
 6754:                     }
 6755:                     if ($fatal) {
 6756:                         if ($container eq 'page') {
 6757:                             $delwarning = &mt('An error occurred updating the contents of the current page.');
 6758:                         } else {
 6759:                             $delwarning = &mt('An error occurred updating the contents of the current folder.');
 6760:                         }
 6761:                     } else {
 6762:                         $delresult = &mt('Archive file removed.');
 6763:                     }
 6764:                 }
 6765:             } else {
 6766:                 $delwarning .=  &mt('Archive file had unexpected item number in folder.').
 6767:                                 ' '.&mt('As a result the archive file has not been removed.');
 6768:             }
 6769:         }
 6770:         $env{'form.cmd'} = $currcmd;
 6771:     }
 6772:     if ($delwarning) {
 6773:         $output = '<p class="LC_warning">'.
 6774:                    $delwarning.
 6775:                    '</p>';
 6776:     }
 6777:     if ($delresult) {
 6778:         $output .= '<p class="LC_info">'.
 6779:                    $delresult.
 6780:                    '</p>';
 6781:     }
 6782:     return $output;
 6783: }
 6784: 
 6785: sub generate_admin_menu {
 6786:     my ($crstype,$canedit) = @_;
 6787:     my $lc_crstype = lc($crstype);
 6788:     my ($home,$other,%outhash)=&authorhosts();
 6789:     my %lt= ( # do not translate here
 6790:                                          'vc'   => 'Verify Content',
 6791:                                          'cv'   => 'Check/Set Resource Versions',
 6792:                                          'ls'   => 'List Resource Identifiers',
 6793:                                          'ct'   => 'Display/Set Shortened URLs for Deep-linking',
 6794:                                          'imse' => 'Export contents to IMS Archive',
 6795:                                          'dcd'  => "Copy $crstype Content to Authoring Space",
 6796:             );
 6797:     my ($candump,$dumpurl);
 6798:     if ($home + $other > 0) {
 6799:         $candump = 'F';
 6800:         if ($home) {
 6801:             $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
 6802:         } else {
 6803:             my @hosts;
 6804:             foreach my $aurole (keys(%outhash)) {
 6805:                 unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
 6806:                     push(@hosts,$outhash{$aurole});
 6807:                 }
 6808:             }
 6809:             if (@hosts == 1) {
 6810:                 my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
 6811:                                '&amp;role='.
 6812:                                &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
 6813:                                &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
 6814:                 $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
 6815:             } else {
 6816:                 $dumpurl = "javascript:choose_switchserver_window()";
 6817:             }
 6818:         }
 6819:     }
 6820:     my @menu=
 6821:         ({  categorytitle=>'Administration',
 6822:             items =>[
 6823:                 {   linktext   => $lt{'vc'},
 6824:                     url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
 6825:                     permission => 'F',
 6826:                     help       => 'Docs_Verify_Content',
 6827:                     icon       => 'verify.png',
 6828:                     linktitle  => 'Verify contents can be retrieved/rendered',
 6829:                 },
 6830:                 {   linktext => $lt{'cv'},
 6831:                     url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
 6832:                     permission => 'F',
 6833:                     help       => 'Docs_Check_Resource_Versions',
 6834:                     icon       => 'resversion.png',
 6835:                     linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
 6836:                 },
 6837:                 {   linktext   => $lt{'ls'},
 6838:                     url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
 6839:                     permission => 'F',
 6840:                     #help => '',
 6841:                     icon       => 'symbs.png',
 6842:                     linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
 6843:                 },
 6844:                 {   linktext   => $lt{'ct'},
 6845:                     url        => "javascript:injectData(document.courseverify,'dummy','shorturls','$lt{'ct'}')",
 6846:                     permission => 'F',
 6847:                     help       => 'Docs_Short_URLs',
 6848:                     icon       => 'shorturls.png',
 6849:                     linktitle  => "Set shortened URLs for a resource or folder in your $lc_crstype for use in deep-linking"
 6850:                 },
 6851:                 ]
 6852:         });
 6853:     if ($canedit) {
 6854:         push(@menu,
 6855:         {   categorytitle=>'Export',
 6856:             items =>[
 6857:                 {   linktext   => $lt{'imse'},
 6858:                     url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
 6859:                     permission => 'F',
 6860:                     help       => 'Docs_Export_Course_Docs',
 6861:                     icon       => 'imsexport.png',
 6862:                     linktitle  => $lt{'imse'},
 6863:                 },
 6864:                 {   linktext   => $lt{'dcd'},
 6865:                     url        => $dumpurl,
 6866:                     permission => $candump,
 6867:                     help       => 'Docs_Dump_Course_Docs',
 6868:                     icon       => 'dump.png',
 6869:                     linktitle  => $lt{'dcd'},
 6870:                 },
 6871:                 ]
 6872:         });
 6873:     }
 6874:     return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
 6875:            '<input type="hidden" id="dummy" />'."\n".
 6876:            &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
 6877:            '</form>';
 6878: }
 6879: 
 6880: sub generate_edit_table {
 6881:     my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile,
 6882:         $need_save,$copyfolder,$canedit) = @_;
 6883:     return unless(ref($orderhash_ref) eq 'HASH');
 6884:     my %orderhash = %{$orderhash_ref};
 6885:     my ($form, $activetab, $active, $disabled);
 6886:     if (($env{'form.active'} ne '') && ($env{'form.active'} ne '00')) {
 6887:         $activetab = $env{'form.active'};
 6888:     }
 6889:     unless ($canedit) {
 6890:         $disabled = ' disabled="disabled"';
 6891:     }
 6892:     my $backicon = $iconpath.'clickhere.gif';
 6893:     my $backtext = &mt('Exit Editor');
 6894:     $form = '<div class="LC_Box" style="margin:0;">'.
 6895:             '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
 6896:             '<li class="goback">'.
 6897:             '<a href="javascript:toContents('."'$jumpto'".');">'.
 6898:             '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
 6899:             '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n".
 6900:             '<li>'.
 6901:             '<a href="javascript:groupopen('."'$readfile'".',1);">'.
 6902:             &mt('Undo Delete').'</a></li>'."\n";
 6903:     if ($env{'form.docslog'}) {
 6904:         $form .= '<li class="active">';
 6905:     } else {
 6906:         $form .= '<li>';
 6907:     }
 6908:     $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
 6909:              &mt('History').'</a></li>'."\n";
 6910:     if ($env{'form.docslog'}) {
 6911:         $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
 6912:                  &mt('Edit').'</a></li>'."\n";
 6913:     }
 6914:     foreach my $name (reverse(sort(keys(%orderhash)))) {
 6915:         if($name ne '00'){
 6916:             if($activetab eq '' || $activetab ne $name){
 6917:                $active = '';
 6918:             }elsif($activetab eq $name){
 6919:                $active = 'class="active"';
 6920:             }
 6921:             $form .= '<li style="float:right" '.$active
 6922:                 .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
 6923:         } else {
 6924: 	    $form .= '<li style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
 6925: 
 6926: 	}
 6927:     }
 6928:     $form .= '</ul>'."\n";
 6929:     $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
 6930: 
 6931:     if ($to_show ne '') {
 6932:         my $saveform;
 6933:         if ($need_save) {
 6934:             my $button = &mt('Make changes');
 6935:             my $path;
 6936:             if ($env{'form.folderpath'}) {
 6937:                 $path =
 6938:                     &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 6939:             }
 6940:             $saveform = <<"END";
 6941: <div id="multisave" style="display:none; clear:both;" >
 6942: <form name="saveactions" method="post" action="/adm/coursedocs" onsubmit="return checkSubmits();">
 6943: <input type="hidden" name="folderpath" value="$path" />
 6944: <input type="hidden" name="symb" value="$env{'form.symb'}" />
 6945: <input type="hidden" name="allhiddenresource" value="" />
 6946: <input type="hidden" name="allencrypturl" value="" />
 6947: <input type="hidden" name="allrandompick" value="" />
 6948: <input type="hidden" name="allrandomorder" value="" />
 6949: <input type="hidden" name="changeparms" value="" />
 6950: <input type="hidden" name="multiremove" value="" />
 6951: <input type="hidden" name="multicut" value="" />
 6952: <input type="hidden" name="multicopy" value="" />
 6953: <input type="hidden" name="multichange" value="" />
 6954: <input type="hidden" name="copyfolder" value="$copyfolder" />
 6955: <input type="submit" name="savemultiples" value="$button" $disabled />
 6956: </form>
 6957: </div>
 6958: END
 6959:         }
 6960:         $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'.$saveform."\n";
 6961:     }
 6962:     foreach my $field (keys(%orderhash)){
 6963: 	if($field ne '00'){
 6964:             if($activetab eq '' || $activetab ne $field){
 6965:                 $active = 'style="display: none;float:left"';
 6966:             }elsif($activetab eq $field){
 6967:                 $active = 'style="display:block;float:left"';
 6968:             }
 6969:             $form .= '<div id="'.$field.$tid.'"'
 6970:                     .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
 6971:                     .'</div>'."\n";
 6972:         }
 6973:     }
 6974:     unless ($env{'form.docslog'}) {
 6975:         $form .= '</div></div>'."\n";
 6976:     }
 6977:     return $form;
 6978: }
 6979: 
 6980: sub editing_js {
 6981:     my ($udom,$uname,$supplementalflag,$coursedom,$coursenum,$posslti,
 6982:         $canedit,$hostname,$navmapref) = @_;
 6983:     my %js_lt = &Apache::lonlocal::texthash(
 6984:                                           p_mnf => 'Name of New Folder',
 6985:                                           t_mnf => 'New Folder',
 6986:                                           p_mnp => 'Name of New Page',
 6987:                                           t_mnp => 'New Page',
 6988:                                           p_mxu => 'Title for the External Score',
 6989:                                           p_msp => 'Name of Simple Course Page',
 6990:                                           p_msb => 'Title for the Problem',
 6991:                                           p_mdb => 'Title for the Drop Box',
 6992:                                           p_mbb => 'Title for the Discussion Board',
 6993:                                           p_mwp => 'Title for Web Page',
 6994:                                           p_mab => "Enter user:domain for User's Personal Information Page",
 6995:                                           p_mab2 => 'Personal Information Page of ',
 6996:                                           p_mab_alrt1 => 'Not a valid user:domain',
 6997:                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
 6998:                                           p_chn => 'New Title',
 6999:                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
 7000:                                           p_rmr2a => 'Remove',
 7001:                                           p_rmr2b => '?',
 7002:                                           p_rmr3a => 'Remove those',
 7003:                                           p_rmr3b => 'items?',
 7004:                                           p_rmr4  => 'WARNING: Removing a resource uploaded to a course cannot be undone via "Undo Delete".',
 7005:                                           p_rmr5  => 'Push "Cancel" and then use "Cut" instead if you might need to undo this change.',
 7006:                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
 7007:                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
 7008:                                           p_ctr2a => 'Cut',
 7009:                                           p_ctr2b => '?',
 7010:                                           p_ctr3a => 'Cut those',
 7011:                                           p_ctr3b => 'items?',
 7012:                                           rpck    => 'Enter number to pick (e.g., 3)',
 7013:                                           imsfile => 'You must choose an IMS package for import',
 7014:                                           imscms  => 'You must select which Course Management System was the source of the IMS package',
 7015:                                           invurl  => 'Invalid URL',
 7016:                                           titbl   => 'Title is blank',
 7017:                                           more    => '(More ...)',
 7018:                                           less    => '(Less ...)',
 7019:                                           noor    => 'No actions selected or changes to settings specified.',
 7020:                                           noch    => 'No changes to settings specified.',
 7021:                                           noac    => 'No actions selected.',
 7022:                                           edri    => 'Editing rights unavailable for your current role.',
 7023:                                         );
 7024: 
 7025:     &js_escape(\%js_lt);
 7026:     my $crstype = &Apache::loncommon::course_type();
 7027:     my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
 7028:     my $main_container_page;
 7029:     if (&HTML::Entities::decode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'}) =~ /\:1$/) {
 7030:         $main_container_page = 1;
 7031:     }
 7032:     my $backtourl;
 7033:     my $toplevelmain = &escape(&default_folderpath($coursenum,$coursedom,$navmapref));
 7034:     my $toplevelsupp = &supplemental_base();
 7035: 
 7036:     if ($env{'docs.exit.'.$env{'request.course.id'}} =~ /^direct_(.+)$/) {
 7037:         my $caller = $1;
 7038:         if ($caller =~ /^supplemental/) {
 7039:             $backtourl = '/adm/supplemental?folderpath='.&escape($caller);
 7040:         } else {
 7041:             my ($map,$id,$res)=&Apache::lonnet::decode_symb($caller);
 7042:             $res = &Apache::lonnet::clutter($res);
 7043:             if (&Apache::lonnet::is_on_map($res)) {
 7044:                 my ($url,$anchor);
 7045:                 if ($res =~ /^([^#]+)#([^#]+)$/) {
 7046:                     $url = $1;
 7047:                     $anchor = $2;
 7048:                     if (($caller =~ m{^([^#]+)\Q#$anchor\E$})) {
 7049:                         $caller = $1.&escape('#').$anchor;
 7050:                     }
 7051:                 } else {
 7052:                     $url = $res;
 7053:                 }
 7054:                 $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($url),'<>&"');
 7055:                 if ($backtourl =~ m{^\Q/uploaded/$coursedom/$coursenum/\Edefault_\d+\.sequence$}) {
 7056:                     $backtourl .= '?navmap=1';
 7057:                 } else {
 7058:                     $backtourl .= '?symb='.
 7059:                                   &HTML::Entities::encode($caller,'<>&"');
 7060:                 }
 7061:                 if ($backtourl =~ m{^\Q/public/$coursedom/$coursenum/syllabus\E}) {
 7062:                     if (($ENV{'SERVER_PORT'} == 443) &&
 7063:                         ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ m{^http://})) {
 7064:                         unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
 7065:                             if ($hostname ne '') {
 7066:                                 $backtourl = 'http://'.$hostname.$backtourl;
 7067:                             }
 7068:                             $backtourl .= (($backtourl =~ /\?/) ? '&amp;':'?').'usehttp=1';
 7069:                         }
 7070:                     }
 7071:                 } elsif ($backtourl =~ m{^/adm/wrapper/ext/(?!https:)}) {
 7072:                     if (($ENV{'SERVER_PORT'} == 443) && ($hostname ne '')) {
 7073:                         unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl($hostname))) {
 7074:                             if ($hostname ne '') {
 7075:                                 $backtourl = 'http://'.$hostname.$backtourl;
 7076:                             }
 7077:                             $backtourl .= (($backtourl =~ /\?/) ? '&amp;':'?').'usehttp=1';
 7078:                         }
 7079:                     }
 7080:                 }
 7081:                 if ($anchor ne '') {
 7082:                     $backtourl .= '#'.&HTML::Entities::encode($anchor,'<>&"');
 7083:                 }
 7084:                 $backtourl = &Apache::loncommon::escape_single($backtourl); 
 7085:             } else {
 7086:                 $backtourl = '/adm/navmaps';
 7087:             }
 7088:         }
 7089:     } elsif ($env{'docs.exit.'.$env{'request.course.id'}} eq '/adm/menu') {
 7090:         $backtourl = '/adm/menu';
 7091:     } elsif ($supplementalflag) {
 7092:         if (($env{'request.role.adv'}) ||
 7093:             (&Apache::lonnet::has_unhidden_suppfiles($coursenum,$coursedom))) {
 7094:             $backtourl = '/adm/supplemental';
 7095:         } else {
 7096:             $backtourl = '/adm/navmaps';
 7097:         }
 7098:     } else {
 7099:         $backtourl = '/adm/navmaps';
 7100:     }
 7101: 
 7102:     my $fieldsets = "'ext','doc'";
 7103:     if ($posslti) {
 7104:         $fieldsets .= ",'tool'";
 7105:     }
 7106:     unless ($main_container_page) {
 7107:         $fieldsets .=",'ims'";
 7108:     }
 7109:     if ($supplementalflag) {
 7110:         $fieldsets = "'suppext','suppdoc'";
 7111:         if ($posslti) {
 7112:             $fieldsets .= ",'supptool'";
 7113:         }
 7114:     }
 7115: 
 7116:     my $jsmakefunctions;
 7117:     if ($canedit) {
 7118:         $jsmakefunctions = <<ENDNEWSCRIPT;
 7119: function makenewfolder(targetform,folderseq) {
 7120:     var foldername=prompt('$js_lt{"p_mnf"}','$js_lt{"t_mnf"}');
 7121:     if (foldername) {
 7122:        targetform.importdetail.value=encodeURIComponent(foldername)+"="+folderseq;
 7123:         targetform.submit();
 7124:     }
 7125: }
 7126: 
 7127: function makenewpage(targetform,folderseq) {
 7128:     var pagename=prompt('$js_lt{"p_mnp"}','$js_lt{"t_mnp"}');
 7129:     if (pagename) {
 7130:         targetform.importdetail.value=encodeURIComponent(pagename)+"="+folderseq;
 7131:         targetform.submit();
 7132:     }
 7133: }
 7134: 
 7135: function makeexamupload() {
 7136:    var title=prompt('$js_lt{"p_mxu"}');
 7137:    if (title) {
 7138:     this.document.forms.newexamupload.importdetail.value=
 7139: 	encodeURIComponent(title)+'=/res/lib/templates/examupload.problem';
 7140:     this.document.forms.newexamupload.submit();
 7141:    }
 7142: }
 7143: 
 7144: function makesmppage() {
 7145:    var title=prompt('$js_lt{"p_msp"}');
 7146:    if (title) {
 7147:     this.document.forms.newsmppg.importdetail.value=
 7148: 	encodeURIComponent(title)+'=/adm/$udom/$uname/new/smppg';
 7149:     this.document.forms.newsmppg.submit();
 7150:    }
 7151: }
 7152: 
 7153: function makewebpage(type) {
 7154:    var title=prompt('$js_lt{"p_mwp"}');
 7155:    var formname;
 7156:    if (type == 'supp') {
 7157:        formname = this.document.forms.supwebpage;
 7158:    } else {
 7159:        formname = this.document.forms.newwebpage;
 7160:    }
 7161:    if (title) {
 7162:        var webpage = formname.importdetail.value;
 7163:        formname.importdetail.value = encodeURIComponent(title)+'='+webpage;
 7164:        formname.submit();
 7165:    }
 7166: }
 7167: 
 7168: function makesmpproblem() {
 7169:    var title=prompt('$js_lt{"p_msb"}');
 7170:    if (title) {
 7171:     this.document.forms.newsmpproblem.importdetail.value=
 7172: 	encodeURIComponent(title)+'=/res/lib/templates/simpleproblem.problem';
 7173:     this.document.forms.newsmpproblem.submit();
 7174:    }
 7175: }
 7176: 
 7177: function makedropbox() {
 7178:    var title=prompt('$js_lt{"p_mdb"}');
 7179:    if (title) {
 7180:     this.document.forms.newdropbox.importdetail.value=
 7181:         encodeURIComponent(title)+'=/res/lib/templates/DropBox.problem';
 7182:     this.document.forms.newdropbox.submit();
 7183:    }
 7184: }
 7185: 
 7186: function makebulboard() {
 7187:    var title=prompt('$js_lt{"p_mbb"}');
 7188:    if (title) {
 7189:     this.document.forms.newbul.importdetail.value=
 7190: 	encodeURIComponent(title)+'=/adm/$udom/$uname/new/bulletinboard';
 7191:     this.document.forms.newbul.submit();
 7192:    }
 7193: }
 7194: 
 7195: function makeabout() {
 7196:    var user=prompt("$js_lt{'p_mab'}");
 7197:    if (user) {
 7198:        var comp=new Array();
 7199:        comp=user.split(':');
 7200:        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
 7201: 	   if ((comp[0]) && (comp[1])) {
 7202: 	       this.document.forms.newaboutsomeone.importdetail.value=
 7203: 		   '$js_lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
 7204:                this.document.forms.newaboutsomeone.submit();
 7205:            } else {
 7206:                alert("$js_lt{'p_mab_alrt1'}");
 7207:            }
 7208:        } else {
 7209:            alert("$js_lt{'p_mab_alrt2'}");
 7210:        }
 7211:     }
 7212: }
 7213: 
 7214: function makenew(targetform) {
 7215:     targetform.submit();
 7216: }
 7217: 
 7218: function changename(folderpath,index,oldtitle) {
 7219:     var title=prompt('$js_lt{"p_chn"}',oldtitle);
 7220:     if (title) {
 7221:         this.document.forms.renameform.markcopy.value='';
 7222:         this.document.forms.renameform.title.value=title;
 7223:         this.document.forms.renameform.cmd.value='rename_'+index;
 7224:         this.document.forms.renameform.folderpath.value=folderpath;
 7225:         this.document.forms.renameform.submit();
 7226:     }
 7227: }
 7228: 
 7229: ENDNEWSCRIPT
 7230:     } else {
 7231:         $jsmakefunctions = <<ENDNEWSCRIPT;
 7232: 
 7233: function makenewfolder() {
 7234:     alert("$js_lt{'edri'}");
 7235: }
 7236: 
 7237: function makenewpage() {
 7238:     alert("$js_lt{'edri'}");
 7239: }
 7240: 
 7241: function makeexamupload() {
 7242:     alert("$js_lt{'edri'}");
 7243: }
 7244: 
 7245: function makesmppage() {
 7246:     alert("$js_lt{'edri'}");
 7247: }
 7248: 
 7249: function makewebpage(type) {
 7250:     alert("$js_lt{'edri'}");
 7251: }
 7252: 
 7253: function makesmpproblem() {
 7254:     alert("$js_lt{'edri'}");
 7255: }
 7256: 
 7257: function makedropbox() {
 7258:     alert("$js_lt{'edri'}");
 7259: }
 7260: 
 7261: function makebulboard() {
 7262:     alert("$js_lt{'edri'}");
 7263: }
 7264: 
 7265: function makeabout() {
 7266:     alert("$js_lt{'edri'}");
 7267: }
 7268: 
 7269: function changename() {
 7270:     alert("$js_lt{'edri'}");
 7271: }
 7272: 
 7273: function makenew() {
 7274:     alert("$js_lt{'edri'}");
 7275: }
 7276: 
 7277: function groupimport() {
 7278:     alert("$js_lt{'edri'}");
 7279: }
 7280: 
 7281: function groupsearch() {
 7282:     alert("$js_lt{'edri'}");
 7283: }
 7284: 
 7285: function groupopen(url,recover) {
 7286:    var options="scrollbars=1,resizable=1,menubar=0";
 7287:    idxflag=1;
 7288:    idx=open("/adm/groupsort?inhibitmenu=yes&mode=simple&recover="+recover+"&readfile="+url,"idxout",options);
 7289:    idx.focus();
 7290: }
 7291: 
 7292: ENDNEWSCRIPT
 7293: 
 7294:     }
 7295:     return <<ENDSCRIPT;
 7296: 
 7297: $jsmakefunctions
 7298: 
 7299: function toggleUpload(caller) {
 7300:     var blocks = Array($fieldsets);
 7301:     for (var i=0; i<blocks.length; i++) {
 7302:         var disp = 'none';
 7303:         if (caller == blocks[i]) {
 7304:             var curr = document.getElementById('upload'+caller+'form').style.display;
 7305:             if (curr == 'none') {
 7306:                 disp='block';
 7307:             }
 7308:         }
 7309:         document.getElementById('upload'+blocks[i]+'form').style.display=disp;
 7310:         if ((caller == 'tool') || (caller == 'supptool')) {
 7311:             if (disp == 'block') {
 7312:                 if (document.getElementById('LC_exttoolid')) {
 7313:                     var toolselector = document.getElementById('LC_exttoolid');
 7314:                     var suppflag = 0;
 7315:                     if (caller == 'supptool') {
 7316:                         suppflag = 1;
 7317:                     }
 7318:                     currForm = document.getElementById('new'+caller);
 7319:                     updateExttool(toolselector,currForm,suppflag);
 7320:                 }
 7321:             }
 7322:         }
 7323:     }
 7324:     resize_scrollbox('contentscroll','1','1');
 7325:     return;
 7326: }
 7327: 
 7328: function toggleMap(caller) {
 7329:     var disp = 'none';
 7330:     if (document.getElementById('importmapform')) {
 7331:         if (caller == 'map') {
 7332:             var curr = document.getElementById('importmapform').style.display;
 7333:             if (curr == 'none') {
 7334:                 disp='block';
 7335:             }
 7336:         }
 7337:         document.getElementById('importmapform').style.display=disp;
 7338:         resize_scrollbox('contentscroll','1','1');
 7339:     }
 7340:     return;
 7341: }
 7342: 
 7343: function makeims(imsform) {
 7344:     if ((imsform.uploaddoc.value == '')  || (!imsform.uploaddoc.value)) {
 7345:         alert("$js_lt{'imsfile'}");
 7346:         return;
 7347:     }
 7348:     if (imsform.source.selectedIndex == 0) {
 7349:         alert("$js_lt{'imscms'}");
 7350:         return;
 7351:     }
 7352:     newWindow = window.open('', 'IMSimport',"HEIGHT=700,WIDTH=750,scrollbars=yes");
 7353:     imsform.submit();
 7354: }
 7355: 
 7356: function updatePick(targetform,index,caller) {
 7357:     var pickitem;
 7358:     var picknumitem;
 7359:     var picknumtext;
 7360:     if (index == 'all') {
 7361:         pickitem = document.getElementById('randompickall');
 7362:         picknumitem = document.getElementById('rpicknumall');
 7363:         picknumtext = document.getElementById('rpicktextall');
 7364:     } else {
 7365:         pickitem = document.getElementById('randompick_'+index);
 7366:         picknumitem = document.getElementById('rpicknum_'+index);
 7367:         picknumtext = document.getElementById('randompicknum_'+index);
 7368:     }
 7369:     if (pickitem.checked) {
 7370:         var picknum=prompt('$js_lt{"rpck"}',picknumitem.value);
 7371:         if (picknum == '' || picknum == null) {
 7372:             if (caller == 'check') {
 7373:                 pickitem.checked=false;
 7374:                 if (index == 'all') {
 7375:                     picknumtext.innerHTML = '';
 7376:                     if (caller == 'link') {
 7377:                         propagateState(targetform,'rpicknum');
 7378:                     }
 7379:                 } else {
 7380:                     checkForSubmit(targetform,'randompick','settings');
 7381:                 }
 7382:             }
 7383:         } else {
 7384:             picknum.toString();
 7385:             var regexdigit=/^\\d+\$/;
 7386:             if (regexdigit.test(picknum)) {
 7387:                 picknumitem.value = picknum;
 7388:                 if (index == 'all') {
 7389:                     picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.cumulativesettings,\\'all\\',\\'link\\');">'+picknum+'</a>';
 7390:                     if (caller == 'link') {
 7391:                         propagateState(targetform,'rpicknum');
 7392:                     }
 7393:                 } else {
 7394:                     picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+index+',\\''+index+'\\',\\'link\\');">'+picknum+'</a>';
 7395:                     checkForSubmit(targetform,'randompick','settings');
 7396:                 }
 7397:             } else {
 7398:                 if (caller == 'check') {
 7399:                     if (index == 'all') {
 7400:                         picknumtext.innerHTML = '';
 7401:                         if (caller == 'link') {
 7402:                             propagateState(targetform,'rpicknum');
 7403:                         }
 7404:                     } else {
 7405:                         pickitem.checked=false;
 7406:                         checkForSubmit(targetform,'randompick','settings');
 7407:                     }
 7408:                 }
 7409:                 return;
 7410:             }
 7411:         }
 7412:     } else {
 7413:         picknumitem.value = '';
 7414:         picknumtext.innerHTML = '';
 7415:         if (index == 'all') {
 7416:             if (caller == 'link') {
 7417:                 propagateState(targetform,'rpicknum');
 7418:             }
 7419:         } else {
 7420:             checkForSubmit(targetform,'randompick','settings');
 7421:         }
 7422:     }
 7423: }
 7424: 
 7425: function propagateState(form,param) {
 7426:     if (document.getElementById(param+'all')) {
 7427:         var setcheck = 0;
 7428:         var rpick = 0;
 7429:         if (param == 'rpicknum') {
 7430:             if (document.getElementById('randompickall')) {
 7431:                 if (document.getElementById('randompickall').checked) {
 7432:                     if (document.getElementById('rpicknumall')) {
 7433:                         rpick = document.getElementById('rpicknumall').value;
 7434:                     }
 7435:                 }
 7436:             }
 7437:         } else {
 7438:             if (document.getElementById(param+'all').checked) {
 7439:                 setcheck = 1;
 7440:             }
 7441:         }
 7442:         var allidxlist;
 7443:         if ((param == 'remove') || (param == 'cut') || (param == 'copy')) {
 7444:             if (document.getElementById('all'+param+'idx')) {
 7445:                 allidxlist = document.getElementById('all'+param+'idx').value;
 7446:             }
 7447:             var actions = new Array ('remove','cut','copy');
 7448:             for (var i=0; i<actions.length; i++) {
 7449:                 if (actions[i] != param) {
 7450:                     if (document.getElementById(actions[i]+'all')) {
 7451:                         document.getElementById(actions[i]+'all').checked = false; 
 7452:                     }
 7453:                 }
 7454:             }
 7455:         }
 7456:         if ((param == 'encrypturl') || (param == 'hiddenresource')) {
 7457:             allidxlist = form.allidx.value;
 7458:         }
 7459:         if ((param == 'randompick') || (param == 'rpicknum') || (param == 'randomorder')) {
 7460:             allidxlist = form.allmapidx.value;
 7461:         }
 7462:         if ((allidxlist != '') && (allidxlist != null)) {
 7463:             var allidxs = allidxlist.split(',');
 7464:             if (allidxs.length > 1) {
 7465:                 for (var i=0; i<allidxs.length; i++) {
 7466:                     if (document.getElementById(param+'_'+allidxs[i])) {
 7467:                         if (param == 'rpicknum') {
 7468:                             if (document.getElementById('randompick_'+allidxs[i])) {
 7469:                                 if (document.getElementById('randompick_'+allidxs[i]).checked) {
 7470:                                     document.getElementById(param+'_'+allidxs[i]).value = rpick;
 7471:                                     if (rpick > 0) {
 7472:                                         document.getElementById('randompicknum_'+allidxs[i]).innerHTML = ':&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+allidxs[i]+',\\''+allidxs[i]+'\\',\\'link\\')">'+rpick+'</a>';
 7473:                                     } else {
 7474:                                         document.getElementById('randompicknum_'+allidxs[i]).innerHTML =  '';
 7475:                                     }
 7476:                                 }
 7477:                             }
 7478:                         } else {
 7479:                             if (setcheck == 1) {
 7480:                                 document.getElementById(param+'_'+allidxs[i]).checked = true;
 7481:                             } else {
 7482:                                 document.getElementById(param+'_'+allidxs[i]).checked = false;
 7483:                                 if (param == 'randompick') {
 7484:                                     document.getElementById('randompicknum_'+allidxs[i]).innerHTML =  '';
 7485:                                 }
 7486:                             }
 7487:                         }
 7488:                     }
 7489:                 }
 7490:                 if (setcheck == 1) {
 7491:                     if ((param == 'remove') || (param == 'cut') || (param == 'copy')) {
 7492:                         var actions = new Array('copy','cut','remove');
 7493:                         for (var i=0; i<actions.length; i++) {
 7494:                             var otheractions;
 7495:                             var otheridxs;
 7496:                             if (actions[i] === param) {
 7497:                                 continue;
 7498:                             } else {
 7499:                                 if (document.getElementById('all'+actions[i]+'idx')) {
 7500:                                     otheractions = document.getElementById('all'+actions[i]+'idx').value;
 7501:                                     otheridxs = otheractions.split(',');
 7502:                                     if (otheridxs.length > 1) {
 7503:                                         for (var j=0; j<otheridxs.length; j++) {
 7504:                                             if (document.getElementById(actions[i]+'_'+otheridxs[j])) {
 7505:                                                 document.getElementById(actions[i]+'_'+otheridxs[j]).checked = false;
 7506:                                             }
 7507:                                         }
 7508:                                     }
 7509:                                 }
 7510:                             }
 7511:                         } 
 7512:                     }
 7513:                 }
 7514:             }
 7515:         }
 7516:     }
 7517:     return;
 7518: }
 7519: 
 7520: function checkForSubmit(targetform,param,context,idx,folderpath,index,oldtitle,skip_confirm,container,folder,confirm_removal) {
 7521:     var canedit = '$canedit';
 7522:     if (canedit == '') {
 7523:         alert("$js_lt{'edri'}");
 7524:         return;
 7525:     }
 7526:     var dosettings;
 7527:     var doaction;
 7528:     var control = document.togglemultsettings;
 7529:     if (context == 'actions') {
 7530:         control = document.togglemultactions;
 7531:         doaction = 1; 
 7532:     } else {
 7533:         dosettings = 1;
 7534:     }
 7535:     if (control) {
 7536:         if (control.showmultpick.length) {
 7537:             for (var i=0; i<control.showmultpick.length; i++) {
 7538:                 if (control.showmultpick[i].checked) {
 7539:                     if (control.showmultpick[i].value == 1) {
 7540:                         if (context == 'settings') {
 7541:                             dosettings = 0;
 7542:                         } else {
 7543:                             doaction = 0;
 7544:                         }
 7545:                     }
 7546:                 }
 7547:             }
 7548:         }
 7549:     }
 7550:     if (context == 'settings') {
 7551:         if (dosettings == 1) {
 7552:             targetform.changeparms.value=param;
 7553:             targetform.submit();
 7554:         }
 7555:     }
 7556:     if (context == 'actions') {
 7557:         if (doaction == 1) {
 7558:             targetform.cmd.value=param+'_'+index;
 7559:             targetform.folderpath.value=folderpath;
 7560:             targetform.markcopy.value=idx+':'+param;
 7561:             targetform.copyfolder.value=folder+'.'+container;
 7562:             if (param == 'remove') {
 7563:                 var doremove = 0;
 7564:                 if (skip_confirm) {
 7565:                     if (confirm_removal) {
 7566:                         if (confirm('$js_lt{"p_rmr4"}\\n$js_lt{"p_rmr5"}\\n\\n$js_lt{"p_rmr2a"} "'+oldtitle+'"$js_lt{"p_rmr2b"}')) {
 7567:                             doremove = 1;
 7568:                         }
 7569:                     } else {
 7570:                         doremove = 1;
 7571:                     }
 7572:                 } else {
 7573:                     if (confirm('$js_lt{"p_rmr1"}\\n\\n$js_lt{"p_rmr2a"} "'+oldtitle+'" $js_lt{"p_rmr2b"}')) {
 7574:                         doremove = 1;
 7575:                     }
 7576:                 }
 7577:                 if (doremove) {
 7578:                     targetform.markcopy.value='';
 7579:                     targetform.copyfolder.value='';
 7580:                     targetform.submit();
 7581:                 }
 7582:             }
 7583:             if (param == 'cut') {
 7584:                 if (skip_confirm || confirm('$js_lt{"p_ctr1a"}\\n$js_lt{"p_ctr1b"}\\n\\n$js_lt{"p_ctr2a"} "'+oldtitle+'" $js_lt{"p_ctr2b"}')) {
 7585:                     targetform.submit();
 7586:                     return;
 7587:                 }
 7588:             }
 7589:             if (param == 'copy') {
 7590:                 targetform.submit();
 7591:                 return;
 7592:             }
 7593:             targetform.markcopy.value='';
 7594:             targetform.copyfolder.value='';
 7595:             targetform.cmd.value='';
 7596:             targetform.folderpath.value='';
 7597:             return;
 7598:         } else {
 7599:             if (document.getElementById(param+'_'+idx)) {
 7600:                 item = document.getElementById(param+'_'+idx);
 7601:                 if (item.type == 'checkbox') {
 7602:                     if (item.checked) {
 7603:                         item.checked = false;
 7604:                     } else {
 7605:                         item.checked = true;
 7606:                         singleCheck(item,idx,param);
 7607:                     }
 7608:                 }
 7609:             }
 7610:         }
 7611:     }
 7612:     return;
 7613: }
 7614: 
 7615: function singleCheck(caller,idx,action) {
 7616:     actions = new Array('cut','copy','remove');
 7617:     if (caller.checked) {
 7618:         for (var i=0; i<actions.length; i++) {
 7619:             if (actions[i] != action) {
 7620:                 if (document.getElementById(actions[i]+'_'+idx)) {
 7621:                     if (document.getElementById(actions[i]+'_'+idx).checked) {
 7622:                         document.getElementById(actions[i]+'_'+idx).checked = false;
 7623:                     }
 7624:                 }
 7625:             }
 7626:         }
 7627:     }
 7628:     return;
 7629: }
 7630: 
 7631: function unselectInactive(nav) {
 7632: currentNav = document.getElementById(nav);
 7633: currentLis = currentNav.getElementsByTagName('LI');
 7634: for (i = 0; i < currentLis.length; i++) {
 7635:         if (currentLis[i].className == 'goback') {
 7636:             currentLis[i].className = 'goback';
 7637:         } else {
 7638: 	    if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
 7639: 		currentLis[i].className = 'right';
 7640: 	    } else {
 7641: 		currentLis[i].className = 'i';
 7642: 	    }
 7643:         }
 7644: }
 7645: }
 7646: 
 7647: function hideAll(current, nav, data) {
 7648: unselectInactive(nav);
 7649: if (current) {
 7650:     if (current.className == 'right'){
 7651: 	current.className = 'right active'
 7652:     } else {
 7653: 	current.className = 'active';
 7654:     }
 7655: }
 7656: currentData = document.getElementById(data);
 7657: currentDivs = currentData.getElementsByTagName('DIV');
 7658: for (i = 0; i < currentDivs.length; i++) {
 7659: 	if(currentDivs[i].className == 'LC_ContentBox'){
 7660: 		currentDivs[i].style.display = 'none';
 7661: 	}
 7662: }
 7663: }
 7664: 
 7665: function openTabs(pageId) {
 7666: 	tabnav = document.getElementById(pageId).getElementsByTagName('UL');	
 7667: 	if(tabnav.length > 2 ){
 7668: 		currentNav = document.getElementById(tabnav[1].id);
 7669: 		currentLis = currentNav.getElementsByTagName('LI');
 7670: 		for(i = 0; i< currentLis.length; i++){
 7671: 			if(currentLis[i].className == 'active') {
 7672: 				funcString = currentLis[i].onclick.toString();
 7673: 				tab = funcString.split('"');
 7674:                                 if(tab.length < 2) {
 7675:                                    tab = funcString.split("'");
 7676:                                 }
 7677: 				currentData = document.getElementById(tab[1]);
 7678:         			currentData.style.display = 'block';
 7679: 			}	
 7680: 		}
 7681: 	}
 7682: }
 7683: 
 7684: function showPage(current, pageId, nav, data) {
 7685:         currstate = current.className;
 7686: 	hideAll(current, nav, data);
 7687: 	openTabs(pageId);
 7688: 	unselectInactive(nav);
 7689:         if ((currstate == 'active') || (currstate == 'right active')) {
 7690:             if (currstate == 'active') {
 7691:                 current.className = '';
 7692:             } else {
 7693:                 current.className = 'right';
 7694:             }
 7695:             activeTab = '';
 7696:             toggleUpload();
 7697:             toggleMap();
 7698:             resize_scrollbox('contentscroll','1','0');
 7699:             return;
 7700:         } else {
 7701:             current.className = 'active';
 7702:         }
 7703: 	currentData = document.getElementById(pageId);
 7704: 	currentData.style.display = 'block';
 7705:         activeTab = pageId;
 7706:         toggleUpload();
 7707:         toggleMap();
 7708:         if (nav == 'mainnav') {
 7709:             var storedpath = "$docs_folderpath";
 7710:             var storedpage = "$main_container_page";
 7711:             var reg = new RegExp("^supplemental");
 7712:             if (pageId == 'mainCourseDocuments') {
 7713:                 if (storedpage == 1) {
 7714:                     document.simpleedit.folderpath.value = '';
 7715:                     document.uploaddocument.folderpath.value = '';
 7716:                 } else {
 7717:                     if (reg.test(storedpath)) {
 7718:                         document.simpleedit.folderpath.value = '$toplevelmain';
 7719:                         document.uploaddocument.folderpath.value = '$toplevelmain';
 7720:                         document.newext.folderpath.value = '$toplevelmain';
 7721:                     } else {
 7722:                         document.simpleedit.folderpath.value = storedpath;
 7723:                         document.uploaddocument.folderpath.value = storedpath;
 7724:                         document.newext.folderpath.value = storedpath;
 7725:                     }
 7726:                 }
 7727:             } else {
 7728:                 if (reg.test(storedpath)) {
 7729:                     document.simpleedit.folderpath.value = storedpath;
 7730:                     document.supuploaddocument.folderpath.value = storedpath;
 7731:                     document.supnewext.folderpath.value = storedpath;
 7732:                 } else {
 7733:                     document.simpleedit.folderpath.value = '$toplevelsupp';
 7734:                     document.supuploaddocument.folderpath.value = '$toplevelsupp';
 7735:                     document.supnewext.folderpath.value = '$toplevelsupp';
 7736:                 }
 7737:             }
 7738:         }
 7739:         resize_scrollbox('contentscroll','1','0');
 7740: 	return false;
 7741: }
 7742: 
 7743: function toContents(jumpto) {
 7744:     var newurl = '$backtourl';
 7745:     if ((newurl == '/adm/navmaps') && (jumpto != '')) {
 7746:         newurl = newurl+'?postdata='+jumpto;
 7747:     }
 7748:     location.href=newurl;
 7749: }
 7750: 
 7751: function togglePick(caller,value) {
 7752:     var disp = 'none';
 7753:     if (document.getElementById('multi'+caller)) {
 7754:         var curr = document.getElementById('multi'+caller).style.display;
 7755:         if (value == 1) {
 7756:             disp='block';
 7757:         }
 7758:         if (curr == disp) {
 7759:             return; 
 7760:         }
 7761:         document.getElementById('multi'+caller).style.display=disp;
 7762:         if (value == 1) {
 7763:             document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$js_lt{'more'}</a>'; 
 7764:         } else {
 7765:             document.getElementById('more'+caller).innerHTML = '';
 7766:         }
 7767:         if (caller == 'actions') { 
 7768:             setClass(value);
 7769:             setBoxes(value);
 7770:         }
 7771:     }
 7772:     var showButton = multiSettings();
 7773:     if (showButton != 1) {
 7774:         showButton = multiActions();
 7775:     }
 7776:     if (document.getElementById('multisave')) {
 7777:         if (showButton == 1) {
 7778:             document.getElementById('multisave').style.display='block';
 7779:         } else {
 7780:             document.getElementById('multisave').style.display='none';
 7781:         }
 7782:     }
 7783:     resize_scrollbox('contentscroll','1','1');
 7784:     return;
 7785: }
 7786: 
 7787: function toggleCheckUncheck(caller,more) {
 7788:     if (more == 1) {
 7789:         document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',0);" style="text-decoration:none;">$js_lt{'less'}</a>';
 7790:         document.getElementById('allfields'+caller).style.display='block';
 7791:     } else {
 7792:         document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$js_lt{'more'}</a>';
 7793:         document.getElementById('allfields'+caller).style.display='none';
 7794:     }
 7795:     resize_scrollbox('contentscroll','1','1');
 7796: }
 7797: 
 7798: function multiSettings() {
 7799:     var inuse = 0;
 7800:     var settingsform = document.togglemultsettings;
 7801:     if (settingsform.showmultpick.length > 1) {
 7802:         for (var i=0; i<settingsform.showmultpick.length; i++) {
 7803:             if (settingsform.showmultpick[i].checked) {
 7804:                 if (settingsform.showmultpick[i].value == 1) {
 7805:                     inuse = 1;  
 7806:                 }
 7807:             }
 7808:         }
 7809:     }
 7810:     return inuse;
 7811: }
 7812: 
 7813: function multiActions() {
 7814:     var inuse = 0;
 7815:     var actionsform = document.togglemultactions;
 7816:     if (actionsform.showmultpick.length > 1) {
 7817:         for (var i=0; i<actionsform.showmultpick.length; i++) {
 7818:             if (actionsform.showmultpick[i].checked) {
 7819:                 if (actionsform.showmultpick[i].value == 1) {
 7820:                     inuse = 1;
 7821:                 }
 7822:             }
 7823:         }
 7824:     }
 7825:     return inuse;
 7826: } 
 7827: 
 7828: function checkSubmits() {
 7829:     var numchanges = 0;
 7830:     var form = document.saveactions;
 7831:     var doactions = multiActions();
 7832:     var cutwarnings = 0;
 7833:     var remwarnings = 0;
 7834:     var removalinfo = 0;
 7835:     if (doactions == 1) {
 7836:         var remidxlist = document.cumulativeactions.allremoveidx.value;
 7837:         if ((remidxlist != '') && (remidxlist != null)) {
 7838:             var remidxs = remidxlist.split(',');
 7839:             for (var i=0; i<remidxs.length; i++) {
 7840:                 if (document.getElementById('remove_'+remidxs[i])) {
 7841:                     if (document.getElementById('remove_'+remidxs[i]).checked) {
 7842:                         form.multiremove.value += remidxs[i]+',';
 7843:                         numchanges ++;
 7844:                         if (document.getElementById('skip_remove_'+remidxs[i])) {
 7845:                             if (document.getElementById('skip_remove_'+remidxs[i]).value == 0) {
 7846:                                 remwarnings ++;
 7847:                             }
 7848:                         }
 7849:                         if (document.getElementById('confirm_removal_'+remidxs[i])) {
 7850:                             if (document.getElementById('confirm_removal_'+remidxs[i]).value == 1) {
 7851:                                 removalinfo ++;
 7852:                             }
 7853:                         }
 7854:                     }
 7855:                 }
 7856:             }
 7857:         }
 7858:         var cutidxlist = document.cumulativeactions.allcutidx.value;
 7859:         if ((cutidxlist != '') && (cutidxlist != null)) {
 7860:             var cutidxs = cutidxlist.split(',');
 7861:             for (var i=0; i<cutidxs.length; i++) {
 7862:                 if (document.getElementById('cut_'+cutidxs[i])) {
 7863:                     if (document.getElementById('cut_'+cutidxs[i]).checked == true) {
 7864:                         form.multicut.value += cutidxs[i]+',';
 7865:                         numchanges ++;
 7866:                         if (document.getElementById('skip_cut_'+cutidxs[i])) {
 7867:                             if (document.getElementById('skip_cut_'+cutidxs[i]).value == 0) {
 7868:                                 cutwarnings ++;
 7869:                             }
 7870:                         }
 7871:                     }
 7872:                 }
 7873:             }
 7874:         }
 7875:         var copyidxlist = document.cumulativeactions.allcopyidx.value;
 7876:         if ((copyidxlist != '') && (copyidxlist != null)) {
 7877:             var copyidxs = copyidxlist.split(',');
 7878:             for (var i=0; i<copyidxs.length; i++) {
 7879:                 if (document.getElementById('copy_'+copyidxs[i])) {
 7880:                     if (document.getElementById('copy_'+copyidxs[i]).checked) {
 7881:                         form.multicopy.value += copyidxs[i]+',';
 7882:                         numchanges ++;
 7883:                     }
 7884:                 }
 7885:             }
 7886:         }
 7887:         if (numchanges > 0) {
 7888:             form.multichange.value = numchanges;
 7889:         }
 7890:     }
 7891:     var dosettings = multiSettings();
 7892:     var haschanges = 0;
 7893:     if (dosettings == 1) {
 7894:         form.allencrypturl.value = '';
 7895:         form.allhiddenresource.value = '';
 7896:         form.changeparms.value = 'all';
 7897:         var patt=new RegExp(",\$");
 7898:         var allidxlist = document.cumulativesettings.allidx.value;
 7899:         if ((allidxlist != '') && (allidxlist != null)) {
 7900:             var allidxs = allidxlist.split(',');
 7901:             if (allidxs.length > 1) {
 7902:                 for (var i=0; i<allidxs.length; i++) {
 7903:                     if (document.getElementById('hiddenresource_'+allidxs[i])) {
 7904:                         if (document.getElementById('hiddenresource_'+allidxs[i]).checked) {
 7905:                             form.allhiddenresource.value += allidxs[i]+',';
 7906:                         }
 7907:                     }
 7908:                     if (document.getElementById('encrypturl_'+allidxs[i])) {
 7909:                         if (document.getElementById('encrypturl_'+allidxs[i]).checked) {
 7910:                             form.allencrypturl.value += allidxs[i]+',';
 7911:                         }
 7912:                     }
 7913:                 }
 7914:                 form.allhiddenresource.value = form.allhiddenresource.value.replace(patt,"");
 7915:                 form.allencrypturl.value = form.allencrypturl.value.replace(patt,"");
 7916:             }
 7917:         }
 7918:         form.allrandompick.value = '';
 7919:         form.allrandomorder.value = '';
 7920:         var allmapidxlist = document.cumulativesettings.allmapidx.value;
 7921:         if ((allmapidxlist != '') && (allmapidxlist != null)) {
 7922:             var allmapidxs = allmapidxlist.split(',');
 7923:             for (var i=0; i<allmapidxs.length; i++) {
 7924:                 var randompick = document.getElementById('randompick_'+allmapidxs[i]);
 7925:                 var rpicknum = document.getElementById('rpicknum_'+allmapidxs[i]);
 7926:                 var randorder = document.getElementById('randomorder_'+allmapidxs[i]);
 7927:                 if ((randompick.checked) && (rpicknum.value != '')) {
 7928:                     form.allrandompick.value += allmapidxs[i]+':'+rpicknum.value+',';
 7929:                 }
 7930:                 if (randorder.checked) {
 7931:                     form.allrandomorder.value += allmapidxs[i]+',';
 7932:                 }
 7933:             }
 7934:             form.allrandompick.value = form.allrandompick.value.replace(patt,"");
 7935:             form.allrandomorder.value = form.allrandomorder.value.replace(patt,"");
 7936:         }
 7937:         if (document.cumulativesettings.currhiddenresource.value != form.allhiddenresource.value) {
 7938:             haschanges = 1;
 7939:         }
 7940:         if (document.cumulativesettings.currencrypturl.value != form.allencrypturl.value) {
 7941:             haschanges = 1;
 7942:         }
 7943:         if (document.cumulativesettings.currrandomorder.value != form.allrandomorder.value) {
 7944:             haschanges = 1;
 7945:         }
 7946:         if (document.cumulativesettings.currrandompick.value != form.allrandompick.value) {
 7947:             haschanges = 1;
 7948:         }
 7949:     }
 7950:     if (doactions == 1) {
 7951:         if (numchanges > 0) {
 7952:             if ((cutwarnings > 0) || (remwarnings > 0) || (removalinfo > 0)) {
 7953:                 if (remwarnings > 0) {
 7954:                     if (!confirm('$js_lt{"p_rmr1"}\\n\\n$js_lt{"p_rmr3a"} '+remwarnings+' $js_lt{"p_rmr3b"}')) {
 7955:                         return false;
 7956:                     }
 7957:                 }
 7958:                 if (removalinfo > 0) {
 7959:                     if (!confirm('$js_lt{"p_rmr4"}\\n$js_lt{"p_rmr5"}\\n\\n$js_lt{"p_rmr3a"} '+removalinfo+' $js_lt{"p_rmr3b"}')) {
 7960:                         return false;
 7961:                     }
 7962:                 }
 7963:                 if (cutwarnings > 0) {
 7964:                     if (!confirm('$js_lt{"p_ctr1a"}\\n$js_lt{"p_ctr1b"}\\n\\n$js_lt{"p_ctr3a"} '+cutwarnings+' $js_lt{"p_ctr3b"}')) {
 7965:                         return false;
 7966:                     }
 7967:                 }
 7968:             }
 7969:             form.submit();
 7970:             return true;
 7971:         }
 7972:     }
 7973:     if (dosettings == 1) {
 7974:         if (haschanges == 1) {
 7975:             form.submit();
 7976:             return true;
 7977:         }
 7978:     }
 7979:     if ((dosettings == 1) && (doactions == 1)) {
 7980:         alert("$js_lt{'noor'}");
 7981:     } else {
 7982:         if (dosettings == 1) {
 7983:             alert("$js_lt{'noch'}");
 7984:         } else {
 7985:             alert("$js_lt{'noac'}");
 7986:         }
 7987:     }
 7988:     return false;
 7989: }
 7990: 
 7991: function setClass(value) {
 7992:     var cutclass = 'LC_docs_cut';
 7993:     var copyclass = 'LC_docs_copy';
 7994:     var removeclass = 'LC_docs_remove';
 7995:     var cutreg = new RegExp("\\\\b"+cutclass+"\\\\b");
 7996:     var copyreg = new RegExp("\\\\b"+copyclass+"\\\\b");
 7997:     var removereg = new RegExp("\\\\"+removeclass+"\\\\b");
 7998:     var links = document.getElementsByTagName('a');
 7999:     for (var i=0; i<links.length; i++) {
 8000:         var classes = links[i].className;
 8001:         if (cutreg.test(classes)) {
 8002:             links[i].className = cutclass;
 8003:             if (value == 1) {
 8004:                 links[i].className += " LC_menubuttons_link";
 8005:             }
 8006:         } else {
 8007:             if (copyreg.test(classes)) {
 8008:                 links[i].className = copyclass;
 8009:                 if (value == 1) {
 8010:                     links[i].className += " LC_menubuttons_link";
 8011:                 } 
 8012:             } else {
 8013:                 if (removereg.test(classes)) {
 8014:                     links[i].className = removeclass;
 8015:                     if (value == 1) {
 8016:                         links[i].className += " LC_menubuttons_link";
 8017:                     }
 8018:                 }
 8019:             }
 8020:         }
 8021:     }
 8022:     return;
 8023: }
 8024: 
 8025: function setBoxes(value) {
 8026:     var remidxlist = document.cumulativeactions.allremoveidx.value;
 8027:     if ((remidxlist != '') && (remidxlist != null)) {
 8028:         var remidxs = remidxlist.split(',');
 8029:         for (var i=0; i<remidxs.length; i++) {
 8030:             if (document.getElementById('remove_'+remidxs[i])) {
 8031:                 var item = document.getElementById('remove_'+remidxs[i]);
 8032:                 if (value == 1) {
 8033:                     item.className = 'LC_docs_remove';
 8034:                 } else {
 8035:                     item.className = 'LC_hidden';
 8036:                 }
 8037:             }
 8038:         }
 8039:     }
 8040:     var cutidxlist = document.cumulativeactions.allcutidx.value;
 8041:     if ((cutidxlist != '') && (cutidxlist != null)) {
 8042:         var cutidxs = cutidxlist.split(',');
 8043:         for (var i=0; i<cutidxs.length; i++) {
 8044:             if (document.getElementById('cut_'+cutidxs[i])) {
 8045:                 var item = document.getElementById('cut_'+cutidxs[i]);
 8046:                 if (value == 1) {
 8047:                     item.className = 'LC_docs_cut';
 8048:                 } else {
 8049:                     item.className = 'LC_hidden';
 8050:                 }
 8051:             }
 8052:         }
 8053:     }
 8054:     var copyidxlist = document.cumulativeactions.allcopyidx.value;
 8055:     if ((copyidxlist != '') && (copyidxlist != null)) {
 8056:         var copyidxs = copyidxlist.split(',');
 8057:         for (var i=0; i<copyidxs.length; i++) {
 8058:             if (document.getElementById('copy_'+copyidxs[i])) {
 8059:                 var item = document.getElementById('copy_'+copyidxs[i]);
 8060:                 if (value == 1) {
 8061:                     item.className = 'LC_docs_copy';
 8062:                 } else {
 8063:                     item.className = 'LC_hidden';
 8064:                 }
 8065:             }
 8066:         }
 8067:     }
 8068:     return;
 8069: }
 8070: 
 8071: ENDSCRIPT
 8072: }
 8073: 
 8074: sub history_tab_js {
 8075:     return <<"ENDHIST";
 8076: function toggleHistoryDisp(choice) {
 8077:     document.docslogform.docslog.value = choice;
 8078:     document.docslogform.submit();
 8079:     return;
 8080: }
 8081: 
 8082: ENDHIST
 8083: }
 8084: 
 8085: sub inject_data_js {
 8086:     return <<ENDINJECT;
 8087: 
 8088: function injectData(current, hiddenField, name, value) {
 8089:         currentElement = document.getElementById(hiddenField);
 8090:         currentElement.name = name;
 8091:         currentElement.value = value;
 8092:         current.submit();
 8093: }
 8094: 
 8095: ENDINJECT
 8096: }
 8097: 
 8098: sub dump_switchserver_js {
 8099:     my @hosts = @_;
 8100:     my %js_lt = &Apache::lonlocal::texthash(
 8101:         dump => 'Copying content to Authoring Space requires switching server.',
 8102:         swit => 'Switch server?',
 8103:     );
 8104:     my %html_js_lt = &Apache::lonlocal::texthash(
 8105:         swit => 'Switch server?',
 8106:         duco => 'Copying Content to Authoring Space',
 8107:         yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
 8108:         chos => 'Choose server',
 8109:     );
 8110:     &js_escape(\%js_lt);
 8111:     &html_escape(\%html_js_lt);
 8112:     &js_escape(\%html_js_lt);
 8113:     my $role = $env{'request.role'};
 8114:     my $js = <<"ENDSWJS";
 8115: <script type="text/javascript">
 8116: function write_switchserver() {
 8117:     var server;
 8118:     if (document.setserver.posshosts.length > 0) {
 8119:         for (var i=0; i<document.setserver.posshosts.length; i++) {
 8120:             if (document.setserver.posshosts[i].checked) {
 8121:                 server = document.setserver.posshosts[i].value;
 8122:             }
 8123:        }
 8124:        opener.document.location.href="/adm/switchserver?otherserver="+server+"&role=$role&origurl=/adm/coursedocs";
 8125:     }
 8126:     window.close();
 8127: }
 8128: </script>
 8129: 
 8130: ENDSWJS
 8131: 
 8132:     my $startpage = &Apache::loncommon::start_page('Choose server',$js,
 8133:                                                    {'only_body' => 1,
 8134:                                                     'js_ready'  => 1,});
 8135:     my $endpage = &Apache::loncommon::end_page({'js_ready'  => 1});
 8136: 
 8137:     my $hostpicker;
 8138:     my $count = 0;
 8139:     foreach my $host (sort(@hosts)) {
 8140:         my $checked;
 8141:         if ($count == 0) {
 8142:             $checked = ' checked="checked"';
 8143:         }
 8144:         $hostpicker .= '<label><input type="radio" name="posshosts" value="'.
 8145:                        $host.'"'.$checked.' />'.$host.'</label>&nbsp;&nbsp;';
 8146:         $count++;
 8147:     }
 8148:     
 8149:     return <<"ENDSWITCHJS";
 8150: 
 8151: function dump_needs_switchserver(url) {
 8152:     if (url!='' && url!= null) {
 8153:         if (confirm("$js_lt{'dump'}\\n$js_lt{'swit'}")) {
 8154:             go(url);
 8155:         }
 8156:     }
 8157:     return;
 8158: }
 8159: 
 8160: function choose_switchserver_window() {
 8161:     newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
 8162:     newWindow.document.open();
 8163:     newWindow.document.writeln('$startpage');
 8164:     newWindow.document.write('<h3>$html_js_lt{'duco'}<\\/h3>\\n'+
 8165:        '<p>$html_js_lt{'yone'}<\\/p>\\n'+
 8166:        '<div class="LC_left_float"><fieldset><legend>$html_js_lt{'chos'}<\\/legend>\\n'+
 8167:        '<form name="setserver" method="post" action="" \\/>\\n'+
 8168:        '$hostpicker\\n'+
 8169:        '<br \\/><br \\/>\\n'+
 8170:        '<input type="button" name="makeswitch" value="$html_js_lt{'swit'}" '+
 8171:        'onclick="write_switchserver();" \\/>\\n'+
 8172:        '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
 8173:     newWindow.document.writeln('$endpage');
 8174:     newWindow.document.close();
 8175:     newWindow.focus();
 8176: }
 8177: 
 8178: ENDSWITCHJS
 8179: }
 8180: 
 8181: sub makedocslogform {
 8182:     my ($formelems,$docslog) = @_;
 8183:     return <<"LOGSFORM";
 8184:  <form action="/adm/coursedocs" method="post" name="docslogform">
 8185:    <input type="hidden" name="docslog" value="$docslog" />
 8186:    $formelems
 8187:  </form>
 8188: LOGSFORM
 8189: }
 8190: 
 8191: sub makesimpleeditform {
 8192:     my ($formelems) = @_;
 8193:     return <<"SIMPFORM";
 8194:  <form name="simpleedit" method="post" action="/adm/coursedocs">
 8195:    <input type="hidden" name="importdetail" value="" />
 8196:    $formelems
 8197:  </form>
 8198: SIMPFORM
 8199: }
 8200: 
 8201: 1;
 8202: __END__
 8203: 
 8204: 
 8205: =head1 NAME
 8206: 
 8207: Apache::londocs.pm
 8208: 
 8209: =head1 SYNOPSIS
 8210: 
 8211: This is part of the LearningOnline Network with CAPA project
 8212: described at http://www.lon-capa.org.
 8213: 
 8214: =head1 SUBROUTINES
 8215: 
 8216: =over
 8217: 
 8218: =item %help=()
 8219: 
 8220: Available help topics
 8221: 
 8222: =item mapread()
 8223: 
 8224: Mapread read maps into LONCAPA::map:: global arrays
 8225: @order and @resources, determines status
 8226: sets @order - pointer to resources in right order
 8227: sets @resources - array with the resources with correct idx
 8228: 
 8229: =item authorhosts()
 8230: 
 8231: Return hash with valid author names
 8232: 
 8233: =item clean()
 8234: 
 8235: =item dumpcourse()
 8236: 
 8237:     Actually dump course
 8238: 
 8239: =item group_import()
 8240: 
 8241:     Imports the given (name, url) resources into the course
 8242:     coursenum, coursedom, and folder must precede the list
 8243: 
 8244: =item breadcrumbs()
 8245: 
 8246: =item log_docs()
 8247: 
 8248: =item docs_change_log()
 8249: 
 8250: =item update_paste_buffer()
 8251: 
 8252: =item print_paste_buffer()
 8253: 
 8254: =item do_paste_from_buffer()
 8255: 
 8256: =item do_buffer_empty() 
 8257: 
 8258: =item clear_from_buffer()
 8259: 
 8260: =item get_newmap_url()
 8261: 
 8262: =item dbcopy()
 8263: 
 8264: =item uniqueness_check()
 8265: 
 8266: =item contained_map_check()
 8267: 
 8268: =item url_paste_fixups()
 8269: 
 8270: =item apply_fixups()
 8271: 
 8272: =item copy_dependencies()
 8273: 
 8274: =item update_parameter()
 8275: 
 8276: =item handle_edit_cmd()
 8277: 
 8278: =item editor()
 8279: 
 8280: =item process_file_upload()
 8281: 
 8282: =item process_secondary_uploads()
 8283: 
 8284: =item is_supplemental_title()
 8285: 
 8286: =item entryline()
 8287: 
 8288: =item tiehash()
 8289: 
 8290: =item untiehash()
 8291: 
 8292: =item checkonthis()
 8293: 
 8294: check on this
 8295: 
 8296: =item verifycontent()
 8297: 
 8298: Verify Content
 8299: 
 8300: =item devalidateversioncache()
 8301: 
 8302: =item checkversions()
 8303: 
 8304: Check Versions
 8305: 
 8306: =item mark_hash_old()
 8307: 
 8308: =item is_hash_old()
 8309: 
 8310: =item changewarning()
 8311: 
 8312: =item init_breadcrumbs()
 8313: 
 8314: Breadcrumbs for special functions
 8315: 
 8316: =item create_list_elements()
 8317: 
 8318: =item create_form_ul()
 8319: 
 8320: =item startContentScreen() 
 8321: 
 8322: =item endContentScreen()
 8323: 
 8324: =item supplemental_base()
 8325: 
 8326: =item embedded_form_elems()
 8327: 
 8328: =item embedded_destination()
 8329: 
 8330: =item return_to_editor()
 8331: 
 8332: =item decompression_info()
 8333: 
 8334: =item decompression_phase_one()
 8335: 
 8336: =item decompression_phase_two()
 8337: 
 8338: =item remove_archive()
 8339: 
 8340: =item generate_admin_menu()
 8341: 
 8342: =item generate_edit_table()
 8343: 
 8344: =item editing_js()
 8345: 
 8346: =item history_tab_js()
 8347: 
 8348: =item inject_data_js()
 8349: 
 8350: =item dump_switchserver_js()
 8351: 
 8352: =item resize_scrollbox_js()
 8353: 
 8354: =item makedocslogform()
 8355: 
 8356: =item makesimpleeditform()
 8357: 
 8358: =back
 8359: 
 8360: =cut

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