File:  [LON-CAPA] / loncom / interface / londocs.pm
Revision 1.466: download - view: text, annotated - select for diffs
Sun Nov 27 22:51:28 2011 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
Direct link into editor

    1: # The LearningOnline Network
    2: # Documents
    3: #
    4: # $Id: londocs.pm,v 1.466 2011/11/27 22:51:28 www 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: 
   30: 
   31: package Apache::londocs;
   32: 
   33: use strict;
   34: use Apache::Constants qw(:common :http);
   35: use Apache::imsexport;
   36: use Apache::lonnet;
   37: use Apache::loncommon;
   38: use Apache::lonhtmlcommon;
   39: use LONCAPA::map();
   40: use Apache::lonratedt();
   41: use Apache::lonxml;
   42: use Apache::lonclonecourse;
   43: use Apache::lonnavmaps;
   44: use HTML::Entities;
   45: use GDBM_File;
   46: use Apache::lonlocal;
   47: use Cwd;
   48: use LONCAPA qw(:DEFAULT :match);
   49: 
   50: my $iconpath;
   51: 
   52: my %hash;
   53: 
   54: my $hashtied;
   55: my %alreadyseen=();
   56: 
   57: my $hadchanges;
   58: 
   59: 
   60: my %help=();
   61: 
   62: 
   63: sub mapread {
   64:     my ($coursenum,$coursedom,$map)=@_;
   65:     return
   66:       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   67: 			     $map);
   68: }
   69: 
   70: sub storemap {
   71:     my ($coursenum,$coursedom,$map)=@_;
   72:     my ($outtext,$errtext)=
   73:       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   74: 			      $map,1);
   75:     if ($errtext) { return ($errtext,2); }
   76: 
   77:     $hadchanges=1;
   78:     return ($errtext,0);
   79: }
   80: 
   81: 
   82: 
   83: sub authorhosts {
   84:     my %outhash=();
   85:     my $home=0;
   86:     my $other=0;
   87:     foreach my $key (keys(%env)) {
   88: 	if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
   89: 	    my $role=$1;
   90: 	    my $realm=$2;
   91: 	    my ($start,$end)=split(/\./,$env{$key});
   92: 	    if (($start) && ($start>time)) { next; }
   93: 	    if (($end) && (time>$end)) { next; }
   94: 	    my ($ca,$cd);
   95: 	    if ($1 eq 'au') {
   96: 		$ca=$env{'user.name'};
   97: 		$cd=$env{'user.domain'};
   98: 	    } else {
   99: 		($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  100: 	    }
  101: 	    my $allowed=0;
  102: 	    my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  103: 	    my @ids=&Apache::lonnet::current_machine_ids();
  104: 	    foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }
  105: 	    if ($allowed) {
  106: 		$home++;
  107: 		$outhash{'home_'.$ca.'@'.$cd}=1;
  108: 	    } else {
  109: 		$outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;
  110: 		$other++;
  111: 	    }
  112: 	}
  113:     }
  114:     return ($home,$other,%outhash);
  115: }
  116: 
  117: 
  118: sub dumpbutton {
  119:     my ($home,$other,%outhash)=&authorhosts();
  120:     my $crstype = &Apache::loncommon::course_type();
  121:     if ($home+$other==0) { return ''; }
  122:     if ($home) {
  123:         my $link =
  124:             "<a class='LC_menubuttons_link' href='javascript:injectData(document.courseverify, \"dummy\", \"dumpcourse\", \""
  125:            .&mt('Dump '.$crstype.' Documents to Construction Space')
  126:            ."\")'>"
  127:            .&mt('Dump '.$crstype.' Documents to Construction Space')
  128:            .'</a>';
  129:         return
  130:             $link.' '
  131:            .&Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs')
  132:            .'<br />';
  133:     } else {
  134:         return
  135:             &mt('Dump '.$crstype.' Documents to Construction Space: available on other servers');
  136:     }
  137: }
  138: 
  139: sub clean {
  140:     my ($title)=@_;
  141:     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
  142:     return $title;
  143: }
  144: 
  145: 
  146: 
  147: sub dumpcourse {
  148:     my ($r) = @_;
  149:     my $crstype = &Apache::loncommon::course_type();
  150:     $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Documents to Construction Space').
  151: 	      '<form name="dumpdoc" action="" method="post">');
  152:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Documents to Construction Space'));
  153:     my ($home,$other,%outhash)=&authorhosts();
  154:     unless ($home) { return ''; }
  155:     my $origcrsid=$env{'request.course.id'};
  156:     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
  157:     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  158: # Do the dumping
  159: 	unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }
  160: 	my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
  161: 	$r->print('<h3>'.&mt('Copying Files').'</h3>');
  162: 	my $title=$env{'form.authorfolder'};
  163: 	$title=&clean($title);
  164: 	my %replacehash=();
  165: 	foreach my $key (keys(%env)) {
  166: 	    if ($key=~/^form\.namefor\_(.+)/) {
  167: 		$replacehash{$1}=$env{$key};
  168: 	    }
  169: 	}
  170: 	my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  171: 	$crs=~s/\_/\//g;
  172: 	foreach my $item (keys(%replacehash)) {
  173: 	    my $newfilename=$title.'/'.$replacehash{$item};
  174: 	    $newfilename=~s/\.(\w+)$//;
  175: 	    my $ext=$1;
  176: 	    $newfilename=&clean($newfilename);
  177: 	    $newfilename.='.'.$ext;
  178: 	    my @dirs=split(/\//,$newfilename);
  179: 	    my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
  180: 	    my $makepath=$path;
  181: 	    my $fail=0;
  182: 	    for (my $i=0;$i<$#dirs;$i++) {
  183: 		$makepath.='/'.$dirs[$i];
  184: 		unless (-e $makepath) {
  185: 		    unless(mkdir($makepath,0777)) { $fail=1; }
  186: 		}
  187: 	    }
  188: 	    $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
  189: 	    if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
  190: 		if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  191: 		    print $fh &Apache::lonclonecourse::rewritefile(
  192:          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  193: 				     (%replacehash,$crs => '')
  194: 								    );
  195: 		} else {
  196: 		    print $fh
  197:          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  198: 		       }
  199: 		$fh->close();
  200: 	    } else {
  201: 		$fail=1;
  202: 	    }
  203: 	    if ($fail) {
  204: 		$r->print('<span class="LC_error">'.&mt('fail').'</span>');
  205: 	    } else {
  206: 		$r->print('<span class="LC_success">'.&mt('ok').'</span>');
  207: 	    }
  208: 	}
  209:     } else {
  210: # Input form
  211: 	unless ($home==1) {
  212: 	    $r->print(
  213: 		      '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');
  214: 	}
  215: 	foreach my $key (sort(keys(%outhash))) {
  216: 	    if ($key=~/^home_(.+)$/) {
  217: 		if ($home==1) {
  218: 		    $r->print(
  219: 		  '<input type="hidden" name="authorspace" value="'.$1.'" />');
  220: 		} else {
  221: 		    $r->print('<option value="'.$1.'">'.$1.' - '.
  222: 			      &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');
  223: 		}
  224: 	    }
  225: 	}
  226: 	unless ($home==1) {
  227: 	    $r->print('</select>');
  228: 	}
  229: 	my $title=$origcrsdata{'description'};
  230: 	$title=~s/[\/\s]+/\_/gs;
  231: 	$title=&clean($title);
  232: 	$r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'
  233:                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');
  234: 	&tiehash();
  235: 	$r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'
  236:                  .&Apache::loncommon::start_data_table()
  237:                  .&Apache::loncommon::start_data_table_header_row()
  238:                  .'<th>'.&mt('Internal Filename').'</th>'
  239:                  .'<th>'.&mt('Title').'</th>'
  240:                  .'<th>'.&mt('Save as ...').'</th>'
  241:                  .&Apache::loncommon::end_data_table_header_row());
  242: 	foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  243: 	    $r->print(&Apache::loncommon::start_data_table_row()
  244:                      .'<td>'.$file.'</td>');
  245: 	    my ($ext)=($file=~/\.(\w+)$/);
  246: 	    my $title=$hash{'title_'.$hash{
  247: 		'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
  248: 	    $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
  249: 	    if (!$title) {
  250: 		$title=$file;
  251: 	    } else {
  252: 		$title=~s|/|_|g;
  253: 	    }
  254: 	    $title=~s/\.(\w+)$//;
  255: 	    $title=&clean($title);
  256: 	    $title.='.'.$ext;
  257: 	    $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
  258:                      .&Apache::loncommon::end_data_table_row());
  259: 	}
  260: 	$r->print(&Apache::loncommon::end_data_table());
  261: 	&untiehash();
  262: 	$r->print(
  263:   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Documents").'" /></p></form>');
  264:     }
  265: }
  266: 
  267: 
  268: 
  269: sub exportbutton {
  270:     my $crstype = &Apache::loncommon::course_type();
  271:     return "<a class='LC_menubuttons_link' href='javascript:injectData(document.courseverify, \"dummy\", \"exportcourse\", \"".&mt('IMS Export')."\")'>".&mt('IMS Export')."</a>".
  272:     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs').'<br />';
  273: }
  274: 
  275: 
  276: 
  277: sub exportcourse {
  278:     my $r=shift;
  279:     my $crstype = &Apache::loncommon::course_type();
  280:     my %discussiontime = &Apache::lonnet::dump('discussiontimes',
  281:                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});
  282:     my $numdisc = keys(%discussiontime);
  283:     my $numprobs = 0;
  284:     my $navmap = Apache::lonnavmaps::navmap->new();
  285:     if (!defined($navmap)) {
  286:         $r->print(&Apache::loncommon::start_page('Export '.$crstype.' to IMS Package').
  287:                   '<h2>'.&mt('IMS Export Failed').'</h2>'.
  288:                   '<div class="LC_error">');
  289:         if ($crstype eq 'Community') {
  290:             $r->print(&mt('Unable to retrieve information about community contents'));
  291:         } else {
  292:             $r->print(&mt('Unable to retrieve information about course contents'));
  293:         }
  294:         $r->print('</div><a href="/adm/coursedocs">');
  295:         if ($crstype eq 'Community') {
  296:             $r->print(&mt('Return to Community Editor'));
  297:         } else {
  298:             $r->print(&mt('Return to Course Editor'));
  299:         }
  300:         $r->print('</a>');
  301:         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
  302:         return;
  303:     }
  304:     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);
  305:     my $curRes;
  306:     my $outcome;
  307: 
  308:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  309:                                             ['finishexport']);
  310:     if ($env{'form.finishexport'}) {
  311:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  312:                                             ['archive','discussion']);
  313: 
  314:         my $format = $env{'form.format'};
  315:         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');
  316:         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');
  317:         if (@exportitems == 0 && @discussions == 0) {
  318:             $outcome = 
  319:                 '<p class="LC_warning">'
  320:                .&mt('As you did not select any content items or discussions'
  321:                    .' for export, an IMS package has not been created.')
  322:                .'</p>'
  323:                .'<p>'
  324:                .&mt('Please [_1]go back[_2] to select either content items'
  325:                    .' or discussions for export.'
  326:                        ,'<a href="javascript:history.go(-1)">'
  327:                        ,'</a>')
  328:                .'</p>';
  329:         } else {
  330:             my $now = time;
  331:             my %symbs;
  332:             my $manifestok = 0;
  333:             my $imsresources;
  334:             my $tempexport;
  335:             my $copyresult;
  336:             my $testbank;
  337:             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport,$format,\$testbank);
  338:             if ($manifestok) {
  339:                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest,$format,$testbank);
  340:                 close($ims_manifest);
  341: 
  342: #Create zip file in prtspool
  343:                 my $imszipfile = '/prtspool/'.
  344:                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
  345:                    time.'_'.rand(1000000000).'.zip';
  346:                 my $cwd = &Cwd::getcwd();
  347:                 my $imszip = '/home/httpd/'.$imszipfile;
  348:                 chdir $tempexport;
  349:                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");
  350:                 close(OUTPUT);
  351:                 chdir $cwd;
  352:                 $outcome .= '<p>'
  353:                            .&mt('[_1]Your IMS package[_2] is ready for download.'
  354:                                ,'<a href="'.$imszipfile.'">','</a>')
  355:                            .'</p>';
  356:                 if ($copyresult) {
  357:                     $outcome .= '<p class="LC_error">'
  358:                                .&mt('The following errors occurred during export - [_1]'
  359:                                    ,$copyresult)
  360:                                .'</p>';
  361:                 }
  362:             } else {
  363:                 $outcome = '<p class="LC_error">'
  364:                           .&mt('Unfortunately you will not be able to retrieve'
  365:                               .' an IMS archive of your course at this time,'
  366:                               .' because there was a problem creating a'
  367:                               .' manifest file.')
  368:                           .'</p>'
  369:                           .'<p><a href="javascript:history.go(-1)">'
  370:                           .&mt('Go Back')
  371:                           .'</a></p>';
  372:             }
  373:         }
  374:         $r->print(&Apache::loncommon::start_page('Export '.$crstype.' to IMS Package'));
  375: 	$r->print(&Apache::lonhtmlcommon::breadcrumbs('IMS Export'));
  376:         $r->print($outcome);
  377:         $r->print(&Apache::loncommon::end_page());
  378:     } else {
  379:         my $display='<form name="exportdoc" action="" method="post">'."\n".
  380:                     '<p>'.
  381:                     &mt('Choose which items you wish to export from your '.$crstype.'.').
  382:                     '</p>'.
  383:                     '<div class="LC_columnSection"><fieldset>'.
  384:                     '<legend>'.&mt('Content items').'</legend>'.
  385:                     '<input type="button" value="'.&mt('check all').'" '.
  386:                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.
  387:                     '&nbsp;&nbsp;<input type="button" value="'.&mt('uncheck all').'"'.
  388:                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset>';
  389:         if ($numdisc > 0) {
  390:             $display .= '<fieldset>'.
  391:                         '<legend>'.&mt('Discussion posts').'</legend>'.
  392:                         '<input type="button" value="'.&mt('check all').'"'.
  393:                         ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.
  394:                         '&nbsp;&nbsp;<input type="button" value="'.&mt('uncheck all').'"'.
  395:                         ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" />'.
  396:                         '</fieldset>';
  397:         }
  398:         $display .= '</div>';
  399:         my $curRes;
  400:         my $depth = 0;
  401:         my $count = 0;
  402:         my $boards = 0;
  403:         my $startcount = 5;
  404:         my %parent = ();
  405:         my %children = ();
  406:         my $lastcontainer = $startcount;
  407:         $display .= &Apache::loncommon::start_data_table()
  408:                    .&Apache::loncommon::start_data_table_header_row()
  409:                    .'<th>'.&mt('Export content item?').'</th>';
  410:         if ($numdisc > 0) {
  411:             $display .= '<th>'.&mt('Export discussion posts?').'</th>';
  412:         }
  413:         $display .= &Apache::loncommon::end_data_table_header_row();
  414:         while ($curRes = $it->next()) {
  415:             if (ref($curRes)) {
  416:                 $count ++;
  417:             }
  418:             if ($curRes == $it->BEGIN_MAP()) {
  419:                 $depth++;
  420:                 $parent{$depth} = $lastcontainer;
  421:             }
  422:             if ($curRes == $it->END_MAP()) {
  423:                 $depth--;
  424:                 $lastcontainer = $parent{$depth};
  425:             }
  426:             if (ref($curRes)) {
  427:                 my $symb = $curRes->symb();
  428:                 my $ressymb = $symb;
  429:                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
  430:                     unless ($ressymb =~ m|adm/wrapper/adm|) {
  431:                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
  432:                     }
  433:                 }
  434:                 my $currelem = $count+$boards+$startcount;
  435:                 $display .= &Apache::loncommon::start_data_table_row()
  436:                            .'<td>'."\n"
  437:                            .'<input type="checkbox" name="archive" value="'.$count.'" ';
  438:                 if (($curRes->is_sequence()) || ($curRes->is_page())) {
  439:                     $lastcontainer = $currelem;
  440:                     $display .= 'onclick="javascript:propagateCheck('."'$currelem'".')"';
  441:                 } elsif ($curRes->is_problem()) {
  442:                     $numprobs ++; 
  443:                 }
  444:                 $display .= ' />'."\n";
  445:                 for (my $i=0; $i<$depth; $i++) {
  446:                     $display .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
  447:                 }
  448:                 if ($curRes->is_sequence()) {
  449:                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n";
  450:                 } elsif ($curRes->is_page()) {
  451:                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif" alt="" />&nbsp;'."\n";
  452:                 }
  453:                 $children{$parent{$depth}} .= $currelem.':';
  454:                 $display .= '&nbsp;'.$curRes->title().'</td>'."\n";
  455: 
  456:                 # Existing discussion posts?
  457:                 if ($discussiontime{$ressymb} > 0) {
  458:                     $boards ++;
  459:                     $display .= '<td align="right">'
  460:                                .'<input type="checkbox" name="discussion" value="'.$count.'" />'
  461:                                .'</td>'."\n";
  462:                 } elsif ($numdisc > 0) {
  463:                     $display .= '<td>&nbsp;</td>'."\n";
  464:                 }
  465:                 $display .= &Apache::loncommon::end_data_table_row();
  466:             }
  467:         }
  468:         $display .= &Apache::loncommon::end_data_table();
  469:         my $scripttag = qq|
  470: <script type="text/javascript">
  471: // <![CDATA[
  472: function checkAll(field) {
  473:     if (field.length > 0) {
  474:         for (i = 0; i < field.length; i++) {
  475:             field[i].checked = true ;
  476:         }
  477:     } else {
  478:         field.checked = true
  479:     }
  480: }
  481: 
  482: function uncheckAll(field) {
  483:     if (field.length > 0) {
  484:         for (i = 0; i < field.length; i++) {
  485:             field[i].checked = false ;
  486:         }
  487:     } else {
  488:         field.checked = false ;
  489:     }
  490: }
  491: 
  492: function propagateCheck(item) {
  493:     if (document.exportdoc.elements[item].checked == true) {
  494:         containerCheck(item)
  495:     }
  496: }
  497: 
  498: function containerCheck(item) {
  499:     document.exportdoc.elements[item].checked = true
  500:     var numitems = $count + $boards + $startcount
  501:     var parents = new Array(numitems)
  502:     for (var i=$startcount; i<numitems; i++) {
  503:         parents[i] = new Array
  504:     }
  505:         |;
  506: 
  507:         foreach my $container (sort { $a <=> $b } (keys(%children))) {
  508:             my @contents = split(/:/,$children{$container});
  509:             for (my $i=0; $i<@contents; $i ++) {
  510:                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
  511:             }
  512:         }
  513: 
  514:         $scripttag .= qq|
  515:     if (parents[item].length > 0) {
  516:         for (var j=0; j<parents[item].length; j++) {
  517:             containerCheck(parents[item][j])
  518:         }
  519:      }
  520: }
  521: // ]]>
  522: </script>
  523:         |;
  524: 	$r->print(&Apache::loncommon::start_page('Export '.$crstype.' to IMS Package',
  525: 						 $scripttag));
  526: 	$r->print(&Apache::lonhtmlcommon::breadcrumbs('IMS Export'));
  527:         if ($numprobs > 0) {
  528:             $display .= '<p><span class="LC_nobreak">'.
  529:                         &mt('Export format for LON-CAPA problems:').
  530:                         '<label><input type="radio" name="format" value="xml" checked="checked" />'.
  531:                         '&nbsp;'.&mt('XML').'</label>'.('&nbsp;' x3).
  532:                         '<label><input type="radio" name="format" value="html" />'.
  533:                         '&nbsp;'.&mt('HTML').'</label>'.('&nbsp;' x3).
  534:                         '<label><input type="radio" name="format" value="plaintext" />'.
  535:                         '&nbsp;'.&mt('Text').'</label></span></p>';
  536:         }
  537: 	$r->print($display.
  538:                   '<p><input type="hidden" name="finishexport" value="1" />'.
  539:                   '<input type="submit" name="exportcourse" value="'.
  540:                   &mt('Export').'" /></p></form>');
  541:     }
  542: }
  543: 
  544: sub create_ims_store {
  545:     my ($now,$manifestok,$outcome,$tempexport,$format,$testbank) = @_;
  546:     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';
  547:     my $ims_manifest;
  548:     if (!-e $$tempexport) {
  549:         mkdir($$tempexport,0700);
  550:     }
  551:     $$tempexport .= '/'.$now;
  552:     if (!-e $$tempexport) {
  553:         mkdir($$tempexport,0700);
  554:     }
  555:     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};
  556:     if (!-e $$tempexport) {
  557:         mkdir($$tempexport,0700);
  558:     }
  559:     if (!-e "$$tempexport/resources") {
  560:         mkdir("$$tempexport/resources",0700);
  561:     }
  562: # open manifest file
  563:     my $manifest = '/imsmanifest.xml';
  564:     my $manifestfilename = $$tempexport.$manifest;
  565:     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {
  566:         $$manifestok=1;
  567:         print $ims_manifest
  568: '<?xml version="1.0" encoding="UTF-8"?>'."\n".
  569: '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.
  570: ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.
  571: ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.
  572: ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.
  573: '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.
  574: '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".
  575: '  <metadata>
  576:     <schema></schema>
  577:     <imsmd:lom>
  578:       <imsmd:general>
  579:         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>
  580:         <imsmd:title>
  581:           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>
  582:         </imsmd:title>
  583:       </imsmd:general>
  584:     </imsmd:lom>
  585:   </metadata>'."\n".
  586: '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".
  587: '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.
  588: ' structure="hierarchical">'."\n".
  589: '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>';
  590:         if ($format eq 'plaintext') {
  591:             my $testbankfilename = $$tempexport.'/testbank.txt';
  592:             $$testbank = Apache::File->new('>'.$testbankfilename);
  593:         }
  594:     } else {
  595:         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'
  596: ;
  597:     }
  598:     return $ims_manifest;
  599: }
  600: 
  601: sub build_package {
  602:     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,
  603:         $ims_manifest,$format,$testbank) = @_;
  604: # first iterator to look for dependencies
  605:     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
  606:     my $curRes;
  607:     my $count = 0;
  608:     my $depth = 0;
  609:     my $lastcontainer = 0;
  610:     my %parent = ();
  611:     my @dependencies = ();
  612:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  613:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  614:     while ($curRes = $it->next()) {
  615:         if (ref($curRes)) {
  616:             $count ++;
  617:         }
  618:         if ($curRes == $it->BEGIN_MAP()) {
  619:             $depth++;
  620:             $parent{$depth} = $lastcontainer;
  621:         }
  622:         if ($curRes == $it->END_MAP()) {
  623:             $depth--;
  624:             $lastcontainer = $parent{$depth};
  625:         }
  626:         if (ref($curRes)) {
  627:             if ($curRes->is_sequence() || $curRes->is_page()) {
  628:                 $lastcontainer = $count;
  629:             }
  630:             if (grep(/^$count$/,@$exportitems)) {
  631:                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);
  632:             }
  633:         }
  634:     }
  635: # second iterator to build manifest and store resources
  636:     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
  637:     $depth = 0;
  638:     my $prevdepth;
  639:     $count = 0;
  640:     my $imsresources;
  641:     my $pkgdepth;
  642:     my $currdirpath = 'Top';
  643:     while ($curRes = $it->next()) {
  644:         if ($curRes == $it->BEGIN_MAP()) {
  645:             $prevdepth = $depth;
  646:             $depth++;
  647:         }
  648:         if ($curRes == $it->END_MAP()) {
  649:             $prevdepth = $depth;
  650:             $depth--;
  651:         }
  652: 
  653:         if (ref($curRes)) {
  654:             $count ++;
  655:             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {
  656:                 my $symb = $curRes->symb();
  657:                 my $isvisible = 'true';
  658:                 my $resourceref;
  659:                 if ($curRes->randomout()) {
  660:                     $isvisible = 'false';
  661:                 }
  662:                 unless ($curRes->is_sequence()) {
  663:                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';
  664:                 }
  665:                 my $step = $prevdepth - $depth;
  666:                 if (($step >= 0) && ($count > 1)) {
  667:                     while ($step >= 0) {
  668:                         print $ims_manifest "\n".'  </item>'."\n";
  669:                         $step --;
  670:                     }
  671:                 }
  672:                 $prevdepth = $depth;
  673: 
  674:                 my $itementry =
  675:               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.
  676:               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.
  677:               '<title>'.$curRes->title().'</title>';
  678:                 print $ims_manifest "\n".$itementry;
  679: 
  680:                 if ($curRes->is_sequence()) {
  681:                     $currdirpath = 'Top';
  682:                     my $pcslist = $curRes->map_hierarchy();
  683:                     if ($pcslist ne '') {
  684:                         foreach my $pc (split(/,/,$pcslist),$curRes->map_pc()) {
  685:                             next if ($pc <= 1);
  686:                             my $res = $navmap->getByMapPc($pc);
  687:                             if (ref($res)) {
  688:                                 my $encloser = $res->title();
  689:                                 if ($encloser) {
  690:                                     if ($currdirpath) {
  691:                                         $currdirpath .= ' -> ';
  692:                                     }
  693:                                     $currdirpath .= $encloser;
  694:                                 }
  695:                             }
  696:                         }
  697:                     }
  698:                 } else {
  699:                     my $content_file;
  700:                     my @hrefs = ();
  701:                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport,$format,$currdirpath,$testbank);
  702:                     if ($content_file) {
  703:                         $imsresources .= "\n".
  704:                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.
  705:                      '" type="webcontent" href="'.$content_file.'">'."\n".
  706:                      '       <file href="'.$content_file.'" />'."\n";
  707:                         foreach my $item (@hrefs) {
  708:                             $imsresources .=
  709:                      '        <file href="'.$item.'" />'."\n";
  710:                         }
  711:                         if (grep(/^$count$/,@$discussions)) {
  712:                             my $ressymb = $symb;
  713:                             my $mode;
  714:                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
  715:                                 unless ($ressymb =~ m|adm/wrapper/adm|) {
  716:                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
  717:                                 }
  718:                                 $mode = 'board';
  719:                             }
  720:                             my %extras = (
  721:                                           caller => 'imsexport',
  722:                                           tempexport => $tempexport.'/resources',
  723:                                           count => $count
  724:                                          );
  725:                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);
  726:                         }
  727:                         $imsresources .= '    </resource>'."\n";
  728:                     }
  729:                 }
  730:                 $pkgdepth = $depth;
  731:             }
  732:         }
  733:     }
  734:     while ($pkgdepth > 0) {
  735:         print $ims_manifest "    </item>\n";
  736:         $pkgdepth --;
  737:     }
  738:     my $resource_text = qq|
  739:     </organization>
  740:   </organizations>
  741:   <resources>
  742:     $imsresources
  743:   </resources>
  744: </manifest>
  745:     |;
  746:     print $ims_manifest $resource_text;
  747: }
  748: 
  749: sub get_dependencies {
  750:     my ($exportitems,$parent,$depth,$dependencies) = @_;
  751:     if ($depth > 1) {
  752:         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {
  753:             push(@{$dependencies},$$parent{$depth});
  754:             if ($depth > 2) {
  755:                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);
  756:             }
  757:         }
  758:     }
  759: }
  760: 
  761: sub process_content {
  762:     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport,$format,$currdirpath,$testbank) = @_;
  763:     my $content_type;
  764:     my $message;
  765:     my @uploads = ();
  766:     if ($curRes->is_sequence()) {
  767:         $content_type = 'sequence';
  768:     } elsif ($curRes->is_page()) {
  769:         $content_type = 'page'; # need to handle individual items in pages.
  770:     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {
  771:         $content_type = 'syllabus';
  772:         my $contents = &Apache::imsexport::templatedpage($content_type);
  773:         if ($contents) {
  774:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  775:         }
  776:     } elsif ($symb =~ m-\.sequence___\d+___ext-) {
  777:         $content_type = 'external';
  778:         my $title = $curRes->title;
  779:         my $contents =  &Apache::imsexport::external($symb,$title);
  780:         if ($contents) {
  781:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  782:         }
  783:     } elsif ($symb =~ m-adm/navmaps$-) {
  784:         $content_type =  'navmap';
  785:     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {
  786:         $content_type = 'simplepage';
  787:         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);
  788:         if ($contents) {
  789:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  790:         }
  791:     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {
  792:         $content_type = 'simpleproblem';
  793:         my $contents =  &Apache::imsexport::simpleproblem($symb);
  794:         if ($contents) {
  795:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  796:         }
  797:     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {
  798:         $content_type = 'examupload';
  799:     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {
  800:         $content_type = 'bulletinboard';
  801:         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);
  802:         if ($contents) {
  803:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  804:         }
  805:     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {
  806:         $content_type = 'aboutme';
  807:         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);
  808:         if ($contents) {
  809:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  810:         }
  811:     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {
  812:         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
  813:     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {
  814:         my $canedit = 0;
  815:         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {
  816:             $canedit= 1;
  817:         }
  818: # only include problem code where current user is author
  819:         if (($format eq 'html') || ($format eq 'plaintext')) {
  820:             my $title = $curRes->title;
  821:             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,$format,$currdirpath,$title,$testbank);
  822:         } elsif ($format eq 'xml') {
  823:             if ($canedit) {
  824:                 $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');
  825:             } else {
  826:                 $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');
  827:             }
  828:         }
  829:     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {
  830:         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
  831:     }
  832:     if (@uploads > 0) {
  833:         foreach my $item (@uploads) {
  834:             my $uploadmsg = '';
  835:             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');
  836:             if ($uploadmsg) {
  837:                 $$copyresult .= $uploadmsg."\n";
  838:             }
  839:         }
  840:     }
  841:     if ($message) {
  842:         $$copyresult .= $message."\n";
  843:     }
  844: }
  845: 
  846: sub replicate_content {
  847:     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller,$currdirpath,
  848:         $title,$testbank) = @_;
  849:     my ($map,$ind,$url);
  850:     if ($caller eq 'templateupload') {
  851:         $url = $symb;
  852:         $url =~ s#//#/#g;
  853:     } else {
  854:         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
  855:     }
  856:     my $content;
  857:     my $filename;
  858:     my $repstatus;
  859:     my $content_name;
  860:     if ($url =~ m-/([^/]+)$-) {
  861:         $filename = $1;
  862:         if (!-e $tempexport.'/resources') {
  863:             mkdir($tempexport.'/resources',0700);
  864:         }
  865:         if (!-e $tempexport.'/resources/'.$count) {
  866:             mkdir($tempexport.'/resources/'.$count,0700);
  867:         }
  868:         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;
  869:         my $copiedfile;
  870:         if ($copiedfile = Apache::File->new('>'.$destination)) {
  871:             my $content;
  872:             if ($caller eq 'resource') {
  873:                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';
  874:                 my $filepath = &Apache::lonnet::filelocation($respath,$url);
  875:                 $content = &Apache::lonnet::getfile($filepath);
  876:                 if ($content eq -1) {
  877:                     $$message = 'Could not copy file '.$filename;
  878:                 } else {
  879:                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');
  880:                     $repstatus = 'ok';
  881:                 }
  882:             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {
  883:                 my $rtncode;
  884:                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);
  885:                 if ($repstatus eq 'ok') {
  886:                     if ($url =~ /\.html?$/i) {
  887:                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');
  888:                     }
  889:                 } else {
  890:                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";
  891:                 }
  892:             } elsif (($caller eq 'noedit') || ($caller eq 'html') || 
  893:                      ($caller eq 'plaintext')) {
  894: # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.
  895:                 my %form = (
  896:                              grade_symb     => $symb,
  897:                              grade_courseid => $cdom.'_'.$cnum,
  898:                              grade_domain   => $env{'user.domain'},
  899:                              grade_username => $env{'user.name'},
  900:                              grade_imsexport => 1,
  901:                              instructor_comments => 'hide',
  902:                            );
  903:                 my $feedurl=&Apache::lonnet::clutter($url);
  904:                 my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
  905:                 if (ref($response)) {
  906:                     if ($response->is_success) {
  907:                         $content = $userview;
  908:                         $content =~ s/\Qonchange="javascript:setSubmittedPart('\E[^\']+\Q');"\E//g;
  909:                         $content =~ s/^\s*[\n\r]+$//;
  910:                         if ($caller eq 'plaintext') {
  911:                             my @lines = split(/[\n\r]+/,$content);
  912:                             my @tosave;
  913:                             my $foilcounter = 0;
  914:                             my @alphabet = ('a'..'z');
  915:                             my $mc_answer;
  916:                             foreach my $line (@lines) {
  917:                                 next if ($line =~ /^\s*$/);
  918:                                 if ($line =~ m{(|\Q<\label>\E)\Q<br />Incorrect:<label>\E}) {
  919:                                     $foilcounter ++;
  920:                                 } elsif ($line =~ m{(|\Q</label>\E)\Q<br />Correct:<b><label>\E}) {
  921:                                     $foilcounter ++;
  922:                                     $mc_answer = $alphabet[$foilcounter-1];
  923:                                 } elsif ($line !~ m{\Q</label>\E(|\Q</b>\E)\Q<br />\E}) {
  924:                                     $line =~ s/^(\s+|\s+)$//g;
  925:                                     $line =~ s{^\Q<b>\E([^<]+)\Q</b>\E$}{1};
  926:                                     $tosave[$foilcounter] .= $line.' ';
  927:                                 }
  928:                                 $content = join("\t",@tosave);
  929:                                 if ($mc_answer) {
  930:                                     $content .= "\t".$mc_answer."\n";
  931:                                 }
  932:                             }
  933:                             if (@tosave) {
  934:                                 my $qtype;
  935:                                 if ($mc_answer) {
  936:                                     $qtype = 'MC';
  937:                                 }
  938:                                 $content = $currdirpath."\t".$title."\t$qtype\t".join("\t",@tosave);
  939:                                 if ($mc_answer) {
  940:                                     $content .= "\t".$mc_answer;
  941:                                 } 
  942:                                 $content .= "\n";
  943:                             }
  944:                         } else {
  945:                             $content = '<html><body>'.$content.'</body></html>';
  946:                         }
  947:                         if (($caller eq 'plaintext') && ($testbank)) {
  948:                             print $testbank $content;
  949:                         }
  950:                     } else {
  951:                         $content = 'Not the owner of this resource';
  952:                     }
  953:                 } else {
  954:                     $content = 'Not the owner of this resource';
  955:                 }
  956:                 $repstatus = 'ok';
  957:             }
  958:             if ($repstatus eq 'ok') {
  959:                 print $copiedfile $content;
  960:             }
  961:             close($copiedfile);
  962:         } else {
  963:             $$message = 'Could not open destination file for '.$filename."<br />\n";
  964:         }
  965:     } else {
  966:         $$message = 'Could not determine name of file for '.$symb."<br />\n";
  967:     }
  968:     if ($repstatus eq 'ok') {
  969:         $content_name = 'resources/'.$count.'/'.$filename;
  970:     }
  971:     return $content_name;
  972: }
  973: 
  974: sub extract_media {
  975:     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;
  976:     my ($dirpath,$container);
  977:     my %allfiles = ();
  978:     my %codebase = ();
  979:     if ($url =~ m-(.*/)([^/]+)$-) {
  980:         $dirpath = $1;
  981:         $container = $2;
  982:     } else {
  983:         $dirpath = $url;
  984:         $container = '';
  985:     }
  986:     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);
  987:     foreach my $embed_file (keys(%allfiles)) {
  988:         my $filename;
  989:         if ($embed_file =~ m#([^/]+)$#) {
  990:             $filename = $1;
  991:         } else {
  992:             $filename = $embed_file;
  993:         }
  994:         my $newname = 'res/'.$filename;
  995:         my ($rtncode,$embed_content,$repstatus);
  996:         my $embed_url;
  997:         if ($embed_file =~ m-^/-) {
  998:             $embed_url = $embed_file;           # points to absolute path
  999:         } else {
 1000:             if ($embed_file =~ m-https?://-) {
 1001:                 next;                           # points to url
 1002:             } else {
 1003:                 $embed_url = $dirpath.$embed_file;  # points to relative path
 1004:             }
 1005:         }
 1006:         if ($caller eq 'resource') {
 1007:             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';
 1008:             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);
 1009:             $embed_content = &Apache::lonnet::getfile($embed_path);
 1010:             unless ($embed_content eq -1) {
 1011:                 $repstatus = 'ok';
 1012:             }
 1013:         } elsif ($caller eq 'uploaded') {
 1014:             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);
 1015:         }
 1016:         if ($repstatus eq 'ok') {
 1017:             my $destination = $tempexport.'/resources/'.$count.'/res';
 1018:             if (!-e "$destination") {
 1019:                 mkdir($destination,0755);
 1020:             }
 1021:             $destination .= '/'.$filename;
 1022:             my $copiedfile;
 1023:             if ($copiedfile = Apache::File->new('>'.$destination)) {
 1024:                 print $copiedfile $embed_content;
 1025:                 push(@{$href},'resources/'.$count.'/res/'.$filename);
 1026:                 my $attrib_regexp = '';
 1027:                 if (@{$allfiles{$embed_file}} > 1) {
 1028:                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});
 1029:                 } else {
 1030:                     $attrib_regexp = $allfiles{$embed_file}[0];
 1031:                 }
 1032:                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;
 1033:                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {
 1034:                     $$content =~ s#\Q$embed_file\E#$newname#gi;
 1035:                 }
 1036:             }
 1037:         } else {
 1038:             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";
 1039:         }
 1040:     }
 1041:     return;
 1042: }
 1043: 
 1044: sub store_template {
 1045:     my ($contents,$tempexport,$count,$content_type) = @_;
 1046:     if ($contents) {
 1047:         if ($tempexport) {
 1048:             if (!-e $tempexport.'/resources') {
 1049:                 mkdir($tempexport.'/resources',0700);
 1050:             }
 1051:             if (!-e $tempexport.'/resources/'.$count) {
 1052:                 mkdir($tempexport.'/resources/'.$count,0700);
 1053:             }
 1054:             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';
 1055:             my $storetemplate;
 1056:             if ($storetemplate = Apache::File->new('>'.$destination)) {
 1057:                 print $storetemplate $contents;
 1058:                 close($storetemplate);
 1059:             }
 1060:             if ($content_type eq 'external') {
 1061:                 return 'resources/'.$count.'/'.$content_type.'.html';
 1062:             } else {
 1063:                 return 'resources/'.$count.'/'.$content_type.'.xml';
 1064:             }
 1065:         }
 1066:     }
 1067: }
 1068: 
 1069: 
 1070: sub group_import {
 1071:     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
 1072: 
 1073:     while (@files) {
 1074: 	my ($name, $url, $residx) = @{ shift(@files) };
 1075:         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
 1076: 	     && ($caller eq 'londocs')
 1077: 	     && (!&Apache::lonnet::stat_file($url))) {
 1078: 
 1079:             my $errtext = '';
 1080:             my $fatal = 0;
 1081:             my $newmapstr = '<map>'."\n".
 1082:                             '<resource id="1" src="" type="start"></resource>'."\n".
 1083:                             '<link from="1" to="2" index="1"></link>'."\n".
 1084:                             '<resource id="2" src="" type="finish"></resource>'."\n".
 1085:                             '</map>';
 1086:             $env{'form.output'}=$newmapstr;
 1087:             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
 1088:                                                 'output',$1.$2);
 1089:             if ($result != m|^/uploaded/|) {
 1090:                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
 1091:                 $fatal = 2;
 1092:             }
 1093:             if ($fatal) {
 1094:                 return ($errtext,$fatal);
 1095:             }
 1096:         }
 1097: 	if ($url) {
 1098: 	    if (!$residx
 1099: 		|| defined($LONCAPA::map::zombies[$residx])) {
 1100: 		$residx = &LONCAPA::map::getresidx($url,$residx);
 1101: 		push(@LONCAPA::map::order, $residx);
 1102: 	    }
 1103: 	    my $ext = 'false';
 1104: 	    if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
 1105: 	    $url  = &LONCAPA::map::qtunescape($url);
 1106: 	    $name = &LONCAPA::map::qtunescape($name);
 1107: 	    $LONCAPA::map::resources[$residx] =
 1108: 		join(':', ($name, $url, $ext, 'normal', 'res'));
 1109: 	}
 1110:     }
 1111:     return &storemap($coursenum, $coursedom, $folder.'.'.$container);
 1112: }
 1113: 
 1114: sub breadcrumbs {
 1115:     my ($allowed,$crstype)=@_;
 1116:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 1117:     my (@folders);
 1118:     if ($env{'form.pagepath'}) {
 1119:         @folders = split('&',$env{'form.pagepath'});
 1120:     } else {
 1121:         @folders=split('&',$env{'form.folderpath'});
 1122:     }
 1123:     my $folderpath;
 1124:     my $cpinfo='';
 1125:     my $plain='';
 1126:     my $randompick=-1;
 1127:     my $isencrypted=0;
 1128:     my $ishidden=0;
 1129:     my $is_random_order=0;
 1130:     if (!$allowed) {
 1131:         my $description = $env{'course.'.$env{'request.course.id'}.'.description'};
 1132:         &Apache::lonhtmlcommon::add_breadcrumb(
 1133:                                                {'href' => '/adm/menu',
 1134:                                                 'title'=> 'Go to main menu',
 1135:                                                 'text' => $description,
 1136:                                                });
 1137:         $plain .= $description.' &gt;';
 1138:     }
 1139:     while (@folders) {
 1140: 	my $folder=shift(@folders);
 1141:     	my $foldername=shift(@folders);
 1142: 	if ($folderpath) {$folderpath.='&';}
 1143: 	$folderpath.=$folder.'&'.$foldername;
 1144: 	my $url='/adm/coursedocs?folderpath='.
 1145: 	    &escape($folderpath);
 1146: 	    my $name=&unescape($foldername);
 1147: # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
 1148:  	    $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
 1149: 	    if ($1 ne '') {
 1150:                $randompick=$1;
 1151:             } else {
 1152:                $randompick=-1;
 1153:             }
 1154:             if ($2) { $ishidden=1; }
 1155:             if ($3) { $isencrypted=1; }
 1156: 	    if ($4 ne '') { $is_random_order = 1; }
 1157:             if ($folder eq 'supplemental') {
 1158:                 $name = &mt('Supplemental '.$crstype.' Documents');
 1159:             }
 1160: 	    &Apache::lonhtmlcommon::add_breadcrumb(
 1161: 		      {'href'=>$url.$cpinfo,
 1162: 		       'title'=>$name,
 1163: 		       'text'=>$name,
 1164: 		       'no_mt'=>1,
 1165: 		       });
 1166: 	$plain.=$name.' &gt; ';
 1167:     }
 1168:     $plain=~s/\&gt\;\s*$//;
 1169:     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
 1170: 					       undef, undef, 1 ),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);
 1171: }
 1172: 
 1173: sub log_docs {
 1174:     return &Apache::lonnet::instructor_log('docslog',@_);
 1175: }
 1176: 
 1177: {
 1178:     my @oldresources=();
 1179:     my @oldorder=();
 1180:     my $parmidx;
 1181:     my %parmaction=();
 1182:     my %parmvalue=();
 1183:     my $changedflag;
 1184: 
 1185:     sub snapshotbefore {
 1186:         @oldresources=@LONCAPA::map::resources;
 1187:         @oldorder=@LONCAPA::map::order;
 1188:         $parmidx=undef;
 1189:         %parmaction=();
 1190:         %parmvalue=();
 1191:         $changedflag=0;
 1192:     }
 1193: 
 1194:     sub remember_parms {
 1195:         my ($idx,$parameter,$action,$value)=@_;
 1196:         $parmidx=$idx;
 1197:         $parmaction{$parameter}=$action;
 1198:         $parmvalue{$parameter}=$value;
 1199:         $changedflag=1;
 1200:     }
 1201: 
 1202:     sub log_differences {
 1203:         my ($plain)=@_;
 1204:         my %storehash=('folder' => $plain,
 1205:                        'currentfolder' => $env{'form.folder'});
 1206:         if ($parmidx) {
 1207:            $storehash{'parameter_res'}=$oldresources[$parmidx];
 1208:            foreach my $parm (keys(%parmaction)) {
 1209:               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
 1210:               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
 1211:            }
 1212:         }
 1213:         my $maxidx=$#oldresources;
 1214:         if ($#LONCAPA::map::resources>$#oldresources) {
 1215:            $maxidx=$#LONCAPA::map::resources;
 1216:         }
 1217:         for (my $idx=0; $idx<=$maxidx; $idx++) {
 1218:            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
 1219:               $storehash{'before_resources_'.$idx}=$oldresources[$idx];
 1220:               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
 1221:               $changedflag=1;
 1222:            }
 1223:            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
 1224:               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
 1225:               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
 1226:               $changedflag=1;
 1227:            }
 1228:         }
 1229: 	$storehash{'maxidx'}=$maxidx;
 1230:         if ($changedflag) { &log_docs(\%storehash); }
 1231:     }
 1232: }
 1233: 
 1234: 
 1235: 
 1236: 
 1237: 
 1238: sub docs_change_log {
 1239:     my ($r)=@_;
 1240:     my $folder=$env{'form.folder'};
 1241:     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));
 1242:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));
 1243:     my %docslog=&Apache::lonnet::dump('nohist_docslog',
 1244:                                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 1245:                                       $env{'course.'.$env{'request.course.id'}.'.num'});
 1246: 
 1247:     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 1248: 
 1249:     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.
 1250:               '<input type="hidden" name="docslog" value="1" />');
 1251: 
 1252:     my %saveable_parameters = ('show' => 'scalar',);
 1253:     &Apache::loncommon::store_course_settings('docs_log',
 1254:                                               \%saveable_parameters);
 1255:     &Apache::loncommon::restore_course_settings('docs_log',
 1256:                                                 \%saveable_parameters);
 1257:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1258: # FIXME: internationalization seems wrong here
 1259:     my %lt=('hiddenresource' => 'Resources hidden',
 1260: 	    'encrypturl'     => 'URL hidden',
 1261: 	    'randompick'     => 'Randomly pick',
 1262: 	    'randomorder'    => 'Randomly ordered',
 1263: 	    'set'            => 'set to',
 1264: 	    'del'            => 'deleted');
 1265:     $r->print(&Apache::loncommon::display_filter().
 1266:               '<input type="hidden" name="folder" value="'.$folder.'" />'.
 1267:               '<input type="submit" value="'.&mt('Display').'" /></form>');
 1268:     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
 1269:               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
 1270:               &mt('After').'</th>'.
 1271:               &Apache::loncommon::end_data_table_header_row());
 1272:     my $shown=0;
 1273:     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
 1274: 	if ($env{'form.displayfilter'} eq 'currentfolder') {
 1275: 	    if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
 1276: 	}
 1277:         my @changes=keys(%{$docslog{$id}{'logentry'}});
 1278:         if ($env{'form.displayfilter'} eq 'containing') {
 1279: 	    my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
 1280: 		&Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
 1281: 	    foreach my $key (@changes) {
 1282: 		$wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
 1283: 	    }
 1284: 	    if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
 1285: 	}
 1286:         my $count = 0;
 1287:         my $time =
 1288:             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
 1289:         my $plainname =
 1290:             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
 1291:                                           $docslog{$id}{'exe_udom'});
 1292:         my $about_me_link =
 1293:             &Apache::loncommon::aboutmewrapper($plainname,
 1294:                                                $docslog{$id}{'exe_uname'},
 1295:                                                $docslog{$id}{'exe_udom'});
 1296:         my $send_msg_link='';
 1297:         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
 1298:              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
 1299:             $send_msg_link ='<br />'.
 1300:                 &Apache::loncommon::messagewrapper(&mt('Send message'),
 1301:                                                    $docslog{$id}{'exe_uname'},
 1302:                                                    $docslog{$id}{'exe_udom'});
 1303:         }
 1304:         $r->print(&Apache::loncommon::start_data_table_row());
 1305:         $r->print('<td>'.$time.'</td>
 1306:                        <td>'.$about_me_link.
 1307:                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.
 1308:                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
 1309:                   $send_msg_link.'</td><td>'.
 1310:                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
 1311: # Before
 1312: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1313: 	    my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
 1314: 	    my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
 1315: 	    if ($oldname ne $newname) {
 1316: 		$r->print(&LONCAPA::map::qtescape($oldname));
 1317: 	    }
 1318: 	}
 1319: 	$r->print('<ul>');
 1320: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1321:             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
 1322: 		$r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
 1323: 	    }
 1324: 	}
 1325: 	$r->print('</ul>');
 1326: # After
 1327:         $r->print('</td><td>');
 1328: 
 1329: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1330: 	    my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
 1331: 	    my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
 1332: 	    if ($oldname ne '' && $oldname ne $newname) {
 1333: 		$r->print(&LONCAPA::map::qtescape($newname));
 1334: 	    }
 1335: 	}
 1336: 	$r->print('<ul>');
 1337: 	for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 1338:             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
 1339: 		$r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
 1340: 	    }
 1341: 	}
 1342: 	$r->print('</ul>');
 1343: 	if ($docslog{$id}{'logentry'}{'parameter_res'}) {
 1344: 	    $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
 1345: 	    foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
 1346: 		if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
 1347: # FIXME: internationalization seems wrong here
 1348: 		    $r->print('<li>'.
 1349: 			      &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
 1350: 				  $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
 1351: 			      .'</li>');
 1352: 		}
 1353: 	    }
 1354: 	    $r->print('</ul>');
 1355: 	}
 1356: # End
 1357:         $r->print('</td>'.&Apache::loncommon::end_data_table_row());
 1358:         $shown++;
 1359:         if (!($env{'form.show'} eq &mt('all')
 1360:               || $shown<=$env{'form.show'})) { last; }
 1361:     }
 1362:     $r->print(&Apache::loncommon::end_data_table());
 1363: }
 1364: 
 1365: sub update_paste_buffer {
 1366:     my ($coursenum,$coursedom) = @_;
 1367: 
 1368:     return if (!defined($env{'form.markcopy'}));
 1369:     return if (!defined($env{'form.copyfolder'}));
 1370:     return if ($env{'form.markcopy'} < 0);
 1371: 
 1372:     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 1373: 				    $env{'form.copyfolder'});
 1374: 
 1375:     return if ($fatal);
 1376: 
 1377: # Mark for copying
 1378:     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
 1379:     if (&is_supplemental_title($title)) {
 1380:         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
 1381: 	($title) = &parse_supplemental_title($title);
 1382:     } elsif ($env{'docs.markedcopy_supplemental'}) {
 1383:         &Apache::lonnet::delenv('docs.markedcopy_supplemental');
 1384:     }
 1385:     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 1386: 
 1387:     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
 1388: 			    'docs.markedcopy_url'   => $url});
 1389:     delete($env{'form.markcopy'});
 1390: }
 1391: 
 1392: sub print_paste_buffer {
 1393:     my ($r,$container) = @_;
 1394:     return if (!defined($env{'docs.markedcopy_url'}));
 1395: 
 1396:     $r->print('<fieldset>'
 1397:              .'<legend>'.&mt('Clipboard').'</legend>'
 1398:              .'<form name="pasteform" action="/adm/coursedocs" method="post">'
 1399:              .'<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> '
 1400:     );
 1401: 
 1402:     my $type;
 1403:     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
 1404: 	$type = &mt('External Resource');
 1405: 	$r->print($type.': '.
 1406: 		  &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
 1407: 		  &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
 1408:     }  else {
 1409: 	my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
 1410: 	my $icon = &Apache::loncommon::icon($extension);
 1411: 	if ($extension eq 'sequence' &&
 1412: 	    $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
 1413: 	    $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
 1414: 	    $icon .= '/navmap.folder.closed.gif';
 1415: 	}
 1416: 	$icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
 1417: 	$r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
 1418:     }
 1419:     if ($container eq 'page') {
 1420: 	$r->print('
 1421: 	<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
 1422: 	<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
 1423: ');
 1424:     } else {
 1425: 	$r->print('
 1426:         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
 1427: ');
 1428:     }
 1429:     $r->print('</form></fieldset>');
 1430: }
 1431: 
 1432: sub do_paste_from_buffer {
 1433:     my ($coursenum,$coursedom,$folder) = @_;
 1434: 
 1435:     if (!$env{'form.pastemarked'}) {
 1436:         return;
 1437:     }
 1438: 
 1439: # paste resource to end of list
 1440:     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
 1441:     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
 1442: # Maps need to be copied first
 1443:     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
 1444: 	$title=&mt('Copy of').' '.$title;
 1445: 	my $newid=$$.int(rand(100)).time;
 1446: 	my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
 1447:         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
 1448:             my $path = $1;
 1449:             my $prefix = $2;
 1450:             my $ancestor = $3;
 1451:             if (length($ancestor) > 10) {
 1452:                 $ancestor = substr($ancestor,-10,10);
 1453:             }
 1454:             $oldid = $path.$prefix.$ancestor;
 1455:         }
 1456:         my $counter = 0;
 1457:         my $newurl=$oldid.$newid.'.'.$ext;
 1458:         my $is_unique = &uniqueness_check($newurl);
 1459:         while (!$is_unique && $counter < 100) {
 1460:             $counter ++;
 1461:             $newid ++;
 1462:             $newurl = $oldid.$newid;
 1463:             $is_unique = &uniqueness_check($newurl);
 1464:         }
 1465:         if (!$is_unique) {
 1466:             if ($url=~/\.page$/) {
 1467:                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
 1468:             } else {
 1469:                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');
 1470:             }
 1471:         }
 1472: 	my $storefn=$newurl;
 1473: 	$storefn=~s{^/\w+/$match_domain/$match_username/}{};
 1474: 	my $paste_map_result =
 1475:             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
 1476: 					       &Apache::lonnet::getfile($url));
 1477:         if ($paste_map_result eq '/adm/notfound.html') {
 1478:             if ($url=~/\.page$/) {
 1479:                 return &mt('Paste failed: an error occurred saving the composite page');
 1480:             } else {
 1481:                 return &mt('Paste failed: an error occurred saving the folder');
 1482:             }
 1483:         }
 1484: 	$url = $newurl;
 1485:     }
 1486: # published maps can only exists once, so remove it from paste buffer when done
 1487:     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
 1488: 	&Apache::lonnet::delenv('docs.markedcopy');
 1489:     }
 1490:     if ($url=~ m{/smppg$}) {
 1491: 	my $db_name = &Apache::lonsimplepage::get_db_name($url);
 1492: 	if ($db_name =~ /^smppage_/) {
 1493: 	    #simple pages, need to copy the db contents to a new one.
 1494: 	    my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
 1495: 	    my $now = time();
 1496: 	    $db_name =~ s{_\d*$ }{_$now}x;
 1497: 	    my $result=&Apache::lonnet::put($db_name,\%contents,
 1498: 					    $coursedom,$coursenum);
 1499: 	    $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
 1500: 	    $title=&mt('Copy of').' '.$title;
 1501: 	}
 1502:     }
 1503:     $title = &LONCAPA::map::qtunescape($title);
 1504:     my $ext='false';
 1505:     if ($url=~m{^http(|s)://}) { $ext='true'; }
 1506:     $url       = &LONCAPA::map::qtunescape($url);
 1507: # Now insert the URL at the bottom
 1508:     my $newidx = &LONCAPA::map::getresidx($url);
 1509:     if ($env{'docs.markedcopy_supplemental'}) {
 1510:         if ($folder =~ /^supplemental/) {
 1511:             $title = $env{'docs.markedcopy_supplemental'};
 1512:         } else {
 1513:             (undef,undef,$title) =
 1514:                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
 1515:         }
 1516:     } else {
 1517:         if ($folder=~/^supplemental/) {
 1518:            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 1519:                   $env{'user.domain'}.'___&&&___'.$title;
 1520:         }
 1521:     }
 1522: 
 1523:     $LONCAPA::map::resources[$newidx]= 	$title.':'.$url.':'.$ext.':normal:res';
 1524:     push(@LONCAPA::map::order, $newidx);
 1525:     return 'ok';
 1526: # Store the result
 1527: }
 1528: 
 1529: sub uniqueness_check {
 1530:     my ($newurl) = @_;
 1531:     my $unique = 1;
 1532:     foreach my $res (@LONCAPA::map::order) {
 1533:         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 1534:         $url=&LONCAPA::map::qtescape($url);
 1535:         if ($newurl eq $url) {
 1536:             $unique = 0;
 1537:             last;
 1538:         }
 1539:     }
 1540:     return $unique;
 1541: }
 1542: 
 1543: my %parameter_type = ( 'randompick'     => 'int_pos',
 1544: 		       'hiddenresource' => 'string_yesno',
 1545: 		       'encrypturl'     => 'string_yesno',
 1546: 		       'randomorder'    => 'string_yesno',);
 1547: my $valid_parameters_re = join('|',keys(%parameter_type));
 1548: # set parameters
 1549: sub update_parameter {
 1550: 
 1551:     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
 1552: 
 1553:     my $which = $env{'form.changeparms'};
 1554:     my $idx = $env{'form.setparms'};
 1555:     if ($env{'form.'.$which.'_'.$idx}) {
 1556: 	my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
 1557: 	                                     : 'yes';
 1558: 	&LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
 1559: 				      $parameter_type{$which});
 1560: 	&remember_parms($idx,$which,'set',$value);
 1561:     } else {
 1562: 	&LONCAPA::map::delparameter($idx,'parameter_'.$which);
 1563: 
 1564: 	&remember_parms($idx,$which,'del');
 1565:     }
 1566:     return 1;
 1567: }
 1568: 
 1569: 
 1570: sub handle_edit_cmd {
 1571:     my ($coursenum,$coursedom) =@_;
 1572: 
 1573:     my ($cmd,$idx)=split('_',$env{'form.cmd'});
 1574: 
 1575:     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
 1576:     my ($title, $url, @rrest) = split(':', $ratstr);
 1577: 
 1578:     if ($cmd eq 'del') {
 1579: 	if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 1580: 	    ($url!~/$LONCAPA::assess_page_seq_re/)) {
 1581: 	    &Apache::lonnet::removeuploadedurl($url);
 1582: 	} else {
 1583: 	    &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 1584: 	}
 1585: 	splice(@LONCAPA::map::order, $idx, 1);
 1586: 
 1587:     } elsif ($cmd eq 'cut') {
 1588: 	&LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 1589: 	splice(@LONCAPA::map::order, $idx, 1);
 1590: 
 1591:     } elsif ($cmd eq 'up'
 1592: 	     && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
 1593: 	@LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
 1594: 
 1595:     } elsif ($cmd eq 'down'
 1596: 	     && defined($LONCAPA::map::order[$idx+1])) {
 1597: 	@LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
 1598: 
 1599:     } elsif ($cmd eq 'rename') {
 1600: 
 1601: 	my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
 1602: 	if ($comment=~/\S/) {
 1603: 	    $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
 1604: 		$comment.':'.join(':', $url, @rrest);
 1605: 	}
 1606: # Devalidate title cache
 1607: 	my $renamed_url=&LONCAPA::map::qtescape($url);
 1608: 	&Apache::lonnet::devalidate_title_cache($renamed_url);
 1609:     } else {
 1610: 	return 0;
 1611:     }
 1612:     return 1;
 1613: }
 1614: 
 1615: sub editor {
 1616:     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 1617:         $supplementalflag,$orderhash)=@_;
 1618:     my $container= ($env{'form.pagepath'}) ? 'page'
 1619: 		                           : 'sequence';
 1620: 
 1621:     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 1622: 				    $folder.'.'.$container);
 1623:     return $errtext if ($fatal);
 1624: 
 1625:     if ($#LONCAPA::map::order<1) {
 1626: 	my $idx=&LONCAPA::map::getresidx();
 1627: 	if ($idx<=0) { $idx=1; }
 1628:        	$LONCAPA::map::order[0]=$idx;
 1629:         $LONCAPA::map::resources[$idx]='';
 1630:     }
 1631: 
 1632:     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order) =
 1633: 	    &breadcrumbs($allowed,$crstype);
 1634:         $r->print($breadcrumbtrail);
 1635: 
 1636:     unless ($allowed) {
 1637:         $randompick = -1;
 1638:     }
 1639: 
 1640: # ------------------------------------------------------------ Process commands
 1641: 
 1642: # ---------------- if they are for this folder and user allowed to make changes
 1643:     if (($allowed) && ($env{'form.folder'} eq $folder)) {
 1644: # set parameters and change order
 1645: 	&snapshotbefore();
 1646: 
 1647: 	if (&update_parameter()) {
 1648: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 1649: 	    return $errtext if ($fatal);
 1650: 	}
 1651: 
 1652: 	if ($env{'form.newpos'} && $env{'form.currentpos'}) {
 1653: # change order
 1654: 	    my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
 1655: 	    splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
 1656: 
 1657: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 1658: 	    return $errtext if ($fatal);
 1659: 	}
 1660: 
 1661: 	if ($env{'form.pastemarked'}) {
 1662:             my $paste_res =
 1663:                 &do_paste_from_buffer($coursenum,$coursedom,$folder);
 1664:             if ($paste_res eq 'ok') {
 1665:                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
 1666:                 return $errtext if ($fatal);
 1667:             } elsif ($paste_res ne '') {
 1668:                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
 1669:             }
 1670: 	}
 1671: 
 1672: 	$r->print($upload_output);
 1673: 
 1674: 	if (&handle_edit_cmd()) {
 1675: 	    ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 1676: 	    return $errtext if ($fatal);
 1677: 	}
 1678: # Group import/search
 1679: 	if ($env{'form.importdetail'}) {
 1680: 	    my @imports;
 1681: 	    foreach my $item (split(/\&/,$env{'form.importdetail'})) {
 1682: 		if (defined($item)) {
 1683: 		    my ($name,$url,$residx)=
 1684: 			map {&unescape($_)} split(/\=/,$item);
 1685: 		    push(@imports, [$name, $url, $residx]);
 1686: 		}
 1687: 	    }
 1688: 	    ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
 1689: 					    $container,'londocs',@imports);
 1690: 	    return $errtext if ($fatal);
 1691: 	}
 1692: # Loading a complete map
 1693: 	if ($env{'form.loadmap'}) {
 1694: 	    if ($env{'form.importmap'}=~/\w/) {
 1695: 		foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
 1696: 		    my ($title,$url,$ext,$type)=split(/\:/,$res);
 1697: 		    my $idx=&LONCAPA::map::getresidx($url);
 1698: 		    $LONCAPA::map::resources[$idx]=$res;
 1699: 		    $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
 1700: 		}
 1701: 		($errtext,$fatal)=&storemap($coursenum,$coursedom,
 1702: 					    $folder.'.'.$container);
 1703: 		return $errtext if ($fatal);
 1704: 	    } else {
 1705: 		$r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
 1706: 
 1707: 	    }
 1708: 	}
 1709: 	&log_differences($plain);
 1710:     }
 1711: # ---------------------------------------------------------------- End commands
 1712: # ---------------------------------------------------------------- Print screen
 1713:     my $idx=0;
 1714:     my $shown=0;
 1715:     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
 1716: 	$r->print('<div class="LC_Box">'.
 1717:           '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
 1718: 		  ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
 1719: 		  ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
 1720: 		  ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
 1721: 		  ($is_random_order?'<li>'.&mt('random order').'</li>':'').
 1722: 		  '</ol>');
 1723:         if ($randompick>=0) {
 1724:             $r->print('<p class="LC_warning">'
 1725:                  .&mt('Caution: this folder is set to randomly pick a subset'
 1726:                      .' of resources. Adding or removing resources from this'
 1727:                      .' folder will change the set of resources that the'
 1728:                      .' students see, resulting in spurious or missing credit'
 1729:                      .' for completed problems, not limited to ones you'
 1730:                      .' modify. Do not modify the contents of this folder if'
 1731:                      .' it is in active student use.')
 1732:                  .'</p>'
 1733:             );
 1734:         }
 1735:         if ($is_random_order) {
 1736:             $r->print('<p class="LC_warning">'
 1737:                  .&mt('Caution: this folder is set to randomly order its'
 1738:                      .' contents. Adding or removing resources from this folder'
 1739:                      .' will change the order of resources shown.')
 1740:                  .'</p>'
 1741:             );
 1742:         }
 1743:         $r->print('</div>');
 1744:     }
 1745: 
 1746:     my ($to_show,$output);
 1747: 
 1748:     &Apache::loncommon::start_data_table_count(); #setup a row counter 
 1749:     foreach my $res (@LONCAPA::map::order) {
 1750:         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 1751:         $name=&LONCAPA::map::qtescape($name);
 1752:         $url=&LONCAPA::map::qtescape($url);
 1753:         unless ($name) {  $name=(split(/\//,$url))[-1]; }
 1754:         unless ($name) { $idx++; next; }
 1755:         $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
 1756:                               $coursenum,$crstype);
 1757:         $idx++;
 1758:         $shown++;
 1759:     }
 1760:     &Apache::loncommon::end_data_table_count();
 1761:     
 1762:     if ($shown) {
 1763:         $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
 1764:                   .&Apache::loncommon::start_data_table(undef,'contentlist');
 1765:         if ($allowed) {
 1766:             $to_show .= &Apache::loncommon::start_data_table_header_row()
 1767:                      .'<th colspan="2">'.&mt('Move').'</th>'
 1768:                      .'<th>'.&mt('Actions').'</th>'
 1769:                      .'<th colspan="2">'.&mt('Document').'</th>';
 1770:             if ($folder !~ /^supplemental/) {
 1771:                 $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
 1772:             }
 1773:             $to_show .= &Apache::loncommon::end_data_table_header_row();
 1774:         }
 1775:         $to_show .= $output.' '
 1776:                  .&Apache::loncommon::end_data_table()
 1777:                  .'<br style="line-height:2px;" />'
 1778:                  .&Apache::loncommon::end_scrollbox();
 1779:     } else {
 1780:         $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
 1781:                  .'<div class="LC_info" id="contentlist">'
 1782:                  .&mt('Currently no documents.')
 1783:                  .'</div>'
 1784:                  .&Apache::loncommon::end_scrollbox();
 1785:     }
 1786:     my $tid = 1;
 1787:     if ($supplementalflag) {
 1788:         $tid = 2;
 1789:     }
 1790:     if ($allowed) {
 1791:         $r->print(&generate_edit_table($tid,$orderhash,$to_show));
 1792:         &print_paste_buffer($r,$container);
 1793:     } else {
 1794:         $r->print($to_show);
 1795:     }
 1796:     return;
 1797: }
 1798: 
 1799: sub process_file_upload {
 1800:     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
 1801: # upload a file, if present
 1802:     my ($parseaction,$showupload,$nextphase,$mimetype);
 1803:     if ($env{'form.parserflag'}) {
 1804:         $parseaction = 'parse';
 1805:     }
 1806:     my $folder=$env{'form.folder'};
 1807:     if ($folder eq '') {
 1808:         $folder='default';
 1809:     }
 1810:     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
 1811:         my $errtext='';
 1812:         my $fatal=0;
 1813:         my $container='sequence';
 1814:         if ($env{'form.pagepath'}) {
 1815:             $container='page';
 1816:         }
 1817:         ($errtext,$fatal)=
 1818:               &mapread($coursenum,$coursedom,$folder.'.'.$container);
 1819:         if ($#LONCAPA::map::order<1) {
 1820:             $LONCAPA::map::order[0]=1;
 1821:             $LONCAPA::map::resources[1]='';
 1822:         }
 1823:         if ($fatal) {
 1824:             $$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>';
 1825:             return;
 1826:         }
 1827:         my $destination = 'docs/';
 1828:         if ($folder =~ /^supplemental/) {
 1829:             $destination = 'supplemental/';
 1830:         }
 1831:         if (($folder eq 'default') || ($folder eq 'supplemental')) {
 1832:             $destination .= 'default/';
 1833:         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 1834:             $destination .=  $2.'/';
 1835:         }
 1836: # this is for a course, not a user, so set context to coursedoc.
 1837:         my $newidx=&LONCAPA::map::getresidx();
 1838:         $destination .= $newidx;
 1839:         my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
 1840: 						$parseaction,$allfiles,
 1841: 						$codebase,undef,undef,undef,undef,
 1842:                                                 undef,undef,\$mimetype);
 1843:         if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
 1844:             my $stored = $1;
 1845:             $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 1846:                           $stored.'</span>').'</p>';
 1847:         } else {
 1848:             my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
 1849:             
 1850:             $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
 1851:             return;
 1852:         }
 1853:         my $ext='false';
 1854:         if ($url=~m{^http://}) { $ext='true'; }
 1855: 	$url     = &LONCAPA::map::qtunescape($url);
 1856:         my $comment=$env{'form.comment'};
 1857: 	$comment = &LONCAPA::map::qtunescape($comment);
 1858:         if ($folder=~/^supplemental/) {
 1859:               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 1860:                   $env{'user.domain'}.'___&&&___'.$comment;
 1861:         }
 1862: 
 1863:         $LONCAPA::map::resources[$newidx]=
 1864: 	    $comment.':'.$url.':'.$ext.':normal:res';
 1865:         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
 1866:         ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 1867: 				    $folder.'.'.$container);
 1868:         if ($fatal) {
 1869:             $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
 1870:             return;
 1871:         } else {
 1872:             if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
 1873:                 $$upload_output = $showupload;
 1874:                 my $total_embedded = scalar(keys(%{$allfiles}));
 1875:                 if ($total_embedded > 0) {
 1876:                     my $uploadphase = 'upload_embedded';
 1877:                     my $primaryurl = &HTML::Entities::encode($url,'<>&"');
 1878: 		    my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
 1879:                     my ($embedded,$num) = 
 1880:                         &Apache::loncommon::ask_for_embedded_content(
 1881:                             '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
 1882:                     if ($embedded) {
 1883:                         if ($num) {
 1884:                             $$upload_output .=
 1885: 			         '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
 1886:                             $nextphase = $uploadphase;
 1887:                         } else {
 1888:                             $$upload_output .= $embedded;
 1889:                         }
 1890:                     } else {
 1891:                         $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
 1892:                     }
 1893:                 } else {
 1894:                     $$upload_output .= &mt('No embedded items identified').'<br />';
 1895:                 }
 1896:                 $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
 1897:             }
 1898:         }
 1899:     }
 1900:     return $nextphase;
 1901: }
 1902: 
 1903: sub is_supplemental_title {
 1904:     my ($title) = @_;
 1905:     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
 1906: }
 1907: 
 1908: sub parse_supplemental_title {
 1909:     my ($title) = @_;
 1910: 
 1911:     my ($foldertitle,$renametitle);
 1912:     if ($title =~ /&amp;&amp;&amp;/) {
 1913: 	$title = &HTML::Entites::decode($title);
 1914:     }
 1915:  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
 1916: 	$renametitle=$4;
 1917: 	my ($time,$uname,$udom) = ($1,$2,$3);
 1918: 	$foldertitle=&Apache::lontexconvert::msgtexconverted($4);
 1919: 	my $name =  &Apache::loncommon::plainname($uname,$udom);
 1920: 	$name = &HTML::Entities::encode($name,'"<>&\'');
 1921:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
 1922: 	$title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
 1923: 	    $name.': <br />'.$foldertitle;
 1924:     }
 1925:     if (wantarray) {
 1926: 	return ($title,$foldertitle,$renametitle);
 1927:     }
 1928:     return $title;
 1929: }
 1930: 
 1931: # --------------------------------------------------------------- An entry line
 1932: 
 1933: sub entryline {
 1934:     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$crstype)=@_;
 1935:     my ($foldertitle,$pagetitle,$renametitle);
 1936:     if (&is_supplemental_title($title)) {
 1937: 	($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
 1938: 	$pagetitle = $foldertitle;
 1939:     } else {
 1940: 	$title=&HTML::Entities::encode($title,'"<>&\'');
 1941: 	$renametitle=$title;
 1942: 	$foldertitle=$title;
 1943: 	$pagetitle=$title;
 1944:     }
 1945: 
 1946:     my $orderidx=$LONCAPA::map::order[$index];
 1947: 
 1948: 
 1949:     $renametitle=~s/\\/\\\\/g;
 1950:     $renametitle=~s/\&quot\;/\\\"/g;
 1951:     $renametitle=~s/ /%20/g;
 1952:     my $line=&Apache::loncommon::start_data_table_row();
 1953:     my ($form_start,$form_end);
 1954: # Edit commands
 1955:     my ($container, $type, $esc_path, $path, $symb);
 1956:     if ($env{'form.folderpath'}) {
 1957: 	$type = 'folder';
 1958:         $container = 'sequence';
 1959: 	$esc_path=&escape($env{'form.folderpath'});
 1960: 	$path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 1961: 	# $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 1962:     }
 1963:     if ($env{'form.pagepath'}) {
 1964:         $type = $container = 'page';
 1965:         $esc_path=&escape($env{'form.pagepath'});
 1966: 	$path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
 1967:         $symb=&escape($env{'form.pagesymb'});
 1968:     }
 1969:     my $cpinfo='';
 1970:     if ($allowed) {
 1971: 	my $incindex=$index+1;
 1972: 	my $selectbox='';
 1973: 	if (($folder!~/^supplemental/) &&
 1974: 	    ($#LONCAPA::map::order>0) &&
 1975: 	    ((split(/\:/,
 1976: 	     $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
 1977: 	     ne '') &&
 1978: 	    ((split(/\:/,
 1979: 	     $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
 1980: 	     ne '')) {
 1981: 	    $selectbox=
 1982: 		'<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
 1983: 		'<select name="newpos" onchange="this.form.submit()">';
 1984: 	    for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
 1985: 		if ($i==$incindex) {
 1986: 		    $selectbox.='<option value="" selected="selected">('.$i.')</option>';
 1987: 		} else {
 1988: 		    $selectbox.='<option value="'.$i.'">'.$i.'</option>';
 1989: 		}
 1990: 	    }
 1991: 	    $selectbox.='</select>';
 1992: 	}
 1993: 	my %lt=&Apache::lonlocal::texthash(
 1994:                 'up' => 'Move Up',
 1995: 		'dw' => 'Move Down',
 1996: 		'rm' => 'Remove',
 1997:                 'ct' => 'Cut',
 1998: 		'rn' => 'Rename',
 1999: 		'cp' => 'Copy');
 2000: 	my $nocopy=0;
 2001:         my $nocut=0;
 2002:         if ($url=~/\.(page|sequence)$/) {
 2003: 	    if ($url =~ m{/res/}) {
 2004: 		# no copy for published maps
 2005: 		$nocopy = 1;
 2006: 	    } else {
 2007: 		foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
 2008: 		    my ($title,$url,$ext,$type)=split(/\:/,$item);
 2009: 		    if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
 2010: 			$nocopy=1;
 2011: 			last;
 2012: 		    }
 2013: 		}
 2014: 	    }
 2015: 	}
 2016:         if ($url=~/^\/res\/lib\/templates\//) {
 2017:            $nocopy=1;
 2018:            $nocut=1;
 2019:         }
 2020:         my $copylink='&nbsp;';
 2021:         my $cutlink='&nbsp;';
 2022: 
 2023: 	my $skip_confirm = 0;
 2024: 	if ( $folder =~ /^supplemental/
 2025: 	     || ($url =~ m{( /smppg$
 2026: 			    |/syllabus$
 2027: 			    |/aboutme$
 2028: 			    |/navmaps$
 2029: 			    |/bulletinboard$
 2030: 			    |\.html$
 2031: 			    |^/adm/wrapper/ext)}x)) {
 2032: 	    $skip_confirm = 1;
 2033: 	}
 2034: 
 2035: 	if (!$nocopy) {
 2036: 	    $copylink=(<<ENDCOPY);
 2037: <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
 2038: ENDCOPY
 2039:         }
 2040: 	if (!$nocut) {
 2041: 	    $cutlink=(<<ENDCUT);
 2042: <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
 2043: ENDCUT
 2044:         }
 2045: 	$form_start = (<<END);
 2046:    <form  action="/adm/coursedocs" method="post">
 2047:    <input type="hidden" name="${type}path" value="$path" />
 2048:    <input type="hidden" name="${type}symb" value="$symb" />
 2049:    <input type="hidden" name="setparms" value="$orderidx" />
 2050:    <input type="hidden" name="changeparms" value="0" />
 2051: END
 2052:         $form_end = '</form>';
 2053: 	$line.=(<<END);
 2054: <td>
 2055: <div class="LC_docs_entry_move">
 2056:   <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'>
 2057:     <img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" />
 2058:   </a>
 2059: </div>
 2060: <div class="LC_docs_entry_move">
 2061:   <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'>
 2062:     <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" />
 2063:   </a>
 2064: </div>
 2065: </td>
 2066: <td>
 2067:    $form_start
 2068:    $selectbox
 2069:    $form_end
 2070: </td>
 2071: <td class="LC_docs_entry_commands">
 2072:    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
 2073: $cutlink
 2074:    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
 2075: $copylink
 2076: </td>
 2077: END
 2078: 
 2079:     }
 2080: # Figure out what kind of a resource this is
 2081:     my ($extension)=($url=~/\.(\w+)$/);
 2082:     my $uploaded=($url=~/^\/*uploaded\//);
 2083:     my $icon=&Apache::loncommon::icon($url);
 2084:     my $isfolder=0;
 2085:     my $ispage=0;
 2086:     my $folderarg;
 2087:     my $pagearg;
 2088:     my $pagefile;
 2089:     if ($uploaded) {
 2090: 	if ($extension eq 'sequence') {
 2091: 	    $icon=$iconpath.'/navmap.folder.closed.gif';
 2092: 	    $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
 2093: 	    $url='/adm/coursedocs?';
 2094: 	    $folderarg=$1;
 2095: 	    $isfolder=1;
 2096:         } elsif ($extension eq 'page') {
 2097:             $icon=$iconpath.'/page.gif';
 2098:             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
 2099:             $pagearg=$1;
 2100:             $url='/adm/coursedocs?';
 2101:             $ispage=1;
 2102: 	} else {
 2103: 	    &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 2104: 	}
 2105:     }
 2106: 
 2107:     my $orig_url = $url;
 2108:     $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 2109:     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
 2110:     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
 2111: 	my $symb=&Apache::lonnet::symbclean(
 2112:           &Apache::lonnet::declutter('uploaded/'.
 2113:            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 2114:            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
 2115:            '.sequence').
 2116:            '___'.$residx.'___'.
 2117: 	   &Apache::lonnet::declutter($url));
 2118: 	(undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 2119: 	$url=&Apache::lonnet::clutter($url);
 2120: 	if ($url=~/^\/*uploaded\//) {
 2121: 	    $url=~/\.(\w+)$/;
 2122: 	    my $embstyle=&Apache::loncommon::fileembstyle($1);
 2123: 	    if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
 2124: 		$url='/adm/wrapper'.$url;
 2125: 	    } elsif ($embstyle eq 'ssi') {
 2126: 		#do nothing with these
 2127: 	    } elsif ($url!~/\.(sequence|page)$/) {
 2128: 		$url='/adm/coursedocs/showdoc'.$url;
 2129: 	    }
 2130: 	} elsif ($url=~m|^/ext/|) {
 2131: 	    $url='/adm/wrapper'.$url;
 2132: 	    $external = 1;
 2133: 	}
 2134:         if (&Apache::lonnet::symbverify($symb,$url)) {
 2135: 	    $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
 2136:         } else {
 2137:             $url='';
 2138:         }
 2139: 	if ($container eq 'page') {
 2140: 	    my $symb=$env{'form.pagesymb'};
 2141: 
 2142: 	    $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 2143: 	    $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
 2144: 	}
 2145:     }
 2146:     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
 2147:     if ($isfolder || $extension eq 'sequence') {
 2148: 	my $foldername=&escape($foldertitle);
 2149: 	my $folderpath=$env{'form.folderpath'};
 2150: 	if ($folderpath) { $folderpath.='&' };
 2151: # Append randompick number, hidden, and encrypted with ":" to foldername,
 2152: # so it gets transferred between levels
 2153: 	$folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
 2154:                                               'parameter_randompick'))[0]
 2155:                                                .':'.((&LONCAPA::map::getparameter($orderidx,
 2156:                                               'parameter_hiddenresource'))[0]=~/^yes$/i)
 2157:                                                .':'.((&LONCAPA::map::getparameter($orderidx,
 2158:                                               'parameter_encrypturl'))[0]=~/^yes$/i)
 2159:                                                .':'.((&LONCAPA::map::getparameter($orderidx,
 2160:                                               'parameter_randomorder'))[0]=~/^yes$/i);
 2161: 	$url.='folderpath='.&escape($folderpath).$cpinfo;
 2162: 	$parameterset='<label>'.&mt('Randomly Pick: ').
 2163: 	    '<input type="text" size="4" onchange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
 2164: 	    (&LONCAPA::map::getparameter($orderidx,
 2165:                                               'parameter_randompick'))[0].
 2166:                                               '" />'.
 2167: '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
 2168:     	my $ro_set=
 2169: 	    ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
 2170: 	$rand_order_text ='
 2171: <span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" onclick="this.form.changeparms.value=\'randomorder\';this.form.submit()" '.$ro_set.' /> '.&mt('Random Order').' </label></span>';
 2172:     }
 2173:     if ($ispage) {
 2174:         my $pagename=&escape($pagetitle);
 2175:         my $pagepath;
 2176:         my $folderpath=$env{'form.folderpath'};
 2177:         if ($folderpath) { $pagepath = $folderpath.'&' };
 2178:         $pagepath.=$pagearg.'&'.$pagename;
 2179: 	my $symb=$env{'form.pagesymb'};
 2180: 	if (!$symb) {
 2181: 	    my $path='uploaded/'.
 2182: 		$env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 2183: 		$env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 2184: 	    $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
 2185: 					       $residx,
 2186: 					       $path.$pagearg.'.page');
 2187: 	}
 2188: 	$url.='pagepath='.&escape($pagepath).
 2189: 	    '&amp;pagesymb='.&escape($symb).$cpinfo;
 2190:     }
 2191:     if (($external) && ($allowed)) {
 2192: 	my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
 2193: 	$external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
 2194:     } else {
 2195: 	undef($external);
 2196:     }
 2197:     my $reinit;
 2198:     if ($crstype eq 'Community') {
 2199:         $reinit = &mt('(re-initialize community to access)');
 2200:     } else {
 2201:         $reinit = &mt('(re-initialize course to access)');
 2202:     }  
 2203:     $line.='
 2204:   <td>
 2205:     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
 2206:   </td>
 2207:   <td>
 2208:     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.$reinit.'</span>').$external."
 2209:   </td>";
 2210:     if (($allowed) && ($folder!~/^supplemental/)) {
 2211:  	my %lt=&Apache::lonlocal::texthash(
 2212:  			      'hd' => 'Hidden',
 2213:  			      'ec' => 'URL hidden');
 2214: 	my $enctext=
 2215: 	    ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
 2216: 	my $hidtext=
 2217: 	    ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
 2218: 	$line.=(<<ENDPARMS);
 2219:   <td class="LC_docs_entry_parameter">
 2220:     $form_start
 2221:     <label><input type="checkbox" name="hiddenresource_$orderidx" onclick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
 2222:     $form_end
 2223:     <br />
 2224:     $form_start
 2225:     <label><input type="checkbox" name="encrypturl_$orderidx" onclick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
 2226:     $form_end
 2227:   </td>
 2228:   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end<br />
 2229:                                       $form_start $rand_order_text $form_end</td>
 2230: ENDPARMS
 2231:     }
 2232:     $line.=&Apache::loncommon::end_data_table_row();
 2233:     return $line;
 2234: }
 2235: 
 2236: =pod
 2237: 
 2238: =item tiehash()
 2239: 
 2240: tie the hash
 2241: 
 2242: =cut
 2243: 
 2244: sub tiehash {
 2245:     my ($mode)=@_;
 2246:     $hashtied=0;
 2247:     if ($env{'request.course.fn'}) {
 2248: 	if ($mode eq 'write') {
 2249: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 2250: 		    &GDBM_WRCREAT(),0640)) {
 2251:                 $hashtied=2;
 2252: 	    }
 2253: 	} else {
 2254: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 2255: 		    &GDBM_READER(),0640)) {
 2256:                 $hashtied=1;
 2257: 	    }
 2258: 	}
 2259:     }
 2260: }
 2261: 
 2262: sub untiehash {
 2263:     if ($hashtied) { untie %hash; }
 2264:     $hashtied=0;
 2265:     return OK;
 2266: }
 2267: 
 2268: 
 2269: 
 2270: 
 2271: sub checkonthis {
 2272:     my ($r,$url,$level,$title)=@_;
 2273:     $url=&unescape($url);
 2274:     $alreadyseen{$url}=1;
 2275:     $r->rflush();
 2276:     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 2277:        $r->print("\n<br />");
 2278:        if ($level==0) {
 2279:            $r->print("<br />");
 2280:        }
 2281:        for (my $i=0;$i<=$level*5;$i++) {
 2282:            $r->print('&nbsp;');
 2283:        }
 2284:        $r->print('<a href="'.$url.'" target="cat">'.
 2285: 		 ($title?$title:$url).'</a> ');
 2286:        if ($url=~/^\/res\//) {
 2287: 	  my $result=&Apache::lonnet::repcopy(
 2288:                               &Apache::lonnet::filelocation('',$url));
 2289:           if ($result eq 'ok') {
 2290:              $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 2291:              $r->rflush();
 2292:              &Apache::lonnet::countacc($url);
 2293:              $url=~/\.(\w+)$/;
 2294:              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 2295: 		 $r->print('<br />');
 2296:                  $r->rflush();
 2297:                  for (my $i=0;$i<=$level*5;$i++) {
 2298:                      $r->print('&nbsp;');
 2299:                  }
 2300:                  $r->print('- '.&mt('Rendering:').' ');
 2301: 		 my ($errorcount,$warningcount)=split(/:/,
 2302: 	       &Apache::lonnet::ssi_body($url,
 2303: 			       ('grade_target'=>'web',
 2304: 				'return_only_error_and_warning_counts' => 1)));
 2305:                  if (($errorcount) ||
 2306:                      ($warningcount)) {
 2307: 		     if ($errorcount) {
 2308:                         $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
 2309:                           &mt('[quant,_1,error]',$errorcount).'</span>');
 2310:                      }
 2311: 		     if ($warningcount) {
 2312:                         $r->print('<span class="LC_warning">'.
 2313:                           &mt('[quant,_1,warning]',$warningcount).'</span>');
 2314:                      }
 2315:                  } else {
 2316:                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 2317:                  }
 2318:                  $r->rflush();
 2319:              }
 2320: 	     my $dependencies=
 2321:                 &Apache::lonnet::metadata($url,'dependencies');
 2322:              foreach my $dep (split(/\,/,$dependencies)) {
 2323: 		 if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 2324:                     &checkonthis($r,$dep,$level+1);
 2325:                  }
 2326:              }
 2327:           } elsif ($result eq 'unavailable') {
 2328:              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 2329:           } elsif ($result eq 'not_found') {
 2330: 	      unless ($url=~/\$/) {
 2331: 		  $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
 2332: 	      } else {
 2333: 		  $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
 2334: 	      }
 2335:           } else {
 2336:              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
 2337:           }
 2338:        }
 2339:     }
 2340: }
 2341: 
 2342: 
 2343: 
 2344: =pod
 2345: 
 2346: =item list_symbs()
 2347: 
 2348: List Symbs
 2349: 
 2350: =cut
 2351: 
 2352: sub list_symbs {
 2353:     my ($r) = @_;
 2354: 
 2355:     my $crstype = &Apache::loncommon::course_type();
 2356:     $r->print(&Apache::loncommon::start_page('Symb List'));
 2357:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
 2358:     &startContentScreen($r,'tools');
 2359:     my $navmap = Apache::lonnavmaps::navmap->new();
 2360:     if (!defined($navmap)) {
 2361:         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
 2362:                   '<div class="LC_error">'.
 2363:                   &mt('Unable to retrieve information about course contents').
 2364:                   '</div>');
 2365:         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
 2366:     } else {
 2367:         $r->print("<pre>\n");
 2368:         foreach my $res ($navmap->retrieveResources()) {
 2369:             $r->print($res->compTitle()."\t".$res->symb()."\n");
 2370:         }
 2371:         $r->print("\n</pre>\n");
 2372:     }
 2373: }
 2374: 
 2375: 
 2376: sub verifycontent {
 2377:     my ($r) = @_;
 2378:     my $crstype = &Apache::loncommon::course_type();
 2379:    $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
 2380:    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
 2381:    &startContentScreen($r,'tools');
 2382:    $hashtied=0;
 2383:    undef %alreadyseen;
 2384:    %alreadyseen=();
 2385:    &tiehash();
 2386:    foreach my $key (keys(%hash)) {
 2387:        if ($hash{$key}=~/\.(page|sequence)$/) {
 2388: 	   if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
 2389: 	       $r->print('<hr /><span class="LC_error">'.
 2390: 			 &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
 2391: 			 &unescape($hash{$key}).'</span><br />'.
 2392: 			 &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
 2393: 	   }
 2394:        }
 2395:        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 2396:            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
 2397:        }
 2398:    }
 2399:    &untiehash();
 2400:    $r->print('<p class="LC_success">'.&mt('Done').'</p>');
 2401: }
 2402: 
 2403: 
 2404: sub devalidateversioncache {
 2405:     my $src=shift;
 2406:     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
 2407: 					  &Apache::lonnet::clutter($src));
 2408: }
 2409: 
 2410: sub checkversions {
 2411:     my ($r) = @_;
 2412:     my $crstype = &Apache::loncommon::course_type();
 2413:     $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
 2414:     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
 2415:     &startContentScreen($r,'tools');
 2416: 
 2417:     my $header='';
 2418:     my $startsel='';
 2419:     my $monthsel='';
 2420:     my $weeksel='';
 2421:     my $daysel='';
 2422:     my $allsel='';
 2423:     my %changes=();
 2424:     my $starttime=0;
 2425:     my $haschanged=0;
 2426:     my %setversions=&Apache::lonnet::dump('resourceversions',
 2427: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 2428: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 2429: 
 2430:     $hashtied=0;
 2431:     &tiehash();
 2432:     my %newsetversions=();
 2433:     if ($env{'form.setmostrecent'}) {
 2434: 	$haschanged=1;
 2435: 	foreach my $key (keys(%hash)) {
 2436: 	    if ($key=~/^ids\_(\/res\/.+)$/) {
 2437: 		$newsetversions{$1}='mostrecent';
 2438:                 &devalidateversioncache($1);
 2439: 	    }
 2440: 	}
 2441:     } elsif ($env{'form.setcurrent'}) {
 2442: 	$haschanged=1;
 2443: 	foreach my $key (keys(%hash)) {
 2444: 	    if ($key=~/^ids\_(\/res\/.+)$/) {
 2445: 		my $getvers=&Apache::lonnet::getversion($1);
 2446: 		if ($getvers>0) {
 2447: 		    $newsetversions{$1}=$getvers;
 2448: 		    &devalidateversioncache($1);
 2449: 		}
 2450: 	    }
 2451: 	}
 2452:     } elsif ($env{'form.setversions'}) {
 2453: 	$haschanged=1;
 2454: 	foreach my $key (keys(%env)) {
 2455: 	    if ($key=~/^form\.set_version_(.+)$/) {
 2456: 		my $src=$1;
 2457: 		if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
 2458: 		    $newsetversions{$src}=$env{$key};
 2459: 		    &devalidateversioncache($src);
 2460: 		}
 2461: 	    }
 2462: 	}
 2463:     }
 2464:     if ($haschanged) {
 2465:         if (&Apache::lonnet::put('resourceversions',\%newsetversions,
 2466: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 2467: 			  $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 2468: 	    $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
 2469: 	} else {
 2470: 	    $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
 2471: 	}
 2472: 	&mark_hash_old();
 2473:     }
 2474:     &changewarning($r,'');
 2475:     if ($env{'form.timerange'} eq 'all') {
 2476: # show all documents
 2477: 	$header=&mt('All Documents in '.$crstype);
 2478: 	$allsel=1;
 2479: 	foreach my $key (keys(%hash)) {
 2480: 	    if ($key=~/^ids\_(\/res\/.+)$/) {
 2481: 		my $src=$1;
 2482: 		$changes{$src}=1;
 2483: 	    }
 2484: 	}
 2485:     } else {
 2486: # show documents which changed
 2487: 	%changes=&Apache::lonnet::dump
 2488: 	 ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
 2489:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 2490: 	my $firstkey=(keys(%changes))[0];
 2491: 	unless ($firstkey=~/^error\:/) {
 2492: 	    unless ($env{'form.timerange'}) {
 2493: 		$env{'form.timerange'}=604800;
 2494: 	    }
 2495: 	    my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 2496: 		.&mt('seconds');
 2497: 	    if ($env{'form.timerange'}==-1) {
 2498: 		$seltext='since start of course';
 2499: 		$startsel='selected';
 2500: 		$env{'form.timerange'}=time;
 2501: 	    }
 2502: 	    $starttime=time-$env{'form.timerange'};
 2503: 	    if ($env{'form.timerange'}==2592000) {
 2504: 		$seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 2505: 		$monthsel='selected';
 2506: 	    } elsif ($env{'form.timerange'}==604800) {
 2507: 		$seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 2508: 		$weeksel='selected';
 2509: 	    } elsif ($env{'form.timerange'}==86400) {
 2510: 		$seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 2511: 		$daysel='selected';
 2512: 	    }
 2513: 	    $header=&mt('Content changed').' '.$seltext;
 2514: 	} else {
 2515: 	    $header=&mt('No content modifications yet.');
 2516: 	}
 2517:     }
 2518:     %setversions=&Apache::lonnet::dump('resourceversions',
 2519: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 2520: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 2521:     my %lt=&Apache::lonlocal::texthash
 2522: 	      ('st' => 'Version changes since start of '.$crstype,
 2523: 	       'lm' => 'Version changes since last Month',
 2524: 	       'lw' => 'Version changes since last Week',
 2525: 	       'sy' => 'Version changes since Yesterday',
 2526:                'al' => 'All Resources (possibly large output)',
 2527: 	       'sd' => 'Display',
 2528: 	       'fi' => 'File',
 2529: 	       'md' => 'Modification Date',
 2530:                'mr' => 'Most recently published Version',
 2531: 	       've' => 'Version used in '.$crstype,
 2532:                'vu' => 'Set Version to be used in '.$crstype,
 2533: 'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
 2534: 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 2535: 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 2536: 	       'di' => 'Differences');
 2537:     $r->print(<<ENDHEADERS);
 2538: <form action="/adm/coursedocs" method="post">
 2539: <input type="hidden" name="versions" value="1" />
 2540: <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
 2541: <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
 2542: <select name="timerange">
 2543: <option value='all' $allsel>$lt{'al'}</option>
 2544: <option value="-1" $startsel>$lt{'st'}</option>
 2545: <option value="2592000" $monthsel>$lt{'lm'}</option>
 2546: <option value="604800" $weeksel>$lt{'lw'}</option>
 2547: <option value="86400" $daysel>$lt{'sy'}</option>
 2548: </select>
 2549: <input type="submit" name="display" value="$lt{'sd'}" />
 2550: <h3>$header</h3>
 2551: <input type="submit" name="setversions" value="$lt{'sv'}" />
 2552: <table border="0">
 2553: ENDHEADERS
 2554:     foreach my $key (sort(keys(%changes))) {
 2555: 	if ($changes{$key}>$starttime) {
 2556: 	    my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
 2557: 	    my $currentversion=&Apache::lonnet::getversion($key);
 2558: 	    if ($currentversion<0) {
 2559: 		$currentversion=&mt('Could not be determined.');
 2560: 	    }
 2561: 	    my $linkurl=&Apache::lonnet::clutter($key);
 2562: 	    $r->print(
 2563: 		      '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
 2564: 		      &Apache::lonnet::gettitle($linkurl).
 2565:                       '</b></font></td></tr>'.
 2566:                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2567:                       '<td colspan="4">'.
 2568:                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.
 2569: 		      '</a></td></tr>'.
 2570:                       '<tr><td></td>'.
 2571:                       '<td title="'.$lt{'md'}.'">'.
 2572: 		      &Apache::lonlocal::locallocaltime(
 2573:                            &Apache::lonnet::metadata($root.'.'.$extension,
 2574:                                                      'lastrevisiondate')
 2575:                                                         ).
 2576:                       '</td>'.
 2577:                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
 2578:                       '<font size="+1">'.$currentversion.'</font>'.
 2579:                       '</span></td>'.
 2580:                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$crstype.': '.
 2581:                       '<font size="+1">');
 2582: # Used in course
 2583: 	    my $usedversion=$hash{'version_'.$linkurl};
 2584: 	    if (($usedversion) && ($usedversion ne 'mostrecent')) {
 2585: 		$r->print($usedversion);
 2586: 	    } else {
 2587: 		$r->print($currentversion);
 2588: 	    }
 2589: 	    $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
 2590:                       '<span class="LC_nobreak">Use: ');
 2591: # Set version
 2592: 	    $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
 2593: 						      'set_version_'.$linkurl,
 2594: 						      {'select_form_order' =>
 2595: 						       ['',1..$currentversion,'mostrecent'],
 2596: 						       '' => '',
 2597: 						       'mostrecent' => &mt('most recent'),
 2598: 						       map {$_,$_} (1..$currentversion)}));
 2599: 	    $r->print('</span></td></tr><tr><td></td>');
 2600: 	    my $lastold=1;
 2601: 	    for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
 2602: 		my $url=$root.'.'.$prevvers.'.'.$extension;
 2603: 		if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
 2604: 		    $starttime) {
 2605: 		    $lastold=$prevvers;
 2606: 		}
 2607: 	    }
 2608:             #
 2609:             # Code to figure out how many version entries should go in
 2610:             # each of the four columns
 2611:             my $entries_per_col = 0;
 2612:             my $num_entries = ($currentversion-$lastold);
 2613:             if ($num_entries % 4 == 0) {
 2614:                 $entries_per_col = $num_entries/4;
 2615:             } else {
 2616:                 $entries_per_col = $num_entries/4 + 1;
 2617:             }
 2618:             my $entries_count = 0;
 2619:             $r->print('<td valign="top"><font size="-2">');
 2620:             my $cols_output = 1;
 2621:             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
 2622: 		my $url=$root.'.'.$prevvers.'.'.$extension;
 2623: 		$r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
 2624: 			  '">'.&mt('Version').' '.$prevvers.'</a> ('.
 2625: 			  &Apache::lonlocal::locallocaltime(
 2626:                                 &Apache::lonnet::metadata($url,
 2627:                                                           'lastrevisiondate')
 2628:                                                             ).
 2629: 			  ')');
 2630: 		if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
 2631:                     $r->print(' <a href="/adm/diff?filename='.
 2632: 			      &Apache::lonnet::clutter($root.'.'.$extension).
 2633: 			      '&versionone='.$prevvers.
 2634: 			      '" target="diffs">'.&mt('Diffs').'</a>');
 2635: 		}
 2636: 		$r->print('</span><br />');
 2637:                 if (++$entries_count % $entries_per_col == 0) {
 2638:                     $r->print('</font></td>');
 2639:                     if ($cols_output != 4) {
 2640:                         $r->print('<td valign="top"><font size="-2">');
 2641:                         $cols_output++;
 2642:                     }
 2643:                 }
 2644: 	    }
 2645:             while($cols_output++ < 4) {
 2646:                 $r->print('</font></td><td><font>')
 2647:             }
 2648: 	    $r->print('</font></td></tr>'."\n");
 2649: 	}
 2650:     }
 2651:     $r->print('</table></form>');
 2652:     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
 2653: 
 2654:     &untiehash();
 2655: }
 2656: 
 2657: sub mark_hash_old {
 2658:     my $retie_hash=0;
 2659:     if ($hashtied) {
 2660: 	$retie_hash=1;
 2661: 	&untiehash();
 2662:     }
 2663:     &tiehash('write');
 2664:     $hash{'old'}=1;
 2665:     &untiehash();
 2666:     if ($retie_hash) { &tiehash(); }
 2667: }
 2668: 
 2669: sub is_hash_old {
 2670:     my $untie_hash=0;
 2671:     if (!$hashtied) {
 2672: 	$untie_hash=1;
 2673: 	&tiehash();
 2674:     }
 2675:     my $return=$hash{'old'};
 2676:     if ($untie_hash) { &untiehash(); }
 2677:     return $return;
 2678: }
 2679: 
 2680: sub changewarning {
 2681:     my ($r,$postexec,$message,$url)=@_;
 2682:     if (!&is_hash_old()) { return; }
 2683:     my $pathvar='folderpath';
 2684:     my $path=&escape($env{'form.folderpath'});
 2685:     if (!defined($url)) {
 2686: 	if (defined($env{'form.pagepath'})) {
 2687: 	    $pathvar='pagepath';
 2688: 	    $path=&escape($env{'form.pagepath'});
 2689: 	    $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
 2690: 	}
 2691: 	$url='/adm/coursedocs?'.$pathvar.'='.$path;
 2692:     }
 2693:     my $course_type = &Apache::loncommon::course_type();
 2694:     if (!defined($message)) {
 2695: 	$message='Changes will become active for your current session after [_1], or the next time you log in.';
 2696:     }
 2697:     $r->print("\n\n".
 2698: '<script type="text/javascript">'."\n".
 2699: '// <![CDATA['."\n".
 2700: 'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
 2701: '// ]]>'."\n".
 2702: '</script>'."\n".
 2703: '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 2704: '<input type="hidden" name="orgurl" value="'.$url.
 2705: '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
 2706: &mt($message,' <input type="hidden" name="'.
 2707:     $env{'request.role'}.'" value="1" /><input type="button" value="'.
 2708:     &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
 2709: $help{'Caching'}.'</p></form>'."\n\n");
 2710: }
 2711: 
 2712: 
 2713: sub init_breadcrumbs {
 2714:     my ($form,$text)=@_;
 2715:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 2716:     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
 2717: 					    text=>&Apache::loncommon::course_type().' Editor',
 2718: 					    faq=>273,
 2719: 					    bug=>'Instructor Interface',
 2720:                                             help => 'Docs_Adding_Course_Doc'});
 2721:     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
 2722: 					    text=>$text,
 2723: 					    faq=>273,
 2724: 					    bug=>'Instructor Interface'});
 2725: }
 2726: 
 2727: # subroutine to list form elements
 2728: sub create_list_elements {
 2729:    my @formarr = @_;
 2730:    my $list = '';
 2731:    for my $button (@formarr){
 2732:         for my $picture(keys %$button) {
 2733:             $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text'});
 2734:         }
 2735:    }
 2736:    return $list;
 2737: }
 2738: 
 2739: # subroutine to create ul from list elements
 2740: sub create_form_ul {
 2741:    my $list = shift;
 2742:    my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
 2743:    return $ul;
 2744: }
 2745: 
 2746: #
 2747: # Start tabs
 2748: #
 2749: 
 2750: sub startContentScreen {
 2751:     my ($r,$mode)=@_;
 2752:     $r->print('<ul class="LC_TabContentBigger" id="mainnav">');
 2753:     $r->print('<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>');
 2754: 
 2755:     my $active = '';
 2756: # does this user have privileges to modify docs?
 2757:     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2758: 
 2759:     my $onclick;
 2760:     my $href;
 2761: 
 2762:     if ($allowed) {
 2763:         $r->print('<li '.(($mode eq 'docs')?' class="active"':'').
 2764:                ' id="tabbededitor"><a href="/adm/coursedocs?forcestandard=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Editor').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
 2765:     }
 2766:     $r->print('<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>');
 2767:     $r->print('<li'.(($mode eq 'courseindex')?' class="active"':'').'><a href="/adm/indexcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Index').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
 2768:     $r->print('<li '.(($mode eq 'supdocs')?' class="active"':'').
 2769:            '><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Documents').'</b></a></li>');
 2770:     $r->print('</ul>');
 2771:     $r->print('<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'
 2772:              .'<div id="maincoursedoc" style="margin:0 0;padding:0 0">');
 2773:     $r->print('<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">');
 2774: }
 2775: 
 2776: #
 2777: # End tabs
 2778: #
 2779: 
 2780: sub endContentScreen {
 2781:    my ($r)=@_;
 2782:    $r->print('</div></div></div>');
 2783: }
 2784: 
 2785: sub supplemental_base {
 2786:     return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Documents'));
 2787: }
 2788: 
 2789: sub handler {
 2790:     my $r = shift;
 2791:     &Apache::loncommon::content_type($r,'text/html');
 2792:     $r->send_http_header;
 2793:     return OK if $r->header_only;
 2794:     my $crstype = &Apache::loncommon::course_type();
 2795: 
 2796: #
 2797: # --------------------------------------------- Initialize help topics for this
 2798:     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
 2799: 	               'Adding_External_Resource','Navigate_Content',
 2800: 	               'Adding_Folders','Docs_Overview', 'Load_Map',
 2801: 	               'Supplemental','Score_Upload_Form','Adding_Pages',
 2802: 	               'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
 2803: 	               'Check_Resource_Versions','Verify_Content') {
 2804: 	$help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 2805:     }
 2806:     # Composite help files
 2807:     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 2808: 		    'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 2809:     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 2810: 		    'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 2811:     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 2812: 		    'Option_Response_Simple');
 2813:     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 2814: 		    'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 2815:     $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
 2816: 		  'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 2817:     $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 2818:     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 2819: 
 2820: # does this user have privileges to modify docs
 2821:     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2822:   if ($allowed && $env{'form.verify'}) {
 2823:       &init_breadcrumbs('verify','Verify Content');
 2824:       &verifycontent($r);
 2825:   } elsif ($allowed && $env{'form.listsymbs'}) {
 2826:       &init_breadcrumbs('listsymbs','List Symbs');
 2827:       &list_symbs($r);
 2828:   } elsif ($allowed && $env{'form.docslog'}) {
 2829:       &init_breadcrumbs('docslog','Show Log');
 2830:       &docs_change_log($r);
 2831:   } elsif ($allowed && $env{'form.versions'}) {
 2832:       &init_breadcrumbs('versions','Check/Set Resource Versions');
 2833:       &checkversions($r);
 2834:   } elsif ($allowed && $env{'form.dumpcourse'}) {
 2835:       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Documents to Construction Space');
 2836:       &dumpcourse($r);
 2837:   } elsif ($allowed && $env{'form.exportcourse'}) {
 2838:       &init_breadcrumbs('exportcourse','IMS Export');
 2839:       &exportcourse($r);
 2840:   } else {
 2841: #
 2842: # Done catching special calls
 2843: # The whole rest is for course and supplemental documents
 2844: # Get the parameters that may be needed
 2845: #
 2846:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2847:                                             ['folderpath','pagepath',
 2848:                                              'pagesymb','forcesupplement','forcestandard',
 2849:                                              'symb','command']);
 2850: 
 2851: # standard=1: this is a "new-style" course with an uploaded map as top level
 2852: # standard=2: this is a "old-style" course, and there is nothing we can do
 2853: 
 2854:     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 2855: 
 2856: # Decide whether this should display supplemental or main content
 2857: # supplementalflag=1: show supplemental documents
 2858: # supplementalflag=0: show standard documents
 2859: 
 2860: 
 2861:     my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 2862:     if (($env{'form.folderpath'}=~/^default/) || $env{'form.folderpath'} eq "" || ($env{'form.pagepath'})) {
 2863:        $supplementalflag=0;
 2864:     }
 2865:     if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 2866:     if ($env{'form.forcestandard'})   { $supplementalflag=0; }
 2867:     unless ($allowed) { $supplementalflag=1; }
 2868:     unless ($standard) { $supplementalflag=1; }
 2869: 
 2870:     my $script='';
 2871:     my $showdoc=0;
 2872:     my $addentries = {};
 2873:     my $containertag;
 2874:     my $uploadtag;
 2875: 
 2876: # Do we directly jump somewhere?
 2877: 
 2878:    if ($env{'form.command'} eq 'direct') {
 2879:        my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
 2880:        if ($resurl=~/\.(sequence|page)$/) {
 2881:            $mapurl=$resurl;
 2882:        }
 2883:        my $maptitle = &Apache::lonnet::gettitle($mapurl);
 2884:        $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
 2885:        my $type=$2;
 2886:        my $path='default&'.&Apache::lonhtmlcommon::entity_encode('Main Course Documents').
 2887:                 '&default&...::::&'.
 2888:                 &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
 2889:                         &Apache::lonhtmlcommon::entity_encode($maptitle).'::::';
 2890:        if ($type eq 'sequence') {
 2891:            $env{'form.folderpath'}=$path;
 2892:            $env{'form.pagepath'}='';
 2893:        } else {
 2894:            $env{'form.pagepath'}=$path;
 2895:            $env{'form.folderpath'}='';
 2896:        }
 2897:    }
 2898: 
 2899: # Where do we store these for when we come back?
 2900:     my $stored_folderpath='docs_folderpath';
 2901:     if ($supplementalflag) {
 2902:        $stored_folderpath='docs_sup_folderpath';
 2903:     }
 2904: 
 2905: # No folderpath, no pagepath, see if we have something stored
 2906:     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
 2907:         &Apache::loncommon::restore_course_settings($stored_folderpath,
 2908:                                               {'folderpath' => 'scalar'});
 2909:     }
 2910:    
 2911: # If we are not allowed to make changes, all we can see are supplemental docs
 2912:     if (!$allowed) {
 2913:         $env{'form.pagepath'}='';
 2914:         unless ($env{'form.folderpath'} =~ /^supplemental/) {
 2915:             $env{'form.folderpath'} = &supplemental_base();
 2916:         }
 2917:     }
 2918: # If we still not have a folderpath, see if we can resurrect at pagepath
 2919:     if (!$env{'form.folderpath'} && $allowed) {
 2920:         &Apache::loncommon::restore_course_settings($stored_folderpath,
 2921:                                               {'pagepath' => 'scalar'});
 2922:     }
 2923: # Make the zeroth entry in supplemental docs page paths, so we can get to top level
 2924:     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 2925:         $env{'form.folderpath'} = &supplemental_base()
 2926:                                   .'&'.
 2927:                                   $env{'form.folderpath'};
 2928:     }
 2929: # If after all of this, we still don't have any paths, make them
 2930:     unless (($env{'form.pagepath'}) || ($env{'form.folderpath'})) {
 2931:        if ($supplementalflag) {
 2932:           $env{'form.folderpath'}=&supplemental_base();
 2933:        } else {
 2934:           $env{'form.folderpath'}='default';
 2935:        }
 2936:     } 
 2937: 
 2938: # Store this
 2939:     &Apache::loncommon::store_course_settings($stored_folderpath,
 2940:                                                 {'pagepath' => 'scalar',
 2941:                                                  'folderpath' => 'scalar'});
 2942: 
 2943:     if ($env{'form.folderpath'}) {
 2944: 	my (@folderpath)=split('&',$env{'form.folderpath'});
 2945: 	$env{'form.foldername'}=&unescape(pop(@folderpath));
 2946: 	$env{'form.folder'}=pop(@folderpath);
 2947:     }
 2948:     if ($env{'form.pagepath'}) {
 2949:         my (@pagepath)=split('&',$env{'form.pagepath'});
 2950:         $env{'form.pagename'}=&unescape(pop(@pagepath));
 2951:         $env{'form.folder'}=pop(@pagepath);
 2952:         $containertag = '<input type="hidden" name="pagepath" value="" />'.
 2953: 	                '<input type="hidden" name="pagesymb" value="" />';
 2954:         $uploadtag = 
 2955:             '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
 2956: 	    '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />'.
 2957:             '<input type="hidden" name="folderpath" value="" />';
 2958:     } else {
 2959:         my $folderpath=$env{'form.folderpath'};
 2960:         if (!$folderpath) {
 2961:             if ($env{'form.folder'} eq '' ||
 2962:                 $env{'form.folder'} eq 'supplemental') {
 2963:                 $folderpath='default&'.
 2964:                     &escape(&mt('Main '.$crstype.' Documents'));
 2965:             }
 2966:         }
 2967:         $containertag = '<input type="hidden" name="folderpath" value="" />';
 2968:         $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
 2969:     }
 2970:     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 2971:        $showdoc='/'.$1;
 2972:     }
 2973:     if ($showdoc) { # got called in sequence from course
 2974: 	$allowed=0; 
 2975:     } else {
 2976:        if ($allowed) {
 2977:          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
 2978:          $script=&Apache::lonratedt::editscript('simple');
 2979:        }
 2980:     }
 2981: 
 2982: # get course data
 2983:     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2984:     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2985: 
 2986: # get personal data
 2987:     my $uname=$env{'user.name'};
 2988:     my $udom=$env{'user.domain'};
 2989:     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 2990: 
 2991: # graphics settings
 2992: 
 2993:     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
 2994: 
 2995:     if ($allowed) {
 2996:         my @tabids;
 2997:         if ($supplementalflag) {
 2998:             @tabids = ('002','ee2','ff2');
 2999:         } else {
 3000:             @tabids = ('aa1','bb1','cc1','ff1');
 3001:             unless ($env{'form.pagepath'}) {
 3002:                 unshift(@tabids,'001');
 3003:                 push(@tabids,('dd1','ee1'));
 3004:             }
 3005:         }
 3006:         my $tabidstr = join("','",@tabids);
 3007: 	$script .= &editing_js($udom,$uname).
 3008:                    &resize_contentdiv_js($tabidstr);
 3009:         $addentries = {
 3010:                         onload   => "javascript:resize_contentdiv('contentscroll','1','1');",
 3011:                       };
 3012:     }
 3013: # -------------------------------------------------------------------- Body tag
 3014:     $script = '<script type="text/javascript">'."\n"
 3015:               .'// <![CDATA['."\n"
 3016:               .$script."\n"
 3017:               .'// ]]>'."\n"
 3018:               .'</script>'."\n";
 3019: 
 3020:     # Breadcrumbs
 3021:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 3022:     unless ($showdoc) {
 3023:         &Apache::lonhtmlcommon::add_breadcrumb({
 3024:             href=>"/adm/coursedocs",text=>"$crstype Contents"});
 3025: 
 3026:         $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
 3027:                                                  {'force_register' => $showdoc,
 3028:                                                   'add_entries'    => $addentries,
 3029:                                                  })
 3030:                  .&Apache::loncommon::help_open_menu('','',273,'RAT')
 3031:                  .&Apache::lonhtmlcommon::breadcrumbs(
 3032:                      'Editing the Table of Contents for your '.$crstype,
 3033:                      'Docs_Adding_Course_Doc')
 3034:         );
 3035:     } else {
 3036:         $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
 3037:                                                 {'force_register' => $showdoc,}));
 3038:     }
 3039: 
 3040:   my %allfiles = ();
 3041:   my %codebase = ();
 3042:   my ($upload_result,$upload_output,$uploadphase);
 3043:   if ($allowed) {
 3044:       if (($env{'form.uploaddoc.filename'}) &&
 3045: 	  ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 3046:           my $context = $1; 
 3047:           # Process file upload - phase one - upload and parse primary file.
 3048: 	  undef($hadchanges);
 3049:           $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
 3050:                                               \%allfiles,\%codebase,$context);
 3051: 	  if ($hadchanges) {
 3052: 	      &mark_hash_old();
 3053: 	  }
 3054:           $r->print($upload_output);
 3055:       } elsif ($env{'form.phase'} eq 'upload_embedded') {
 3056:           # Process file upload - phase two - upload embedded objects 
 3057:           $uploadphase = 'check_embedded';
 3058:           my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
 3059:           my $state = &embedded_form_elems($uploadphase,$primaryurl,
 3060:                                            $env{'form.newidx'});
 3061:           my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3062:           my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3063:           my ($destination,$dir_root) = &embedded_destination();
 3064:           my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
 3065:           my $actionurl = '/adm/coursedocs';
 3066:           my ($result,$flag) = 
 3067:               &Apache::loncommon::upload_embedded('coursedoc',$destination,
 3068:                   $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
 3069:                   $actionurl);
 3070:           $r->print($result.&return_to_editor());
 3071:       } elsif ($env{'form.phase'} eq 'check_embedded') {
 3072:           # Process file upload - phase three - modify references in HTML file
 3073:           $uploadphase = 'modified_orightml';
 3074:           my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3075:           my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3076:           my ($destination,$dir_root) = &embedded_destination();
 3077:           $r->print(&Apache::loncommon::modify_html_refs('coursedoc',$destination,
 3078:                                                          $docuname,$docudom,undef,
 3079:                                                          $dir_root).
 3080:                    &return_to_editor());
 3081:       }
 3082:   }
 3083: 
 3084:   unless ($showdoc || $uploadphase) {  
 3085: # -----------------------------------------------------------------------------
 3086:        my %lt=&Apache::lonlocal::texthash(
 3087:                 'uplm' => 'Upload a new main '.lc($crstype).' document',
 3088:                 'upls' => 'Upload a new supplemental '.lc($crstype).' document',
 3089:                 'impp' => 'Import a document',
 3090: 		'copm' => 'All documents out of a published map into this folder',
 3091:                 'upld' => 'Import Document',
 3092:                 'srch' => 'Search',
 3093:                 'impo' => 'Import',
 3094: 		'wish' => 'Import from Wishlist',
 3095:                 'selm' => 'Select Map',
 3096:                 'load' => 'Load Map',
 3097:                 'reco' => 'Recover Deleted Documents',
 3098:                 'newf' => 'New Folder',
 3099:                 'newp' => 'New Composite Page',
 3100:                 'extr' => 'External Resource',
 3101:                 'syll' => 'Syllabus',
 3102:                 'navc' => 'Table of Contents',
 3103:                 'sipa' => 'Simple Course Page',
 3104:                 'sipr' => 'Simple Problem',
 3105:                 'drbx' => 'Drop Box',
 3106:                 'scuf' => 'External Scores (handgrade, upload, clicker)',
 3107:                 'bull' => 'Discussion Board',
 3108:                 'mypi' => 'My Personal Information Page',
 3109:                 'grpo' => 'Group Portfolio',
 3110:                 'rost' => 'Course Roster',
 3111: 				'abou' => 'Personal Information Page for a User',
 3112:                 'imsf' => 'IMS Import',
 3113:                 'imsl' => 'Import IMS package',
 3114:                 'file' =>  'File',
 3115:                 'title' => 'Title',
 3116:                 'comment' => 'Comment',
 3117:                 'parse' => 'Upload embedded images/multimedia files if HTML file',
 3118: 		'nd' => 'Upload Document',
 3119: 		'pm' => 'Published Map',
 3120: 		'sd' => 'Special Document',
 3121: 		'mo' => 'More Options',
 3122: 					  );
 3123: # -----------------------------------------------------------------------------
 3124: 	my $fileupload=(<<FIUP);
 3125: 	$lt{'file'}:<br />
 3126: 	<input type="file" name="uploaddoc" size="40" />
 3127: FIUP
 3128: 
 3129: 	my $checkbox=(<<CHBO);
 3130: 	<!-- <label>$lt{'parse'}?
 3131: 	<input type="checkbox" name="parserflag" />
 3132: 	</label> -->
 3133: 	<label>
 3134: 	<input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
 3135: 	</label>
 3136: CHBO
 3137: 
 3138:     my $fileuploada = "<br clear='all' /><input type='submit' value='".$lt{'upld'}."' /> $help{'Uploading_From_Harddrive'}";
 3139: 	my $fileuploadform=(<<FUFORM);
 3140: 	<form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 3141: 	<input type="hidden" name="active" value="aa" />
 3142: 	$fileupload
 3143: 	<br />
 3144: 	$lt{'title'}:<br />
 3145: 	<input type="text" size="60" name="comment" />
 3146: 	$uploadtag
 3147: 	<input type="hidden" name="cmd" value="upload_default" />
 3148: 	<br />
 3149: 	<span class="LC_nobreak" style="float:left">
 3150: 	$checkbox
 3151: 	</span>
 3152: FUFORM
 3153:     $fileuploadform .= $fileuploada.'</form>';
 3154: 
 3155: 	my $simpleeditdefaultform=(<<SEDFFORM);
 3156: 	<form action="/adm/coursedocs" method="post" name="simpleeditdefault">
 3157: 	<input type="hidden" name="active" value="bb" />
 3158: SEDFFORM
 3159: 	my @simpleeditdefaultforma = ( 
 3160: 	{ '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => "$uploadtag<a class='LC_menubuttons_link' href='javascript:groupsearch()'>$lt{'srch'}</a>" },
 3161: 	{ '<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'}" },
 3162: 	{ '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{wish}.'" onclick="javascript:open_Wishlist_Import();" />' => "<a class='LC_menubuttons_link' href='javascript:open_Wishlist_Import();'>$lt{'wish'}</a>" },
 3163: 	);
 3164: 	$simpleeditdefaultform .= &create_form_ul(&create_list_elements(@simpleeditdefaultforma));
 3165: 	$simpleeditdefaultform .=(<<SEDFFORM);
 3166: 	<hr id="bb_hrule" style="width:0px;text-align:left;margin-left:0" />
 3167: 	$lt{'copm'}<br />
 3168: 	<input type="text" size="40" name="importmap" /><br />
 3169: 	<span class="LC_nobreak" style="float:left"><input type="button"
 3170: 	onclick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
 3171: 	value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
 3172: 	$help{'Load_Map'}</span>
 3173: 	</form>
 3174: SEDFFORM
 3175: 
 3176:       my $extresourcesform=(<<ERFORM);
 3177:       <form action="/adm/coursedocs" method="post" name="newext">
 3178:       $uploadtag
 3179:       <input type="hidden" name="importdetail" value="" />
 3180:       <a class="LC_menubuttons_link" href="javascript:makenewext('newext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
 3181:       </form>
 3182: ERFORM
 3183: 
 3184: 
 3185:     if ($allowed) {
 3186: 	&update_paste_buffer($coursenum,$coursedom);
 3187:        my %lt=&Apache::lonlocal::texthash(
 3188: 					 'vc' => 'Verify Content',
 3189: 					 'cv' => 'Check/Set Resource Versions',
 3190: 					 'ls' => 'List Symbs',
 3191:                                          'sl' => 'Show Log'
 3192: 					  );
 3193: 
 3194: 	$r->print(<<HIDDENFORM);
 3195: 	<form name="renameform" method="post" action="/adm/coursedocs">
 3196:    <input type="hidden" name="title" />
 3197:    <input type="hidden" name="cmd" />
 3198:    <input type="hidden" name="markcopy" />
 3199:    <input type="hidden" name="copyfolder" />
 3200:    $containertag
 3201:  </form>
 3202:  <form name="simpleedit" method="post" action="/adm/coursedocs">
 3203:    <input type="hidden" name="importdetail" value="" />
 3204:    $uploadtag
 3205:  </form>
 3206: HIDDENFORM
 3207:     }
 3208: 
 3209: # Generate the tabs
 3210:     &startContentScreen($r,($supplementalflag?'supdocs':'docs'));
 3211: 
 3212: 
 3213: #
 3214: 
 3215:     my $savefolderpath;
 3216: 
 3217:     if ($allowed) {
 3218:        my $folder=$env{'form.folder'};
 3219:        if ($folder eq '' || $supplementalflag) {
 3220:            $folder='default';
 3221: 	   $savefolderpath = $env{'form.folderpath'};
 3222: 	   $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
 3223:            $uploadtag = '<input type="hidden" name="folderpath" value="'.
 3224: 	       &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 3225:        }
 3226:        my $postexec='';
 3227:        if ($folder eq 'default') {
 3228:            $r->print('<script type="text/javascript">'."\n"
 3229:                     .'// <![CDATA['."\n"
 3230:                     .'this.window.name="loncapaclient";'."\n"
 3231:                     .'// ]]>'."\n"
 3232:                     .'</script>'."\n"
 3233:        );
 3234:        } else {
 3235:            #$postexec='self.close();';
 3236:        }
 3237:        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
 3238:                      '.sequence';
 3239:        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
 3240:                      '.page';
 3241: 	my $container='sequence';
 3242: 	if ($env{'form.pagepath'}) {
 3243: 	    $container='page';
 3244: 	}
 3245: 	my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 3246: 
 3247: 
 3248: 
 3249: 	my $recoverform=(<<RFORM);
 3250: 	<form action="/adm/groupsort" method="post" name="recover">
 3251: 	<a class="LC_menubuttons_link" href="javascript:groupopen('$readfile',1)">$lt{'reco'}</a>
 3252: 	</form>
 3253: RFORM
 3254: 
 3255: 	my $imspform=(<<IMSPFORM);
 3256: 	<form action="/adm/imsimportdocs" method="post" name="ims">
 3257: 	<input type="hidden" name="folder" value="$folder" />
 3258: 	<a class="LC_menubuttons_link" href="javascript:makeims();">$lt{'imsf'}</a>
 3259: 	</form>
 3260: IMSPFORM
 3261: 
 3262: 	my $newnavform=(<<NNFORM);
 3263: 	<form action="/adm/coursedocs" method="post" name="newnav">
 3264: 	<input type="hidden" name="active" value="cc" />
 3265: 	$uploadtag
 3266: 	<input type="hidden" name="importdetail" 
 3267: 	value="$lt{'navc'}=/adm/navmaps" />
 3268: 	<a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
 3269: 	$help{'Navigate_Content'}
 3270: 	</form>
 3271: NNFORM
 3272: 	my $newsmppageform=(<<NSPFORM);
 3273: 	<form action="/adm/coursedocs" method="post" name="newsmppg">
 3274: 	<input type="hidden" name="active" value="cc" />
 3275: 	$uploadtag
 3276: 	<input type="hidden" name="importdetail" value="" />
 3277: 	<a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
 3278: 	$help{'Simple Page'}
 3279: 	</form>
 3280: NSPFORM
 3281: 
 3282: 	my $newsmpproblemform=(<<NSPROBFORM);
 3283: 	<form action="/adm/coursedocs" method="post" name="newsmpproblem">
 3284: 	<input type="hidden" name="active" value="cc" />
 3285: 	$uploadtag
 3286: 	<input type="hidden" name="importdetail" value="" />
 3287: 	<a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
 3288: 	$help{'Simple Problem'}
 3289: 	</form>
 3290: 
 3291: NSPROBFORM
 3292: 
 3293: 	my $newdropboxform=(<<NDBFORM);
 3294: 	<form action="/adm/coursedocs" method="post" name="newdropbox">
 3295: 	<input type="hidden" name="active" value="cc" />
 3296: 	$uploadtag
 3297: 	<input type="hidden" name="importdetail" value="" />
 3298: 	<a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
 3299: 	</form>
 3300: NDBFORM
 3301: 
 3302: 	my $newexuploadform=(<<NEXUFORM);
 3303: 	<form action="/adm/coursedocs" method="post" name="newexamupload">
 3304: 	<input type="hidden" name="active" value="cc" />
 3305: 	$uploadtag
 3306: 	<input type="hidden" name="importdetail" value="" />
 3307: 	<a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
 3308: 	$help{'Score_Upload_Form'}
 3309: 	</form>
 3310: NEXUFORM
 3311: 
 3312: 	my $newbulform=(<<NBFORM);
 3313: 	<form action="/adm/coursedocs" method="post" name="newbul">
 3314: 	<input type="hidden" name="active" value="cc" />
 3315: 	$uploadtag
 3316: 	<input type="hidden" name="importdetail" value="" />
 3317: 	<a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
 3318: 	$help{'Bulletin Board'}
 3319: 	</form>
 3320: NBFORM
 3321: 
 3322: 	my $newaboutmeform=(<<NAMFORM);
 3323: 	<form action="/adm/coursedocs" method="post" name="newaboutme">
 3324: 	<input type="hidden" name="active" value="cc" />
 3325: 	$uploadtag
 3326: 	<input type="hidden" name="importdetail" 
 3327: 	value="$plainname=/adm/$udom/$uname/aboutme" />
 3328: 	<a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
 3329: 	$help{'My Personal Information Page'}
 3330: 	</form>
 3331: NAMFORM
 3332: 
 3333: 	my $newaboutsomeoneform=(<<NASOFORM);
 3334: 	<form action="/adm/coursedocs" method="post" name="newaboutsomeone">
 3335: 	<input type="hidden" name="active" value="cc" />
 3336: 	$uploadtag
 3337: 	<input type="hidden" name="importdetail" value="" />
 3338: 	<a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
 3339: 	</form>
 3340: NASOFORM
 3341: 
 3342: 
 3343: 	my $newrosterform=(<<NROSTFORM);
 3344: 	<form action="/adm/coursedocs" method="post" name="newroster">
 3345: 	<input type="hidden" name="active" value="cc" />
 3346: 	$uploadtag
 3347: 	<input type="hidden" name="importdetail" 
 3348: 	value="$lt{'rost'}=/adm/viewclasslist" />
 3349: 	<a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
 3350: 	$help{'Course Roster'}
 3351: 	</form>
 3352: NROSTFORM
 3353: 
 3354: my $specialdocumentsform;
 3355: my @specialdocumentsforma;
 3356: my $gradingform;
 3357: my @gradingforma;
 3358: my $communityform;
 3359: my @communityforma;
 3360: my $newfolderform;
 3361: my $newfolderb;
 3362: 
 3363: 	my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 3364: 	
 3365: 	my $newpageform=(<<NPFORM);
 3366: 	<form action="/adm/coursedocs" method="post" name="newpage">
 3367: 	<input type="hidden" name="folderpath" value="$path" />
 3368: 	<input type="hidden" name="importdetail" value="" />
 3369: 	<input type="hidden" name="active" value="cc" />
 3370: 	<a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
 3371: 	$help{'Adding_Pages'}
 3372: 	</form>
 3373: NPFORM
 3374: 
 3375: 
 3376: 	$newfolderform=(<<NFFORM);
 3377: 	<form action="/adm/coursedocs" method="post" name="newfolder">
 3378: 	<input type="hidden" name="folderpath" value="$path" />
 3379: 	<input type="hidden" name="importdetail" value="" />
 3380: 	<input type="hidden" name="active" value="aa" />
 3381: 	<a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
 3382: 	</form>
 3383: NFFORM
 3384: 
 3385: 	my $newsylform=(<<NSYLFORM);
 3386: 	<form action="/adm/coursedocs" method="post" name="newsyl">
 3387: 	<input type="hidden" name="active" value="cc" />
 3388: 	$uploadtag
 3389: 	<input type="hidden" name="importdetail" 
 3390: 	value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
 3391: 	<a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
 3392: 	$help{'Syllabus'}
 3393: 
 3394: 	</form>
 3395: NSYLFORM
 3396: 
 3397: 	my $newgroupfileform=(<<NGFFORM);
 3398: 	<form action="/adm/coursedocs" method="post" name="newgroupfiles">
 3399: 	<input type="hidden" name="active" value="cc" />
 3400: 	$uploadtag
 3401: 	<input type="hidden" name="importdetail"
 3402: 	value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
 3403: 	<a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
 3404: 	$help{'Group Portfolio'}
 3405: 	</form>
 3406: NGFFORM
 3407: 	@specialdocumentsforma=(
 3408: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
 3409: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
 3410: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
 3411:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
 3412:         );
 3413:         $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
 3414: 
 3415: 
 3416:         my @importdoc = (
 3417:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'newext\');" />'=>$extresourcesform},
 3418:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:makeims();" />'=>$imspform},);
 3419:         $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc)) . '<hr id="cc_hrule" style="width:0px;text-align:left;margin-left:0" />' . $fileuploadform;
 3420: 
 3421:         @gradingforma=(
 3422:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
 3423:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
 3424:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
 3425: 
 3426:         );
 3427:         $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
 3428: 
 3429:         @communityforma=(
 3430:        {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
 3431:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
 3432:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
 3433:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
 3434:         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
 3435:         );
 3436:         $communityform = &create_form_ul(&create_list_elements(@communityforma));
 3437: 
 3438: 
 3439: 
 3440: my @tools = (
 3441: #	{'<img class="LC_noBorder LC_middle" align="left" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" />'=>$extresourcesform},
 3442: #	{'<img class="LC_noBorder LC_middle" align="left" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" />'=>$imspform},
 3443: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/recover.png" alt="'.$lt{reco}.'" onclick="javascript:groupopen(\''.$readfile.'\',1)" />'=>$recoverform},
 3444: 	);
 3445: 
 3446: my %orderhash = (
 3447:                 'aa' => ['Import Documents',$fileuploadform],
 3448:                 'bb' => ['Published Resources',$simpleeditdefaultform],
 3449:                 'cc' => ['Grading Resources',$gradingform],
 3450: 		'ff' => ['Tools', &create_form_ul(&create_list_elements(@tools)).&generate_admin_options(\%help,\%env)],
 3451:                 );
 3452: unless ($env{'form.pagepath'}) {
 3453:     $orderhash{'00'} = ['Newfolder',$newfolderform];
 3454:     $orderhash{'dd'} = ['Community Resources',$communityform];
 3455:     $orderhash{'ee'} = ['Special Documents',$specialdocumentsform];
 3456: }
 3457: 
 3458:  $hadchanges=0;
 3459:        unless ($supplementalflag) {
 3460:           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 3461:                               $supplementalflag,\%orderhash);
 3462:           if ($error) {
 3463:              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 3464:           }
 3465:           if ($hadchanges) {
 3466:              &mark_hash_old();
 3467:           }
 3468: 
 3469:           &changewarning($r,'');
 3470:         }
 3471:     }
 3472: 
 3473: # Supplemental documents start here
 3474: 
 3475:        my $folder=$env{'form.folder'};
 3476:        unless ($supplementalflag) {
 3477: 	   $folder='supplemental';
 3478:        }
 3479:        if ($folder =~ /^supplemental$/ &&
 3480: 	   (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
 3481:           $env{'form.folderpath'} = &supplemental_base();
 3482:        } elsif ($allowed) {
 3483: 	  $env{'form.folderpath'} = $savefolderpath;
 3484:        }
 3485:        $env{'form.pagepath'} = '';
 3486:        if ($allowed) {
 3487: 	   my $folderseq=
 3488: 	       '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
 3489: 	       '.sequence';
 3490: 
 3491: 	   my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 3492: 
 3493: 	my $supupdocformbtn = "<input type='submit' value='".$lt{'upld'}."' />$help{'Uploading_From_Harddrive'}";
 3494: 	my $supupdocform=(<<SUPDOCFORM);
 3495: 	<form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
 3496: 	<input type="hidden" name="active" value="ee" />	
 3497: 	$fileupload
 3498: 	<br />
 3499: 	<br />
 3500: 	<span class="LC_nobreak">
 3501: 	$checkbox
 3502: 	</span>
 3503: 	<br /><br />
 3504: 	$lt{'comment'}:<br />
 3505: 	<textarea cols="50" rows="4" name="comment"></textarea>
 3506: 	<br />
 3507: 	<input type="hidden" name="folderpath" value="$path" />
 3508: 	<input type="hidden" name="cmd" value="upload_supplemental" />
 3509: SUPDOCFORM
 3510: 	$supupdocform .=  &create_form_ul(&Apache::lonhtmlcommon::htmltag('li',$supupdocformbtn,{class => 'LC_menubuttons_inline_text'}))."</form>";
 3511: 
 3512: 	my $supnewfolderform=(<<SNFFORM);
 3513: 	<form action="/adm/coursedocs" method="post" name="supnewfolder">
 3514: 	<input type="hidden" name="active" value="ee" />
 3515: 	<input type="hidden" name="folderpath" value="$path" />
 3516: 	<input type="hidden" name="importdetail" value="" />
 3517: 	<a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
 3518: 	$help{'Adding_Folders'}
 3519: 	</form>
 3520: SNFFORM
 3521: 	
 3522: 
 3523: 	my $supnewextform=(<<SNEFORM);
 3524: 	<form action="/adm/coursedocs" method="post" name="supnewext">
 3525: 	<input type="hidden" name="active" value="ff" />
 3526: 	<input type="hidden" name="folderpath" value="$path" />
 3527: 	<input type="hidden" name="importdetail" value="" />
 3528: 	<a class="LC_menubuttons_link" href="javascript:makenewext('supnewext');">$lt{'extr'}</a> $help{'Adding_External_Resource'}
 3529: 	</form>
 3530: SNEFORM
 3531: 
 3532: 	my $supnewsylform=(<<SNSFORM);
 3533: 	<form action="/adm/coursedocs" method="post" name="supnewsyl">
 3534: 	<input type="hidden" name="active" value="ff" />
 3535: 	<input type="hidden" name="folderpath" value="$path" />
 3536: 	<input type="hidden" name="importdetail" 
 3537: 	value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
 3538: 	<a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
 3539: 	$help{'Syllabus'}
 3540: 	</form>
 3541: SNSFORM
 3542: 
 3543: 	my $supnewaboutmeform=(<<SNAMFORM);
 3544: 	<form action="/adm/coursedocs" method="post" name="supnewaboutme">
 3545: 	<input type="hidden" name="active" value="ff" />
 3546: 	<input type="hidden" name="folderpath" value="$path" />
 3547: 	<input type="hidden" name="importdetail" 
 3548: 	value="$plainname=/adm/$udom/$uname/aboutme" />
 3549: 	<a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
 3550: 	$help{'My Personal Information Page'}
 3551: 	</form>
 3552: SNAMFORM
 3553: 
 3554: 
 3555: my @specialdocs = (
 3556: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.supnewsyl.submit()" />'
 3557:             =>$supnewsylform},
 3558: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
 3559:             =>$supnewaboutmeform},
 3560: 		);
 3561: my @supimportdoc = (
 3562: 		{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'supnewext\');" />'
 3563:             =>$supnewextform},
 3564:         );
 3565: $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc)) . '<hr id="ee_hrule" style="width:0px;text-align:left;margin-left:0" />' . $supupdocform;
 3566: my %suporderhash = (
 3567: 		'00' => ['Supnewfolder', $supnewfolderform],
 3568:                 'ee' => ['Import Documents',$supupdocform],
 3569:                 'ff' => ['Special Documents',&create_form_ul(&create_list_elements(@specialdocs))]
 3570:                 );
 3571:         if ($supplementalflag) {
 3572:            my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 3573:                                $supplementalflag,\%suporderhash);
 3574:            if ($error) {
 3575:               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 3576:            }
 3577:         }
 3578:     } elsif ($supplementalflag) {
 3579:         my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
 3580:                             $supplementalflag);
 3581:         if ($error) {
 3582:             $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 3583:         }
 3584:     }
 3585: 
 3586:     &endContentScreen($r);
 3587: 
 3588:     if ($allowed) {
 3589: 	$r->print('
 3590: <form method="post" name="extimport" action="/adm/coursedocs">
 3591:   <input type="hidden" name="title" />
 3592:   <input type="hidden" name="url" />
 3593:   <input type="hidden" name="useform" />
 3594:   <input type="hidden" name="residx" />
 3595: </form>');
 3596:     }
 3597:   } else {
 3598:       unless ($uploadphase) {
 3599: # -------------------------------------------------------- This is showdoc mode
 3600:           $r->print("<h1>".&mt('Uploaded Document').' - '.
 3601: 		&Apache::lonnet::gettitle($r->uri).'</h1><p>'.
 3602: &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
 3603:           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
 3604:       }
 3605:   }
 3606:  }
 3607:  $r->print(&Apache::loncommon::end_page());
 3608:  return OK;
 3609: }
 3610: 
 3611: sub embedded_form_elems {
 3612:     my ($phase,$primaryurl,$newidx) = @_;
 3613:     my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 3614:     return <<STATE;
 3615:     <input type="hidden" name="folderpath" value="$folderpath" />
 3616:     <input type="hidden" name="cmd" value="upload_embedded" />
 3617:     <input type="hidden" name="newidx" value="$newidx" />
 3618:     <input type="hidden" name="phase" value="$phase" />
 3619:     <input type="hidden" name="primaryurl" value="$primaryurl" />
 3620: STATE
 3621: }
 3622: 
 3623: sub embedded_destination {
 3624:     my $folder=$env{'form.folder'};
 3625:     my $destination = 'docs/';
 3626:     if ($folder =~ /^supplemental/) {
 3627:         $destination = 'supplemental/';
 3628:     }
 3629:     if (($folder eq 'default') || ($folder eq 'supplemental')) {
 3630:         $destination .= 'default/';
 3631:     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 3632:         $destination .=  $2.'/';
 3633:     }
 3634:     $destination .= $env{'form.newidx'};
 3635:     my $dir_root = '/userfiles';
 3636:     return ($destination,$dir_root);
 3637: }
 3638: 
 3639: sub return_to_editor {
 3640:     my $actionurl = '/adm/coursedocs';
 3641:     return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
 3642:            '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
 3643:            '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
 3644:            '</a></p>';
 3645: }
 3646: 
 3647: sub generate_admin_options {
 3648:   my ($help_ref,$env_ref) = @_;
 3649:   my %lt=&Apache::lonlocal::texthash(
 3650:                                          'vc' => 'Verify Content',
 3651:                                          'cv' => 'Check/Set Resource Versions',
 3652:                                          'ls' => 'List Symbs',
 3653:                                          'sl' => 'Show Log',
 3654:                                          'imse' => 'IMS Export',
 3655:                                          'dcd' => 'Dump Course Documents to Construction Space: available on other servers'
 3656:                                           );
 3657:   my %help = %{$help_ref};
 3658:   my %env = %{$env_ref};
 3659:   my $dumpbut=&dumpbutton();
 3660:   my $exportbut=&exportbutton();
 3661:   my @list = (
 3662: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/verify.png" alt="'.$lt{vc}.'"  onclick=\'javascript:injectData(document.courseverify, "dummy", "verify", "'.$lt{'vc'}.'")\' />' 
 3663:         => "<a class='LC_menubuttons_link' href='javascript:injectData(document.courseverify, \"dummy\", \"verify\", \"$lt{'vc'}\")'>$lt{'vc'}</a>$help{'Verify_Content'}"},
 3664: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/resversion.png" alt="'.$lt{cv}.'"  onclick=\'javascript:injectData(document.courseverify, "dummy", "versions", "'.$lt{'cv'}.'")\' />'
 3665:         =>"<a class='LC_menubuttons_link' href='javascript:injectData(document.courseverify, \"dummy\", \"versions\", \"$lt{'cv'}\")'>$lt{'cv'}</a>$help{'Check_Resource_Versions'}"},
 3666: 	);
 3667:   if($dumpbut ne ''){
 3668:   push @list, {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dump.png" alt="'.$lt{dcd}.'" />'=>$dumpbut};
 3669:   }
 3670:   push @list, ({'<img class="LC_noBorder LC_middle" src="/res/adm/pages/imsexport.png" alt="'.$lt{imse}.'" onclick="javascript:injectData(document.courseverify, \'dummy\', \'exportcourse\', \''.&mt('IMS Export').'\');" />'
 3671:           =>$exportbut},
 3672: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/symbs.png" alt="'.$lt{ls}.'"  onclick=\'javascript:injectData(document.courseverify, "dummy", "listsymbs", "'.$lt{'ls'}.'")\'  />'
 3673:         =>"<a class='LC_menubuttons_link' href='javascript:injectData(document.courseverify, \"dummy\", \"listsymbs\", \"$lt{'ls'}\")'>$lt{'ls'}</a><input type='hidden' name='folder' value='$env{'form.folder'}' />"},
 3674: 	{'<img class="LC_noBorder LC_middle" src="/res/adm/pages/document-properties.png" alt="'.$lt{sl}.'"  onclick=\'javascript:injectData(document.courseverify, "dummy", "docslog", "'.$lt{'sl'}.'")\'  />'
 3675:         =>"<a class='LC_menubuttons_link' href='javascript:injectData(document.courseverify, \"dummy\", \"docslog\", \"$lt{'sl'}\")'>$lt{'sl'}</a>"},
 3676: 	);
 3677:   return '<form action="/adm/coursedocs" method="post" name="courseverify"><input type="hidden" id="dummy" />'.&create_form_ul(&create_list_elements(@list)).'</form>';
 3678: 
 3679: }
 3680: 
 3681: 
 3682: sub generate_edit_table {
 3683:     my ($tid,$orderhash_ref,$to_show) = @_;
 3684:     return unless(ref($orderhash_ref) eq 'HASH');
 3685:     my %orderhash = %{$orderhash_ref};
 3686:     my $form;
 3687:     my $activetab;
 3688:     my $active;
 3689:     if($env{'form.active'} ne ''){
 3690:         $activetab = $env{'form.active'};
 3691:     }
 3692:     $form = '<div class="LC_Box" style="margin:0;">'.
 3693:              '<ul id="navigation'.$tid.'" class="LC_TabContent">';
 3694:     foreach my $name (reverse(sort(keys(%orderhash)))) {
 3695:         if($name ne '00'){
 3696:             if($activetab eq '' || $activetab ne $name){
 3697:                $active = '';
 3698:             }elsif($activetab eq $name){
 3699:                $active = 'class="active"';
 3700:             }
 3701:             $form .= '<li style="float:right" '.$active
 3702:                 .' onmouseover="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"'
 3703:                 .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>';
 3704:         } else {
 3705: 	    $form .= '<li '.$active.' style="float:right">'.${$orderhash{$name}}[1].'</li>';
 3706: 
 3707: 	}
 3708:     }
 3709:     $form .= '</ul>';
 3710:     $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">';
 3711: 
 3712:     if ($to_show ne '') {
 3713:         $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>';
 3714:     }
 3715:     foreach my $field (keys(%orderhash)){
 3716: 	if($field ne '00'){
 3717:             if($activetab eq '' || $activetab ne $field){
 3718:                 $active = 'style="display: none;float:left"';
 3719:             }elsif($activetab eq $field){
 3720:                 $active = 'style="display:block;float:left"';
 3721:             }
 3722:             $form .= '<div id="'.$field.$tid.'"'
 3723:                     .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
 3724:                     .'</div>';
 3725:         }
 3726:     }
 3727:     $form .= '</div></div>';
 3728: 
 3729:     return $form;
 3730: }
 3731: 
 3732: sub editing_js {
 3733:     my ($udom,$uname) = @_;
 3734:     my $now = time();
 3735:     my %lt = &Apache::lonlocal::texthash(
 3736:                                           p_mnf => 'Name of New Folder',
 3737:                                           t_mnf => 'New Folder',
 3738:                                           p_mnp => 'Name of New Page',
 3739:                                           t_mnp => 'New Page',
 3740:                                           p_mxu => 'Title for the External Score',
 3741:                                           p_msp => 'Name of Simple Course Page',
 3742:                                           p_msb => 'Title for the Problem',
 3743:                                           p_mdb => 'Title for the Drop Box',
 3744:                                           p_mbb => 'Title for the Discussion Board',
 3745:                                           p_mab => "Enter user:domain for User's Personal Information Page",
 3746:                                           p_mab2 => 'Personal Information Page of ',
 3747:                                           p_mab_alrt1 => 'Not a valid user:domain',
 3748:                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
 3749:                                           p_chn => 'New Title',
 3750:                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
 3751:                                           p_rmr2a => 'Remove[_99]',
 3752:                                           p_rmr2b => '?[_99]',
 3753:                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
 3754:                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
 3755:                                           p_ctr2a => 'Cut[_98]',
 3756:                                           p_ctr2b => '?[_98]'
 3757:                                         );
 3758: 
 3759:     my $crstype = &Apache::loncommon::course_type();
 3760:     my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
 3761:     my $docs_pagepath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.pagepath'},'<>&"');
 3762:     my $main_container_page;
 3763:     if ($docs_folderpath eq '') {
 3764:         if ($docs_pagepath ne '') {
 3765:             $main_container_page = 1;
 3766:         }
 3767:     }
 3768:     my $toplevelmain = 'default&Main%20'.$crstype.'%20Documents';
 3769:     my $toplevelsupp = &supplemental_base();
 3770: 
 3771:     return <<ENDNEWSCRIPT;
 3772: function makenewfolder(targetform,folderseq) {
 3773:     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
 3774:     if (foldername) {
 3775:        targetform.importdetail.value=escape(foldername)+"="+folderseq;
 3776:         targetform.submit();
 3777:     }
 3778: }
 3779: 
 3780: function makenewpage(targetform,folderseq) {
 3781:     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
 3782:     if (pagename) {
 3783:         targetform.importdetail.value=escape(pagename)+"="+folderseq;
 3784:         targetform.submit();
 3785:     }
 3786: }
 3787: 
 3788: function makenewext(targetname) {
 3789:     this.document.forms.extimport.useform.value=targetname;
 3790:     this.document.forms.extimport.title.value='';
 3791:     this.document.forms.extimport.url.value='';
 3792:     this.document.forms.extimport.residx.value='';
 3793:     window.open('/adm/rat/extpickframe.html');
 3794: }
 3795: 
 3796: function edittext(targetname,residx,title,url) {
 3797:     this.document.forms.extimport.useform.value=targetname;
 3798:     this.document.forms.extimport.residx.value=residx;
 3799:     this.document.forms.extimport.url.value=url;
 3800:     this.document.forms.extimport.title.value=title;
 3801:     window.open('/adm/rat/extpickframe.html');
 3802: }
 3803: 
 3804: function makeexamupload() {
 3805:    var title=prompt('$lt{"p_mxu"}');
 3806:    if (title) {
 3807:     this.document.forms.newexamupload.importdetail.value=
 3808: 	escape(title)+'=/res/lib/templates/examupload.problem';
 3809:     this.document.forms.newexamupload.submit();
 3810:    }
 3811: }
 3812: 
 3813: function makesmppage() {
 3814:    var title=prompt('$lt{"p_msp"}');
 3815:    if (title) {
 3816:     this.document.forms.newsmppg.importdetail.value=
 3817: 	escape(title)+'=/adm/$udom/$uname/$now/smppg';
 3818:     this.document.forms.newsmppg.submit();
 3819:    }
 3820: }
 3821: 
 3822: function makesmpproblem() {
 3823:    var title=prompt('$lt{"p_msb"}');
 3824:    if (title) {
 3825:     this.document.forms.newsmpproblem.importdetail.value=
 3826: 	escape(title)+'=/res/lib/templates/simpleproblem.problem';
 3827:     this.document.forms.newsmpproblem.submit();
 3828:    }
 3829: }
 3830: 
 3831: function makedropbox() {
 3832:    var title=prompt('$lt{"p_mdb"}');
 3833:    if (title) {
 3834:     this.document.forms.newdropbox.importdetail.value=
 3835:         escape(title)+'=/res/lib/templates/DropBox.problem';
 3836:     this.document.forms.newdropbox.submit();
 3837:    }
 3838: }
 3839: 
 3840: function makebulboard() {
 3841:    var title=prompt('$lt{"p_mbb"}');
 3842:    if (title) {
 3843:     this.document.forms.newbul.importdetail.value=
 3844: 	escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
 3845:     this.document.forms.newbul.submit();
 3846:    }
 3847: }
 3848: 
 3849: function makeabout() {
 3850:    var user=prompt("$lt{'p_mab'}");
 3851:    if (user) {
 3852:        var comp=new Array();
 3853:        comp=user.split(':');
 3854:        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
 3855: 	   if ((comp[0]) && (comp[1])) {
 3856: 	       this.document.forms.newaboutsomeone.importdetail.value=
 3857: 		   '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
 3858:        this.document.forms.newaboutsomeone.submit();
 3859:    } else {
 3860:        alert("$lt{'p_mab_alrt1'}");
 3861:    }
 3862: } else {
 3863:    alert("$lt{'p_mab_alrt2'}");
 3864: }
 3865: }
 3866: }
 3867: 
 3868: function makeims() {
 3869: var caller = document.forms.ims.folder.value;
 3870: var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
 3871: newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");
 3872: newWindow.location.href = newlocation;
 3873: }
 3874: 
 3875: 
 3876: function finishpick() {
 3877: var title=this.document.forms.extimport.title.value;
 3878: var url=this.document.forms.extimport.url.value;
 3879: var form=this.document.forms.extimport.useform.value;
 3880: var residx=this.document.forms.extimport.residx.value;
 3881: eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');
 3882: }
 3883: 
 3884: function changename(folderpath,index,oldtitle,container,pagesymb) {
 3885: var title=prompt('$lt{"p_chn"}',oldtitle);
 3886: if (title) {
 3887: this.document.forms.renameform.markcopy.value=-1;
 3888: this.document.forms.renameform.title.value=title;
 3889: this.document.forms.renameform.cmd.value='rename_'+index;
 3890: if (container == 'sequence') {
 3891:     this.document.forms.renameform.folderpath.value=folderpath;
 3892: }
 3893: if (container == 'page') {
 3894:     this.document.forms.renameform.pagepath.value=folderpath;
 3895:     this.document.forms.renameform.pagesymb.value=pagesymb;
 3896: }
 3897: this.document.forms.renameform.submit();
 3898: }
 3899: }
 3900: 
 3901: function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {
 3902: if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
 3903: this.document.forms.renameform.markcopy.value=-1;
 3904: this.document.forms.renameform.cmd.value='del_'+index;
 3905: if (container == 'sequence') {
 3906:     this.document.forms.renameform.folderpath.value=folderpath;
 3907: }
 3908: if (container == 'page') {
 3909:     this.document.forms.renameform.pagepath.value=folderpath;
 3910:     this.document.forms.renameform.pagesymb.value=pagesymb;
 3911: }
 3912: this.document.forms.renameform.submit();
 3913: }
 3914: }
 3915: 
 3916: function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {
 3917: if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
 3918: this.document.forms.renameform.cmd.value='cut_'+index;
 3919: this.document.forms.renameform.markcopy.value=index;
 3920: this.document.forms.renameform.copyfolder.value=folder+'.'+container;
 3921: if (container == 'sequence') {
 3922:     this.document.forms.renameform.folderpath.value=folderpath;
 3923: }
 3924: if (container == 'page') {
 3925:     this.document.forms.renameform.pagepath.value=folderpath;
 3926:     this.document.forms.renameform.pagesymb.value=pagesymb;
 3927: }
 3928: this.document.forms.renameform.submit();
 3929: }
 3930: }
 3931: 
 3932: function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
 3933: this.document.forms.renameform.markcopy.value=index;
 3934: this.document.forms.renameform.copyfolder.value=folder+'.'+container;
 3935: if (container == 'sequence') {
 3936: this.document.forms.renameform.folderpath.value=folderpath;
 3937: }
 3938: if (container == 'page') {
 3939: this.document.forms.renameform.pagepath.value=folderpath;
 3940: this.document.forms.renameform.pagesymb.value=pagesymb;
 3941: }
 3942: this.document.forms.renameform.submit();
 3943: }
 3944: 
 3945: function unselectInactive(nav) {
 3946: currentNav = document.getElementById(nav);
 3947: currentLis = currentNav.getElementsByTagName('LI');
 3948: for (i = 0; i < currentLis.length; i++) {
 3949: 	if(currentLis[i].className == 'right active' || currentLis[i].className == 'right'){
 3950: 		currentLis[i].className = 'right';
 3951: 	}else{
 3952: 		currentLis[i].className = 'i';
 3953: 	}
 3954: }
 3955: }
 3956: 
 3957: function hideAll(current, nav, data) {
 3958: unselectInactive(nav);
 3959: if(current.className == 'right'){
 3960: 	current.className = 'right active'
 3961: 	}else{
 3962: 	current.className = 'active';
 3963: }
 3964: currentData = document.getElementById(data);
 3965: currentDivs = currentData.getElementsByTagName('DIV');
 3966: for (i = 0; i < currentDivs.length; i++) {
 3967: 	if(currentDivs[i].className == 'LC_ContentBox'){
 3968: 		currentDivs[i].style.display = 'none';
 3969: 	}
 3970: }
 3971: }
 3972: 
 3973: function openTabs(pageId) {
 3974: 	tabnav = document.getElementById(pageId).getElementsByTagName('UL');	
 3975: 	if(tabnav.length > 2 ){
 3976: 		currentNav = document.getElementById(tabnav[1].id);
 3977: 		currentLis = currentNav.getElementsByTagName('LI');
 3978: 		for(i = 0; i< currentLis.length; i++){
 3979: 			if(currentLis[i].className == 'active') {
 3980: 				funcString = currentLis[i].onclick.toString();
 3981: 				tab = funcString.split('"');
 3982:                                 if(tab.length < 2) {
 3983:                                    tab = funcString.split("'");
 3984:                                 }
 3985: 				currentData = document.getElementById(tab[1]);
 3986:         			currentData.style.display = 'block';
 3987: 			}	
 3988: 		}
 3989: 	}
 3990: }
 3991: 
 3992: function showPage(current, pageId, nav, data) {
 3993: 	hideAll(current, nav, data);
 3994: 	openTabs(pageId);
 3995: 	unselectInactive(nav);
 3996: 	current.className = 'active';
 3997: 	currentData = document.getElementById(pageId);
 3998: 	currentData.style.display = 'block';
 3999:         activeTab = pageId;
 4000:         if (nav == 'mainnav') {
 4001:             var storedpath = "$docs_folderpath";
 4002:             if (storedpath == '') {
 4003:                 storedpath = "$docs_pagepath";
 4004:             }
 4005:             var storedpage = "$main_container_page";
 4006:             var reg = new RegExp("^supplemental");
 4007:             if (pageId == 'mainCourseDocuments') {
 4008:                 if (storedpage == 1) {
 4009:                     document.simpleedit.folderpath.value = '';
 4010:                     document.uploaddocument.folderpath.value = '';
 4011:                 } else {
 4012:                     if (reg.test(storedpath)) {
 4013:                         document.simpleedit.folderpath.value = '$toplevelmain';
 4014:                         document.uploaddocument.folderpath.value = '$toplevelmain';
 4015:                         document.newext.folderpath.value = '$toplevelmain';
 4016:                     } else {
 4017:                         document.simpleedit.folderpath.value = storedpath;
 4018:                         document.uploaddocument.folderpath.value = storedpath;
 4019:                         document.newext.folderpath.value = storedpath;
 4020:                     }
 4021:                 }
 4022:             } else {
 4023:                 if (reg.test(storedpath)) {
 4024:                     document.simpleedit.folderpath.value = storedpath;
 4025:                     document.supuploaddocument.folderpath.value = storedpath;
 4026:                     document.supnewext.folderpath.value = storedpath;
 4027:                 } else {
 4028:                     document.simpleedit.folderpath.value = '$toplevelsupp';
 4029:                     document.supuploaddocument.folderpath.value = '$toplevelsupp';
 4030:                     document.supnewext.folderpath.value = '$toplevelsupp';
 4031:                 }
 4032:             }
 4033:         }
 4034:         resize_contentdiv('contentscroll','1','0');
 4035: 	return false;
 4036: }
 4037: 
 4038: function injectData(current, hiddenField, name, value) {
 4039: 	currentElement = document.getElementById(hiddenField);
 4040: 	currentElement.name = name;
 4041: 	currentElement.value = value;
 4042: 	current.submit();
 4043: }
 4044: 
 4045: ENDNEWSCRIPT
 4046: }
 4047: 
 4048: sub resize_contentdiv_js {
 4049:     my ($tabidstr) = @_;
 4050:     my $viewport_js = &Apache::loncommon::viewport_geometry_js();
 4051:     return <<ENDRESIZESCRIPT;
 4052: 
 4053: window.onresize=resizeContentEditor;
 4054: 
 4055: var activeTab;
 4056: 
 4057: $viewport_js
 4058: 
 4059: function resize_contentdiv(scrollboxname,chkw,chkh) {
 4060:     var scrollboxid = 'div_'+scrollboxname;
 4061:     var scrolltableid = 'table_'+scrollboxname;
 4062:     var scrollbox;
 4063:     var scrolltable;
 4064: 
 4065:     if (document.getElementById("contenteditor") == null) {
 4066:         return;
 4067:     }
 4068: 
 4069:     if (document.getElementById(scrollboxid) == null) {
 4070:         return;
 4071:     } else {
 4072:         scrollbox = document.getElementById(scrollboxid);
 4073:     }
 4074: 
 4075:     if (document.getElementById(scrolltableid) == null) {
 4076:         return;
 4077:     } else {
 4078:         scrolltable = document.getElementById(scrolltableid);
 4079:     }
 4080: 
 4081:     init_geometry();
 4082:     var vph = Geometry.getViewportHeight();
 4083:     var vpw = Geometry.getViewportWidth();
 4084: 
 4085:     var alltabs = ['$tabidstr'];
 4086:     var listwchange;
 4087:     if (chkw == 1) {
 4088:         var contenteditorw = document.getElementById("contenteditor").offsetWidth;
 4089:         var contentlistw;
 4090:         var contentlistid = document.getElementById("contentlist");
 4091:         if (contentlistid != null) {
 4092:             contentlistw = document.getElementById("contentlist").offsetWidth;
 4093:         }
 4094:         var contentlistwstart = contentlistw;
 4095: 
 4096:         var scrollboxw = scrollbox.offsetWidth;
 4097:         var scrollboxscrollw = scrollbox.scrollWidth;
 4098: 
 4099:         var offsetw = parseInt(vpw * 0.015);
 4100:         var paddingw = parseInt(vpw * 0.09);
 4101: 
 4102:         var minscrollboxw = 250;
 4103: 
 4104:         var maxtabw = 0;
 4105:         var actabw = 0;
 4106:         for (var i=0; i<alltabs.length; i++) {
 4107:             if (activeTab == alltabs[i]) {
 4108:                 actabw = document.getElementById(alltabs[i]).offsetWidth;
 4109:                 if (actabw > maxtabw) {
 4110:                     maxtabw = actabw;
 4111:                 }
 4112:             } else {
 4113:                 if (document.getElementById(alltabs[i]) != null) {
 4114:                     var thistab = document.getElementById(alltabs[i]);
 4115:                     thistab.style.visibility = 'hidden';
 4116:                     thistab.style.display = 'block';
 4117:                     var tabw = document.getElementById(alltabs[i]).offsetWidth;
 4118:                     thistab.style.display = 'none';
 4119:                     thistab.style.visibility = '';
 4120:                     if (tabw > maxtabw) {
 4121:                         maxtabw = tabw;
 4122:                     }
 4123:                 }
 4124:             }
 4125:         }
 4126: 
 4127:         if (maxtabw > 0) {
 4128:             var newscrollboxw;
 4129:             if (maxtabw+paddingw+scrollboxscrollw<contenteditorw) {
 4130:                 newscrollboxw = contenteditorw-paddingw-maxtabw;
 4131:                 if (newscrollboxw < minscrollboxw) {
 4132:                     newscrollboxw = minscrollboxw;
 4133:                 }
 4134:                 scrollbox.style.width = newscrollboxw+"px";
 4135:                 if (newscrollboxw != scrollboxw) {
 4136:                     var newcontentlistw = newscrollboxw-offsetw;
 4137:                     contentlistid.style.width = newcontentlistw+"px";
 4138:                 }
 4139:             } else {
 4140:                 newscrollboxw = contenteditorw-paddingw-maxtabw;
 4141:                 if (newscrollboxw < minscrollboxw) {
 4142:                     newscrollboxw = minscrollboxw;
 4143:                 }
 4144:                 scrollbox.style.width = newscrollboxw+"px";
 4145:                 if (newscrollboxw != scrollboxw) {
 4146:                     var newcontentlistw = newscrollboxw-offsetw;
 4147:                     contentlistid.style.width = newcontentlistw+"px";
 4148:                 }
 4149:             }
 4150: 
 4151:             if (newscrollboxw != scrollboxw) {
 4152:                 var newscrolltablew = newscrollboxw+offsetw;
 4153:                 scrolltable.style.width = newscrolltablew+"px";
 4154:             }
 4155:         }
 4156: 
 4157:         if (contentlistid.offsetWidth != contentlistwstart) {
 4158:             listwchange = 1;
 4159:         }
 4160: 
 4161:         if (activeTab == 'cc1') {
 4162:             if (document.getElementById('cc_hrule') != null) {
 4163:                 document.getElementById('cc_hrule').style.width=actabw+"px";
 4164:             }
 4165:         } else {
 4166:             if (activeTab == 'bb1') {
 4167:                 if (document.getElementById('bb_hrule') != null) {
 4168:                     document.getElementById('bb_hrule').style.width=actabw+"px";
 4169:                 }
 4170:             } else {
 4171:                 if (activeTab == 'ee2') {
 4172:                     if (document.getElementById('ee_hrule') != null) {
 4173:                         document.getElementById('ee_hrule').style.width=actabw+"px";
 4174:                     }
 4175:                 }
 4176:             }
 4177:         }
 4178:     }
 4179:     if ((chkh == 1) || (listwchange)) {
 4180:         var primaryheight = document.getElementById("LC_nav_bar").offsetHeight;
 4181:         var secondaryheight = document.getElementById("LC_secondary_menu").offsetHeight;
 4182:         var crumbsheight = document.getElementById("LC_breadcrumbs").offsetHeight;
 4183:         var dccidheight = document.getElementById("dccid").offsetHeight;
 4184: 
 4185:         var uploadresultheight = 0;
 4186:         if (document.getElementById("uploadfileresult") != null) {
 4187:             uploadresultheight = document.getElementById("uploadfileresult").offsetHeight;
 4188:         }
 4189:         var tabbedheight = document.getElementById("tabbededitor").offsetHeight;
 4190:         var contenteditorheight = document.getElementById("contenteditor").offsetHeight;
 4191:         var scrollboxheight = scrollbox.offsetHeight;
 4192:         var scrollboxscrollheight = scrollbox.scrollHeight;
 4193:         var freevspace = vph-(primaryheight+secondaryheight+crumbsheight+dccidheight+uploadresultheight+tabbedheight+contenteditorheight);
 4194: 
 4195:         var minvscrollbox = 200;
 4196:         var offsetv = 20;
 4197:         var newscrollboxheight;
 4198:         if (freevspace < 0) {
 4199:             newscrollboxheight = scrollboxheight+freevspace-offsetv;
 4200:             if (newscrollboxheight < minvscrollbox) {
 4201:                 newscrollboxheight = minvscrollbox;
 4202:             }
 4203:             scrollbox.style.height = newscrollboxheight + "px";
 4204:         } else {
 4205:             if (scrollboxscrollheight > scrollboxheight) {
 4206:                 if (freevspace > offsetv) {
 4207:                     newscrollboxheight = scrollboxheight+freevspace-offsetv;
 4208:                     if (newscrollboxheight < minvscrollbox) {
 4209:                         newscrollboxheight = minvscrollbox;
 4210:                     }
 4211:                     scrollbox.style.height = newscrollboxheight+"px";
 4212:                 }
 4213:             }
 4214:         }
 4215:         scrollboxheight = scrollbox.offsetHeight;
 4216:         var contentlistheight = document.getElementById("contentlist").offsetHeight;
 4217: 
 4218:         if (scrollboxscrollheight <= scrollboxheight) {
 4219:             if ((contentlistheight+offsetv)<scrollboxheight) {
 4220:                 newscrollheight = contentlistheight+offsetv;
 4221:                 scrollbox.style.height = newscrollheight+"px";
 4222:             }
 4223:         }
 4224:     }
 4225:     return;
 4226: }
 4227: 
 4228: function resizeContentEditor() {
 4229:     var timer;
 4230:     clearTimeout(timer)
 4231:     timer=setTimeout('resize_contentdiv("contentscroll","1","1")',500);
 4232: }
 4233: 
 4234: ENDRESIZESCRIPT
 4235:     return;
 4236: }
 4237: 
 4238: 1;
 4239: __END__
 4240: 
 4241: 
 4242: =head1 NAME
 4243: 
 4244: Apache::londocs.pm
 4245: 
 4246: =head1 SYNOPSIS
 4247: 
 4248: This is part of the LearningOnline Network with CAPA project
 4249: described at http://www.lon-capa.org.
 4250: 
 4251: =head1 SUBROUTINES
 4252: 
 4253: =over
 4254: 
 4255: =item %help=()
 4256: 
 4257: Available help topics
 4258: 
 4259: =item mapread()
 4260: 
 4261: Mapread read maps into LONCAPA::map:: global arrays
 4262: @order and @resources, determines status
 4263: sets @order - pointer to resources in right order
 4264: sets @resources - array with the resources with correct idx
 4265: 
 4266: =item authorhosts()
 4267: 
 4268: Return hash with valid author names
 4269: 
 4270: =item dumpbutton()
 4271: 
 4272: Generate "dump" button
 4273: 
 4274: =item clean()
 4275: 
 4276: =item dumpcourse()
 4277: 
 4278:     Actually dump course
 4279: 
 4280: 
 4281: =item exportbutton()
 4282: 
 4283:     Generate "export" button
 4284: 
 4285: =item exportcourse()
 4286: 
 4287: =item create_ims_store()
 4288: 
 4289: =item build_package()
 4290: 
 4291: =item get_dependencies()
 4292: 
 4293: =item process_content()
 4294: 
 4295: =item replicate_content()
 4296: 
 4297: =item extract_media()
 4298: 
 4299: =item store_template()
 4300: 
 4301: =item group_import()
 4302: 
 4303:     Imports the given (name, url) resources into the course
 4304:     coursenum, coursedom, and folder must precede the list
 4305: 
 4306: =item breadcrumbs()
 4307: 
 4308: =item log_docs()
 4309: 
 4310: =item docs_change_log()
 4311: 
 4312: =item update_paste_buffer()
 4313: 
 4314: =item print_paste_buffer()
 4315: 
 4316: =item do_paste_from_buffer()
 4317: 
 4318: =item update_parameter()
 4319: 
 4320: =item handle_edit_cmd()
 4321: 
 4322: =item editor()
 4323: 
 4324: =item process_file_upload()
 4325: 
 4326: =item process_secondary_uploads()
 4327: 
 4328: =item is_supplemental_title()
 4329: 
 4330: =item parse_supplemental_title()
 4331: 
 4332: =item entryline()
 4333: 
 4334: =item tiehash()
 4335: 
 4336: =item untiehash()
 4337: 
 4338: =item checkonthis()
 4339: 
 4340: check on this
 4341: 
 4342: =item verifycontent()
 4343: 
 4344: Verify Content
 4345: 
 4346: =item devalidateversioncache() & checkversions()
 4347: 
 4348: Check Versions
 4349: 
 4350: =item mark_hash_old()
 4351: 
 4352: =item is_hash_old()
 4353: 
 4354: =item changewarning()
 4355: 
 4356: =item init_breadcrumbs()
 4357: 
 4358: Breadcrumbs for special functions
 4359: 
 4360: =back
 4361: 
 4362: =cut

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