File:  [LON-CAPA] / loncom / interface / londocs.pm
Revision 1.243: download - view: text, annotated - select for diffs
Fri Jul 21 00:21:28 2006 UTC (17 years, 11 months ago) by www
Branches: MAIN
CVS tags: version_2_1_99_2, version_2_1_99_1, HEAD
Bug #4931: clear out IMPORT shopping basket. Maybe overkill, but it seems to
work.

    1: # The LearningOnline Network
    2: # Documents
    3: #
    4: # $Id: londocs.pm,v 1.243 2006/07/21 00:21: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: package Apache::londocs;
   30: 
   31: use strict;
   32: use Apache::Constants qw(:common :http);
   33: use Apache::imsexport;
   34: use Apache::lonnet;
   35: use Apache::loncommon;
   36: use Apache::lonratedt;
   37: use Apache::lonratsrv;
   38: use Apache::lonxml;
   39: use Apache::loncreatecourse;
   40: use Apache::lonnavmaps;
   41: use HTML::Entities;
   42: use GDBM_File;
   43: use Apache::lonlocal;
   44: use Cwd;
   45: use LONCAPA;
   46: 
   47: my $iconpath;
   48: 
   49: my %hash;
   50: 
   51: my $hashtied;
   52: my %alreadyseen=();
   53: 
   54: my $hadchanges;
   55: 
   56: # Available help topics
   57: 
   58: my %help=();
   59: 
   60: # Mapread read maps into lonratedt::global arrays 
   61: # @order and @resources, determines status
   62: # sets @order - pointer to resources in right order
   63: # sets @resources - array with the resources with correct idx
   64: #
   65: 
   66: sub mapread {
   67:     my ($coursenum,$coursedom,$map)=@_;
   68:     return
   69:       &Apache::lonratedt::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   70:                                 $map);
   71: }
   72: 
   73: sub storemap {
   74:     my ($coursenum,$coursedom,$map)=@_;
   75:     my ($outtext,$errtext)=
   76:       &Apache::lonratedt::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
   77:                                 $map,1);
   78:     if ($errtext) { return ($errtext,2); }
   79:     
   80:     $hadchanges=1;
   81:     return ($errtext,0);
   82: }
   83: 
   84: # ----------------------------------------- Return hash with valid author names
   85: 
   86: sub authorhosts {
   87:     my %outhash=();
   88:     my $home=0;
   89:     my $other=0;
   90:     foreach (keys %env) {
   91: 	if ($_=~/^user\.role\.(au|ca)\.(.+)$/) {
   92: 	    my $role=$1;
   93: 	    my $realm=$2;
   94: 	    my ($start,$end)=split(/\./,$env{$_});
   95: 	    if (($start) && ($start>time)) { next; }
   96: 	    if (($end) && (time>$end)) { next; }
   97: 	    my $ca; my $cd;
   98: 	    if ($1 eq 'au') {
   99: 		$ca=$env{'user.name'};
  100: 		$cd=$env{'user.domain'};
  101: 	    } else {
  102: 		($cd,$ca)=($realm=~/^\/(\w+)\/(\w+)$/);
  103: 	    }
  104: 	    my $allowed=0;
  105: 	    my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  106: 	    my @ids=&Apache::lonnet::current_machine_ids();
  107: 	    foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }
  108: 	    if ($allowed) {
  109: 		$home++;
  110: 		$outhash{'home_'.$ca.'@'.$cd}=1;
  111: 	    } else {
  112: 		$outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;
  113: 		$other++;
  114: 	    }
  115: 	}
  116:     }
  117:     return ($home,$other,%outhash);
  118: }
  119: # ------------------------------------------------------ Generate "dump" button
  120: 
  121: sub dumpbutton {
  122:     my ($home,$other,%outhash)=&authorhosts();
  123:     my $type = &Apache::loncommon::course_type();
  124:     if ($home+$other==0) { return ''; }
  125:     my $output='</td><td bgcolor="#DDDDCC">';
  126:     if ($home) {
  127: 	return '</td><td bgcolor="#DDDDCC">'.
  128: 	    '<input type="submit" name="dumpcourse" value="'.
  129: 	    &mt('Dump '.$type.' DOCS to Construction Space').'" />'.
  130: 	    &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');
  131:     } else {
  132: 	return'</td><td bgcolor="#DDDDCC">'.
  133:      &mt('Dump '.$type.
  134: 	 ' DOCS to Construction Space: available on other servers');
  135:     }
  136: }
  137: 
  138: sub clean {
  139:     my ($title)=@_;
  140:     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
  141:     return $title;	
  142: }
  143: # -------------------------------------------------------- Actually dump course
  144: 
  145: sub dumpcourse {
  146:     my ($r) = @_;
  147:     my $type = &Apache::loncommon::course_type();
  148:     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').
  149: 	      '<form name="dumpdoc" method="post">');
  150:     my ($home,$other,%outhash)=&authorhosts();
  151:     unless ($home) { return ''; }
  152:     my $origcrsid=$env{'request.course.id'};
  153:     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
  154:     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  155: # Do the dumping
  156: 	unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }
  157: 	my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
  158: 	$r->print('<h3>'.&mt('Copying Files').'</h3>');
  159: 	my $title=$env{'form.authorfolder'};
  160: 	$title=&clean($title);
  161: 	my %replacehash=();
  162: 	foreach (keys %env) {
  163: 	    if ($_=~/^form\.namefor\_(.+)/) {
  164: 		$replacehash{$1}=$env{$_};
  165: 	    }
  166: 	}
  167: 	my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  168: 	$crs=~s/\_/\//g;
  169: 	foreach (keys %replacehash) {
  170: 	    my $newfilename=$title.'/'.$replacehash{$_};
  171: 	    $newfilename=~s/\.(\w+)$//;
  172: 	    my $ext=$1;
  173: 	    $newfilename=&clean($newfilename);
  174: 	    $newfilename.='.'.$ext;
  175: 	    my @dirs=split(/\//,$newfilename);
  176: 	    my $path='/home/'.$ca.'/public_html';
  177: 	    my $makepath=$path;
  178: 	    my $fail=0;
  179: 	    for (my $i=0;$i<$#dirs;$i++) {
  180: 		$makepath.='/'.$dirs[$i];
  181: 		unless (-e $makepath) { 
  182: 		    unless(mkdir($makepath,0777)) { $fail=1; } 
  183: 		}
  184: 	    }
  185: 	    $r->print('<br /><tt>'.$_.'</tt> => <tt>'.$newfilename.'</tt>: ');
  186: 	    if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
  187: 		if ($_=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  188: 		    print $fh &Apache::loncreatecourse::rewritefile(
  189:          &Apache::loncreatecourse::readfile($env{'request.course.id'},$_),
  190: 				     (%replacehash,$crs => '')
  191: 								    );
  192: 		} else {
  193: 		    print $fh
  194:          &Apache::loncreatecourse::readfile($env{'request.course.id'},$_);
  195: 		       }
  196: 		$fh->close();
  197: 	    } else {
  198: 		$fail=1;
  199: 	    }
  200: 	    if ($fail) {
  201: 		$r->print('<font color="red">fail</font>');
  202: 	    } else {
  203: 		$r->print('<font color="green">ok</font>');
  204: 	    }
  205: 	}
  206:     } else {
  207: # Input form
  208: 	unless ($home==1) {
  209: 	    $r->print(
  210: 		      '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');
  211: 	}
  212: 	foreach (sort keys %outhash) {
  213: 	    if ($_=~/^home_(.+)$/) {
  214: 		if ($home==1) {
  215: 		    $r->print(
  216: 		  '<input type="hidden" name="authorspace" value="'.$1.'" />');
  217: 		} else {
  218: 		    $r->print('<option value="'.$1.'">'.$1.' - '.
  219: 			      &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');
  220: 		}
  221: 	    }
  222: 	}
  223: 	unless ($home==1) {
  224: 	    $r->print('</select>');
  225: 	}
  226: 	my $title=$origcrsdata{'description'};
  227: 	$title=~s/[\/\s]+/\_/gs;
  228: 	$title=&clean($title);
  229: 	$r->print('<h3>'.&mt('Folder in Construction Space').'</h3><input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');
  230: 	&tiehash();
  231: 	$r->print('<h3>'.&mt('Filenames in Construction Space').'</h3><table border="2"><tr><th>'.&mt('Internal Filename').'</th><th>'.&mt('Title').'</th><th>'.&mt('Save as ...').'</th></tr>');
  232: 	foreach (&Apache::loncreatecourse::crsdirlist($origcrsid,'userfiles')) {
  233: 	    $r->print('<tr><td>'.$_.'</td>');
  234: 	    my ($ext)=($_=~/\.(\w+)$/);
  235: 	    my $title=$hash{'title_'.$hash{
  236: 		'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$_}};
  237: 	    $title=~s/&colon;/:/g;
  238: 	    $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
  239: 	    if (!$title) {
  240: 		$title=$_;
  241: 	    } else {
  242: 		$title=~s|/|_|g;
  243: 	    }
  244: 	    $title=~s/\.(\w+)$//;
  245: 	    $title=&clean($title);
  246: 	    $title.='.'.$ext;
  247: 	    $r->print("\n<td><input type='text' size='60' name='namefor_".$_."' value='".$title."' /></td></tr>\n");
  248: 	}
  249: 	$r->print("</table>\n");
  250: 	&untiehash();
  251: 	$r->print(
  252:   '<p><input type="submit" name="dumpcourse" value="'.&mt('Dump [_1] DOCS',$type).'" /></p></form>');
  253:     }
  254: }
  255: 
  256: # ------------------------------------------------------ Generate "export" button
  257: 
  258: sub exportbutton {
  259:     my $type = &Apache::loncommon::course_type();
  260:     return '</td><td bgcolor="#DDDDCC">'.
  261:             '<input type="submit" name="exportcourse" value="'.
  262:             &mt('Export '.$type.' to IMS').'" />'.
  263:     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');
  264: }
  265: 
  266: sub exportcourse {
  267:     my $r=shift;
  268:     my $type = &Apache::loncommon::course_type();
  269:     my %discussiontime = &Apache::lonnet::dump('discussiontimes',
  270:                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});
  271:     my $numdisc = keys %discussiontime;
  272:     my $navmap = Apache::lonnavmaps::navmap->new();
  273:     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);
  274:     my $curRes;
  275:     my $outcome;
  276: 
  277:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  278:                                             ['finishexport']);
  279:     if ($env{'form.finishexport'}) {
  280:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  281:                                             ['archive','discussion']);
  282: 
  283:         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');
  284:         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');
  285:         if (@exportitems == 0 && @discussions == 0) {
  286:             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';
  287:         } else {
  288:             my $now = time;
  289:             my %symbs;
  290:             my $manifestok = 0;
  291:             my $imsresources;
  292:             my $tempexport;
  293:             my $copyresult;
  294:             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);
  295:             if ($manifestok) {
  296:                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);
  297:                 close($ims_manifest);
  298: 
  299: #Create zip file in prtspool
  300:                 my $imszipfile = '/prtspool/'.
  301:                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
  302:                    time.'_'.rand(1000000000).'.zip';
  303:                 my $cwd = &Cwd::getcwd();
  304:                 my $imszip = '/home/httpd/'.$imszipfile;
  305:                 chdir $tempexport;
  306:                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");
  307:                 close(OUTPUT);
  308:                 chdir $cwd;
  309:                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);
  310:                 if ($copyresult) {
  311:                     $outcome .= 'The following errors occurred during export - '.$copyresult;
  312:                 }
  313:             } else {
  314:                 $outcome = '<br />Unfortunately you will not be able to retrieve an IMS archive of this posts at this time, because there was a problem creating a manifest file.<br />';
  315:             }
  316:         }
  317:         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));
  318:         $r->print($outcome);
  319:         $r->print(&Apache::loncommon::end_page());
  320:     } else {
  321:         my $display;
  322:         $display = '<form name="exportdoc" method="post">'."\n";
  323:         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');
  324:         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.
  325:                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.
  326:                     '<input type="button" value="check all" '.
  327:                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.
  328:                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
  329:                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.
  330:                     '<td>&nbsp;</td><td>&nbsp;</td>'.
  331:                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.
  332:                     '</b></legend><input type="button" value="check all"'.
  333:                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.
  334:                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
  335:                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.
  336:                     '</tr></table>';
  337:         my $curRes;
  338:         my $depth = 0;
  339:         my $count = 0;
  340:         my $boards = 0;
  341:         my $startcount = 5;
  342:         my %parent = ();
  343:         my %children = ();
  344:         my $lastcontainer = $startcount;
  345:         my @bgcolors = ('#F6F6F6','#FFFFFF');
  346:         $display .= '<table cellspacing="0"><tr>'.
  347:             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";
  348:         if ($numdisc > 0) {
  349:             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";
  350:         }
  351:         $display.='&nbsp;</td></tr>';
  352:         while ($curRes = $it->next()) {
  353:             if (ref($curRes)) {
  354:                 $count ++;
  355:             }
  356:             if ($curRes == $it->BEGIN_MAP()) {
  357:                 $depth++;
  358:                 $parent{$depth} = $lastcontainer;
  359:             }
  360:             if ($curRes == $it->END_MAP()) {
  361:                 $depth--;
  362:                 $lastcontainer = $parent{$depth};
  363:             }
  364:             if (ref($curRes)) {
  365:                 my $symb = $curRes->symb();
  366:                 my $ressymb = $symb;
  367:                 if ($ressymb =~ m|adm/(\w+)/(\w+)/(\d+)/bulletinboard$|) {
  368:                     unless ($ressymb =~ m|adm/wrapper/adm|) {
  369:                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
  370:                     }
  371:                 }
  372:                 my $color = $count%2;
  373:                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".
  374:                     '<input type="checkbox" name="archive" value="'.$count.'" ';
  375:                 if (($curRes->is_sequence()) || ($curRes->is_page())) {
  376:                     my $checkitem = $count + $boards + $startcount;
  377:                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';
  378:                 }
  379:                 $display .= ' />'."\n";
  380:                 for (my $i=0; $i<$depth; $i++) {
  381:                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" width="25" height="1" alt="" border="0" /><img src="/adm/lonIcons/whitespace1.gif" width="25" height="1" alt="" border="0" />'."\n";
  382:                 }
  383:                 if ($curRes->is_sequence()) {
  384:                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";
  385:                     $lastcontainer = $count + $startcount + $boards;
  386:                 } elsif ($curRes->is_page()) {
  387:                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";
  388:                     $lastcontainer = $count + $startcount + $boards;
  389:                 }
  390:                 my $currelem = $count+$boards+$startcount;
  391:                 $children{$parent{$depth}} .= $currelem.':';
  392:                 $display .= '&nbsp;'.$curRes->title().'</td>';
  393:                 if ($discussiontime{$ressymb} > 0) {
  394:                     $boards ++;
  395:                     $currelem = $count+$boards+$startcount;
  396:                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";
  397:                 } else {
  398:                     $display .= '<td colspan="2">&nbsp;</td>'."\n";
  399:                 }
  400:             }
  401:         }
  402:         my $scripttag = qq|
  403: <script>
  404: 
  405: function checkAll(field) {
  406:     if (field.length > 0) {
  407:         for (i = 0; i < field.length; i++) {
  408:             field[i].checked = true ;
  409:         }
  410:     } else {
  411:         field.checked = true
  412:     }
  413: }
  414:                                                                                 
  415: function uncheckAll(field) {
  416:     if (field.length > 0) {
  417:         for (i = 0; i < field.length; i++) {
  418:             field[i].checked = false ;
  419:         }
  420:     } else {
  421:         field.checked = false ;
  422:     }
  423: }
  424: 
  425: function propagateCheck(item) {
  426:     if (document.exportdoc.elements[item].checked == true) {
  427:         containerCheck(item)
  428:     }
  429: } 
  430: 
  431: function containerCheck(item) {
  432:     document.exportdoc.elements[item].checked = true
  433:     var numitems = $count + $boards + $startcount
  434:     var parents = new Array(numitems)
  435:     for (var i=$startcount; i<numitems; i++) {
  436:         parents[i] = new Array
  437:     }
  438:         |;
  439: 
  440:         foreach my $container (sort { $a <=> $b } keys %children) {
  441:             my @contents = split/:/,$children{$container};
  442:             for (my $i=0; $i<@contents; $i ++) {
  443:                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
  444:             }
  445:         }
  446: 
  447:         $scripttag .= qq|
  448:     if (parents[item].length > 0) {
  449:         for (var j=0; j<parents[item].length; j++) {
  450:             containerCheck(parents[item][j])
  451:         }
  452:      }   
  453: }
  454: 
  455: </script>
  456:         |;
  457: 	$r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',
  458: 						 $scripttag));
  459: 	$r->print($display.'</table>'.
  460:                   '<p><input type="hidden" name="finishexport" value="1">'.
  461:                   '<input type="submit" name="exportcourse" value="'.
  462:                   &mt('Export '.$type.' DOCS').'" /></p></form>'.
  463: 		  &Apache::loncommon::end_page());
  464:     }
  465: }
  466: 
  467: sub create_ims_store {
  468:     my ($now,$manifestok,$outcome,$tempexport) = @_;
  469:     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';
  470:     my $ims_manifest;
  471:     if (!-e $$tempexport) {
  472:         mkdir($$tempexport,0700);
  473:     }
  474:     $$tempexport .= '/'.$now;
  475:     if (!-e $$tempexport) {
  476:         mkdir($$tempexport,0700);
  477:     }
  478:     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};
  479:     if (!-e $$tempexport) {
  480:         mkdir($$tempexport,0700);
  481:     }
  482:     if (!-e "$$tempexport/resources") {
  483:         mkdir("$$tempexport/resources",0700);
  484:     }
  485: # open manifest file
  486:     my $manifest = '/imsmanifest.xml';
  487:     my $manifestfilename = $$tempexport.$manifest;
  488:     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {
  489:         $$manifestok=1;
  490:         print $ims_manifest
  491: '<?xml version="1.0" encoding="UTF-8"?>'."\n".
  492: '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.
  493: ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.
  494: ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.
  495: ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.
  496: '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.
  497: '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".
  498: '  <metadata>
  499:     <schema></schema>
  500:     <imsmd:lom>
  501:       <imsmd:general>
  502:         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>
  503:         <imsmd:title>
  504:           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>
  505:         </imsmd:title>
  506:       </imsmd:general>
  507:     </imsmd:lom>
  508:   </metadata>'."\n".
  509: '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".
  510: '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.
  511: ' structure="hierarchical">'."\n".
  512: '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'
  513:     } else {
  514:         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'
  515: ;
  516:     }
  517:     return $ims_manifest;
  518: }
  519: 
  520: sub build_package {
  521:     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;
  522: # first iterator to look for dependencies
  523:     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
  524:     my $curRes;
  525:     my $count = 0;
  526:     my $depth = 0;
  527:     my $lastcontainer = 0;
  528:     my %parent = ();
  529:     my @dependencies = ();
  530:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  531:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  532:     while ($curRes = $it->next()) {
  533:         if (ref($curRes)) {
  534:             $count ++;
  535:         }
  536:         if ($curRes == $it->BEGIN_MAP()) {
  537:             $depth++;
  538:             $parent{$depth} = $lastcontainer;
  539:         }
  540:         if ($curRes == $it->END_MAP()) {
  541:             $depth--;
  542:             $lastcontainer = $parent{$depth};
  543:         }
  544:         if (ref($curRes)) {
  545:             if ($curRes->is_sequence() || $curRes->is_page()) {
  546:                 $lastcontainer = $count;
  547:             }
  548:             if (grep/^$count$/,@$exportitems) {
  549:                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);
  550:             }
  551:         }
  552:     }
  553: # second iterator to build manifest and store resources
  554:     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
  555:     $depth = 0;
  556:     my $prevdepth;
  557:     $count = 0;
  558:     my $imsresources;
  559:     my $pkgdepth;
  560:     while ($curRes = $it->next()) {
  561:         if ($curRes == $it->BEGIN_MAP()) {
  562:             $prevdepth = $depth;
  563:             $depth++;
  564:         }
  565:         if ($curRes == $it->END_MAP()) {
  566:             $prevdepth = $depth;
  567:             $depth--;
  568:         }
  569: 
  570:         if (ref($curRes)) {
  571:             $count ++;
  572:             if ((grep/^$count$/,@$exportitems) || (grep/^$count$/,@dependencies)) {
  573:                 my $symb = $curRes->symb();
  574:                 my $isvisible = 'true';
  575:                 my $resourceref;
  576:                 if ($curRes->randomout()) {
  577:                     $isvisible = 'false';
  578:                 }
  579:                 unless ($curRes->is_sequence()) {
  580:                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';
  581:                 }
  582:                 my $step = $prevdepth - $depth;
  583:                 if (($step >= 0) && ($count > 1)) {
  584:                     while ($step >= 0) {
  585:                         print $ims_manifest "\n".'  </item>'."\n";
  586:                         $step --;
  587:                     }
  588:                 }
  589:                 $prevdepth = $depth;
  590: 
  591:                 my $itementry =
  592:               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.
  593:               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.
  594:               '<title>'.$curRes->title().'</title>';
  595:                 print $ims_manifest "\n".$itementry;
  596: 
  597:                 unless ($curRes->is_sequence()) {
  598:                     my $content_file;
  599:                     my @hrefs = ();
  600:                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);
  601:                     if ($content_file) {
  602:                         $imsresources .= "\n".
  603:                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.
  604:                      '" type="webcontent" href="'.$content_file.'">'."\n".
  605:                      '       <file href="'.$content_file.'" />'."\n";
  606:                         foreach (@hrefs) {
  607:                             $imsresources .=
  608:                      '        <file href="'.$_.'" />'."\n";
  609:                         }
  610:                         if (grep/^$count$/,@$discussions) {
  611:                             my $ressymb = $symb;
  612:                             my $mode;
  613:                             if ($ressymb =~ m|adm/(\w+)/(\w+)/(\d+)/bulletinboard$|) {
  614:                                 unless ($ressymb =~ m|adm/wrapper/adm|) {
  615:                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
  616:                                 }
  617:                                 $mode = 'board';
  618:                             }
  619:                             my %extras = (
  620:                                           caller => 'imsexport',
  621:                                           tempexport => $tempexport.'/resources',
  622:                                           count => $count
  623:                                          );
  624:                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);
  625:                         }
  626:                         $imsresources .= '    </resource>'."\n";
  627:                     }
  628:                 }
  629:                 $pkgdepth = $depth;
  630:             }
  631:         }
  632:     }
  633:     while ($pkgdepth > 0) {
  634:         print $ims_manifest "    </item>\n";
  635:         $pkgdepth --;
  636:     }
  637:     my $resource_text = qq|
  638:     </organization>
  639:   </organizations>
  640:   <resources>
  641:     $imsresources
  642:   </resources>
  643: </manifest>
  644:     |;
  645:     print $ims_manifest $resource_text;
  646: }
  647: 
  648: sub get_dependencies {
  649:     my ($exportitems,$parent,$depth,$dependencies) = @_;
  650:     if ($depth > 1) {
  651:         if ((!grep/^$$parent{$depth}$/,@$exportitems) && (!grep/^$$parent{$depth}$/,@$dependencies)) {
  652:             push @$dependencies, $$parent{$depth};
  653:             if ($depth > 2) {
  654:                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);
  655:             }
  656:         }
  657:     }
  658: }
  659: 
  660: sub process_content {
  661:     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;
  662:     my $content_type;
  663:     my $message;
  664:     my @uploads = ();
  665:     if ($curRes->is_sequence()) {
  666:         $content_type = 'sequence';
  667:     } elsif ($curRes->is_page()) {
  668:         $content_type = 'page'; # need to handle individual items in pages.
  669:     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {
  670:         $content_type = 'syllabus';
  671:         my $contents = &Apache::imsexport::templatedpage($content_type);
  672:         if ($contents) {
  673:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  674:         }
  675:     } elsif ($symb =~ m-\.sequence___\d+___ext-) {
  676:         $content_type = 'external';
  677:         my $title = $curRes->title;
  678:         my $contents =  &Apache::imsexport::external($symb,$title);
  679:         if ($contents) {
  680:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  681:         }
  682:     } elsif ($symb =~ m-adm/navmaps$-) {
  683:         $content_type =  'navmap';
  684:     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {
  685:         $content_type = 'simplepage';
  686:         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);
  687:         if ($contents) {
  688:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  689:         }
  690:     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {
  691:         $content_type = 'simpleproblem';
  692:         my $contents =  &Apache::imsexport::simpleproblem($symb);
  693:         if ($contents) {
  694:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  695:         }
  696:     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {
  697:         $content_type = 'examupload';
  698:     } elsif ($symb =~ m-adm/(\w+)/(\w+)/(\d+)/bulletinboard$-) {
  699:         $content_type = 'bulletinboard';
  700:         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);
  701:         if ($contents) {
  702:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  703:         }
  704:     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {
  705:         $content_type = 'aboutme';
  706:         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);
  707:         if ($contents) {
  708:             $$content_file = &store_template($contents,$tempexport,$count,$content_type);
  709:         }
  710:     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {
  711:         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
  712:     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {
  713:         my $canedit = 0;
  714:         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {
  715:             $canedit= 1;
  716:         }
  717: # only include problem code where current user is author
  718:         if ($canedit) {
  719:             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');
  720:         } else {
  721:             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');
  722:         }
  723:     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {
  724:         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
  725:     }
  726:     if (@uploads > 0) {
  727:         foreach my $item (@uploads) {
  728:             my $uploadmsg = '';
  729:             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');
  730:             if ($uploadmsg) {
  731:                 $$copyresult .= $uploadmsg."\n";
  732:             }
  733:         }
  734:     }
  735:     if ($message) {
  736:         $$copyresult .= $message."\n";
  737:     }
  738: }
  739: 
  740: sub replicate_content {
  741:     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;
  742:     my ($map,$ind,$url);
  743:     if ($caller eq 'templateupload') {
  744:         $url = $symb;
  745:         $url =~ s#//#/#g;
  746:     } else { 
  747:         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
  748:     }
  749:     my $content;
  750:     my $filename;
  751:     my $repstatus;
  752:     my $content_name;
  753:     if ($url =~ m-/([^/]+)$-) {
  754:         $filename = $1;
  755:         if (!-e $tempexport.'/resources') {
  756:             mkdir($tempexport.'/resources',0700);
  757:         }
  758:         if (!-e $tempexport.'/resources/'.$count) {
  759:             mkdir($tempexport.'/resources/'.$count,0700);
  760:         }
  761:         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;
  762:         my $copiedfile;
  763:         if ($copiedfile = Apache::File->new('>'.$destination)) {
  764:             my $content;
  765:             if ($caller eq 'resource') {
  766:                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';
  767:                 my $filepath = &Apache::lonnet::filelocation($respath,$url);
  768:                 $content = &Apache::lonnet::getfile($filepath);
  769:                 if ($content eq -1) {
  770:                     $$message = 'Could not copy file '.$filename;
  771:                 } else {
  772:                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');
  773:                     $repstatus = 'ok';
  774:                 }
  775:             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {
  776:                 my $rtncode;
  777:                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);
  778:                 if ($repstatus eq 'ok') {
  779:                     if ($url =~ /\.html?$/i) {
  780:                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');
  781:                     }
  782:                 } else {
  783:                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";
  784:                 }
  785:             } elsif ($caller eq 'noedit') {
  786: # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this. 
  787:                 $repstatus = 'ok';
  788:                 $content = 'Not the owner of this resource'; 
  789:             }
  790:             if ($repstatus eq 'ok') {
  791:                 print $copiedfile $content;
  792:             }
  793:             close($copiedfile);
  794:         } else {
  795:             $$message = 'Could not open destination file for '.$filename."<br />\n";
  796:         }
  797:     } else {
  798:         $$message = 'Could not determine name of file for '.$symb."<br />\n";
  799:     }
  800:     if ($repstatus eq 'ok') {
  801:         $content_name = 'resources/'.$count.'/'.$filename;
  802:     }
  803:     return $content_name;
  804: }
  805: 
  806: sub extract_media {
  807:     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;
  808:     my ($dirpath,$container);
  809:     my %allfiles = ();
  810:     my %codebase = ();
  811:     if ($url =~ m-(.*/)([^/]+)$-) {
  812:         $dirpath = $1;
  813:         $container = $2;
  814:     } else {
  815:         $dirpath = $url;
  816:         $container = '';
  817:     }
  818:     &Apache::lonnet::extract_embedded_items(undef,undef,\%allfiles,\%codebase,$content);
  819:     foreach my $embed_file (keys(%allfiles)) {
  820:         my $filename;
  821:         if ($embed_file =~ m#([^/]+)$#) {
  822:             $filename = $1;
  823:         } else {
  824:             $filename = $embed_file;
  825:         }
  826:         my $newname = 'res/'.$filename;
  827:         my ($rtncode,$embed_content,$repstatus);
  828:         my $embed_url;
  829:         if ($embed_file =~ m-^/-) {
  830:             $embed_url = $embed_file;           # points to absolute path
  831:         } else {
  832:             if ($embed_file =~ m-https?://-) {
  833:                 next;                           # points to url
  834:             } else {
  835:                 $embed_url = $dirpath.$embed_file;  # points to relative path
  836:             }
  837:         }
  838:         if ($caller eq 'resource') {
  839:             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';  
  840:             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url); 
  841:             $embed_content = &Apache::lonnet::getfile($embed_path);
  842:             unless ($embed_content eq -1) {
  843:                 $repstatus = 'ok';
  844:             }
  845:         } elsif ($caller eq 'uploaded') {
  846:             
  847:             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);
  848:         }
  849:         if ($repstatus eq 'ok') {
  850:             my $destination = $tempexport.'/resources/'.$count.'/res';
  851:             if (!-e "$destination") {
  852:                 mkdir($destination,0755);
  853:             }
  854:             $destination .= '/'.$filename;
  855:             my $copiedfile;
  856:             if ($copiedfile = Apache::File->new('>'.$destination)) {
  857:                 print $copiedfile $embed_content;
  858:                 push @{$href}, 'resources/'.$count.'/res/'.$filename;
  859:                 my $attrib_regexp = '';
  860:                 if (@{$allfiles{$embed_file}} > 1) {
  861:                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});
  862:                 } else {
  863:                     $attrib_regexp = $allfiles{$embed_file}[0];
  864:                 }
  865:                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;
  866:                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {
  867:                     $$content =~ s#\Q$embed_file\E#$newname#gi;
  868:                 }
  869:             }
  870:         } else {
  871:             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";
  872:         }
  873:     }
  874:     return;
  875: }
  876: 
  877: sub store_template {
  878:     my ($contents,$tempexport,$count,$content_type) = @_;
  879:     if ($contents) {
  880:         if ($tempexport) {
  881:             if (!-e $tempexport.'/resources') {
  882:                 mkdir($tempexport.'/resources',0700);
  883:             }
  884:             if (!-e $tempexport.'/resources/'.$count) {
  885:                 mkdir($tempexport.'/resources/'.$count,0700);
  886:             }
  887:             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';
  888:             my $storetemplate;
  889:             if ($storetemplate = Apache::File->new('>'.$destination)) {
  890:                 print $storetemplate $contents;
  891:                 close($storetemplate);
  892:             }
  893:             if ($content_type eq 'external') {
  894:                 return 'resources/'.$count.'/'.$content_type.'.html';
  895:             } else {
  896:                 return 'resources/'.$count.'/'.$content_type.'.xml';
  897:             }
  898:         }
  899:     }
  900: }
  901: 
  902: # Imports the given (name, url) resources into the course
  903: # coursenum, coursedom, and folder must precede the list
  904: sub group_import {
  905:     my $coursenum = shift;
  906:     my $coursedom = shift;
  907:     my $folder = shift;
  908:     my $container = shift;
  909:     my $caller = shift;
  910:     while (@_) {
  911: 	my $name = shift;
  912: 	my $url = shift;
  913:         if (($url =~ m#^/uploaded/$coursedom/$coursenum/(default_\d+\.)(page|sequence)$#) && ($caller eq 'londocs')) {
  914:             my $errtext = '';
  915:             my $fatal = 0;
  916:             my $newmapstr = '<map>'."\n".
  917:                             '<resource id="1" src="" type="start"></resource>'."\n".
  918:                             '<link from="1" to="2" index="1"></link>'."\n".
  919:                             '<resource id="2" src="" type="finish"></resource>'."\n".
  920:                             '</map>';
  921:             $env{'form.output'}=$newmapstr;
  922:             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
  923:                                                 'output',$1.$2);
  924:             if ($result != m|^/uploaded/|) {
  925:                 $errtext.='Map not saved: A network error occured when trying to save the new map. ';
  926:                 $fatal = 2;
  927:             }
  928:             if ($fatal) {
  929:                 return ($errtext,$fatal);
  930:             }
  931:         }
  932: 	if ($url) {
  933: 	    my $idx = &Apache::lonratedt::getresidx($url);
  934: 	    $Apache::lonratedt::order[$#Apache::lonratedt::order+1]=$idx;
  935: 	    my $ext = 'false';
  936: 	    if ($url=~/^http:\/\//) { $ext = 'true'; }
  937: 	    $url =~ s/:/\&colon;/g;
  938: 	    $name =~ s/:/\&colon;/g;
  939: 	    $Apache::lonratedt::resources[$idx] = 
  940: 		join ':', ($name, $url, $ext, 'normal', 'res');
  941: 	}
  942:     }
  943:     return &storemap($coursenum, $coursedom, $folder.'.'.$container);
  944: }
  945: 
  946: sub breadcrumbs {
  947:     my ($where)=@_;
  948:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  949:     my (@folders);
  950:     if ($env{'form.pagepath'}) {
  951:         @folders = split('&',$env{'form.pagepath'});
  952:     } else {
  953:         @folders=split('&',$env{'form.folderpath'});
  954:     }
  955:     my $folderpath;
  956:     my $cpinfo='';
  957:     if ($env{'form.markedcopy_url'}) {
  958:        $cpinfo='&markedcopy_url='.
  959:                &escape($env{'form.markedcopy_url'}).
  960:                '&markedcopy_title='.
  961:                &escape($env{'form.markedcopy_title'});
  962:     }
  963:     my $randompick=-1;
  964:     my $isencrypted=0;
  965:     my $ishidden=0;
  966:     while (@folders) {
  967: 	my $folder=shift(@folders);
  968: 	my $foldername=shift(@folders);
  969: 	if ($folderpath) {$folderpath.='&';}
  970: 	$folderpath.=$folder.'&'.$foldername;
  971: 	my $url='/adm/coursedocs?folderpath='.
  972: 	    &escape($folderpath);
  973:             my $name=&unescape($foldername);
  974: # randompick number, hidden, encrypted is appended with ":"s to the foldername	
  975:             $name=~s/\:(\d*)\:(\w*)\:(\w*)$//;
  976:             if ($1 ne '') { 
  977:                $randompick=$1;
  978:             } else {
  979:                $randompick=-1;
  980:             }
  981:             if ($2) { $ishidden=1; }
  982:             if ($3) { $isencrypted=1; }
  983: 	    &Apache::lonhtmlcommon::add_breadcrumb(
  984: 		      {'href'=>$url.$cpinfo,
  985: 		       'title'=>$name,
  986: 		       'text'=>'<font size="+1">'.
  987: 			   $name.'</font>'
  988: 		       });
  989:     }
  990:     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
  991: 					       'LC_docs_path'),$randompick,$ishidden,$isencrypted);
  992: }
  993: 
  994: sub editor {
  995:     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output)=@_;
  996:     my $errtext='';
  997:     my $fatal=0;
  998:     my $container='sequence';
  999:     if ($env{'form.pagepath'}) {
 1000:         $container='page';
 1001:     }
 1002:     ($errtext,$fatal)=
 1003:               &mapread($coursenum,$coursedom,$folder.'.'.$container);
 1004:     if ($#Apache::lonratedt::order<1) {
 1005: 	my $idx=&Apache::lonratedt::getresidx();
 1006: 	if ($idx<=0) { $idx=1; }
 1007:        	$Apache::lonratedt::order[0]=$idx;
 1008:         $Apache::lonratedt::resources[$idx]='';
 1009:     }
 1010:     if (defined($env{'form.markcopy'})) {
 1011: # Mark for copying
 1012: 	my ($title,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$env{'form.markcopy'}]]);
 1013: 	$env{'form.markedcopy_title'}=$title;
 1014: 	$env{'form.markedcopy_url'}=$url;
 1015:     }
 1016:     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted)=&breadcrumbs($folder);
 1017:     $r->print($breadcrumbtrail);
 1018:     if ($fatal) {
 1019: 	   $r->print('<p><font color="red">'.$errtext.'</font></p>');
 1020:     } else {
 1021: # ------------------------------------------------------------ Process commands
 1022: 
 1023: # ---------------- if they are for this folder and user allowed to make changes
 1024: 	if (($allowed) && ($env{'form.folder'} eq $folder)) {
 1025: # set parameters and change order
 1026: 	    if (defined($env{'form.setparms'})) {
 1027: 		my $idx=$env{'form.setparms'};
 1028: # set parameters
 1029: 		if ($env{'form.randpick_'.$idx}) {
 1030: 		    &Apache::lonratedt::storeparameter($idx,'parameter_randompick',$env{'form.randpick_'.$idx},'int_pos');
 1031: 		} else {
 1032: 		    &Apache::lonratedt::delparameter($idx,'parameter_randompick');
 1033: 		}
 1034: 		if ($env{'form.hidprs_'.$idx}) {
 1035: 		    &Apache::lonratedt::storeparameter($idx,'parameter_hiddenresource','yes','string_yesno');
 1036: 		} else {
 1037: 		    &Apache::lonratedt::delparameter($idx,'parameter_hiddenresource');
 1038: 		}
 1039: 		if ($env{'form.encprs_'.$idx}) {
 1040: 		    &Apache::lonratedt::storeparameter($idx,'parameter_encrypturl','yes','string_yesno');
 1041: 		} else {
 1042: 		    &Apache::lonratedt::delparameter($idx,'parameter_encrypturl');
 1043: 		}
 1044: 
 1045: 		if ($env{'form.newpos'}) {
 1046: # change order
 1047: 
 1048: 		    my $newpos=$env{'form.newpos'}-1;
 1049: 		    my $currentpos=$env{'form.currentpos'}-1;
 1050: 		    my $i;
 1051: 		    my @neworder=();
 1052: 		    if ($newpos>$currentpos) {
 1053: # moving stuff up
 1054: 			for ($i=0;$i<$currentpos;$i++) {
 1055: 			    $neworder[$i]=$Apache::lonratedt::order[$i];
 1056: 			}
 1057: 			for ($i=$currentpos;$i<$newpos;$i++) {
 1058: 			    $neworder[$i]=$Apache::lonratedt::order[$i+1];
 1059: 			}
 1060:                         $neworder[$newpos]=$Apache::lonratedt::order[$currentpos];
 1061: 			for ($i=$newpos+1;$i<=$#Apache::lonratedt::order;$i++) {
 1062: 			    $neworder[$i]=$Apache::lonratedt::order[$i];
 1063: 			}
 1064: 		    } else {
 1065: # moving stuff down
 1066: 			for ($i=0;$i<$newpos;$i++) {
 1067: 			    $neworder[$i]=$Apache::lonratedt::order[$i];
 1068: 			}
 1069: 			$neworder[$newpos]=$Apache::lonratedt::order[$currentpos];
 1070: 			for ($i=$newpos+1;$i<$currentpos+1;$i++) {
 1071: 			    $neworder[$i]=$Apache::lonratedt::order[$i-1];
 1072: 			}
 1073: 			for ($i=$currentpos+1;$i<=$#Apache::lonratedt::order;$i++) {
 1074: 			    $neworder[$i]=$Apache::lonratedt::order[$i];
 1075: 			}
 1076: 		    }
 1077: 		    @Apache::lonratedt::order=@neworder;
 1078: 		}
 1079: # store the changed version
 1080: 
 1081: 		($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 1082: 		if ($fatal) {
 1083: 		    $r->print('<p><font color="red">'.$errtext.'</font></p>');
 1084: 		    return;
 1085: 		}
 1086: 		
 1087: 	    }
 1088: 	    if ($env{'form.pastemarked'}) {
 1089: # paste resource to end of list
 1090:                 my $url=$env{'form.markedcopy_url'};
 1091: 		my $title=$env{'form.markedcopy_title'};
 1092: # Maps need to be copied first
 1093: 		if (($url=~/\.(page|sequence)$/) || ($url=~/^\/uploaded\//)) {
 1094: 		    $title=&mt('Copy of').' '.$title;
 1095:                     my $newid=$$.time;
 1096: 		    $url=~/^(.+)\.(\w+)$/;
 1097: 		    my $newurl=$1.$newid.'.'.$2;
 1098: 		    my $storefn=$newurl;
 1099:                     $storefn=~s/^\/\w+\/\w+\/\w+\///;
 1100: 		    &Apache::loncreatecourse::writefile
 1101: 			($env{'request.course.id'},$storefn,
 1102: 			 &Apache::lonnet::getfile($url));
 1103: 		    $url=$newurl;
 1104: 		}
 1105: 		$title=~s/\</\&lt\;/g;
 1106: 		$title=~s/\>/\&gt\;/g;
 1107: 		$title=~s/\:/\&colon;/g;
 1108: 		my $ext='false';
 1109: 		if ($url=~/^http\:\/\//) { $ext='true'; }
 1110: 		$url=~s/\:/\&colon;/g;
 1111: # Now insert the URL at the bottom
 1112:                 my $newidx=&Apache::lonratedt::getresidx($url);
 1113: 		$Apache::lonratedt::resources[$newidx]=
 1114: 		    $title.':'.$url.':'.$ext.':normal:res';
 1115: 		$Apache::lonratedt::order[1+$#Apache::lonratedt::order]=$newidx;
 1116: # Store the result
 1117: 		($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 1118: 		if ($fatal) {
 1119: 		    $r->print('<p><font color="red">'.$errtext.'</font></p>');
 1120: 		    return;
 1121: 		}
 1122: 
 1123: 	    }
 1124:             $r->print($upload_output);
 1125: 	    if ($env{'form.cmd'}) {
 1126:                 my ($cmd,$idx)=split(/\_/,$env{'form.cmd'});
 1127:                 if ($cmd eq 'del') {
 1128: 		    my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);
 1129: 		    if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
 1130: 			($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
 1131: 			&Apache::lonnet::removeuploadedurl($url);
 1132: 		    } else {
 1133: 			&Apache::lonratedt::makezombie($Apache::lonratedt::order[$idx]);
 1134: 		    }
 1135: 		    for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {
 1136:                         $Apache::lonratedt::order[$i]=
 1137:                           $Apache::lonratedt::order[$i+1];
 1138:                     }
 1139:                     $#Apache::lonratedt::order--;
 1140:                 } elsif ($cmd eq 'cut') {
 1141: 		    my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);
 1142: 		    &Apache::lonratedt::makezombie($Apache::lonratedt::order[$idx]);
 1143: 		    for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {
 1144:                         $Apache::lonratedt::order[$i]=
 1145:                           $Apache::lonratedt::order[$i+1];
 1146:                     }
 1147:                     $#Apache::lonratedt::order--;
 1148:                 } elsif ($cmd eq 'up') {
 1149: 		  if (($idx) && (defined($Apache::lonratedt::order[$idx-1]))) {
 1150:                     my $i=$Apache::lonratedt::order[$idx-1];
 1151:                     $Apache::lonratedt::order[$idx-1]=
 1152: 			$Apache::lonratedt::order[$idx];
 1153:                     $Apache::lonratedt::order[$idx]=$i;
 1154: 		   }
 1155:                 } elsif ($cmd eq 'down') {
 1156: 		   if (defined($Apache::lonratedt::order[$idx+1])) {
 1157:                     my $i=$Apache::lonratedt::order[$idx+1];
 1158:                     $Apache::lonratedt::order[$idx+1]=
 1159: 			$Apache::lonratedt::order[$idx];
 1160:                     $Apache::lonratedt::order[$idx]=$i;
 1161: 		   }
 1162:                 } elsif ($cmd eq 'rename') {
 1163:                     my $ratstr = $Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]];
 1164:                     my ($rtitle,@rrest)=split(/\:/,
 1165:                        $Apache::lonratedt::resources[
 1166: 				       $Apache::lonratedt::order[$idx]]);
 1167:                     my $comment=
 1168:                      &HTML::Entities::decode($env{'form.title'});
 1169:                     $comment=~s/\</\&lt\;/g;
 1170:                     $comment=~s/\>/\&gt\;/g;
 1171:                     $comment=~s/\:/\&colon;/g;
 1172: 		    if ($comment=~/\S/) {
 1173: 			$Apache::lonratedt::resources[
 1174: 				       $Apache::lonratedt::order[$idx]]=
 1175: 				            $comment.':'.join(':',@rrest);
 1176: 		    }
 1177: # Devalidate title cache
 1178:                     my $renamed_url=$rrest[0];
 1179: # Has the &colon;-escaping
 1180:                     $renamed_url=~s/\&colon\;/\:/g;
 1181: 		    &Apache::lonnet::devalidate_title_cache($renamed_url);
 1182:                 }
 1183: # Store the changed version
 1184: 		($errtext,$fatal)=&storemap($coursenum,$coursedom,
 1185: 					    $folder.'.'.$container);
 1186: 		if ($fatal) {
 1187: 		    $r->print('<p><font color="red">'.$errtext.'</font></p>');
 1188: 		    return;
 1189: 		}
 1190:             }
 1191: # Group import/search
 1192: 	    if ($env{'form.importdetail'}) {
 1193: 		my @imports;
 1194: #		&Apache::lonnet::logthis("imp detail ".$env{'form.importdetail'});
 1195: 		foreach (split(/\&/,$env{'form.importdetail'})) {
 1196: 		    if (defined($_)) {
 1197: 			my ($name,$url)=split(/\=/,$_);
 1198: 			$name=&unescape($name);
 1199: 			$url=&unescape($url);
 1200: 			push @imports, $name, $url;
 1201: 		    }
 1202: 		}
 1203: # Store the changed version
 1204: 		($errtext,$fatal)=group_import($coursenum, $coursedom, $folder,
 1205: 					       $container,'londocs',@imports);
 1206: 		if ($fatal) {
 1207: 		    $r->print('<p><font color="red">'.$errtext.'</font></p>');
 1208: 		    return;
 1209: 		}
 1210:             }
 1211: # Loading a complete map
 1212: 	   if ($env{'form.loadmap'}) {
 1213:                if ($env{'form.importmap'}=~/\w/) {
 1214: 	          foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
 1215: 		      my ($title,$url,$ext,$type)=split(/\:/,$_);
 1216:                       my $idx=&Apache::lonratedt::getresidx($url);
 1217:                       $Apache::lonratedt::resources[$idx]=$_;
 1218:                       $Apache::lonratedt::order
 1219: 		          [$#Apache::lonratedt::order+1]=$idx;
 1220: 	          }
 1221: # Store the changed version
 1222:   	          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 1223: 					   $folder.'.'.$container);
 1224: 	          if ($fatal) {
 1225: 		      $r->print('<p><font color="red">'.$errtext.'</font></p>');
 1226: 		      return;
 1227: 	          }
 1228:                } else {
 1229:                    $r->print('<p><font color="red">'.&mt('No map selected.').'</font></p>');
 1230:                }
 1231:            }
 1232:        }
 1233: # ---------------------------------------------------------------- End commands
 1234: # ---------------------------------------------------------------- Print screen
 1235:         my $idx=0;
 1236: 	my $shown=0;
 1237:         if (($ishidden) || ($isencrypted) || ($randompick>=0)) {
 1238:            $r->print('<p>'.&mt('Parameters').':<ul>'.
 1239:                      ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
 1240:                      ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
 1241:                      ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
 1242:                      '</ul></p>');
 1243:         }                                                                                                     
 1244:         if ($randompick>=0) {
 1245:            $r->print('<p>'.&mt('Caution: this folder is set to randomly pick a subset of resources. Adding or removing resources from this folder will change the set of resources that the students see, resulting in spurious or missing credit for completed problems, not limited to ones you modify. Do not modify the contents of this folder if it is in active student use.').'</p>');
 1246:         }
 1247:         $r->print('<table>');
 1248:         foreach (@Apache::lonratedt::order) {
 1249:            my ($name,$url)=split(/\:/,$Apache::lonratedt::resources[$_]);
 1250: 	   $name=&Apache::lonratsrv::qtescape($name);
 1251: 	   $url=&Apache::lonratsrv::qtescape($url);
 1252:            unless ($name) {  $name=(split(/\//,$url))[-1]; }
 1253:            unless ($name) { $idx++; next; }
 1254:            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));
 1255:            $idx++;
 1256: 	   $shown++;
 1257:         }
 1258: 	unless ($shown) {
 1259: 	    $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
 1260: 	}
 1261:         $r->print("\n</table>\n");
 1262: 	if ($env{'form.markedcopy_url'}) {
 1263: 	    $r->print(<<ENDPASTE);
 1264: <p><form name="pasteform" action="/adm/coursedocs" method="post">
 1265: <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />
 1266: <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />
 1267: ENDPASTE
 1268:             $r->print(
 1269: 	   '<input type="submit" name="pastemarked" value="'.&mt('Paste').
 1270: 		      '" /> '.&Apache::loncommon::filedescription(
 1271: 		(split(/\./,$env{'form.markedcopy_url'}))[-1]).': '.
 1272: 		      $env{'form.markedcopy_title'});
 1273:             if ($container eq 'page') {
 1274: 		$r->print(<<PAGEINFO);
 1275: <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />
 1276: <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />
 1277: PAGEINFO
 1278:             } else {
 1279: 		$r->print(<<FOLDERINFO);
 1280: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 1281: FOLDERINFO
 1282: 	    }
 1283: 	    $r->print('</form></p>');
 1284: 	}
 1285:     }
 1286: }
 1287: 
 1288: sub process_file_upload {
 1289:     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
 1290: # upload a file, if present
 1291:     my $parseaction;
 1292:    if ($env{'form.parserflag'}) {
 1293:         $parseaction = 'parse';
 1294:     }
 1295:     my $phase_status;
 1296:     my $folder=$env{'form.folder'};
 1297:     if ($folder eq '') {
 1298:         $folder='default';
 1299:     }
 1300:     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
 1301:         my $errtext='';
 1302:         my $fatal=0;
 1303:         my $container='sequence';
 1304:         if ($env{'form.pagepath'}) {
 1305:             $container='page';
 1306:         }
 1307:         ($errtext,$fatal)=
 1308:               &mapread($coursenum,$coursedom,$folder.'.'.$container);
 1309:         if ($#Apache::lonratedt::order<1) {
 1310:             $Apache::lonratedt::order[0]=1;
 1311:             $Apache::lonratedt::resources[1]='';
 1312:         }
 1313:         if ($fatal) {
 1314:             return 'failed';
 1315:         }
 1316:         my $destination = 'docs/';
 1317:         if ($folder =~ /^supplemental/) {
 1318:             $destination = 'supplemental/';
 1319:         }
 1320:         if (($folder eq 'default') || ($folder eq 'supplemental')) {
 1321:             $destination .= 'default/';
 1322:         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 1323:             $destination .=  $2.'/';
 1324:         }
 1325: # this is for a course, not a user, so set coursedoc flag
 1326: # probably the only place in the system where this should be "1"
 1327:         my $newidx=&Apache::lonratedt::getresidx();
 1328:         $destination .= $newidx;
 1329:         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
 1330: 						$parseaction,$allfiles,
 1331: 						$codebase);
 1332:         my $ext='false';
 1333:         if ($url=~/^http\:\/\//) { $ext='true'; }
 1334:         $url=~s/\:/\&colon;/g;
 1335:         my $comment=$env{'form.comment'};
 1336:         $comment=~s/\</\&lt\;/g;
 1337:         $comment=~s/\>/\&gt\;/g;
 1338:         $comment=~s/\:/\&colon;/g;
 1339:         if ($folder=~/^supplemental/) {
 1340:               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 1341:                   $env{'user.domain'}.'___&&&___'.$comment;
 1342:         }
 1343: 
 1344:         $Apache::lonratedt::resources[$newidx]=
 1345:                   $comment.':'.$url.':'.$ext.':normal:res';
 1346:         $Apache::lonratedt::order[$#Apache::lonratedt::order+1]= $newidx;
 1347:         ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 1348: 				    $folder.'.'.$container);
 1349:         if ($fatal) {
 1350:             $$upload_output .= '<p><font color="red">'.$errtext.'</font></p>';
 1351:             return 'failed';
 1352:         } else {
 1353:             if ($parseaction eq 'parse') {
 1354:                 my $total_embedded = keys(%{$allfiles});
 1355:                 if ($total_embedded > 0) {
 1356:                     my $num = 0;
 1357:                     $$upload_output .= 'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />
 1358:    <form name="upload_embedded" action="/adm/coursedocs"
 1359:                   method="post" enctype="multipart/form-data">
 1360:    <input type="hidden" name="folderpath" value="'.$env{'form.folderpath'}.'" />   <input type="hidden" name="cmd" value="upload_embedded" />
 1361:    <input type="hidden" name="newidx" value="'.$newidx.'" />
 1362:    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
 1363:    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
 1364:                     $$upload_output .= '<b>Upload embedded files</b>:<br />
 1365:    <table>';
 1366:                     foreach my $embed_file (keys(%{$allfiles})) {
 1367:                         $$upload_output .= '<tr><td>'.$embed_file.
 1368:           '<input name="embedded_item_'.$num.'" type="file" />
 1369:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 1370:                         my $attrib;
 1371:                         if (@{$$allfiles{$embed_file}} > 1) {
 1372:                             $attrib = join(':',@{$$allfiles{$embed_file}});
 1373:                         } else {
 1374:                             $attrib = $$allfiles{$embed_file}[0];
 1375:                         }
 1376:                         $$upload_output .=
 1377:            '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.$attrib.'" />';
 1378:                         if (exists($$codebase{$embed_file})) {
 1379:                             $$upload_output .= 
 1380:           '<input name="codebase_'.$num.'" type="hidden" value="'.&escape($$codebase{$embed_file}).'" />';
 1381:                         }
 1382:                         $$upload_output .= '</td></tr>';
 1383:                         $num ++;
 1384:                     }
 1385:                     $phase_status = 'phasetwo';
 1386:                     $$upload_output .= '</table><br />
 1387:    <input type ="submit" value="Complete upload" />
 1388:    </form>';
 1389:                 } else {
 1390:                     $$upload_output .= 'No embedded items identified<br />';
 1391:                 }
 1392:             }
 1393:         }
 1394:     }
 1395:     return $phase_status;
 1396: }
 1397: 
 1398: sub process_secondary_uploads {
 1399:     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
 1400:     my $folder=$env{'form.folder'};
 1401:     my $destination = 'docs/';
 1402:     if ($folder =~ /^supplemental/) {
 1403:         $destination = 'supplemental/';
 1404:     }
 1405:     if (($folder eq 'default') || ($folder eq 'supplemental')) {
 1406:         $destination .= 'default/';
 1407:     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 1408:         $destination .=  $2.'/';
 1409:     }
 1410:     $destination .= $newidx;
 1411:     my ($url,$filename);
 1412:     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
 1413:     ($filename) = ($url =~ m-^/uploaded/$coursedom/$coursenum/$destination/(.+)$-);
 1414:     return $filename;
 1415: }
 1416: 
 1417: # --------------------------------------------------------------- An entry line
 1418: 
 1419: sub entryline {
 1420:     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
 1421:     $title=~s/\&colon\;/\:/g;
 1422:     $title=&HTML::Entities::encode(&HTML::Entities::decode(
 1423:      &unescape($title)),'"<>&\'');
 1424:     my $renametitle=$title;
 1425:     my $foldertitle=$title;
 1426:     my $pagetitle=$title;
 1427:     my $orderidx=$Apache::lonratedt::order[$index];
 1428:     if ($title=~ /^(\d+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(.*)$/	) { 
 1429: 	$foldertitle=&Apache::lontexconvert::msgtexconverted($4);
 1430: 	$renametitle=$4;
 1431: 	$title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.
 1432: 	    &Apache::loncommon::plainname($2,$3).': <br />'.
 1433: 	    $foldertitle;
 1434:     }
 1435:     $renametitle=~s/\\/\\\\/g;
 1436:     $renametitle=~s/\&quot\;/\\\"/g;
 1437:     my $line='<tr>';
 1438: # Edit commands
 1439:     my $container;
 1440:     my $folderpath;
 1441:     if ($env{'form.folderpath'}) {
 1442:         $container = 'sequence';
 1443: 	$folderpath=&escape($env{'form.folderpath'});
 1444: 	# $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 1445:     }
 1446:     my ($pagepath,$pagesymb);
 1447:     if ($env{'form.pagepath'}) {
 1448:         $container = 'page';
 1449:         $pagepath=&escape($env{'form.pagepath'});
 1450:         $pagesymb=&escape($env{'form.pagesymb'});
 1451:     }
 1452:     my $cpinfo='';
 1453:     if ($env{'form.markedcopy_url'}) {
 1454:        $cpinfo='&markedcopy_url='.
 1455:                &escape($env{'form.markedcopy_url'}).
 1456:                '&markedcopy_title='.
 1457:                &escape($env{'form.markedcopy_title'});
 1458:     }
 1459:     if ($allowed) {
 1460: 	my $incindex=$index+1;
 1461: 	my $selectbox='';
 1462: 	if (($folder!~/^supplemental/) &&
 1463: 	    ($#Apache::lonratedt::order>0) && 
 1464: 	    ((split(/\:/,
 1465: 	     $Apache::lonratedt::resources[$Apache::lonratedt::order[0]]))[1] 
 1466: 	     ne '') && 
 1467: 	    ((split(/\:/,
 1468: 	     $Apache::lonratedt::resources[$Apache::lonratedt::order[1]]))[1] 
 1469: 	     ne '')) {
 1470: 	    $selectbox=
 1471: 		'<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
 1472: 		'<select name="newpos" onChange="this.form.submit()">';
 1473: 	    for (my $i=1;$i<=$#Apache::lonratedt::order+1;$i++) {
 1474: 		if ($i==$incindex) {
 1475: 		    $selectbox.='<option value="" selected="1">('.$i.')</option>';
 1476: 		} else {
 1477: 		    $selectbox.='<option value="'.$i.'">'.$i.'</option>';
 1478: 		}
 1479: 	    }
 1480: 	    $selectbox.='</select>';
 1481: 	}
 1482: 	my %lt=&Apache::lonlocal::texthash(
 1483:                 'up' => 'Move Up',
 1484: 		'dw' => 'Move Down',
 1485: 		'rm' => 'Remove',
 1486:                 'ct' => 'Cut',
 1487: 		'rn' => 'Rename',
 1488: 		'cp' => 'Copy');
 1489: 	my $nocopy=0;
 1490:         if ($url=~/\.(page|sequence)$/) {
 1491: 	    foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url))) {
 1492: 		my ($title,$url,$ext,$type)=split(/\:/,$_);
 1493: 		if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
 1494: 		    $nocopy=1;
 1495: 		    last;
 1496: 		}
 1497: 	    }
 1498: 	}
 1499:         my $copylink='&nbsp;';
 1500:         if ($env{'form.pagepath'}) {
 1501:            unless ($nocopy) {
 1502:                $copylink=(<<ENDCOPY);
 1503: <a href='javascript:markcopy("$pagepath","$index","$renametitle","page","$pagesymb");'>
 1504: <font size="-2" color="#000099">$lt{'cp'}</font></a></td>
 1505: ENDCOPY
 1506:             }
 1507:             $line.=(<<END);
 1508: <form name="entry_$index" action="/adm/coursedocs" method="post">
 1509: <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />
 1510: <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />
 1511: <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />
 1512: <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />
 1513: <input type="hidden" name="setparms" value="$orderidx" />
 1514: <td><table border='0' cellspacing='2' cellpadding='0'>
 1515: <tr><td bgcolor="#DDDDDD">
 1516: <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>
 1517: <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>
 1518: <tr><td bgcolor="#DDDDDD">
 1519: <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>
 1520: <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>
 1521: </table></td>
 1522: <td>$selectbox
 1523: </td><td bgcolor="#DDDDDD">
 1524: <a href='javascript:removeres("$pagepath","$index","$renametitle","page","$pagesymb");'>
 1525: <font size="-2" color="#990000">$lt{'rm'}</font></a>
 1526: <a href='javascript:cutres("$pagepath","$index","$renametitle","page","$pagesymb");'>
 1527: <font size="-2" color="#550044">$lt{'ct'}</font></a>
 1528: <a href='javascript:changename("$pagepath","$index","$renametitle","page","$pagesymb");'>
 1529: <font size="-2" color="#009900">$lt{'rn'}</font></a>
 1530: $copylink
 1531: END
 1532:         } else {
 1533:            unless ($nocopy) {
 1534:                $copylink=(<<ENDCOPY);
 1535: <a href='javascript:markcopy("$folderpath","$index","$renametitle","sequence");'>
 1536: <font size="-2" color="#000099">$lt{'cp'}</font></a></td>
 1537: ENDCOPY
 1538:             }
 1539:             $line.=(<<END); 
 1540: <form name="entry_$index" action="/adm/coursedocs" method="post">
 1541: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 1542: <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />
 1543: <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />
 1544: <input type="hidden" name="setparms" value="$orderidx" />
 1545: <td><table border='0' cellspacing='2' cellpadding='0'>
 1546: <tr><td bgcolor="#DDDDDD">
 1547: <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath$cpinfo'>
 1548: <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>
 1549: <tr><td bgcolor="#DDDDDD">
 1550: <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath$cpinfo'>
 1551: <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>
 1552: </table></td>
 1553: <td>$selectbox
 1554: </td><td bgcolor="#DDDDDD">
 1555: <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>
 1556: <font size="-2" color="#990000">$lt{'rm'}</font></a>
 1557: <a href='javascript:cutres("$folderpath","$index","$renametitle","sequence");'>
 1558: <font size="-2" color="#550044">$lt{'ct'}</font></a>
 1559: <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>
 1560: <font size="-2" color="#009900">$lt{'rn'}</font></a>
 1561: $copylink
 1562: END
 1563:         }
 1564:     }
 1565: # Figure out what kind of a resource this is
 1566:     my ($extension)=($url=~/\.(\w+)$/);
 1567:     my $uploaded=($url=~/^\/*uploaded\//);
 1568:     my $icon=&Apache::loncommon::icon($url);
 1569:     my $isfolder=0;
 1570:     my $ispage=0;
 1571:     my $folderarg;
 1572:     my $pagearg;
 1573:     my $pagefile;
 1574:     if ($uploaded) {
 1575: 	if ($extension eq 'sequence') {
 1576: 	    $icon=$iconpath.'/folder_closed.gif';
 1577: 	    $url=~/$coursenum\/([\/\w]+)\.sequence$/;
 1578: 	    $url='/adm/coursedocs?';
 1579: 	    $folderarg=$1;
 1580: 	    $isfolder=1;
 1581:         } elsif ($extension eq 'page') {
 1582:             $icon=$iconpath.'/page.gif';
 1583:             $url=~/$coursenum\/([\/\w]+)\.page$/;
 1584:             $pagearg=$1;
 1585:             $url='/adm/coursedocs?';
 1586:             $ispage=1;
 1587: 	} else {
 1588: 	    &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 1589: 	}
 1590:     }
 1591:     $url=~s-^http(\&colon\;|:)//-/adm/wrapper/ext/-;
 1592:     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
 1593: 	my $symb=&Apache::lonnet::symbclean(
 1594:           &Apache::lonnet::declutter('uploaded/'.
 1595:            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 1596:            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
 1597:            '.sequence').
 1598:            '___'.$residx.'___'.
 1599: 	   &Apache::lonnet::declutter($url));
 1600: 	(undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 1601: 	$url=&Apache::lonnet::clutter($url);
 1602: 	if ($url=~/^\/*uploaded\//) {
 1603: 	    $url=~/\.(\w+)$/;
 1604: 	    my $embstyle=&Apache::loncommon::fileembstyle($1);
 1605: 	    if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
 1606: 		$url='/adm/wrapper'.$url;
 1607: 	    } elsif ($embstyle eq 'ssi') {
 1608: 		#do nothing with these
 1609: 	    } elsif ($url!~/\.(sequence|page)$/) {
 1610: 		$url='/adm/coursedocs/showdoc'.$url;
 1611: 	    }
 1612: 	} elsif ($url=~m|^/ext/|) { 
 1613: 	    $url='/adm/wrapper'.$url;
 1614: 	}
 1615:         if (&Apache::lonnet::symbverify($symb,$url)) {
 1616: 	    $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
 1617:         } else {
 1618:             $url='';
 1619:         }
 1620: 	if ($container eq 'page') {
 1621: 	    my $symb=$env{'form.pagesymb'};
 1622: 	    	    
 1623: 	    $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 1624: 	    $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
 1625: 	}
 1626:     }
 1627:     my $parameterset='&nbsp;';
 1628:     if ($isfolder || $extension eq 'sequence') {
 1629: 	my $foldername=&escape($foldertitle);
 1630: 	my $folderpath=$env{'form.folderpath'};
 1631: 	if ($folderpath) { $folderpath.='&' };
 1632: # Append randompick number, hidden, and encrypted with ":" to foldername, 
 1633: # so it gets transferred between levels
 1634: 	$folderpath.=$folderarg.'&'.$foldername.':'.(&Apache::lonratedt::getparameter($orderidx,
 1635:                                               'parameter_randompick'))[0]
 1636:                                                .':'.((&Apache::lonratedt::getparameter($orderidx,
 1637:                                               'parameter_hiddenresource'))[0]=~/^yes$/i)
 1638:                                                .':'.((&Apache::lonratedt::getparameter($orderidx,
 1639:                                               'parameter_encrypturl'))[0]=~/^yes$/i);
 1640: 	$url.='folderpath='.&escape($folderpath).$cpinfo;
 1641: 	$parameterset='<label>'.&mt('Randomly Pick: ').
 1642: 	    '<input type="text" size="4" onChange="this.form.submit()" name="randpick_'.$orderidx.'" value="'.
 1643: 	    (&Apache::lonratedt::getparameter($orderidx,
 1644:                                               'parameter_randompick'))[0].
 1645:                                               '" />'.
 1646: '<font size="-2"><a href="javascript:void(0)">'.&mt('Store').'</a></font></label>';
 1647:        
 1648:     }
 1649:     if ($ispage) {
 1650:         my $pagename=&escape($pagetitle);
 1651:         my $pagepath;
 1652:         my $folderpath=$env{'form.folderpath'};
 1653:         if ($folderpath) { $pagepath = $folderpath.'&' };
 1654:         $pagepath.=$pagearg.'&'.$pagename;
 1655: 	my $symb=$env{'form.pagesymb'};
 1656: 	if (!$symb) {
 1657: 	    my $path='uploaded/'.
 1658: 		$env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 1659: 		$env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 1660: 	    $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
 1661: 					       $residx,
 1662: 					       $path.$pagearg.'.page');
 1663: 	}
 1664: 	$url.='pagepath='.&escape($pagepath).
 1665: 	    '&pagesymb='.&escape($symb).$cpinfo;
 1666:     }
 1667:     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.
 1668: 	'" border="0"></a></td>'.
 1669:         "<td bgcolor='#FFFFBB'>".($url?"<a href=\"$url\">":'').$title.
 1670:         ($url?'</a>':' <font size="-2">'.&mt('(re-initialize course to access)').'</font>')."</td>";
 1671:     if (($allowed) && ($folder!~/^supplemental/)) {
 1672:  	my %lt=&Apache::lonlocal::texthash(
 1673:  			      'hd' => 'Hidden',
 1674:  			      'ec' => 'URL hidden');
 1675: 	my $enctext=
 1676: 	    ((&Apache::lonratedt::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
 1677: 	my $hidtext=
 1678: 	    ((&Apache::lonratedt::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
 1679: 	$line.=(<<ENDPARMS);
 1680: <td bgcolor="#BBBBFF"><font size='-2'>
 1681: <nobr><label><input type="checkbox" name="hidprs_$orderidx" onClick="this.form.submit()" $hidtext /> $lt{'hd'}</label></nobr></td>
 1682: <td bgcolor="#BBBBFF"><font size='-2'>
 1683: <nobr><label><input type="checkbox" name="encprs_$orderidx" onClick="this.form.submit()" $enctext /> $lt{'ec'}</label></nobr></td>
 1684: <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>
 1685: ENDPARMS
 1686:     }
 1687:     $line.="</form></tr>";
 1688:     return $line;
 1689: }
 1690: 
 1691: # ---------------------------------------------------------------- tie the hash
 1692: 
 1693: sub tiehash {
 1694:     my ($mode)=@_;
 1695:     $hashtied=0;
 1696:     if ($env{'request.course.fn'}) {
 1697: 	if ($mode eq 'write') {
 1698: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 1699: 		    &GDBM_WRCREAT(),0640)) {
 1700:                 $hashtied=2;
 1701: 	    }
 1702: 	} else {
 1703: 	    if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 1704: 		    &GDBM_READER(),0640)) {
 1705:                 $hashtied=1;
 1706: 	    }
 1707: 	}
 1708:     }    
 1709: }
 1710: 
 1711: sub untiehash {
 1712:     if ($hashtied) { untie %hash; }
 1713:     $hashtied=0;
 1714:     return OK;
 1715: }
 1716: 
 1717: # --------------------------------------------------------------- check on this
 1718: 
 1719: sub checkonthis {
 1720:     my ($r,$url,$level,$title)=@_;
 1721:     $url=&unescape($url);
 1722:     $alreadyseen{$url}=1;
 1723:     $r->rflush();
 1724:     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 1725:        $r->print("\n<br />");
 1726:        for (my $i=0;$i<=$level*5;$i++) {
 1727:            $r->print('&nbsp;');
 1728:        }
 1729:        $r->print('<a href="'.$url.'" target="cat">'.
 1730: 		 ($title?$title:$url).'</a> ');
 1731:        if ($url=~/^\/res\//) {
 1732: 	  my $result=&Apache::lonnet::repcopy(
 1733:                               &Apache::lonnet::filelocation('',$url));
 1734:           if ($result eq 'ok') {
 1735:              $r->print('<font color="green">'.&mt('ok').'</font>');
 1736:              $r->rflush();
 1737:              &Apache::lonnet::countacc($url);
 1738:              $url=~/\.(\w+)$/;
 1739:              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 1740: 		 $r->print('<br />');
 1741:                  $r->rflush();
 1742:                  for (my $i=0;$i<=$level*5;$i++) {
 1743:                      $r->print('&nbsp;');
 1744:                  }
 1745:                  $r->print('- '.&mt('Rendering').': ');
 1746: 		 my ($errorcount,$warningcount)=split(/:/,
 1747: 	       &Apache::lonnet::ssi_body($url,
 1748: 			       ('grade_target'=>'web',
 1749: 				'return_only_error_and_warning_counts' => 1)));
 1750:                  if (($errorcount) ||
 1751:                      ($warningcount)) {
 1752: 		     if ($errorcount) {
 1753:                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.
 1754: 			  $errorcount.' '.
 1755: 				  &mt('error(s)').'</b></font> ');
 1756:                      }
 1757: 		     if ($warningcount) {
 1758:                         $r->print('<font color="blue">'.
 1759: 			  $warningcount.' '.
 1760: 				  &mt('warning(s)').'</font>');
 1761:                      }
 1762:                  } else {
 1763:                      $r->print('<font color="green">'.&mt('ok').'</font>');
 1764:                  }
 1765:                  $r->rflush();
 1766:              }
 1767: 	     my $dependencies=
 1768:                 &Apache::lonnet::metadata($url,'dependencies');
 1769:              foreach (split(/\,/,$dependencies)) {
 1770: 		 if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {
 1771:                     &checkonthis($r,$_,$level+1);
 1772:                  }
 1773:              }
 1774:           } elsif ($result eq 'unavailable') {
 1775:              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');
 1776:           } elsif ($result eq 'not_found') {
 1777: 	      unless ($url=~/\$/) {
 1778: 		  $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');
 1779: 	      } else {
 1780: 		  $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');
 1781: 	      }
 1782:           } else {
 1783:              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');
 1784:           }
 1785:       }
 1786:    }
 1787: }
 1788: 
 1789: 
 1790: #
 1791: # ----------------------------------------------------------------- List Symbs
 1792: # 
 1793: sub list_symbs {
 1794:     my ($r) = @_;
 1795: 
 1796:     $r->print(&Apache::loncommon::start_page('Symb List'));
 1797:     my $navmap = Apache::lonnavmaps::navmap->new();
 1798:     $r->print("<pre>\n");
 1799:     foreach my $res ($navmap->retrieveResources()) {
 1800: 	$r->print($res->compTitle()."\t".$res->symb()."\n");
 1801:     }
 1802:     $r->print("\n</pre>\n");
 1803:     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
 1804: }
 1805: 
 1806: 
 1807: #
 1808: # -------------------------------------------------------------- Verify Content
 1809: # 
 1810: sub verifycontent {
 1811:     my ($r) = @_;
 1812:     my $type = &Apache::loncommon::course_type();
 1813:    my $loaderror=&Apache::lonnet::overloaderror($r);
 1814:    if ($loaderror) { return $loaderror; }
 1815:    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
 1816:    $hashtied=0;
 1817:    undef %alreadyseen;
 1818:    %alreadyseen=();
 1819:    &tiehash();
 1820:    foreach (keys %hash) {
 1821:        if ($hash{$_}=~/\.(page|sequence)$/) {
 1822: 	   if (($_=~/^src_/) && ($alreadyseen{&unescape($hash{$_})})) {
 1823: 	       $r->print('<hr /><font color="red">'.
 1824: 			 &mt('The following sequence or page is included more than once in your '.$type.': ').
 1825: 			 &unescape($hash{$_}).'</font><br />'.
 1826: 			 &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
 1827: 	   }
 1828:        }
 1829:        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$_})})) {
 1830:            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});
 1831:        }
 1832:    }
 1833:    &untiehash();
 1834:    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
 1835: 	     &mt('Return to DOCS').'</a>');
 1836: }
 1837: 
 1838: 
 1839: # -------------------------------------------------------------- Check Versions
 1840: 
 1841: sub devalidateversioncache {
 1842:     my $src=shift;
 1843:     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
 1844: 					  &Apache::lonnet::clutter($src));
 1845: }
 1846: 
 1847: sub checkversions {
 1848:     my ($r) = @_;
 1849:     my $type = &Apache::loncommon::course_type();
 1850:     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
 1851:     my $header='';
 1852:     my $startsel='';
 1853:     my $monthsel='';
 1854:     my $weeksel='';
 1855:     my $daysel='';
 1856:     my $allsel='';
 1857:     my %changes=();
 1858:     my $starttime=0;
 1859:     my $haschanged=0;
 1860:     my %setversions=&Apache::lonnet::dump('resourceversions',
 1861: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 1862: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 1863: 
 1864:     $hashtied=0;
 1865:     &tiehash();
 1866:     my %newsetversions=();
 1867:     if ($env{'form.setmostrecent'}) {
 1868: 	$haschanged=1;
 1869: 	foreach (keys %hash) {
 1870: 	    if ($_=~/^ids\_(\/res\/.+)$/) {
 1871: 		$newsetversions{$1}='mostrecent';
 1872:                 &devalidateversioncache($1);
 1873: 	    }
 1874: 	}
 1875:     } elsif ($env{'form.setcurrent'}) {
 1876: 	$haschanged=1;
 1877: 	foreach (keys %hash) {
 1878: 	    if ($_=~/^ids\_(\/res\/.+)$/) {
 1879: 		my $getvers=&Apache::lonnet::getversion($1);
 1880: 		if ($getvers>0) {
 1881: 		    $newsetversions{$1}=$getvers;
 1882: 		    &devalidateversioncache($1);
 1883: 		}
 1884: 	    }
 1885: 	}
 1886:     } elsif ($env{'form.setversions'}) {
 1887: 	$haschanged=1;
 1888: 	foreach (keys %env) {
 1889: 	    if ($_=~/^form\.set_version_(.+)$/) {
 1890: 		my $src=$1;
 1891: 		if (($env{$_}) && ($env{$_} ne $setversions{$src})) {
 1892: 		    $newsetversions{$src}=$env{$_};
 1893: 		    &devalidateversioncache($src);
 1894: 		}
 1895: 	    }
 1896: 	}
 1897:     }
 1898:     if ($haschanged) {
 1899:         if (&Apache::lonnet::put('resourceversions',\%newsetversions,
 1900: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 1901: 			  $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {		
 1902: 	    $r->print('<h1>'.&mt('Your Version Settings have been Stored').'</h1>');
 1903: 	} else {
 1904: 	    $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Store your Version Settings').'</font></h1>');
 1905: 	}
 1906: 	&mark_hash_old();
 1907:     }
 1908:     &changewarning($r,'');
 1909:     if ($env{'form.timerange'} eq 'all') {
 1910: # show all documents
 1911: 	$header=&mt('All Documents in '.$type);
 1912: 	$allsel=1;
 1913: 	foreach (keys %hash) {
 1914: 	    if ($_=~/^ids\_(\/res\/.+)$/) {
 1915: 		my $src=$1;
 1916: 		$changes{$src}=1;
 1917: 	    }
 1918: 	}
 1919:     } else {
 1920: # show documents which changed
 1921: 	%changes=&Apache::lonnet::dump
 1922: 	 ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
 1923:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 1924: 	my $firstkey=(keys %changes)[0];
 1925: 	unless ($firstkey=~/^error\:/) {
 1926: 	    unless ($env{'form.timerange'}) {
 1927: 		$env{'form.timerange'}=604800;
 1928: 	    }
 1929: 	    my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 1930: 		.&mt('seconds');
 1931: 	    if ($env{'form.timerange'}==-1) {
 1932: 		$seltext='since start of course';
 1933: 		$startsel='selected';
 1934: 		$env{'form.timerange'}=time;
 1935: 	    }
 1936: 	    $starttime=time-$env{'form.timerange'};
 1937: 	    if ($env{'form.timerange'}==2592000) {
 1938: 		$seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 1939: 		$monthsel='selected';
 1940: 	    } elsif ($env{'form.timerange'}==604800) {
 1941: 		$seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 1942: 		$weeksel='selected';
 1943: 	    } elsif ($env{'form.timerange'}==86400) {
 1944: 		$seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 1945: 		$daysel='selected';
 1946: 	    }
 1947: 	    $header=&mt('Content changed').' '.$seltext;
 1948: 	} else {
 1949: 	    $header=&mt('No content modifications yet.');
 1950: 	}
 1951:     }
 1952:     %setversions=&Apache::lonnet::dump('resourceversions',
 1953: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
 1954: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
 1955:     my %lt=&Apache::lonlocal::texthash
 1956: 	      ('st' => 'Version changes since start of '.$type,
 1957: 	       'lm' => 'Version changes since last Month',
 1958: 	       'lw' => 'Version changes since last Week',
 1959: 	       'sy' => 'Version changes since Yesterday',
 1960:                'al' => 'All Resources (possibly large output)',
 1961: 	       'sd' => 'Display',
 1962: 	       'fi' => 'File',
 1963: 	       'md' => 'Modification Date',
 1964:                'mr' => 'Most recently published Version',
 1965: 	       've' => 'Version used in '.$type,
 1966:                'vu' => 'Set Version to be used in '.$type,
 1967: 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',
 1968: 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 1969: 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 1970: 	       'di' => 'Differences');
 1971:     $r->print(<<ENDHEADERS);
 1972: <form action="/adm/coursedocs" method="post">
 1973: <input type="hidden" name="versions" value="1" />
 1974: <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
 1975: <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
 1976: <select name="timerange">
 1977: <option value='all' $allsel>$lt{'al'}</option>
 1978: <option value="-1" $startsel>$lt{'st'}</option>
 1979: <option value="2592000" $monthsel>$lt{'lm'}</option>
 1980: <option value="604800" $weeksel>$lt{'lw'}</option>
 1981: <option value="86400" $daysel>$lt{'sy'}</option>
 1982: </select>
 1983: <input type="submit" name="display" value="$lt{'sd'}" />
 1984: <h3>$header</h3>
 1985: <input type="submit" name="setversions" value="$lt{'sv'}" />
 1986: <table border="0">
 1987: ENDHEADERS
 1988:     foreach (sort keys %changes) {
 1989: 	if ($changes{$_}>$starttime) {
 1990: 	    my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);
 1991: 	    my $currentversion=&Apache::lonnet::getversion($_);
 1992: 	    if ($currentversion<0) {
 1993: 		$currentversion=&mt('Could not be determined.');
 1994: 	    }
 1995: 	    my $linkurl=&Apache::lonnet::clutter($_);
 1996: 	    $r->print(
 1997: 		      '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
 1998: 		      &Apache::lonnet::gettitle($linkurl).
 1999:                       '</b></font></td></tr>'.
 2000:                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2001:                       '<td colspan="4">'.
 2002:                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.
 2003: 		      '</a></td></tr>'.
 2004:                       '<tr><td></td>'.
 2005:                       '<td title="'.$lt{'md'}.'">'.
 2006: 		      &Apache::lonlocal::locallocaltime(
 2007:                            &Apache::lonnet::metadata($root.'.'.$extension,
 2008:                                                      'lastrevisiondate')
 2009:                                                         ).
 2010:                       '</td>'.
 2011:                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.
 2012:                       '<font size="+1">'.$currentversion.'</font>'.
 2013:                       '</nobr></td>'.
 2014:                       '<td title="'.$lt{'ve'}.'"><nobr>In '.$type.': '.
 2015:                       '<font size="+1">');
 2016: # Used in course
 2017: 	    my $usedversion=$hash{'version_'.$linkurl};
 2018: 	    if (($usedversion) && ($usedversion ne 'mostrecent')) {
 2019: 		$r->print($usedversion);
 2020: 	    } else {
 2021: 		$r->print($currentversion);
 2022: 	    }
 2023: 	    $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.
 2024:                       '<nobr>Use: ');
 2025: # Set version
 2026: 	    $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
 2027: 						      'set_version_'.$linkurl,
 2028: 						      ('select_form_order' =>
 2029: 						       ['',1..$currentversion,'mostrecent'],
 2030: 						       '' => '',
 2031: 						       'mostrecent' => 'most recent',
 2032: 						       map {$_,$_} (1..$currentversion))));
 2033: 	    $r->print('</nobr></td></tr><tr><td></td>');
 2034: 	    my $lastold=1;
 2035: 	    for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
 2036: 		my $url=$root.'.'.$prevvers.'.'.$extension;
 2037: 		if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
 2038: 		    $starttime) {
 2039: 		    $lastold=$prevvers;
 2040: 		}
 2041: 	    }
 2042:             # 
 2043:             # Code to figure out how many version entries should go in
 2044:             # each of the four columns
 2045:             my $entries_per_col = 0;
 2046:             my $num_entries = ($currentversion-$lastold);
 2047:             if ($num_entries % 4 == 0) {
 2048:                 $entries_per_col = $num_entries/4;
 2049:             } else {
 2050:                 $entries_per_col = $num_entries/4 + 1;
 2051:             }
 2052:             my $entries_count = 0;
 2053:             $r->print('<td valign="top"><font size="-2">'); 
 2054:             my $cols_output = 1;
 2055:             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
 2056: 		my $url=$root.'.'.$prevvers.'.'.$extension;
 2057: 		$r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).
 2058: 			  '">'.&mt('Version').' '.$prevvers.'</a> ('.
 2059: 			  &Apache::lonlocal::locallocaltime(
 2060:                                 &Apache::lonnet::metadata($url,
 2061:                                                           'lastrevisiondate')
 2062:                                                             ).
 2063: 			  ')');
 2064: 		if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
 2065:                     $r->print(' <a href="/adm/diff?filename='.
 2066: 			      &Apache::lonnet::clutter($root.'.'.$extension).
 2067: 			      '&versionone='.$prevvers.
 2068: 			      '">'.&mt('Diffs').'</a>');
 2069: 		}
 2070: 		$r->print('</nobr><br />');
 2071:                 if (++$entries_count % $entries_per_col == 0) {
 2072:                     $r->print('</font></td>');
 2073:                     if ($cols_output != 4) {
 2074:                         $r->print('<td valign="top"><font size="-2">');
 2075:                         $cols_output++;
 2076:                     }
 2077:                 }
 2078: 	    }
 2079:             while($cols_output++ < 4) {
 2080:                 $r->print('</font></td><td><font>')
 2081:             }
 2082: 	    $r->print('</font></td></tr>'."\n");
 2083: 	}
 2084:     }
 2085:     $r->print('</table></form>');
 2086:     $r->print('<h1>'.&mt('Done').'.</h1>');
 2087: 
 2088:     &untiehash();
 2089: }
 2090: 
 2091: sub mark_hash_old {
 2092:     my $retie_hash=0;
 2093:     if ($hashtied) {
 2094: 	$retie_hash=1;
 2095: 	&untiehash();
 2096:     }
 2097:     &tiehash('write');
 2098:     $hash{'old'}=1;
 2099:     &untiehash();
 2100:     if ($retie_hash) { &tiehash(); }
 2101: }
 2102: 
 2103: sub is_hash_old {
 2104:     my $untie_hash=0;
 2105:     if (!$hashtied) {
 2106: 	$untie_hash=1;
 2107: 	&tiehash();
 2108:     }
 2109:     my $return=$hash{'old'};
 2110:     if ($untie_hash) { &untiehash(); }
 2111:     return $return;
 2112: }
 2113: 
 2114: sub changewarning {
 2115:     my ($r,$postexec,$message,$url)=@_;
 2116:     if (!&is_hash_old()) { return; }
 2117:     my $pathvar='folderpath';
 2118:     my $path=&escape($env{'form.folderpath'});
 2119:     if (!defined($url)) {
 2120: 	if (defined($env{'form.pagepath'})) {
 2121: 	    $pathvar='pagepath';
 2122: 	    $path=&escape($env{'form.pagepath'});
 2123: 	    $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
 2124: 	}
 2125: 	$url='/adm/coursedocs?'.$pathvar.'='.$path;
 2126:     }
 2127:     my $course_type = &Apache::loncommon::course_type();
 2128:     if (!defined($message)) {
 2129: 	$message='Changes will become active for your current session after [_1], or the next time you log in.';
 2130:     }
 2131:     $r->print("\n\n".
 2132: '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n". 
 2133: '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 2134: '<input type="hidden" name="orgurl" value="'.$url.
 2135: '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.
 2136: &mt($message,' <input type="hidden" name="'.
 2137:     $env{'request.role'}.'" value="1" /><input type="button" value="'.
 2138:     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
 2139: $help{'Caching'}.'</font></h3></form>'."\n\n");
 2140: }
 2141: 
 2142: # ================================================================ Main Handler
 2143: sub handler {
 2144:     my $r = shift;
 2145:     &Apache::loncommon::content_type($r,'text/html');
 2146:     $r->send_http_header;
 2147:     return OK if $r->header_only;
 2148:     my $type = &Apache::loncommon::course_type();
 2149: 
 2150: # --------------------------------------------- Initialize help topics for this
 2151:     foreach ('Adding_Course_Doc','Main_Course_Documents',
 2152: 	     'Adding_External_Resource','Navigate_Content',
 2153: 	     'Adding_Folders','Docs_Overview', 'Load_Map',
 2154: 	     'Supplemental','Score_Upload_Form','Adding_Pages',
 2155: 	     'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
 2156: 	     'Check_Resource_Versions','Verify_Content') {
 2157: 	$help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);
 2158:     }
 2159:     # Composite help files
 2160:     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 2161: 		    'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 2162:     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 2163: 		    'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 2164:     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 2165: 		    'Option_Response_Simple');
 2166:     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 2167: 		    'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 2168:     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
 2169: 		  'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 2170:     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 2171: 
 2172: # does this user have privileges to modify docs
 2173:     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2174: 
 2175:   if ($allowed && $env{'form.verify'}) {
 2176:       &verifycontent($r);
 2177:   } elsif ($allowed && $env{'form.listsymbs'}) {
 2178:       &list_symbs($r);
 2179:   } elsif ($allowed && $env{'form.versions'}) {
 2180:       &checkversions($r);
 2181:   } elsif ($allowed && $env{'form.dumpcourse'}) {
 2182:       &dumpcourse($r);
 2183:   } elsif ($allowed && $env{'form.exportcourse'}) {
 2184:       &exportcourse($r);
 2185:   } else {
 2186: # is this a standard course?
 2187: 
 2188:     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 2189:     my $forcestandard = 0;
 2190:     my $forcesupplement;
 2191:     my $script='';
 2192:     my $showdoc=0;
 2193:     my $containertag;
 2194:     my $uploadtag;
 2195:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2196: 					    ['folderpath','pagepath',
 2197: 					     'pagesymb','markedcopy_url',
 2198: 					     'markedcopy_title']);
 2199:     if ($env{'form.folderpath'}) {
 2200: 	my (@folderpath)=split('&',$env{'form.folderpath'});
 2201: 	$env{'form.foldername'}=&unescape(pop(@folderpath));
 2202: 	$env{'form.folder'}=pop(@folderpath);
 2203:     }
 2204:     if ($env{'form.pagepath'}) {
 2205:         my (@pagepath)=split('&',$env{'form.pagepath'});
 2206:         $env{'form.pagename'}=&unescape(pop(@pagepath));
 2207:         $env{'form.folder'}=pop(@pagepath);
 2208:         $containertag = '<input type="hidden" name="pagepath" value="" />'.
 2209: 	    '<input type="hidden" name="pagesymb" value="" />';
 2210:         $uploadtag = '<input type="hidden" name="pagepath" value="'.$env{'form.pagepath'}.'" />'.
 2211: 	    '<input type="hidden" name="pagesymb" value="'.$env{'form.pagesymb'}.'" />';
 2212:     }
 2213:     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 2214:        $showdoc='/'.$1;
 2215:     }
 2216:     unless ($showdoc) { # got called from remote
 2217:        if (($env{'form.folder'}=~/^(?:group|default)_/) || 
 2218:           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
 2219:            $forcestandard = 1;
 2220:        } 
 2221:        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
 2222: 
 2223:        if ($allowed) { 
 2224:          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
 2225:          $script=&Apache::lonratedt::editscript('simple'); 
 2226:        }
 2227:     } else { # got called in sequence from course
 2228:        $allowed=0;
 2229:     }
 2230: 
 2231: # get course data
 2232:     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2233:     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2234: 
 2235: # get personal data 
 2236:     my $uname=$env{'user.name'};
 2237:     my $udom=$env{'user.domain'};
 2238:     my $plainname=&escape(
 2239:                      &Apache::loncommon::plainname($uname,$udom));
 2240: 
 2241: # graphics settings
 2242: 
 2243:     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
 2244: 
 2245:     if ($allowed) {
 2246: 	$script .= &editing_js($udom,$uname);
 2247:     }
 2248: # -------------------------------------------------------------------- Body tag
 2249:     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
 2250:     $r->print(&Apache::loncommon::start_page("$type Documents", $script,
 2251: 					     {'force_register' => $showdoc,}).
 2252: 	      &Apache::loncommon::help_open_menu('','',273,'RAT'));
 2253:   
 2254:   my %allfiles = ();
 2255:   my %codebase = ();
 2256:   my ($upload_result,$upload_output);
 2257:   if ($allowed) {
 2258:       if (($env{'form.uploaddoc.filename'}) &&                                               ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 2259: # Process file upload - phase one - upload and parse primary file.  
 2260:           $upload_result = &process_file_upload(\$upload_output,$coursenum,
 2261: 						$coursedom,\%allfiles,
 2262: 						\%codebase,$1);
 2263:           if ($upload_result eq 'phasetwo') {
 2264:               $r->print($upload_output);
 2265:           }
 2266:       } elsif ($env{'form.phasetwo'}) {
 2267:           my %newname = ();
 2268:           my %origname = ();
 2269:           my %attribs = ();
 2270:           my $updateflag = 0;
 2271:           my $residx = $env{'form.newidx'};
 2272:           my $primary_url = &unescape($env{'form.primaryurl'});
 2273: # Process file upload - phase two - gather secondary files.
 2274:           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
 2275:               if ($env{'form.embedded_item_'.$i.'.filename'}) {
 2276:                   my $javacodebase;
 2277:                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
 2278:                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
 2279:                   if (exists($env{'form.embedded_codebase_'.$i})) {
 2280:                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
 2281:                       $origname{$i} =~ s#^\Q$javacodebase\E/##; 
 2282:                   }
 2283:                   my @attributes = ();
 2284:                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
 2285:                       @attributes = split/:/,$env{'form.embedded_attrib_'.$i};
 2286:                   } else {
 2287:                       @attributes = ($env{'form.embedded_attrib_'.$i});
 2288:                   }
 2289:                   foreach (@attributes) {
 2290:                       push(@{$attribs{$i}},&unescape($_));
 2291:                   }
 2292:                   if ($javacodebase) {
 2293:                       $codebase{$i} = $javacodebase;
 2294:                       $codebase{$i} =~ s#/$##;
 2295:                       $updateflag = 1;
 2296:                   }
 2297:               }
 2298:               unless ($newname{$i} eq $origname{$i}) {
 2299:                   $updateflag = 1;
 2300:               }
 2301:           }
 2302: # Process file upload - phase three - modify primary file
 2303:           if ($updateflag) {
 2304:               my ($content,$rtncode);
 2305:               my $updateflag = 0;
 2306:               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
 2307:               if ($getstatus eq 'ok') {
 2308:                   foreach my $item (keys %newname) {
 2309:                       if ($newname{$item} ne $origname{$item}) {
 2310:                           my $attrib_regexp = '';
 2311:                           if (@{$attribs{$item}} > 1) {
 2312:                               $attrib_regexp = join('|',@{$attribs{$item}});
 2313:                           } else {
 2314:                               $attrib_regexp = $attribs{$item}[0];
 2315:                           }
 2316:                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
 2317:                           } 
 2318:                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi; 
 2319:                       }
 2320:                       if (exists($codebase{$item})) {
 2321:                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
 2322:                       }
 2323:                   }
 2324: # Save edited file.
 2325:                   my $saveresult;
 2326:                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2327:                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2328:                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
 2329:               } else {
 2330:                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus); 
 2331:               }
 2332:           }
 2333:       }
 2334:   }
 2335: 
 2336:   unless ($showdoc ||  $upload_result eq 'phasetwo') {
 2337: # -----------------------------------------------------------------------------
 2338:        my %lt=&Apache::lonlocal::texthash(
 2339:                 'uplm' => 'Upload a new main '.lc($type).' document',
 2340:                 'upls' => 'Upload a new supplemental '.lc($type).' document',
 2341:                 'impp' => 'Import a document',
 2342:                 'pubd' => 'Published documents',
 2343: 		'copm' => 'All documents out of a published map into this folder',
 2344:                 'spec' => 'Special documents',
 2345:                 'upld' => 'Upload Document',
 2346:                 'srch' => 'Search',
 2347:                 'impo' => 'Import',
 2348: 		'book' => 'Import Bookmarks',
 2349:                 'selm' => 'Select Map',
 2350:                 'load' => 'Load Map',
 2351:                 'reco' => 'Recover Deleted Resources',
 2352:                 'newf' => 'New Folder',
 2353:                 'newp' => 'New Composite Page',
 2354:                 'extr' => 'External Resource',
 2355:                 'syll' => 'Syllabus',
 2356:                 'navc' => 'Navigate Contents',
 2357:                 'sipa' => 'Simple Page',
 2358:                 'sipr' => 'Simple Problem',
 2359:                 'drbx' => 'Drop Box',
 2360:                 'scuf' => 'Score Upload Form',
 2361:                 'bull' => 'Bulletin Board',
 2362:                 'mypi' => 'My Personal Info',
 2363: 		'abou' => 'About User',
 2364:                 'imsf' => 'Import IMS package',
 2365:                 'file' =>  'File',
 2366:                 'title' => 'Title',
 2367:                 'comment' => 'Comment',
 2368:                 'parse' => 'If HTML file, upload embedded images/multimedia files'
 2369: 					  );
 2370: # -----------------------------------------------------------------------------
 2371:     if ($allowed) {
 2372:        my $dumpbut=&dumpbutton();
 2373:        my $exportbut=&exportbutton();
 2374:        my %lt=&Apache::lonlocal::texthash(
 2375: 					 'vc' => 'Verify Content',
 2376: 					 'cv' => 'Check/Set Resource Versions',
 2377: 					 'ls' => 'List Symbs',
 2378: 					  );
 2379: 
 2380:        my $folderpath=$env{'form.folderpath'};
 2381:        if (!$folderpath) {
 2382: 	   if ($env{'form.folder'} eq '' ||
 2383: 	       $env{'form.folder'} eq 'supplemental') {
 2384: 	       $folderpath='default&'.
 2385: 		   &escape(&mt('Main '.$type.' Documents'));
 2386: 	   }
 2387:        }
 2388:        unless ($env{'form.pagepath'}) {
 2389:            $containertag = '<input type="hidden" name="folderpath" value="" />';
 2390:            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';
 2391:        }
 2392: 
 2393:        $r->print(<<ENDCOURSEVERIFY);
 2394: <form name="renameform" method="post" action="/adm/coursedocs">
 2395: <input type="hidden" name="title" />
 2396: <input type="hidden" name="cmd" />
 2397: <input type="hidden" name="markcopy" />
 2398: $containertag
 2399: </form>
 2400: <form name="simpleedit" method="post" action="/adm/coursedocs">
 2401: <input type=hidden name="importdetail" value="">
 2402: $uploadtag
 2403: </form>
 2404: <form action="/adm/coursedocs" method="post" name="courseverify">
 2405: <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">
 2406: <tr><td bgcolor="#DDDDCC">
 2407: <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}
 2408: </td><td bgcolor="#DDDDCC">
 2409:     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}
 2410: $dumpbut
 2411: $exportbut
 2412: </td><td bgcolor="#DDDDCC">
 2413:     <input type="submit" name="listsymbs" value="$lt{'ls'}" />
 2414: </td></tr></table>
 2415: </form>
 2416: ENDCOURSEVERIFY
 2417:        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',
 2418: 		     &mt('Editing the Table of Contents for your '.$type)));
 2419:     }
 2420: # --------------------------------------------------------- Standard documents
 2421:     $r->print('<table border=2 cellspacing=4 cellpadding=4>');
 2422:     if (($standard) && ($allowed) && (!$forcesupplement)) {
 2423: 	$r->print('<tr><td bgcolor="#BBBBBB">');
 2424: #  '<h2>'.&mt('Main Course Documents').
 2425: #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');
 2426:        my $folder=$env{'form.folder'};
 2427:        if ($folder eq '' || $folder eq 'supplemental') {
 2428:            $folder='default';
 2429: 	   $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));
 2430:        }
 2431:        my $postexec='';
 2432:        if ($folder eq 'default') {
 2433: 	   $r->print('<script>this.window.name="loncapaclient";</script>');
 2434:        } else {
 2435:            #$postexec='self.close();';
 2436:        }
 2437:        $hadchanges=0;
 2438:        &editor($r,$coursenum,$coursedom,$folder,$allowed,$upload_output);
 2439:        if ($hadchanges) {
 2440: 	   &mark_hash_old()
 2441:        }
 2442:        &changewarning($r,$postexec);
 2443:        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
 2444:                      '.sequence';
 2445:        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
 2446:                      '.page';
 2447: 	my $container='sequence';
 2448: 	if ($env{'form.pagepath'}) {
 2449: 	    $container='page';
 2450: 	}
 2451: 	my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 2452:        $r->print(<<ENDFORM);
 2453: <table cellspacing=4 cellpadding=4><tr>
 2454: <th bgcolor="#DDDDDD">$lt{'uplm'}</th>
 2455: <th bgcolor="#DDDDDD">$lt{'impp'}</th>
 2456: <th bgcolor="#DDDDDD">$lt{'spec'}</th>
 2457: </tr>
 2458: <tr><td bgcolor="#DDDDDD">
 2459: $lt{'file'}:<br />
 2460: <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 2461: <input type="file" name="uploaddoc" size="40">
 2462: <br />
 2463: $lt{'title'}:<br />
 2464: <input type="text" size="50" name="comment">
 2465: $uploadtag
 2466: <input type="hidden" name="cmd" value="upload_default">
 2467: <br />
 2468: <nobr>
 2469: <label>$lt{'parse'}?
 2470: <input type="checkbox" name="parserflag" />
 2471: </label>
 2472: </nobr>
 2473: <br />
 2474: <br />
 2475: <nobr>
 2476: <input type="submit" value="$lt{'upld'}">
 2477:  $help{'Uploading_From_Harddrive'}
 2478: </nobr>
 2479: </form>
 2480: </td>
 2481: <td bgcolor="#DDDDDD">
 2482: <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
 2483: $lt{'pubd'}<br />
 2484: $uploadtag
 2485: <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}" />
 2486: <br />
 2487: <nobr>
 2488: <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}" />
 2489: $help{'Importing_LON-CAPA_Resource'}
 2490: </nobr>
 2491: <br />
 2492: <input type=button onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
 2493: <p>
 2494: <hr />
 2495: $lt{'copm'}<br />
 2496: <input type="text" size="40" name="importmap"><br />
 2497: <nobr><input type=button 
 2498: onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
 2499: value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">
 2500: $help{'Load_Map'}</nobr>
 2501: </p>
 2502: </form>
 2503: <hr />
 2504: <form action="/adm/groupsort" method="post" name="recover">
 2505: <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />
 2506: </form>
 2507: ENDFORM
 2508:        unless ($env{'form.pagepath'}) {
 2509: 	   $r->print(<<ENDFORM);
 2510: <hr />
 2511: <form action="/adm/coursedocs" method="post" name="newext">
 2512: $uploadtag
 2513: <input type=hidden name="importdetail" value="">
 2514: <nobr>
 2515: <input name="newext" type="button" onClick="javascript:makenewext('newext');"
 2516: value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
 2517: </nobr>
 2518: </form>
 2519: <br /><form action="/adm/imsimportdocs" method="post" name="ims">
 2520: <input type="hidden" name="folder" value="$folder" />
 2521: <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />
 2522: </nobr>
 2523: </form>
 2524: ENDFORM
 2525:        }
 2526:        $r->print('</td><td bgcolor="#DDDDDD">');
 2527:        unless ($env{'form.pagepath'}) {
 2528:            $r->print(<<ENDFORM);
 2529: <br /><form action="/adm/coursedocs" method="post" name="newfolder">
 2530: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 2531: <input type=hidden name="importdetail" value="">
 2532: <nobr>
 2533: <input name="newfolder" type="button"
 2534: onClick="javascript:makenewfolder(this.form,'$folderseq');"
 2535: value="$lt{'newf'}" />$help{'Adding_Folders'}
 2536: </nobr>
 2537: </form>
 2538: <br /><form action="/adm/coursedocs" method="post" name="newpage">
 2539: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 2540: <input type=hidden name="importdetail" value="">
 2541: <nobr>
 2542: <input name="newpage" type="button"
 2543: onClick="javascript:makenewpage(this.form,'$pageseq');"
 2544: value="$lt{'newp'}" />$help{'Adding_Pages'}
 2545: </nobr>
 2546: </form>
 2547: <br /><form action="/adm/coursedocs" method="post" name="newsyl">
 2548: $uploadtag
 2549: <input type=hidden name="importdetail" 
 2550: value="Syllabus=/public/$coursedom/$coursenum/syllabus">
 2551: <nobr>
 2552: <input name="newsyl" type="submit" value="$lt{'syll'}" /> 
 2553:  $help{'Syllabus'}
 2554: </nobr>
 2555: </form>
 2556: <br /><form action="/adm/coursedocs" method="post" name="newnav">
 2557: $uploadtag
 2558: <input type=hidden name="importdetail" 
 2559: value="Navigate Content=/adm/navmaps">
 2560: <nobr>
 2561: <input name="newnav" type="submit" value="$lt{'navc'}" />
 2562: $help{'Navigate_Content'}
 2563: </nobr>
 2564: </form>
 2565: <br /><form action="/adm/coursedocs" method="post" name="newsmppg">
 2566: $uploadtag
 2567: <input type=hidden name="importdetail" value="">
 2568: <nobr>
 2569: <input name="newsmppg" type="button" value="$lt{'sipa'}"
 2570: onClick="javascript:makesmppage();" /> $help{'Simple Page'}
 2571: </nobr>
 2572: </form>
 2573: <br /><form action="/adm/coursedocs" method="post" name="newsmpproblem">
 2574: $uploadtag
 2575: <input type=hidden name="importdetail" value="">
 2576: <nobr>
 2577: <input name="newsmpproblem" type="button" value="$lt{'sipr'}"
 2578: onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}
 2579: </nobr>
 2580: </form>
 2581: <br /><form action="/adm/coursedocs" method="post" name="newdropbox">
 2582: $uploadtag      
 2583: <input type=hidden name="importdetail" value="">
 2584: <nobr>          
 2585: <input name="newdropbox" type="button" value="$lt{'drbx'}"
 2586: onClick="javascript:makedropbox();" />
 2587: </nobr>         
 2588: </form> 
 2589: <br /><form action="/adm/coursedocs" method="post" name="newexamupload">
 2590: $uploadtag
 2591: <input type=hidden name="importdetail" value="">
 2592: <nobr>
 2593: <input name="newexamupload" type="button" value="$lt{'scuf'}"
 2594: onClick="javascript:makeexamupload();" />
 2595: $help{'Score_Upload_Form'}
 2596: </nobr>
 2597: </form>
 2598: <br /><form action="/adm/coursedocs" method="post" name="newbul">
 2599: $uploadtag
 2600: <input type=hidden name="importdetail" value="">
 2601: <nobr>
 2602: <input name="newbulletin" type="button" value="$lt{'bull'}"
 2603: onClick="javascript:makebulboard();" />
 2604: $help{'Bulletin Board'}
 2605: </nobr>
 2606: </form>
 2607: <br /><form action="/adm/coursedocs" method="post" name="newaboutme">
 2608: $uploadtag
 2609: <input type=hidden name="importdetail" 
 2610: value="$plainname=/adm/$udom/$uname/aboutme">
 2611: <nobr>
 2612: <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
 2613: $help{'My Personal Info'}
 2614: </nobr>
 2615: </form>
 2616: <br /><form action="/adm/coursedocs" method="post" name="newaboutsomeone">
 2617: $uploadtag
 2618: <input type=hidden name="importdetail" value="">
 2619: <nobr>
 2620: <input name="newaboutsomeone" type="button" value="$lt{'abou'}" 
 2621: onClick="javascript:makeabout();" />
 2622: </nobr>
 2623: </form>
 2624: ENDFORM
 2625:        }
 2626:        if ($env{'form.pagepath'}) {
 2627:            $r->print(<<ENDBLOCK);
 2628: <form action="/adm/coursedocs" method="post" name="newsmpproblem">
 2629: $uploadtag
 2630: <input type=hidden name="importdetail" value="">
 2631: <nobr>
 2632: <input name="newsmpproblem" type="button" value="$lt{'sipr'}"
 2633: onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}
 2634: </nobr>
 2635: </form>
 2636: <br /><form action="/adm/coursedocs" method="post" name="newexamupload">
 2637: $uploadtag
 2638: <input type=hidden name="importdetail" value="">
 2639: <nobr>
 2640: <input name="newexamupload" type="button" value="$lt{'scuf'}"
 2641: onClick="javascript:makeexamupload();" />
 2642: $help{'Score_Upload_Form'}
 2643: </nobr>
 2644: </form>
 2645: ENDBLOCK
 2646:        }
 2647:        $r->print('</td></tr>'."\n".
 2648: '</table>');
 2649:        $r->print('</td></tr>');
 2650:     }
 2651: # ----------------------------------------------------- Supplemental documents
 2652:     if (!$forcestandard) {
 2653:        $r->print('<tr><td bgcolor="#BBBBBB">');
 2654: # '<h2>'.&mt('Supplemental Course Documents').
 2655: #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');
 2656:        my $folder=$env{'form.folder'};
 2657:        unless ($folder=~/^supplemental/) {
 2658: 	   $folder='supplemental';
 2659:        }
 2660:        if ($folder =~ /^supplemental$/ &&
 2661: 	   $env{'form.folderpath'} =~ /^default\&/) {
 2662: 	   $env{'form.folderpath'}='supplemental&'.
 2663: 	       &escape(&mt('Supplemental '.$type.' Documents'));
 2664:        }
 2665:        &editor($r,$coursenum,$coursedom,$folder,$allowed);
 2666:        if ($allowed) {
 2667:        my $folderseq=
 2668:                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
 2669:                      '.sequence';
 2670: 
 2671:           $r->print(<<ENDSUPFORM);
 2672: <table cellspacing=4 cellpadding=4><tr>
 2673: <th bgcolor="#DDDDDD">$lt{'upls'}</th>
 2674: <th bgcolor="#DDDDDD">$lt{'spec'}</th>
 2675: </tr>
 2676: <tr><td bgcolor="#DDDDDD">
 2677: <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 2678: <input type="file" name="uploaddoc" size="40">
 2679: <br />
 2680: <br />
 2681: <nobr>
 2682: <label>$lt{'parse'}?
 2683: <input type="checkbox" name="parserflag" />
 2684: </label>
 2685: </nobr>
 2686: <br /><br />
 2687: $lt{'comment'}:<br />
 2688: <textarea cols=50 rows=4 name='comment'>
 2689: </textarea>
 2690: <br />
 2691: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 2692: <input type="hidden" name="cmd" value="upload_supplemental">
 2693: <nobr>
 2694: <input type="submit" value="$lt{'upld'}">
 2695:  $help{'Uploading_From_Harddrive'}
 2696: </nobr>
 2697: </form>
 2698: </td>
 2699: <td bgcolor="#DDDDDD">
 2700: <form action="/adm/coursedocs" method="post" name="supnewfolder">
 2701: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 2702: <input type=hidden name="importdetail" value="">
 2703: <nobr>
 2704: <input name="newfolder" type="button"
 2705: onClick="javascript:makenewfolder(this.form,'$folderseq');"
 2706: value="$lt{'newf'}" /> $help{'Adding_Folders'}
 2707: </nobr>
 2708: </form>
 2709: <br /><form action="/adm/coursedocs" method="post" name="supnewext">
 2710: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 2711: <input type=hidden name="importdetail" value="">
 2712: <nobr>
 2713: <input name="newext" type="button" 
 2714: onClick="javascript:makenewext('supnewext');"
 2715: value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
 2716: </nobr>
 2717: </form>
 2718: <br /><form action="/adm/coursedocs" method="post" name="supnewsyl">
 2719: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 2720: <input type=hidden name="importdetail" 
 2721: value="Syllabus=/public/$coursedom/$coursenum/syllabus">
 2722: <nobr>
 2723: <input name="newsyl" type="submit" value="$lt{'syll'}" />
 2724: $help{'Syllabus'}
 2725: </nobr>
 2726: </form>
 2727: <br /><form action="/adm/coursedocs" method="post" name="subnewaboutme">
 2728: <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />
 2729: <input type=hidden name="importdetail" 
 2730: value="$plainname=/adm/$udom/$uname/aboutme">
 2731: <nobr>
 2732: <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
 2733: $help{'My Personal Info'}
 2734: </nobr>
 2735: </form>
 2736: </td></tr>
 2737: </table></td></tr>
 2738: ENDSUPFORM
 2739:        }
 2740:     }
 2741:     if ($allowed) {
 2742: 	$r->print('<form method="POST" name="extimport" action="/adm/coursedocs"><input type="hidden" name="title" /><input type="hidden" name="url" /><input type="hidden" name="useform" /></form>');
 2743:     }
 2744:     $r->print('</table>');
 2745:   } else {
 2746:       unless ($upload_result eq 'phasetwo') {
 2747: # -------------------------------------------------------- This is showdoc mode
 2748:           $r->print("<h1>".&mt('Uploaded Document').' - '.
 2749: 		&Apache::lonnet::gettitle($r->uri).'</h1><p>'.
 2750: &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".
 2751:           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');
 2752:       }
 2753:   }
 2754:  }
 2755:  $r->print(&Apache::loncommon::end_page());
 2756:  return OK;
 2757: } 
 2758: 
 2759: 
 2760: sub editing_js {
 2761:     my ($udom,$uname) = @_;
 2762:     my $now = time();
 2763: 
 2764:     return <<ENDNEWSCRIPT;
 2765: function makenewfolder(targetform,folderseq) {
 2766:     var foldername=prompt('Name of New Folder','New Folder');
 2767:     if (foldername) {
 2768:        targetform.importdetail.value=escape(foldername)+"="+folderseq;
 2769:         targetform.submit();
 2770:     }
 2771: }
 2772: 
 2773: function makenewpage(targetform,folderseq) {
 2774:     var pagename=prompt('Name of New Page','New Page');
 2775:     if (pagename) {
 2776:         targetform.importdetail.value=escape(pagename)+"="+folderseq;
 2777:         targetform.submit();
 2778:     }
 2779: }
 2780: 
 2781: function makenewext(targetname) {
 2782:     this.document.forms.extimport.useform.value=targetname;
 2783:     window.open('/adm/rat/extpickframe.html');
 2784: }
 2785: 
 2786: function makeexamupload() {
 2787:    var title=prompt('Listed Title for the Uploaded Score');
 2788:    if (title) { 
 2789:     this.document.forms.newexamupload.importdetail.value=
 2790: 	escape(title)+'=/res/lib/templates/examupload.problem';
 2791:     this.document.forms.newexamupload.submit();
 2792:    }
 2793: }
 2794: 
 2795: function makesmppage() {
 2796:    var title=prompt('Listed Title for the Page');
 2797:    if (title) { 
 2798:     this.document.forms.newsmppg.importdetail.value=
 2799: 	escape(title)+'=/adm/$udom/$uname/$now/smppg';
 2800:     this.document.forms.newsmppg.submit();
 2801:    }
 2802: }
 2803: 
 2804: function makesmpproblem() {
 2805:    var title=prompt('Listed Title for the Problem');
 2806:    if (title) { 
 2807:     this.document.forms.newsmpproblem.importdetail.value=
 2808: 	escape(title)+'=/res/lib/templates/simpleproblem.problem';
 2809:     this.document.forms.newsmpproblem.submit();
 2810:    }
 2811: }
 2812: 
 2813: function makedropbox() {
 2814:    var title=prompt('Listed Title for the Drop Box');
 2815:    if (title) { 
 2816:     this.document.forms.newdropbox.importdetail.value=
 2817:         escape(title)+'=/res/lib/templates/DropBox.problem';
 2818:     this.document.forms.newdropbox.submit();
 2819:    }
 2820: }
 2821: 
 2822: function makebulboard() {
 2823:    var title=prompt('Listed Title for the Bulletin Board');
 2824:    if (title) {
 2825:     this.document.forms.newbul.importdetail.value=
 2826: 	escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
 2827:     this.document.forms.newbul.submit();
 2828:    }
 2829: }
 2830: 
 2831: function makeabout() {
 2832:    var user=prompt("Enter user:domain for User's 'About Me' Page");
 2833:    if (user) {
 2834:        var comp=new Array();
 2835:        comp=user.split(':');
 2836:        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
 2837: 	   if ((comp[0]) && (comp[1])) {
 2838: 	       this.document.forms.newaboutsomeone.importdetail.value=
 2839: 		   'About '+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
 2840: 	       this.document.forms.newaboutsomeone.submit();
 2841: 	   } else {
 2842:                alert("Not a valid user:domain");
 2843:            }
 2844:        } else {
 2845:            alert("Please enter both user and domain in the format user:domain"); 
 2846:        }
 2847:    }
 2848: }
 2849: 
 2850: function makeims() {
 2851:     var caller = document.forms.ims.folder.value;
 2852:     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
 2853:     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");
 2854:     newWindow.location.href = newlocation;
 2855: }
 2856: 
 2857: 
 2858: function finishpick() {
 2859:     var title=this.document.forms.extimport.title.value;
 2860:     var url=this.document.forms.extimport.url.value;
 2861:     var form=this.document.forms.extimport.useform.value;
 2862:     eval
 2863:      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+
 2864:     '";this.document.forms.'+form+'.submit();');
 2865: }
 2866: 
 2867: function changename(folderpath,index,oldtitle,container,pagesymb) {
 2868:     var title=prompt('New Title',oldtitle);
 2869:     if (title) {
 2870: 	this.document.forms.renameform.title.value=title;
 2871: 	this.document.forms.renameform.cmd.value='rename_'+index;
 2872:         if (container == 'sequence') {
 2873: 	    this.document.forms.renameform.folderpath.value=folderpath;
 2874:         }
 2875:         if (container == 'page') {
 2876:             this.document.forms.renameform.pagepath.value=folderpath;
 2877:             this.document.forms.renameform.pagesymb.value=pagesymb;
 2878:         }
 2879:         this.document.forms.renameform.submit();
 2880:     }
 2881: }
 2882: 
 2883: function removeres(folderpath,index,oldtitle,container,pagesymb) {
 2884:     if (confirm('WARNING: Removing a resource makes associated grades and scores inaccessible!\\nRemove "'+oldtitle+'"?')) {
 2885: 	this.document.forms.renameform.cmd.value='del_'+index;
 2886:         if (container == 'sequence') {
 2887:             this.document.forms.renameform.folderpath.value=folderpath;
 2888:         }
 2889:         if (container == 'page') {
 2890:             this.document.forms.renameform.pagepath.value=folderpath;
 2891:             this.document.forms.renameform.pagesymb.value=pagesymb;
 2892:         }
 2893:         this.document.forms.renameform.submit();
 2894:     }
 2895: }
 2896: 
 2897: function cutres(folderpath,index,oldtitle,container,pagesymb) {
 2898:     if (confirm('WARNING: Cutting a resource makes associated grades and scores inaccessible!\\nGrades remain inaccessible if resource is pasted into another folder.\\nCut "'+oldtitle+'"?')) {
 2899: 	this.document.forms.renameform.cmd.value='cut_'+index;
 2900: 	this.document.forms.renameform.markcopy.value=index;
 2901:         if (container == 'sequence') {
 2902:             this.document.forms.renameform.folderpath.value=folderpath;
 2903:         }
 2904:         if (container == 'page') {
 2905:             this.document.forms.renameform.pagepath.value=folderpath;
 2906:             this.document.forms.renameform.pagesymb.value=pagesymb;
 2907:         }
 2908:         this.document.forms.renameform.submit();
 2909:     }
 2910: }
 2911: 
 2912: function markcopy(folderpath,index,oldtitle,container,pagesymb) {
 2913:     this.document.forms.renameform.markcopy.value=index;
 2914:     if (container == 'sequence') {
 2915: 	this.document.forms.renameform.folderpath.value=folderpath;
 2916:     }
 2917:     if (container == 'page') {
 2918: 	this.document.forms.renameform.pagepath.value=folderpath;
 2919: 	this.document.forms.renameform.pagesymb.value=pagesymb;
 2920:     }
 2921:     this.document.forms.renameform.submit();
 2922: }
 2923: 
 2924: ENDNEWSCRIPT
 2925: }
 2926: 1;
 2927: __END__

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