Diff for /loncom/interface/londocs.pm between versions 1.203 and 1.328

version 1.203, 2005/08/30 15:41:32 version 1.328, 2009/01/28 13:24:54
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::londocs;  
   
 use strict;  package Apache::londocs;
 use Apache::Constants qw(:common :http);  
 use Apache::imsexport;  use strict;
 use Apache::lonnet;  use Apache::Constants qw(:common :http);
 use Apache::loncommon;  use Apache::imsexport;
 use Apache::lonratedt;  use Apache::lonnet;
 use Apache::lonratsrv;  use Apache::loncommon;
 use Apache::lonxml;  use LONCAPA::map();
 use Apache::loncreatecourse;  use Apache::lonratedt();
 use Apache::lonnavmaps;  use Apache::lonxml;
 use HTML::Entities;  use Apache::lonclonecourse;
 use GDBM_File;  use Apache::lonnavmaps;
 use Apache::lonlocal;  use HTML::Entities;
 use Cwd;  use GDBM_File;
   use Apache::lonlocal;
 my $iconpath;  use Cwd;
   use LONCAPA qw(:DEFAULT :match);
 my %hash;  
   my $iconpath;
 my $hashtied;  
 my %alreadyseen=();  my %hash;
   
 my $hadchanges;  my $hashtied;
   my %alreadyseen=();
 # Available help topics  
   my $hadchanges;
 my %help=();  
   
 # Mapread read maps into lonratedt::global arrays   my %help=();
 # @order and @resources, determines status  
 # sets @order - pointer to resources in right order  
 # sets @resources - array with the resources with correct idx  sub mapread {
 #      my ($coursenum,$coursedom,$map)=@_;
       return
 sub mapread {        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
     my ($coursenum,$coursedom,$map)=@_;       $map);
     return  }
       &Apache::lonratedt::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.  
                                 $map);  sub storemap {
 }      my ($coursenum,$coursedom,$map)=@_;
       my ($outtext,$errtext)=
 sub storemap {        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
     my ($coursenum,$coursedom,$map)=@_;        $map,1);
     my ($outtext,$errtext)=      if ($errtext) { return ($errtext,2); }
       &Apache::lonratedt::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.     
                                 $map,1);      $hadchanges=1;
     if ($errtext) { return ($errtext,2); }      return ($errtext,0);
       }
     $hadchanges=1;  
     return ($errtext,0);  
 }  
   sub authorhosts {
 # ----------------------------------------- Return hash with valid author names      my %outhash=();
       my $home=0;
 sub authorhosts {      my $other=0;
     my %outhash=();      foreach my $key (keys(%env)) {
     my $home=0;   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     my $other=0;      my $role=$1;
     foreach (keys %env) {      my $realm=$2;
  if ($_=~/^user\.role\.(au|ca)\.(.+)$/) {      my ($start,$end)=split(/\./,$env{$key});
     my $role=$1;      if (($start) && ($start>time)) { next; }
     my $realm=$2;      if (($end) && (time>$end)) { next; }
     my ($start,$end)=split(/\./,$env{$_});      my ($ca,$cd);
     if (($start) && ($start>time)) { next; }      if ($1 eq 'au') {
     if (($end) && (time>$end)) { next; }   $ca=$env{'user.name'};
     my $ca; my $cd;   $cd=$env{'user.domain'};
     if ($1 eq 'au') {      } else {
  $ca=$env{'user.name'};   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  $cd=$env{'user.domain'};      }
     } else {      my $allowed=0;
  ($cd,$ca)=($realm=~/^\/(\w+)\/(\w+)$/);      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
     }      my @ids=&Apache::lonnet::current_machine_ids();
     my $allowed=0;      foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);      if ($allowed) {
     my @ids=&Apache::lonnet::current_machine_ids();   $home++;
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }   $outhash{'home_'.$ca.'@'.$cd}=1;
     if ($allowed) {      } else {
  $home++;   $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;
  $outhash{'home_'.$ca.'@'.$cd}=1;   $other++;
     } else {      }
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;   }
  $other++;      }
     }      return ($home,$other,%outhash);
  }  }
     }  
     return ($home,$other,%outhash);  
 }  sub dumpbutton {
 # ------------------------------------------------------ Generate "dump" button      my ($home,$other,%outhash)=&authorhosts();
       my $type = &Apache::loncommon::course_type();
 sub dumpbutton {      if ($home+$other==0) { return ''; }
     my ($home,$other,%outhash)=&authorhosts();      if ($home) {
     if ($home+$other==0) { return ''; }   return '<input type="submit" name="dumpcourse" value="'.
     my $output='</td><td bgcolor="#DDDDCC">';      &mt('Dump '.$type.' DOCS to Construction Space').'" />'.
     if ($home) {      &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');
  return '</td><td bgcolor="#DDDDCC">'.      } else {
     '<input type="submit" name="dumpcourse" value="'.   return '<div>'.
     &mt('Dump Course DOCS to Construction Space').'" />'.       &mt('Dump '.$type.
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');   ' DOCS to Construction Space: available on other servers').
     } else {   '</div>';
  return'</td><td bgcolor="#DDDDCC">'.      }
      &mt('Dump Course DOCS to Construction Space: available on other servers');  }
     }  
 }  sub clean {
       my ($title)=@_;
 sub clean {      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
     my ($title)=@_;      return $title;
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;  }
     return $title;  
 }  
 # -------------------------------------------------------- Actually dump course  
   sub dumpcourse {
 sub dumpcourse {      my ($r) = @_;
     my $r=shift;      my $type = &Apache::loncommon::course_type();
     my $html=&Apache::lonxml::xmlbegin();      $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').
     $r->print($html.'<head><title>Dump DOCS</title></head>'.        '<form name="dumpdoc" method="post">');
         &Apache::loncommon::bodytag('Dump Course DOCS to Construction Space').      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));
       '<form name="dumpdoc" method="post">');      my ($home,$other,%outhash)=&authorhosts();
     my ($home,$other,%outhash)=&authorhosts();      unless ($home) { return ''; }
     unless ($home) { return ''; }      my $origcrsid=$env{'request.course.id'};
     my $origcrsid=$env{'request.course.id'};      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {  # Do the dumping
 # Do the dumping   unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }   my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   my $title=$env{'form.authorfolder'};
  my $title=$env{'form.authorfolder'};   $title=&clean($title);
  my ($ext)=($title=~s/\.(\w+)$//);   my %replacehash=();
  $title=&clean($title);   foreach my $key (keys(%env)) {
  $title.='.'.$ext;      if ($key=~/^form\.namefor\_(.+)/) {
  my %replacehash=();   $replacehash{$1}=$env{$key};
  foreach (keys %env) {      }
     if ($_=~/^form\.namefor\_(.+)/) {   }
  $replacehash{$1}=$env{$_};   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
     }   $crs=~s/\_/\//g;
  }   foreach my $item (keys(%replacehash)) {
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';      my $newfilename=$title.'/'.$replacehash{$item};
  $crs=~s/\_/\//g;      $newfilename=~s/\.(\w+)$//;
  foreach (keys %replacehash) {      my $ext=$1;
     my $newfilename=$title.'/'.$replacehash{$_};      $newfilename=&clean($newfilename);
     $newfilename=&clean($newfilename);      $newfilename.='.'.$ext;
     my @dirs=split(/\//,$newfilename);      my @dirs=split(/\//,$newfilename);
     my $path='/home/'.$ca.'/public_html';      my $path='/home/'.$ca.'/public_html';
     my $makepath=$path;      my $makepath=$path;
     my $fail=0;      my $fail=0;
     for (my $i=0;$i<$#dirs;$i++) {      for (my $i=0;$i<$#dirs;$i++) {
  $makepath.='/'.$dirs[$i];   $makepath.='/'.$dirs[$i];
  unless (-e $makepath) {    unless (-e $makepath) {
     unless(mkdir($makepath,0777)) { $fail=1; }       unless(mkdir($makepath,0777)) { $fail=1; }
  }   }
     }      }
     $r->print('<br /><tt>'.$_.'</tt> => <tt>'.$newfilename.'</tt>: ');      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
  if ($_=~/\.(sequence|page|html|htm|xml|xhtml)$/) {   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
     print $fh &Apache::loncreatecourse::rewritefile(      print $fh &Apache::lonclonecourse::rewritefile(
          &Apache::loncreatecourse::readfile($env{'request.course.id'},$_),           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
      (%replacehash,$crs => '')       (%replacehash,$crs => '')
     );      );
  } else {   } else {
     print $fh      print $fh
          &Apache::loncreatecourse::readfile($env{'request.course.id'},$_);           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
        }         }
  $fh->close();   $fh->close();
     } else {      } else {
  $fail=1;   $fail=1;
     }      }
     if ($fail) {      if ($fail) {
  $r->print('<font color="red">fail</font>');   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
     } else {      } else {
  $r->print('<font color="green">ok</font>');   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     }      }
  }   }
     } else {      } else {
 # Input form  # Input form
  unless ($home==1) {   unless ($home==1) {
     $r->print(      $r->print(
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');        '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');
  }   }
  foreach (sort keys %outhash) {   foreach my $key (sort(keys(%outhash))) {
     if ($_=~/^home_(.+)$/) {      if ($key=~/^home_(.+)$/) {
  if ($home==1) {   if ($home==1) {
     $r->print(      $r->print(
   '<input type="hidden" name="authorspace" value="'.$1.'" />');    '<input type="hidden" name="authorspace" value="'.$1.'" />');
  } else {   } else {
     $r->print('<option value="'.$1.'">'.$1.' - '.      $r->print('<option value="'.$1.'">'.$1.' - '.
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');        &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');
  }   }
     }      }
  }   }
  unless ($home==1) {   unless ($home==1) {
     $r->print('</select>');      $r->print('</select>');
  }   }
  my $title=$origcrsdata{'description'};   my $title=$origcrsdata{'description'};
  $title=~s/\s+/\_/gs;   $title=~s/[\/\s]+/\_/gs;
  $title=&clean($title);   $title=&clean($title);
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3><input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');   $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'
  &tiehash();                   .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');
  $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>');   &tiehash();
  foreach (&Apache::loncreatecourse::crsdirlist($origcrsid,'userfiles')) {   $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'
     $r->print('<tr><td>'.$_.'</td>');                   .&Apache::loncommon::start_data_table()
     my ($ext)=($_=~/\.(\w+)$/);                   .&Apache::loncommon::start_data_table_header_row()
     my $title=$hash{'title_'.$hash{                   .'<th>'.&mt('Internal Filename').'</th>'
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$_}};                   .'<th>'.&mt('Title').'</th>'
     $title=~s/&colon;/:/g;                   .'<th>'.&mt('Save as ...').'</th>'
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');                   .&Apache::loncommon::end_data_table_header_row());
     unless ($title) {   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  $title=$_;      $r->print(&Apache::loncommon::start_data_table_row()
     }                       .'<td>'.$file.'</td>');
     $title=~s/\.(\w+)$//;      my ($ext)=($file=~/\.(\w+)$/);
     $title=&clean($title);      my $title=$hash{'title_'.$hash{
     $title.='.'.$ext;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     $r->print("\n<td><input type='text' size='60' name='namefor_".$_."' value='".$title."' /></td></tr>\n");      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
  }      if (!$title) {
  $r->print("</table>\n");   $title=$file;
  &untiehash();      } else {
  $r->print(   $title=~s|/|_|g;
   '<p><input type="submit" name="dumpcourse" value="'.&mt('Dump Course DOCS').'" /></p></form>');      }
     }      $title=~s/\.(\w+)$//;
 }      $title=&clean($title);
       $title.='.'.$ext;
 # ------------------------------------------------------ Generate "export" button      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
                        .&Apache::loncommon::end_data_table_row());
 sub exportbutton {   }
     return '</td><td bgcolor="#DDDDCC">'.   $r->print(&Apache::loncommon::end_data_table());
             '<input type="submit" name="exportcourse" value="'.   &untiehash();
             &mt('Export Course to IMS').'" />';   $r->print(
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');
 }      }
   }
 sub exportcourse {  
     my $r=shift;  
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',  
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});  sub exportbutton {
     my $numdisc = keys %discussiontime;      my $type = &Apache::loncommon::course_type();
     my $navmap = Apache::lonnavmaps::navmap->new();      return '<input type="submit" name="exportcourse" value="'.
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);              &mt('Export '.$type.' to IMS').'" />'.
     my $curRes;      &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');
     my $outcome;  }
   
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  
                                             ['finishexport']);  
     if ($env{'form.finishexport'}) {  sub exportcourse {
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      my $r=shift;
                                             ['archive','discussion']);      my $type = &Apache::loncommon::course_type();
       my %discussiontime = &Apache::lonnet::dump('discussiontimes',
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');                                                 $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');      my $numdisc = keys(%discussiontime);
         if (@exportitems == 0 && @discussions == 0) {      my $navmap = Apache::lonnavmaps::navmap->new();
             $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';      if (!defined($navmap)) {
         } else {          $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').
             my $now = time;                    '<h2>IMS Export Failed</h2>'.
             my %symbs;                    '<div class="LC_error">'.
             my $manifestok = 0;                    &mt('Unable to retrieve information about course contents').
             my $imsresources;                    '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');
             my $tempexport;          &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
             my $copyresult;          return;
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);      }
             if ($manifestok) {      my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);      my $curRes;
                 close($ims_manifest);      my $outcome;
   
 #Create zip file in prtspool      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                 my $imszipfile = '/prtspool/'.                                              ['finishexport']);
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.      if ($env{'form.finishexport'}) {
                    time.'_'.rand(1000000000).'.zip';          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                 my $cwd = &Cwd::getcwd();                                              ['archive','discussion']);
                 my $imszip = '/home/httpd/'.$imszipfile;  
                 chdir $tempexport;          my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");          my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');
                 close(OUTPUT);          if (@exportitems == 0 && @discussions == 0) {
                 chdir $cwd;              $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';
                 $outcome .= 'Download the zip file from <a href="'.$imszipfile.'">IMS course archive</a><br />';          } else {
                 if ($copyresult) {              my $now = time;
                     $outcome .= 'The following errors occurred during export - '.$copyresult;              my %symbs;
                 }              my $manifestok = 0;
             } else {              my $imsresources;
                 $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 />';              my $tempexport;
             }              my $copyresult;
         }              my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);
  my $html=&Apache::lonxml::xmlbegin();              if ($manifestok) {
         $r->print($html.'<head><title>Export Course</title></head>'.                  &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);
             &Apache::loncommon::bodytag('Export course to IMS content package'));                  close($ims_manifest);
         $r->print($outcome);  
         $r->print('</body></html>');  #Create zip file in prtspool
     } else {                  my $imszipfile = '/prtspool/'.
         my $display;                  $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
         $display = '<form name="exportdoc" method="post">'."\n";                     time.'_'.rand(1000000000).'.zip';
         $display .= 'Choose which items you wish to export from your course.<br /><br />';                  my $cwd = &Cwd::getcwd();
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                  my $imszip = '/home/httpd/'.$imszipfile;
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.                  chdir $tempexport;
                     '<input type="button" value="check all" '.                  open(OUTPUT, "zip -r $imszip *  2> /dev/null |");
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.                  close(OUTPUT);
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.                  chdir $cwd;
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.                  $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);
                     '<td>&nbsp;</td><td>&nbsp;</td>'.                  if ($copyresult) {
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.                      $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);
                     '</b></legend><input type="button" value="check all"'.                  }
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.              } else {
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.                  $outcome = '<br />'.&mt('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 />';
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.              }
                     '</tr></table>';          }
         my $curRes;          $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));
         my $depth = 0;   $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));
         my $count = 0;          $r->print($outcome);
         my $boards = 0;          $r->print(&Apache::loncommon::end_page());
         my $startcount = 5;      } else {
         my %parent = ();          my $display;
         my %children = ();          $display = '<form name="exportdoc" method="post">'."\n";
         my $lastcontainer = $startcount;          $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');
         my @bgcolors = ('#F6F6F6','#FFFFFF');          $display .= '<table border="0" cellspacing="0" cellpadding="3">'.
         $display .= '<table cellspacing="0"><tr>'.                      '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";                      '<input type="button" value="check all" '.
         if ($numdisc > 0) {                      'onclick="javascript:checkAll(document.exportdoc.archive)" />'.
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";                      '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
         }                      ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.
         $display.='&nbsp;</td></tr>';                      '<td>&nbsp;</td><td>&nbsp;</td>'.
         while ($curRes = $it->next()) {                      '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.
             if (ref($curRes)) {                      '</b></legend><input type="button" value="check all"'.
                 $count ++;                      ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.
             }                      '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
             if ($curRes == $it->BEGIN_MAP()) {                      ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.
                 $depth++;                      '</tr></table>';
                 $parent{$depth} = $lastcontainer;          my $curRes;
             }          my $depth = 0;
             if ($curRes == $it->END_MAP()) {          my $count = 0;
                 $depth--;          my $boards = 0;
                 $lastcontainer = $parent{$depth};          my $startcount = 5;
             }          my %parent = ();
             if (ref($curRes)) {          my %children = ();
                 my $symb = $curRes->symb();          my $lastcontainer = $startcount;
                 my $ressymb = $symb;          my @bgcolors = ('#F6F6F6','#FFFFFF');
                 if ($ressymb =~ m|adm/(\w+)/(\w+)/(\d+)/bulletinboard$|) {          $display .= '<table cellspacing="0"><tr>'.
                     unless ($ressymb =~ m|adm/wrapper/adm|) {              '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';          if ($numdisc > 0) {
                     }              $display.='<b>Export&nbsp;discussion posts?</b>'."\n";
                 }          }
                 my $color = $count%2;          $display.='&nbsp;</td></tr>';
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".          while ($curRes = $it->next()) {
                     '<input type="checkbox" name="archive" value="'.$count.'" ';              if (ref($curRes)) {
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {                  $count ++;
                     my $checkitem = $count + $boards + $startcount;              }
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';              if ($curRes == $it->BEGIN_MAP()) {
                 }                  $depth++;
                 $display .= ' />'."\n";                  $parent{$depth} = $lastcontainer;
                 for (my $i=0; $i<$depth; $i++) {              }
                     $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";              if ($curRes == $it->END_MAP()) {
                 }                  $depth--;
                 if ($curRes->is_sequence()) {                  $lastcontainer = $parent{$depth};
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";              }
                     $lastcontainer = $count + $startcount + $boards;              if (ref($curRes)) {
                 } elsif ($curRes->is_page()) {                  my $symb = $curRes->symb();
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";                  my $ressymb = $symb;
                     $lastcontainer = $count + $startcount + $boards;                  if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
                 }                      unless ($ressymb =~ m|adm/wrapper/adm|) {
                 my $currelem = $count+$boards+$startcount;                          $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
                 $children{$parent{$depth}} .= $currelem.':';                      }
                 $display .= '&nbsp;'.$curRes->title().'</td>';                  }
                 if ($discussiontime{$ressymb} > 0) {                  my $color = $count%2;
                     $boards ++;                  $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".
                     $currelem = $count+$boards+$startcount;                      '<input type="checkbox" name="archive" value="'.$count.'" ';
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";                  if (($curRes->is_sequence()) || ($curRes->is_page())) {
                 } else {                      my $checkitem = $count + $boards + $startcount;
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";                      $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';
                 }                  }
             }                  $display .= ' />'."\n";
         }                  for (my $i=0; $i<$depth; $i++) {
         my $scripttag = qq|                      $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";
 <script>                  }
                   if ($curRes->is_sequence()) {
 function checkAll(field) {                      $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";
     if (field.length > 0) {                      $lastcontainer = $count + $startcount + $boards;
         for (i = 0; i < field.length; i++) {                  } elsif ($curRes->is_page()) {
             field[i].checked = true ;                      $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";
         }                      $lastcontainer = $count + $startcount + $boards;
     } else {                  }
         field.checked = true                  my $currelem = $count+$boards+$startcount;
     }                  $children{$parent{$depth}} .= $currelem.':';
 }                  $display .= '&nbsp;'.$curRes->title().'</td>';
                                                                                                   if ($discussiontime{$ressymb} > 0) {
 function uncheckAll(field) {                      $boards ++;
     if (field.length > 0) {                      $currelem = $count+$boards+$startcount;
         for (i = 0; i < field.length; i++) {                      $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";
             field[i].checked = false ;                  } else {
         }                      $display .= '<td colspan="2">&nbsp;</td>'."\n";
     } else {                  }
         field.checked = false ;              }
     }          }
 }          my $scripttag = qq|
   <script>
 function propagateCheck(item) {  
     if (document.exportdoc.elements[item].checked == true) {  function checkAll(field) {
         containerCheck(item)      if (field.length > 0) {
     }          for (i = 0; i < field.length; i++) {
 }               field[i].checked = true ;
           }
 function containerCheck(item) {      } else {
     document.exportdoc.elements[item].checked = true          field.checked = true
     var numitems = $count + $boards + $startcount      }
     var parents = new Array(numitems)  }
     for (var i=$startcount; i<numitems; i++) {                                                                                 
         parents[i] = new Array  function uncheckAll(field) {
     }      if (field.length > 0) {
         |;          for (i = 0; i < field.length; i++) {
               field[i].checked = false ;
         foreach my $container (sort { $a <=> $b } keys %children) {          }
             my @contents = split/:/,$children{$container};      } else {
             for (my $i=0; $i<@contents; $i ++) {          field.checked = false ;
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";      }
             }  }
         }  
   function propagateCheck(item) {
         $scripttag .= qq|      if (document.exportdoc.elements[item].checked == true) {
     if (parents[item].length > 0) {          containerCheck(item)
         for (var j=0; j<parents[item].length; j++) {      }
             containerCheck(parents[item][j])  }
         }  
      }     function containerCheck(item) {
 }      document.exportdoc.elements[item].checked = true
       var numitems = $count + $boards + $startcount
 </script>      var parents = new Array(numitems)
         |;      for (var i=$startcount; i<numitems; i++) {
  my $html=&Apache::lonxml::xmlbegin();          parents[i] = new Array
         $r->print($html.'<head><title>Export Course</title>'.$scripttag.'</head>'.      }
             &Apache::loncommon::bodytag('Export course to IMS content package'          |;
 ));  
           foreach my $container (sort { $a <=> $b } (keys(%children))) {
         $r->print($display.'</table>'.              my @contents = split(/:/,$children{$container});
                   '<p><input type="hidden" name="finishexport" value="1">'.              for (my $i=0; $i<@contents; $i ++) {
                   '<input type="submit" name="exportcourse" value="'.                  $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   &mt('Export Course DOCS').'" /></p></form></body></html>');              }
     }          }
 }  
           $scripttag .= qq|
 sub create_ims_store {      if (parents[item].length > 0) {
     my ($now,$manifestok,$outcome,$tempexport) = @_;          for (var j=0; j<parents[item].length; j++) {
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';              containerCheck(parents[item][j])
     my $ims_manifest;          }
     if (!-e $$tempexport) {       }  
         mkdir($$tempexport,0700);  }
     }  
     $$tempexport .= '/'.$now;  </script>
     if (!-e $$tempexport) {          |;
         mkdir($$tempexport,0700);   $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',
     }   $scripttag));
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};   $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));
     if (!-e $$tempexport) {   $r->print($display.'</table>'.
         mkdir($$tempexport,0700);                    '<p><input type="hidden" name="finishexport" value="1">'.
     }                    '<input type="submit" name="exportcourse" value="'.
     if (!-e "$$tempexport/resources") {                    &mt('Export '.$type.' DOCS').'" /></p></form>');
         mkdir("$$tempexport/resources",0700);      }
     }  }
 # open manifest file  
     my $manifest = '/imsmanifest.xml';  sub create_ims_store {
     my $manifestfilename = $$tempexport.$manifest;      my ($now,$manifestok,$outcome,$tempexport) = @_;
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';
         $$manifestok=1;      my $ims_manifest;
         print $ims_manifest      if (!-e $$tempexport) {
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".          mkdir($$tempexport,0700);
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.      }
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.      $$tempexport .= '/'.$now;
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.      if (!-e $$tempexport) {
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.          mkdir($$tempexport,0700);
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.      }
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};
 '  <metadata>      if (!-e $$tempexport) {
     <schema></schema>          mkdir($$tempexport,0700);
     <imsmd:lom>      }
       <imsmd:general>      if (!-e "$$tempexport/resources") {
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>          mkdir("$$tempexport/resources",0700);
         <imsmd:title>      }
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>  # open manifest file
         </imsmd:title>      my $manifest = '/imsmanifest.xml';
       </imsmd:general>      my $manifestfilename = $$tempexport.$manifest;
     </imsmd:lom>      if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {
   </metadata>'."\n".          $$manifestok=1;
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".          print $ims_manifest
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.  '<?xml version="1.0" encoding="UTF-8"?>'."\n".
 ' structure="hierarchical">'."\n".  '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'  ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.
     } else {  ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'  ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.
 ;  '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.
     }  '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".
     return $ims_manifest;  '  <metadata>
 }      <schema></schema>
       <imsmd:lom>
 sub build_package {        <imsmd:general>
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;          <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>
 # first iterator to look for dependencies          <imsmd:title>
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);            <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>
     my $curRes;          </imsmd:title>
     my $count = 0;        </imsmd:general>
     my $depth = 0;      </imsmd:lom>
     my $lastcontainer = 0;    </metadata>'."\n".
     my %parent = ();  '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".
     my @dependencies = ();  '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};  ' structure="hierarchical">'."\n".
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};  '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'
     while ($curRes = $it->next()) {      } else {
         if (ref($curRes)) {          $$outcome .= 'An error occurred opening the IMS manifest file.<br />'
             $count ++;  ;
         }      }
         if ($curRes == $it->BEGIN_MAP()) {      return $ims_manifest;
             $depth++;  }
             $parent{$depth} = $lastcontainer;  
         }  sub build_package {
         if ($curRes == $it->END_MAP()) {      my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;
             $depth--;  # first iterator to look for dependencies
             $lastcontainer = $parent{$depth};      my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
         }      my $curRes;
         if (ref($curRes)) {      my $count = 0;
             if ($curRes->is_sequence() || $curRes->is_page()) {      my $depth = 0;
                 $lastcontainer = $count;      my $lastcontainer = 0;
             }      my %parent = ();
             if (grep/^$count$/,@$exportitems) {      my @dependencies = ();
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);      my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
             }      my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
         }      while ($curRes = $it->next()) {
     }          if (ref($curRes)) {
 # second iterator to build manifest and store resources              $count ++;
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);          }
     $depth = 0;          if ($curRes == $it->BEGIN_MAP()) {
     my $prevdepth;              $depth++;
     $count = 0;              $parent{$depth} = $lastcontainer;
     my $imsresources;          }
     my $pkgdepth;          if ($curRes == $it->END_MAP()) {
     while ($curRes = $it->next()) {              $depth--;
         if ($curRes == $it->BEGIN_MAP()) {              $lastcontainer = $parent{$depth};
             $prevdepth = $depth;          }
             $depth++;          if (ref($curRes)) {
         }              if ($curRes->is_sequence() || $curRes->is_page()) {
         if ($curRes == $it->END_MAP()) {                  $lastcontainer = $count;
             $prevdepth = $depth;              }
             $depth--;              if (grep(/^$count$/,@$exportitems)) {
         }                  &get_dependencies($exportitems,\%parent,$depth,\@dependencies);
               }
         if (ref($curRes)) {          }
             $count ++;      }
             if ((grep/^$count$/,@$exportitems) || (grep/^$count$/,@dependencies)) {  # second iterator to build manifest and store resources
                 my $symb = $curRes->symb();      $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
                 my $isvisible = 'true';      $depth = 0;
                 my $resourceref;      my $prevdepth;
                 if ($curRes->randomout()) {      $count = 0;
                     $isvisible = 'false';      my $imsresources;
                 }      my $pkgdepth;
                 unless ($curRes->is_sequence()) {      while ($curRes = $it->next()) {
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';          if ($curRes == $it->BEGIN_MAP()) {
                 }              $prevdepth = $depth;
                 my $step = $prevdepth - $depth;              $depth++;
                 if (($step >= 0) && ($count > 1)) {          }
                     while ($step >= 0) {          if ($curRes == $it->END_MAP()) {
                         print $ims_manifest "\n".'  </item>'."\n";              $prevdepth = $depth;
                         $step --;              $depth--;
                     }          }
                 }  
                 $prevdepth = $depth;          if (ref($curRes)) {
               $count ++;
                 my $itementry =              if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.                  my $symb = $curRes->symb();
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.                  my $isvisible = 'true';
               '<title>'.$curRes->title().'</title>';                  my $resourceref;
                 print $ims_manifest "\n".$itementry;                  if ($curRes->randomout()) {
                       $isvisible = 'false';
                 unless ($curRes->is_sequence()) {                  }
                     my $content_file;                  unless ($curRes->is_sequence()) {
                     my @hrefs = ();                      $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);                  }
                     if ($content_file) {                  my $step = $prevdepth - $depth;
                         $imsresources .= "\n".                  if (($step >= 0) && ($count > 1)) {
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.                      while ($step >= 0) {
                      '" type="webcontent" href="'.$content_file.'">'."\n".                          print $ims_manifest "\n".'  </item>'."\n";
                      '       <file href="'.$content_file.'" />'."\n";                          $step --;
                         foreach (@hrefs) {                      }
                             $imsresources .=                  }
                      '        <file href="'.$_.'" />'."\n";                  $prevdepth = $depth;
                         }  
                         if (grep/^$count$/,@$discussions) {                  my $itementry =
                             my $ressymb = $symb;                '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.
                             my $mode;                '" isvisible="'.$isvisible.'" '.$resourceref.'>'.
                             if ($ressymb =~ m|adm/(\w+)/(\w+)/(\d+)/bulletinboard$|) {                '<title>'.$curRes->title().'</title>';
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {                  print $ims_manifest "\n".$itementry;
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';  
                                 }                  unless ($curRes->is_sequence()) {
                                 $mode = 'board';                      my $content_file;
                             }                      my @hrefs = ();
                             my %extras = (                      &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);
                                           caller => 'imsexport',                      if ($content_file) {
                                           tempexport => $tempexport.'/resources',                          $imsresources .= "\n".
                                           count => $count                       '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.
                                          );                       '" type="webcontent" href="'.$content_file.'">'."\n".
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);                       '       <file href="'.$content_file.'" />'."\n";
                         }                          foreach my $item (@hrefs) {
                         $imsresources .= '    </resource>'."\n";                              $imsresources .=
                     }                       '        <file href="'.$item.'" />'."\n";
                 }                          }
                 $pkgdepth = $depth;                          if (grep(/^$count$/,@$discussions)) {
             }                              my $ressymb = $symb;
         }                              my $mode;
     }                              if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
     while ($pkgdepth > 0) {                                  unless ($ressymb =~ m|adm/wrapper/adm|) {
         print $ims_manifest "    </item>\n";                                      $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
         $pkgdepth --;                                  }
     }                                  $mode = 'board';
     my $resource_text = qq|                              }
     </organization>                              my %extras = (
   </organizations>                                            caller => 'imsexport',
   <resources>                                            tempexport => $tempexport.'/resources',
     $imsresources                                            count => $count
   </resources>                                           );
 </manifest>                              my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);
     |;                          }
     print $ims_manifest $resource_text;                          $imsresources .= '    </resource>'."\n";
 }                      }
                   }
 sub get_dependencies {                  $pkgdepth = $depth;
     my ($exportitems,$parent,$depth,$dependencies) = @_;              }
     if ($depth > 1) {          }
         if ((!grep/^$$parent{$depth}$/,@$exportitems) && (!grep/^$$parent{$depth}$/,@$dependencies)) {      }
             push @$dependencies, $$parent{$depth};      while ($pkgdepth > 0) {
             if ($depth > 2) {          print $ims_manifest "    </item>\n";
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);          $pkgdepth --;
             }      }
         }      my $resource_text = qq|
     }      </organization>
 }    </organizations>
     <resources>
 sub process_content {      $imsresources
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;    </resources>
     my $content_type;  </manifest>
     my $message;      |;
     my @uploads = ();      print $ims_manifest $resource_text;
     if ($curRes->is_sequence()) {  }
         $content_type = 'sequence';  
     } elsif ($curRes->is_page()) {  sub get_dependencies {
         $content_type = 'page'; # need to handle individual items in pages.      my ($exportitems,$parent,$depth,$dependencies) = @_;
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {      if ($depth > 1) {
         $content_type = 'syllabus';          if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {
         my $contents = &Apache::imsexport::templatedpage($content_type);              push(@{$dependencies},$$parent{$depth});
         if ($contents) {              if ($depth > 2) {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);                  &get_dependencies($exportitems,$parent,$depth-1,$dependencies);
         }              }
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {          }
         $content_type = 'external';      }
         my $title = $curRes->title;  }
         my $contents =  &Apache::imsexport::external($symb,$title);  
         if ($contents) {  sub process_content {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;
         }      my $content_type;
     } elsif ($symb =~ m-adm/navmaps$-) {      my $message;
         $content_type =  'navmap';      my @uploads = ();
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {      if ($curRes->is_sequence()) {
         $content_type = 'simplepage';          $content_type = 'sequence';
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);      } elsif ($curRes->is_page()) {
         if ($contents) {          $content_type = 'page'; # need to handle individual items in pages.
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {
         }          $content_type = 'syllabus';
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {          my $contents = &Apache::imsexport::templatedpage($content_type);
         $content_type = 'simpleproblem';          if ($contents) {
         my $contents =  &Apache::imsexport::simpleproblem($symb);              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         if ($contents) {          }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      } elsif ($symb =~ m-\.sequence___\d+___ext-) {
         }          $content_type = 'external';
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {          my $title = $curRes->title;
         $content_type = 'examupload';          my $contents =  &Apache::imsexport::external($symb,$title);
     } elsif ($symb =~ m-adm/(\w+)/(\w+)/(\d+)/bulletinboard$-) {          if ($contents) {
         $content_type = 'bulletinboard';              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);          }
         if ($contents) {      } elsif ($symb =~ m-adm/navmaps$-) {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          $content_type =  'navmap';
         }      } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {          $content_type = 'simplepage';
         $content_type = 'aboutme';          my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);          if ($contents) {
         if ($contents) {              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          }
         }      } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {          $content_type = 'simpleproblem';
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');          my $contents =  &Apache::imsexport::simpleproblem($symb);
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {          if ($contents) {
         my $canedit = 0;              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {          }
             $canedit= 1;      } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {
         }          $content_type = 'examupload';
 # only include problem code where current user is author      } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {
         if ($canedit) {          $content_type = 'bulletinboard';
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');          my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);
         } else {          if ($contents) {
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         }          }
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {      } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');          $content_type = 'aboutme';
     }          my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);
     if (@uploads > 0) {          if ($contents) {
         foreach my $item (@uploads) {              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
             my $uploadmsg = '';          }
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');      } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {
             if ($uploadmsg) {          $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
                 $$copyresult .= $uploadmsg."\n";      } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {
             }          my $canedit = 0;
         }          if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {
     }              $canedit= 1;
     if ($message) {          }
         $$copyresult .= $message."\n";  # only include problem code where current user is author
     }          if ($canedit) {
 }              $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');
           } else {
 sub replicate_content {              $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;          }
     my ($map,$ind,$url);      } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {
     if ($caller eq 'templateupload') {          $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
         $url = $symb;      }
         $url =~ s#//#/#g;      if (@uploads > 0) {
     } else {           foreach my $item (@uploads) {
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);              my $uploadmsg = '';
     }              &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');
     my $content;              if ($uploadmsg) {
     my $filename;                  $$copyresult .= $uploadmsg."\n";
     my $repstatus;              }
     my $content_name;          }
     if ($url =~ m-/([^/]+)$-) {      }
         $filename = $1;      if ($message) {
         if (!-e $tempexport.'/resources') {          $$copyresult .= $message."\n";
             mkdir($tempexport.'/resources',0700);      }
         }  }
         if (!-e $tempexport.'/resources/'.$count) {  
             mkdir($tempexport.'/resources/'.$count,0700);  sub replicate_content {
         }      my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;      my ($map,$ind,$url);
         my $copiedfile;      if ($caller eq 'templateupload') {
         if ($copiedfile = Apache::File->new('>'.$destination)) {          $url = $symb;
             my $content;          $url =~ s#//#/#g;
             if ($caller eq 'resource') {      } else {
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';          ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);      }
                 $content = &Apache::lonnet::getfile($filepath);      my $content;
                 if ($content eq -1) {      my $filename;
                     $$message = 'Could not copy file '.$filename;      my $repstatus;
                 } else {      my $content_name;
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');      if ($url =~ m-/([^/]+)$-) {
                     $repstatus = 'ok';          $filename = $1;
                 }          if (!-e $tempexport.'/resources') {
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {              mkdir($tempexport.'/resources',0700);
                 my $rtncode;          }
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);          if (!-e $tempexport.'/resources/'.$count) {
                 if ($repstatus eq 'ok') {              mkdir($tempexport.'/resources/'.$count,0700);
                     if ($url =~ /\.html?$/i) {          }
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');          my $destination = $tempexport.'/resources/'.$count.'/'.$filename;
                     }          my $copiedfile;
                 } else {          if ($copiedfile = Apache::File->new('>'.$destination)) {
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";              my $content;
                 }              if ($caller eq 'resource') {
             } elsif ($caller eq 'noedit') {                  my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.                   my $filepath = &Apache::lonnet::filelocation($respath,$url);
                 $repstatus = 'ok';                  $content = &Apache::lonnet::getfile($filepath);
                 $content = 'Not the owner of this resource';                   if ($content eq -1) {
             }                      $$message = 'Could not copy file '.$filename;
             if ($repstatus eq 'ok') {                  } else {
                 print $copiedfile $content;                      &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');
             }                      $repstatus = 'ok';
             close($copiedfile);                  }
         } else {              } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {
             $$message = 'Could not open destination file for '.$filename."<br />\n";                  my $rtncode;
         }                  $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);
     } else {                  if ($repstatus eq 'ok') {
         $$message = 'Could not determine name of file for '.$symb."<br />\n";                      if ($url =~ /\.html?$/i) {
     }                          &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');
     if ($repstatus eq 'ok') {                      }
         $content_name = 'resources/'.$count.'/'.$filename;                  } else {
     }                      $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";
     return $content_name;                  }
 }              } elsif ($caller eq 'noedit') {
   # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.
 sub extract_media {                  $repstatus = 'ok';
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;                  $content = 'Not the owner of this resource';
     my ($dirpath,$container);              }
     my %allfiles = ();              if ($repstatus eq 'ok') {
     my %codebase = ();                  print $copiedfile $content;
     if ($url =~ m-(.*/)([^/]+)$-) {              }
         $dirpath = $1;              close($copiedfile);
         $container = $2;          } else {
     } else {              $$message = 'Could not open destination file for '.$filename."<br />\n";
         $dirpath = $url;          }
         $container = '';      } else {
     }          $$message = 'Could not determine name of file for '.$symb."<br />\n";
     &Apache::lonnet::extract_embedded_items(undef,undef,\%allfiles,\%codebase,$content);      }
     foreach my $embed_file (keys(%allfiles)) {      if ($repstatus eq 'ok') {
         my $filename;          $content_name = 'resources/'.$count.'/'.$filename;
         if ($embed_file =~ m#([^/]+)$#) {      }
             $filename = $1;      return $content_name;
         } else {  }
             $filename = $embed_file;  
         }  sub extract_media {
         my $newname = 'res/'.$filename;      my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;
         my ($rtncode,$embed_content,$repstatus);      my ($dirpath,$container);
         my $embed_url;      my %allfiles = ();
         if ($embed_file =~ m-^/-) {      my %codebase = ();
             $embed_url = $embed_file;           # points to absolute path      if ($url =~ m-(.*/)([^/]+)$-) {
         } else {          $dirpath = $1;
             if ($embed_file =~ m-https?://-) {          $container = $2;
                 next;                           # points to url      } else {
             } else {          $dirpath = $url;
                 $embed_url = $dirpath.$embed_file;  # points to relative path          $container = '';
             }      }
         }      &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);
         if ($caller eq 'resource') {      foreach my $embed_file (keys(%allfiles)) {
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';            my $filename;
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);           if ($embed_file =~ m#([^/]+)$#) {
             $embed_content = &Apache::lonnet::getfile($embed_path);              $filename = $1;
             unless ($embed_content eq -1) {          } else {
                 $repstatus = 'ok';              $filename = $embed_file;
             }          }
         } elsif ($caller eq 'uploaded') {          my $newname = 'res/'.$filename;
                       my ($rtncode,$embed_content,$repstatus);
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);          my $embed_url;
         }          if ($embed_file =~ m-^/-) {
         if ($repstatus eq 'ok') {              $embed_url = $embed_file;           # points to absolute path
             my $destination = $tempexport.'/resources/'.$count.'/res';          } else {
             if (!-e "$destination") {              if ($embed_file =~ m-https?://-) {
                 mkdir($destination,0755);                  next;                           # points to url
             }              } else {
             $destination .= '/'.$filename;                  $embed_url = $dirpath.$embed_file;  # points to relative path
             my $copiedfile;              }
             if ($copiedfile = Apache::File->new('>'.$destination)) {          }
                 print $copiedfile $embed_content;          if ($caller eq 'resource') {
                 push @{$href}, 'resources/'.$count.'/res/'.$filename;              my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';  
                 my $attrib_regexp = '';              my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);
                 if (@{$allfiles{$embed_file}} > 1) {              $embed_content = &Apache::lonnet::getfile($embed_path);
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});              unless ($embed_content eq -1) {
                 } else {                  $repstatus = 'ok';
                     $attrib_regexp = $allfiles{$embed_file}[0];              }
                 }          } elsif ($caller eq 'uploaded') {
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;             
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {              $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);
                     $$content =~ s#\Q$embed_file\E#$newname#gi;          }
                 }          if ($repstatus eq 'ok') {
             }              my $destination = $tempexport.'/resources/'.$count.'/res';
         } else {              if (!-e "$destination") {
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";                  mkdir($destination,0755);
         }              }
     }              $destination .= '/'.$filename;
     return;              my $copiedfile;
 }              if ($copiedfile = Apache::File->new('>'.$destination)) {
                   print $copiedfile $embed_content;
 sub store_template {                  push(@{$href},'resources/'.$count.'/res/'.$filename);
     my ($contents,$tempexport,$count,$content_type) = @_;                  my $attrib_regexp = '';
     if ($contents) {                  if (@{$allfiles{$embed_file}} > 1) {
         if ($tempexport) {                      $attrib_regexp = join('|',@{$allfiles{$embed_file}});
             if (!-e $tempexport.'/resources') {                  } else {
                 mkdir($tempexport.'/resources',0700);                      $attrib_regexp = $allfiles{$embed_file}[0];
             }                  }
             if (!-e $tempexport.'/resources/'.$count) {                  $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;
                 mkdir($tempexport.'/resources/'.$count,0700);                  if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {
             }                      $$content =~ s#\Q$embed_file\E#$newname#gi;
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';                  }
             my $storetemplate;              }
             if ($storetemplate = Apache::File->new('>'.$destination)) {          } else {
                 print $storetemplate $contents;              $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";
                 close($storetemplate);          }
             }      }
             if ($content_type eq 'external') {      return;
                 return 'resources/'.$count.'/'.$content_type.'.html';  }
             } else {  
                 return 'resources/'.$count.'/'.$content_type.'.xml';  sub store_template {
             }      my ($contents,$tempexport,$count,$content_type) = @_;
         }      if ($contents) {
     }          if ($tempexport) {
 }              if (!-e $tempexport.'/resources') {
                   mkdir($tempexport.'/resources',0700);
 # Imports the given (name, url) resources into the course              }
 # coursenum, coursedom, and folder must precede the list              if (!-e $tempexport.'/resources/'.$count) {
 sub group_import {                  mkdir($tempexport.'/resources/'.$count,0700);
     my $coursenum = shift;              }
     my $coursedom = shift;              my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';
     my $folder = shift;              my $storetemplate;
     my $container = shift;              if ($storetemplate = Apache::File->new('>'.$destination)) {
     my $caller = shift;                  print $storetemplate $contents;
     while (@_) {                  close($storetemplate);
  my $name = shift;              }
  my $url = shift;              if ($content_type eq 'external') {
         if (($url =~ m#^/uploaded/$coursedom/$coursenum/(default_\d+\.)(page|sequence)$#) && ($caller eq 'londocs')) {                  return 'resources/'.$count.'/'.$content_type.'.html';
             my $errtext = '';              } else {
             my $fatal = 0;                  return 'resources/'.$count.'/'.$content_type.'.xml';
             my $newmapstr = '<map>'."\n".              }
                             '<resource id="1" src="" type="start"></resource>'."\n".          }
                             '<link from="1" to="2" index="1"></link>'."\n".      }
                             '<resource id="2" src="" type="finish"></resource>'."\n".  }
                             '</map>';  
             $env{'form.output'}=$newmapstr;  
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,  sub group_import {
                                                 'output',$1.$2);      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
             if ($result != m|^/uploaded/|) {  
                 $errtext.='Map not saved: A network error occured when trying to save the new map. ';      while (@files) {
                 $fatal = 2;   my ($name, $url, $residx) = @{ shift(@files) };
             }          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
             if ($fatal) {       && ($caller eq 'londocs')
                 return ($errtext,$fatal);       && (!&Apache::lonnet::stat_file($url))) {
             }      
         }              my $errtext = '';
  if ($url) {              my $fatal = 0;
     my $idx = &Apache::lonratedt::getresidx($url);              my $newmapstr = '<map>'."\n".
     $Apache::lonratedt::order[$#Apache::lonratedt::order+1]=$idx;                              '<resource id="1" src="" type="start"></resource>'."\n".
     my $ext = 'false';                              '<link from="1" to="2" index="1"></link>'."\n".
     if ($url=~/^http:\/\//) { $ext = 'true'; }                              '<resource id="2" src="" type="finish"></resource>'."\n".
     $url =~ s/:/\&colon;/g;                              '</map>';
     $name =~ s/:/\&colon;/g;              $env{'form.output'}=$newmapstr;
     $Apache::lonratedt::resources[$idx] =               my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
  join ':', ($name, $url, $ext, 'normal', 'res');                                                  'output',$1.$2);
  }              if ($result != m|^/uploaded/|) {
     }                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);                  $fatal = 2;
 }              }
               if ($fatal) {
 sub breadcrumbs {                  return ($errtext,$fatal);
     my ($where)=@_;              }
     &Apache::lonhtmlcommon::clear_breadcrumbs();          }
     my (@folders);   if ($url) {
     if ($env{'form.pagepath'}) {      if (!$residx
         @folders = split('&',$env{'form.pagepath'});   || defined($LONCAPA::map::zombies[$residx])) {
     } else {   $residx = &LONCAPA::map::getresidx($url,$residx);
         @folders=split('&',$env{'form.folderpath'});   push(@LONCAPA::map::order, $residx);
     }      }
     my $folderpath;      my $ext = 'false';
     my $cpinfo='';      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
     if ($env{'form.markedcopy_url'}) {      $url  = &LONCAPA::map::qtunescape($url);
  &Apache::lonnet::logthis('Found '.$env{'form.markedcopy_url'});      $name = &LONCAPA::map::qtunescape($name);
        $cpinfo='&markedcopy_url='.      $LONCAPA::map::resources[$residx] =
                &Apache::lonnet::escape($env{'form.markedcopy_url'}).   join(':', ($name, $url, $ext, 'normal', 'res'));
                '&markedcopy_title='.   }
                &Apache::lonnet::escape($env{'form.markedcopy_title'});      }
     }      return &storemap($coursenum, $coursedom, $folder.'.'.$container);
     while (@folders) {  }
  my $folder=shift(@folders);  
  my $foldername=shift(@folders);  sub breadcrumbs {
  if ($folderpath) {$folderpath.='&';}      my ($where,$allowed,$type)=@_;
  $folderpath.=$folder.'&'.$foldername;      &Apache::lonhtmlcommon::clear_breadcrumbs();
  my $url='/adm/coursedocs?folderpath='.      my (@folders);
     &Apache::lonnet::escape($folderpath);      if ($env{'form.pagepath'}) {
     &Apache::lonhtmlcommon::add_breadcrumb(          @folders = split('&',$env{'form.pagepath'});
       {'href'=>$url.$cpinfo,      } else {
        'title'=>&Apache::lonnet::unescape($foldername),          @folders=split('&',$env{'form.folderpath'});
        'text'=>'<font size="+1">'.      }
    &Apache::lonnet::unescape($foldername).'</font>'      my $folderpath;
        });      my $cpinfo='';
              my $plain='';
         my $randompick=-1;
     }      my $isencrypted=0;
     return &Apache::lonhtmlcommon::breadcrumbs(undef,undef,undef,undef,undef,      my $ishidden=0;
        0,'nohelp');      my $is_random_order=0;
 }      while (@folders) {
    my $folder=shift(@folders);
 sub editor {      my $foldername=shift(@folders);
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output)=@_;   if ($folderpath) {$folderpath.='&';}
     my $errtext='';   $folderpath.=$folder.'&'.$foldername;
     my $fatal=0;   my $url='/adm/coursedocs?folderpath='.
     my $container='sequence';      &escape($folderpath);
     if ($env{'form.pagepath'}) {      my $name=&unescape($foldername);
         $container='page';  # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
     }       $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
     ($errtext,$fatal)=      if ($1 ne '') {
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                 $randompick=$1;
     if ($#Apache::lonratedt::order<1) {              } else {
  my $idx=&Apache::lonratedt::getresidx();                 $randompick=-1;
  if ($idx<=0) { $idx=1; }              }
         $Apache::lonratedt::order[0]=$idx;              if ($2) { $ishidden=1; }
         $Apache::lonratedt::resources[$idx]='';              if ($3) { $isencrypted=1; }
     }      if ($4 ne '') { $is_random_order = 1; }
     if (defined($env{'form.markcopy'})) {              if ($folder eq 'supplemental') {
 # Mark for copying                  if ($allowed) {
  my ($title,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$env{'form.markcopy'}]]);                      $name = &mt('Supplemental '.$type.' Documents');
  $env{'form.markedcopy_title'}=$title;                  } else {
  $env{'form.markedcopy_url'}=$url;                      $name = &mt($type.' Documents');
     }                  }
     $r->print(&breadcrumbs($folder));              }
     if ($fatal) {      &Apache::lonhtmlcommon::add_breadcrumb(
    $r->print('<p><font color="red">'.$errtext.'</font></p>');        {'href'=>$url.$cpinfo,
     } else {         'title'=>$name,
 # ------------------------------------------------------------ Process commands         'text'=>'<font size="+1">'.
      $name.'</font>',
 # ---------------- if they are for this folder and user allowed to make changes         'no_mt'=>1,
  if (($allowed) && ($env{'form.folder'} eq $folder)) {         });
 # set parameters and change order   $plain.=$name.' &gt; ';
     if (defined($env{'form.setparms'})) {      }
  my $idx=$env{'form.setparms'};      $plain=~s/\&gt\;\s*$//;
 # set parameters      return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
  if ($env{'form.randpick_'.$idx}) {         'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);
     &Apache::lonratedt::storeparameter($idx,'parameter_randompick',$env{'form.randpick_'.$idx},'int_pos');  }
  } else {  
     &Apache::lonratedt::delparameter($idx,'parameter_randompick');  sub log_docs {
  }      return &Apache::lonnet::instructor_log('docslog',@_);
  if ($env{'form.hidprs_'.$idx}) {  }
     &Apache::lonratedt::storeparameter($idx,'parameter_hiddenresource','yes','string_yesno');  
  } else {  {
     &Apache::lonratedt::delparameter($idx,'parameter_hiddenresource');      my @oldresources=();
  }      my @oldorder=();
  if ($env{'form.encprs_'.$idx}) {      my $parmidx;
     &Apache::lonratedt::storeparameter($idx,'parameter_encrypturl','yes','string_yesno');      my %parmaction=();
  } else {      my %parmvalue=();
     &Apache::lonratedt::delparameter($idx,'parameter_encrypturl');      my $changedflag;
  }  
       sub snapshotbefore {
  if ($env{'form.newpos'}) {          @oldresources=@LONCAPA::map::resources;
 # change order          @oldorder=@LONCAPA::map::order;
           $parmidx=undef;
     my $newpos=$env{'form.newpos'}-1;          %parmaction=();
     my $currentpos=$env{'form.currentpos'}-1;          %parmvalue=();
     my $i;          $changedflag=0;
     my @neworder=();      }
     if ($newpos>$currentpos) {  
 # moving stuff up      sub remember_parms {
  for ($i=0;$i<$currentpos;$i++) {          my ($idx,$parameter,$action,$value)=@_;
     $neworder[$i]=$Apache::lonratedt::order[$i];          $parmidx=$idx;
  }          $parmaction{$parameter}=$action;
  for ($i=$currentpos;$i<$newpos;$i++) {          $parmvalue{$parameter}=$value;
     $neworder[$i]=$Apache::lonratedt::order[$i+1];          $changedflag=1;
  }      }
                         $neworder[$newpos]=$Apache::lonratedt::order[$currentpos];  
  for ($i=$newpos+1;$i<=$#Apache::lonratedt::order;$i++) {      sub log_differences {
     $neworder[$i]=$Apache::lonratedt::order[$i];          my ($plain)=@_;
  }          my %storehash=('folder' => $plain,
     } else {                         'currentfolder' => $env{'form.folder'});
 # moving stuff down          if ($parmidx) {
  for ($i=0;$i<$newpos;$i++) {             $storehash{'parameter_res'}=$oldresources[$parmidx];
     $neworder[$i]=$Apache::lonratedt::order[$i];             foreach my $parm (keys(%parmaction)) {
  }                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
  $neworder[$newpos]=$Apache::lonratedt::order[$currentpos];                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
  for ($i=$newpos+1;$i<$currentpos+1;$i++) {             }
     $neworder[$i]=$Apache::lonratedt::order[$i-1];          }
  }          my $maxidx=$#oldresources;
  for ($i=$currentpos+1;$i<=$#Apache::lonratedt::order;$i++) {          if ($#LONCAPA::map::resources>$#oldresources) {
     $neworder[$i]=$Apache::lonratedt::order[$i];             $maxidx=$#LONCAPA::map::resources;
  }          }
     }          for (my $idx=0; $idx<=$maxidx; $idx++) {
     @Apache::lonratedt::order=@neworder;             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
  }                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
 # store the changed version                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
                 $changedflag=1;
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);             }
  if ($fatal) {             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
     $r->print('<p><font color="red">'.$errtext.'</font></p>');                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
     return;                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  }                $changedflag=1;
              }
     }          }
     if ($env{'form.pastemarked'}) {   $storehash{'maxidx'}=$maxidx;
 # paste resource to end of list          if ($changedflag) { &log_docs(\%storehash); }
                 my $url=$env{'form.markedcopy_url'};      }
  my $title=$env{'form.markedcopy_title'};  }
 # Maps need to be copied first  
  if (($url=~/\.(page|sequence)$/) || ($url=~/^\/uploaded\//)) {  
     $title=&mt('Copy of').' '.$title;  
                     my $newid=$$.time;  
     $url=~/^(.+)\.(\w+)$/;  
     my $newurl=$1.$newid.'.'.$2;  sub docs_change_log {
     my $storefn=$newurl;      my ($r)=@_;
                     $storefn=~s/^\/\w+\/\w+\/\w+\///;      my $folder=$env{'form.folder'};
     &Apache::loncreatecourse::writefile      $r->print(&Apache::loncommon::start_page('Course Document Change Log'));
  ($env{'request.course.id'},$storefn,      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));
  &Apache::lonnet::getfile($url));      my %docslog=&Apache::lonnet::dump('nohist_docslog',
     $url=$newurl;                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
  }                                        $env{'course.'.$env{'request.course.id'}.'.num'});
  $title=~s/\</\&lt\;/g;  
  $title=~s/\>/\&gt\;/g;      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
  $title=~s/\:/\&colon;/g;  
  my $ext='false';      $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.
  if ($url=~/^http\:\/\//) { $ext='true'; }                '<input type="hidden" name="docslog" value="1" />');
  $url=~s/\:/\&colon;/g;  
 # Now insert the URL at the bottom      my %saveable_parameters = ('show' => 'scalar',);
                 my $newidx=&Apache::lonratedt::getresidx($url);      &Apache::loncommon::store_course_settings('docs_log',
  $Apache::lonratedt::resources[$newidx]=                                                \%saveable_parameters);
     $title.':'.$url.':'.$ext.':normal:res';      &Apache::loncommon::restore_course_settings('docs_log',
  $Apache::lonratedt::order[1+$#Apache::lonratedt::order]=$newidx;                                                  \%saveable_parameters);
 # Store the result      if (!$env{'form.show'}) { $env{'form.show'}=10; }
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      my %lt=('hiddenresource' => 'Resources hidden',
  if ($fatal) {      'encrypturl'     => 'URL hidden',
     $r->print('<p><font color="red">'.$errtext.'</font></p>');      'randompick'     => 'Randomly pick',
     return;      'randomorder'    => 'Randomly ordered',
  }      'set'            => 'set to',
       'del'            => 'deleted');
     }      $r->print(&Apache::loncommon::display_filter().
             $r->print($upload_output);                '<input type="hidden" name="folder" value="'.$folder.'" />'.
     if ($env{'form.cmd'}) {                '<input type="submit" value="'.&mt('Display').'" /></form>');
                 my ($cmd,$idx)=split(/\_/,$env{'form.cmd'});      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
                 if ($cmd eq 'del') {                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
     my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);                &mt('After').'</th>'.
     if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&                &Apache::loncommon::end_data_table_header_row());
  ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library)$/)) {      my $shown=0;
  &Apache::lonnet::removeuploadedurl($url);      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     } else {   if ($env{'form.displayfilter'} eq 'currentfolder') {
  &Apache::lonratedt::makezombie($Apache::lonratedt::order[$idx]);      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
     }   }
     for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {          my @changes=keys(%{$docslog{$id}{'logentry'}});
                         $Apache::lonratedt::order[$i]=          if ($env{'form.displayfilter'} eq 'containing') {
                           $Apache::lonratedt::order[$i+1];      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
                     }   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
                     $#Apache::lonratedt::order--;      foreach my $key (@changes) {
                 } elsif ($cmd eq 'cut') {   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
     my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);      }
     &Apache::lonratedt::makezombie($Apache::lonratedt::order[$idx]);      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }        
     for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {   }
                         $Apache::lonratedt::order[$i]=          my $count = 0;
                           $Apache::lonratedt::order[$i+1];          my $time =
                     }              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
                     $#Apache::lonratedt::order--;          my $plainname =
                 } elsif ($cmd eq 'up') {              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
   if (($idx) && (defined($Apache::lonratedt::order[$idx-1]))) {                                            $docslog{$id}{'exe_udom'});
                     my $i=$Apache::lonratedt::order[$idx-1];          my $about_me_link =
                     $Apache::lonratedt::order[$idx-1]=              &Apache::loncommon::aboutmewrapper($plainname,
  $Apache::lonratedt::order[$idx];                                                 $docslog{$id}{'exe_uname'},
                     $Apache::lonratedt::order[$idx]=$i;                                                 $docslog{$id}{'exe_udom'});
    }          my $send_msg_link='';
                 } elsif ($cmd eq 'down') {          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
    if (defined($Apache::lonratedt::order[$idx+1])) {               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
                     my $i=$Apache::lonratedt::order[$idx+1];              $send_msg_link ='<br />'.
                     $Apache::lonratedt::order[$idx+1]=                  &Apache::loncommon::messagewrapper(&mt('Send message'),
  $Apache::lonratedt::order[$idx];                                                     $docslog{$id}{'exe_uname'},
                     $Apache::lonratedt::order[$idx]=$i;                                                     $docslog{$id}{'exe_udom'});
    }          }
                 } elsif ($cmd eq 'rename') {          $r->print(&Apache::loncommon::start_data_table_row());
                     my $ratstr = $Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]];          $r->print('<td>'.$time.'</td>
                     my ($rtitle,@rrest)=split(/\:/,                         <td>'.$about_me_link.
                        $Apache::lonratedt::resources[                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
        $Apache::lonratedt::order[$idx]]);                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
                     my $comment=                    $send_msg_link.'</td><td>'.
                      &HTML::Entities::decode($env{'form.title'});                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
                     $comment=~s/\</\&lt\;/g;  # Before
                     $comment=~s/\>/\&gt\;/g;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                     $comment=~s/\:/\&colon;/g;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     if ($comment=~/\S/) {      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
  $Apache::lonratedt::resources[      if ($oldname ne $newname) {
        $Apache::lonratedt::order[$idx]]=   $r->print(&LONCAPA::map::qtescape($oldname));
             $comment.':'.join(':',@rrest);      }
     }   }
                 }   $r->print('<ul>');
 # Store the changed version   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
     $folder.'.'.$container);   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
  if ($fatal) {      }
     $r->print('<p><font color="red">'.$errtext.'</font></p>');   }
     return;   $r->print('</ul>');
  }  # After
             }          $r->print('</td><td>');
 # Group import/search  
     if ($env{'form.importdetail'}) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  my @imports;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
  foreach (split(/\&/,$env{'form.importdetail'})) {      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
     if (defined($_)) {      if ($oldname ne '' && $oldname ne $newname) {
  my ($name,$url)=split(/\=/,$_);   $r->print(&LONCAPA::map::qtescape($newname));
  $name=&Apache::lonnet::unescape($name);      }
  $url=&Apache::lonnet::unescape($url);   }        
  push @imports, $name, $url;   $r->print('<ul>');
     }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  }              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
 # Store the changed version   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
  ($errtext,$fatal)=group_import($coursenum, $coursedom, $folder,      }
        $container,'londocs',@imports);   }
  if ($fatal) {   $r->print('</ul>');
     $r->print('<p><font color="red">'.$errtext.'</font></p>');   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
     return;      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
  }      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
             }   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
 # Loading a complete map      $r->print('<li>'.
    if (($env{'form.importmap'}) && ($env{'form.loadmap'})) {        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
        foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
    my ($title,$url,$ext,$type)=split(/\:/,$_);        .'</li>');
                    my $idx=&Apache::lonratedt::getresidx($url);   }
                    $Apache::lonratedt::resources[$idx]=$_;      }
                    $Apache::lonratedt::order      $r->print('</ul>');
        [$#Apache::lonratedt::order+1]=$idx;   }
        }  # End
           $r->print('</td>'.&Apache::loncommon::end_data_table_row());
 # Store the changed version          $shown++;
        ($errtext,$fatal)=&storemap($coursenum,$coursedom,          if (!($env{'form.show'} eq &mt('all')
    $folder.'.'.$container);                || $shown<=$env{'form.show'})) { last; }
        if ($fatal) {      }
    $r->print('<p><font color="red">'.$errtext.'</font></p>');      $r->print(&Apache::loncommon::end_data_table());
    return;  }
        }  
            }  sub update_paste_buffer {
        }      my ($coursenum,$coursedom) = @_;
 # ---------------------------------------------------------------- End commands  
 # ---------------------------------------------------------------- Print screen      return if (!defined($env{'form.markcopy'}));
         my $idx=0;      return if (!defined($env{'form.copyfolder'}));
  my $shown=0;      return if ($env{'form.markcopy'} < 0);
         $r->print('<table>');  
         foreach (@Apache::lonratedt::order) {      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
            my ($name,$url)=split(/\:/,$Apache::lonratedt::resources[$_]);      $env{'form.copyfolder'});
            unless ($name) {  $name=(split(/\//,$url))[-1]; }     
            unless ($name) { $idx++; next; }      return if ($fatal);
            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));  
            $idx++;  # Mark for copying
    $shown++;      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
         }      if (&is_supplemental_title($title)) {
  unless ($shown) {          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
     $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');   ($title) = &parse_supplemental_title($title);
  }      } elsif ($env{'docs.markedcopy_supplemental'}) {
         $r->print("\n</table>\n");          &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');
  if ($env{'form.markedcopy_url'}) {      }
     $r->print(<<ENDPASTE);      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 <p><form name="pasteform" action="/adm/coursedocs" method="post">  
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      'docs.markedcopy_url'   => $url});
 ENDPASTE      delete($env{'form.markcopy'});
             $r->print(  }
    '<input type="submit" name="pastemarked" value="'.&mt('Paste').  
       '" /> '.&Apache::loncommon::filedescription(  sub print_paste_buffer {
  (split(/\./,$env{'form.markedcopy_url'}))[-1]).': '.      my ($r,$container) = @_;
       $env{'form.markedcopy_title'});      return if (!defined($env{'docs.markedcopy_url'}));
             if ($container eq 'page') {  
  $r->print(<<PAGEINFO);      $r->print(<<ENDPASTE);
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />  <form name="pasteform" action="/adm/coursedocs" method="post"><p>
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />  ENDPASTE
 PAGEINFO      $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');
             } else {  
  $r->print(<<FOLDERINFO);      my $type;
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
 FOLDERINFO   $type = &mt('External Resource');
     }   $r->print($type.': '.
     $r->print('</form></p>');    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
  }    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
     }      }  else {
 }   my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
    my $icon = &Apache::loncommon::icon($extension);
 sub process_file_upload {   if ($extension eq 'sequence' &&
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;      $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
 # upload a file, if present      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     my $parseaction;      $icon .= '/folder_closed.gif';
    if ($env{'form.parserflag'}) {   }
         $parseaction = 'parse';   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
     }   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
     my $phase_status;      }
     my $folder=$env{'form.folder'};      if ($container eq 'page') {
     if ($folder eq '') {   $r->print('
         $folder='default';   <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
     }   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {  ');
         my $errtext='';      } else {
         my $fatal=0;   $r->print('
         my $container='sequence';          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
         if ($env{'form.pagepath'}) {  ');
             $container='page';      }
         }      $r->print('</p></form>');
         ($errtext,$fatal)=  }
               &mapread($coursenum,$coursedom,$folder.'.'.$container);  
         if ($#Apache::lonratedt::order<1) {  sub do_paste_from_buffer {
             $Apache::lonratedt::order[0]=1;      my ($coursenum,$coursedom,$folder) = @_;
             $Apache::lonratedt::resources[1]='';  
         }      if (!$env{'form.pastemarked'}) {
         if ($fatal) {          return;
             return 'failed';      }
         }  
         my $destination = 'docs/';  # paste resource to end of list
         if ($folder =~ /^supplemental/) {      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
             $destination = 'supplemental/';      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
         }  # Maps need to be copied first
         if (($folder eq 'default') || ($folder eq 'supplemental')) {      if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
             $destination .= 'default/';   $title=&mt('Copy of').' '.$title;
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {   my $newid=$$.int(rand(100)).time;
             $destination .=  $2.'/';   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
         }          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
 # this is for a course, not a user, so set coursedoc flag              my $path = $1;
 # probably the only place in the system where this should be "1"              my $prefix = $2;
         my $newidx=&Apache::lonratedt::getresidx();              my $ancestor = $3;
         $destination .= $newidx;              if (length($ancestor) > 10) {
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,                  $ancestor = substr($ancestor,-10,10);
  $parseaction,$allfiles,              }
  $codebase);              $oldid = $path.$prefix.$ancestor;
         my $ext='false';          }
         if ($url=~/^http\:\/\//) { $ext='true'; }          my $counter = 0;
         $url=~s/\:/\&colon;/g;          my $newurl=$oldid.$newid.'.'.$ext;
         my $comment=$env{'form.comment'};          my $is_unique = &uniqueness_check($newurl);
         $comment=~s/\</\&lt\;/g;          while (!$is_unique && $counter < 100) {
         $comment=~s/\>/\&gt\;/g;              $counter ++;
         $comment=~s/\:/\&colon;/g;              $newid ++;
         if ($folder=~/^supplemental/) {              $newurl = $oldid.$newid;
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.              $is_unique = &uniqueness_check($newurl);
                   $env{'user.domain'}.'___&&&___'.$comment;          }
         }          if (!$is_unique) {
               if ($url=~/\.page$/) {
         $Apache::lonratedt::resources[$newidx]=                  return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
                   $comment.':'.$url.':'.$ext.':normal:res';              } else {
         $Apache::lonratedt::order[$#Apache::lonratedt::order+1]= $newidx;                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,              }
     $folder.'.'.$container);          }
         if ($fatal) {   my $storefn=$newurl;
             $$upload_output .= '<p><font color="red">'.$errtext.'</font></p>';   $storefn=~s{^/\w+/$match_domain/$match_username/}{};
             return 'failed';   my $paste_map_result =
         } else {              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
             if ($parseaction eq 'parse') {         &Apache::lonnet::getfile($url));
                 my $total_embedded = keys(%{$allfiles});          if ($paste_map_result eq '/adm/notfound.html') {
                 if ($total_embedded > 0) {              if ($url=~/\.page$/) {
                     my $num = 0;                  return &mt('Paste failed: an error occurred saving the composite page');
                     $$upload_output .= 'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />              } else {
    <form name="upload_embedded" action="/adm/coursedocs"                  return &mt('Paste failed: an error occurred saving the folder');
                   method="post" enctype="multipart/form-data">              }
    <input type="hidden" name="folderpath" value="'.$env{'form.folderpath'}.'" />   <input type="hidden" name="cmd" value="upload_embedded" />          }
    <input type="hidden" name="newidx" value="'.$newidx.'" />   $url = $newurl;
    <input type="hidden" name="primaryurl" value="'.&Apache::lonnet::escape($url).'" />      }
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';  # published maps can only exists once, so remove it from paste buffer when done
                     $$upload_output .= '<b>Upload embedded files</b>:<br />      if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
    <table>';   &Apache::lonnet::delenv('docs\\.markedcopy');
                     foreach my $embed_file (keys(%{$allfiles})) {      }
                         $$upload_output .= '<tr><td>'.$embed_file.      if ($url=~ m{/smppg$}) {
           '<input name="embedded_item_'.$num.'" type="file" />   my $db_name = &Apache::lonsimplepage::get_db_name($url);
            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&Apache::lonnet::escape($embed_file).'" />';   if ($db_name =~ /^smppage_/) {
                         my $attrib;      #simple pages, need to copy the db contents to a new one.
                         if (@{$$allfiles{$embed_file}} > 1) {      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
                             $attrib = join(':',@{$$allfiles{$embed_file}});      my $now = time();
                         } else {      $db_name =~ s{_\d*$ }{_$now}x;
                             $attrib = $$allfiles{$embed_file}[0];      my $result=&Apache::lonnet::put($db_name,\%contents,
                         }      $coursedom,$coursenum);
                         $$upload_output .=      $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
            '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.$attrib.'" />';      $title=&mt('Copy of').' '.$title;
                         if (exists($$codebase{$embed_file})) {   }
                             $$upload_output .=       }
           '<input name="codebase_'.$num.'" type="hidden" value="'.&Apache::lonnet::escape($$codebase{$embed_file}).'" />';      $title = &LONCAPA::map::qtunescape($title);
                         }      my $ext='false';
                         $$upload_output .= '</td></tr>';      if ($url=~m{^http(|s)://}) { $ext='true'; }
                         $num ++;      $url       = &LONCAPA::map::qtunescape($url);
                     }  # Now insert the URL at the bottom
                     $phase_status = 'phasetwo';      my $newidx = &LONCAPA::map::getresidx($url);
                     $$upload_output .= '</table><br />      if ($env{'docs.markedcopy_supplemental'}) {
    <input type ="submit" value="Complete upload" />          if ($folder =~ /^supplemental/) {
    </form>';              $title = $env{'docs.markedcopy_supplemental'};
                 } else {          } else {
                     $$upload_output .= 'No embedded items identified<br />';              (undef,undef,$title) =
                 }                  &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
             }          }
         }      } else {
     }          if ($folder=~/^supplemental/) {
     return $phase_status;             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 }                    $env{'user.domain'}.'___&&&___'.$title;
           }
 sub process_secondary_uploads {      }
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;  
     my $folder=$env{'form.folder'};      $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
     my $destination = 'docs/';      push(@LONCAPA::map::order, $newidx);
     if ($folder =~ /^supplemental/) {      return 'ok';
         $destination = 'supplemental/';  # Store the result
     }  }
     if (($folder eq 'default') || ($folder eq 'supplemental')) {  
         $destination .= 'default/';  sub uniqueness_check {
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {      my ($newurl) = @_;
         $destination .=  $1.'/';      my $unique = 1;
     }      foreach my $res (@LONCAPA::map::order) {
     $destination .= $newidx;          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     my ($url,$filename);          $url=&LONCAPA::map::qtescape($url);
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);          if ($newurl eq $url) {
     ($filename) = ($url =~ m-^/uploaded/$coursedom/$coursenum/$destination/(.+)$-);              $unique = 0;
     return $filename;              last;    
 }          }
       }
 # --------------------------------------------------------------- An entry line      return $unique;
   }
 sub entryline {  
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;  my %parameter_type = ( 'randompick'     => 'int_pos',
     $title=~s/\&colon\;/\:/g;         'hiddenresource' => 'string_yesno',
     $title=&HTML::Entities::encode(&HTML::Entities::decode(         'encrypturl'     => 'string_yesno',
      &Apache::lonnet::unescape($title)),'"<>&\'');         'randomorder'    => 'string_yesno',);
     my $renametitle=$title;  my $valid_parameters_re = join('|',keys(%parameter_type));
     my $foldertitle=$title;  # set parameters
     my $pagetitle=$title;  sub update_parameter {
     my $orderidx=$Apache::lonratedt::order[$index];  
     if ($title=~ /^(\d+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(.*)$/ ) {       return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);  
  $renametitle=$4;      my $which = $env{'form.changeparms'};
  $title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.      my $idx = $env{'form.setparms'};
     &Apache::loncommon::plainname($2,$3).': <br />'.      if ($env{'form.'.$which.'_'.$idx}) {
     $foldertitle;   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
     }                                       : 'yes';
     $renametitle=~s/\&quot\;/\\\"/g;   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
     my $line='<tr>';        $parameter_type{$which});
 # Edit commands   &remember_parms($idx,$which,'set',$value);
     my $container;      } else {
     my $folderpath;   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
     if ($env{'form.folderpath'}) {  
         $container = 'sequence';   &remember_parms($idx,$which,'del');
  $folderpath=&Apache::lonnet::escape($env{'form.folderpath'});      }
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');      return 1;
     }  }
     my ($pagepath,$pagesymb);  
     if ($env{'form.pagepath'}) {  
         $container = 'page';  sub handle_edit_cmd {
         $pagepath=&Apache::lonnet::escape($env{'form.pagepath'});      my ($coursenum,$coursedom) =@_;
         $pagesymb=&Apache::lonnet::escape($env{'form.pagesymb'});  
     }      my ($cmd,$idx)=split('_',$env{'form.cmd'});
     my $cpinfo='';  
     if ($env{'form.markedcopy_url'}) {      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
        $cpinfo='&markedcopy_url='.      my ($title, $url, @rrest) = split(':', $ratstr);
                &Apache::lonnet::escape($env{'form.markedcopy_url'}).  
                '&markedcopy_title='.      if ($cmd eq 'del') {
                &Apache::lonnet::escape($env{'form.markedcopy_title'});   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
     }      ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
     if ($allowed) {      &Apache::lonnet::removeuploadedurl($url);
  my $incindex=$index+1;   } else {
  my $selectbox='';      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  if (($folder!~/^supplemental/) &&   }
     ($#Apache::lonratedt::order>0) &&    splice(@LONCAPA::map::order, $idx, 1);
     ((split(/\:/,  
      $Apache::lonratedt::resources[$Apache::lonratedt::order[0]]))[1]       } elsif ($cmd eq 'cut') {
      ne '') &&    &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     ((split(/\:/,   splice(@LONCAPA::map::order, $idx, 1);
      $Apache::lonratedt::resources[$Apache::lonratedt::order[1]]))[1]   
      ne '')) {      } elsif ($cmd eq 'up'
     $selectbox=       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
  '<select name="newpos" onChange="this.form.submit()">';  
     for (my $i=1;$i<=$#Apache::lonratedt::order+1;$i++) {      } elsif ($cmd eq 'down'
  if ($i==$incindex) {       && defined($LONCAPA::map::order[$idx+1])) {
     $selectbox.='<option value="" selected="1">('.$i.')</option>';   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
  } else {  
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';      } elsif ($cmd eq 'rename') {
  }  
     }   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
     $selectbox.='</select>';   if ($comment=~/\S/) {
  }      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
  my %lt=&Apache::lonlocal::texthash(   $comment.':'.join(':', $url, @rrest);
                 'up' => 'Move Up',   }
  'dw' => 'Move Down',  # Devalidate title cache
  'rm' => 'Remove',   my $renamed_url=&LONCAPA::map::qtescape($url);
                 'ct' => 'Cut',   &Apache::lonnet::devalidate_title_cache($renamed_url);
  'rn' => 'Rename',      } else {
  'cp' => 'Copy');   return 0;
         if ($env{'form.pagepath'}) {      }
             $line.=(<<END);      return 1;
 <form name="entry_$index" action="/adm/coursedocs" method="post">  }
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />  
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />  sub editor {
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />  
 <input type="hidden" name="setparms" value="$orderidx" />      my $container= ($env{'form.pagepath'}) ? 'page'
 <td><table border='0' cellspacing='2' cellpadding='0'>                             : 'sequence';
 <tr><td bgcolor="#DDDDDD">  
 <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>      $folder.'.'.$container);
 <tr><td bgcolor="#DDDDDD">      return $errtext if ($fatal);
 <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>  
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>      if ($#LONCAPA::map::order<1) {
 </table></td>   my $idx=&LONCAPA::map::getresidx();
 <td>$selectbox   if ($idx<=0) { $idx=1; }
 </td><td bgcolor="#DDDDDD">          $LONCAPA::map::order[0]=$idx;
 <a href='javascript:removeres("$pagepath","$index","$renametitle","page","$pagesymb");'>          $LONCAPA::map::resources[$idx]='';
 <font size="-2" color="#990000">$lt{'rm'}</font></a>      }
 <a href='javascript:cutres("$pagepath","$index","$renametitle","page","$pagesymb");'>     
 <font size="-2" color="#550044">$lt{'ct'}</font></a>      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=
 <a href='javascript:changename("$pagepath","$index","$renametitle","page","$pagesymb");'>   &breadcrumbs($folder,$allowed,$type);
 <font size="-2" color="#009900">$lt{'rn'}</font></a>      $r->print($breadcrumbtrail);
 <a href='javascript:markcopy("$pagepath","$index","$renametitle","page","$pagesymb");'>     
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>  # ------------------------------------------------------------ Process commands
 END  
         } else {  # ---------------- if they are for this folder and user allowed to make changes
             $line.=(<<END);       if (($allowed) && ($env{'form.folder'} eq $folder)) {
 <form name="entry_$index" action="/adm/coursedocs" method="post">  # set parameters and change order
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   &snapshotbefore();
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />  
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />   if (&update_parameter()) {
 <input type="hidden" name="setparms" value="$orderidx" />      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 <td><table border='0' cellspacing='2' cellpadding='0'>      return $errtext if ($fatal);
 <tr><td bgcolor="#DDDDDD">   }
 <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath$cpinfo'>  
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
 <tr><td bgcolor="#DDDDDD">  # change order
 <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath$cpinfo'>      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
 </table></td>  
 <td>$selectbox      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 </td><td bgcolor="#DDDDDD">      return $errtext if ($fatal);
 <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>   }
 <font size="-2" color="#990000">$lt{'rm'}</font></a>      
 <a href='javascript:cutres("$folderpath","$index","$renametitle","sequence");'>   if ($env{'form.pastemarked'}) {
 <font size="-2" color="#550044">$lt{'ct'}</font></a>              my $paste_res =
 <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
 <font size="-2" color="#009900">$lt{'rn'}</font></a>              if ($paste_res eq 'ok') {
 <a href='javascript:markcopy("$folderpath","$index","$renametitle","sequence");'>                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>                  return $errtext if ($fatal);
 END              } elsif ($paste_res ne '') {
         }                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
     }              }
 # Figure out what kind of a resource this is   }
     my ($extension)=($url=~/\.(\w+)$/);  
     my $uploaded=($url=~/^\/*uploaded\//);   $r->print($upload_output);
     my $icon=&Apache::loncommon::icon($url);  
     my $isfolder=0;   if (&handle_edit_cmd()) {
     my $ispage=0;      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     my $folderarg;      return $errtext if ($fatal);
     my $pagearg;   }
     my $pagefile;  # Group import/search
     if ($uploaded) {   if ($env{'form.importdetail'}) {
  if ($extension eq 'sequence') {      my @imports;
     $icon=$iconpath.'/folder_closed.gif';      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
     $url=~/$coursenum\/([\/\w]+)\.sequence$/;   if (defined($item)) {
     $url='/adm/coursedocs?';      my ($name,$url,$residx)=
     $folderarg=$1;   map {&unescape($_)} split(/\=/,$item);
     $isfolder=1;      push(@imports, [$name, $url, $residx]);
         } elsif ($extension eq 'page') {   }
             $icon=$iconpath.'/page.gif';      }
             $url=~/$coursenum\/([\/\w]+)\.page$/;      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
             $pagearg=$1;      $container,'londocs',@imports);
             $url='/adm/coursedocs?';      return $errtext if ($fatal);
             $ispage=1;   }
  } else {  # Loading a complete map
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);   if ($env{'form.loadmap'}) {
  }      if ($env{'form.importmap'}=~/\w/) {
     }   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
     $url=~s/^http\&colon\;\/\//\/adm\/wrapper\/ext\//;      my ($title,$url,$ext,$type)=split(/\:/,$res);
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {      my $idx=&LONCAPA::map::getresidx($url);
  my $symb=&Apache::lonnet::symbclean(      $LONCAPA::map::resources[$idx]=$res;
           &Apache::lonnet::declutter('uploaded/'.      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.   }
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
            '.sequence').      $folder.'.'.$container);
            '___'.$residx.'___'.   return $errtext if ($fatal);
    &Apache::lonnet::declutter($url));      } else {
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
  $url=&Apache::lonnet::clutter($url);  
  if ($url=~/^\/*uploaded\//) {      }
     $url=~/\.(\w+)$/;   }
     my $embstyle=&Apache::loncommon::fileembstyle($1);   &log_differences($plain);
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {      }
  $url='/adm/wrapper'.$url;  # ---------------------------------------------------------------- End commands
     } elsif ($embstyle eq 'ssi') {  # ---------------------------------------------------------------- Print screen
  #do nothing with these      my $idx=0;
     } elsif ($url!~/\.(sequence|page)$/) {      my $shown=0;
  $url='/adm/coursedocs/showdoc'.$url;      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
     }   $r->print('<p>'.&mt('Parameters').':<ul>'.
  } elsif ($url=~m|^/ext/|) {     ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
     $url='/adm/wrapper'.$url;    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
  }    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
  $url.=(($url=~/\?/)?'&':'?').'symb='.&Apache::lonnet::escape($symb);    '</ul></p>');
  if ($container eq 'page') {      }                                                                                                    
     my $symb=$env{'form.pagesymb'};      if ($randompick>=0) {
            $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>');
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);      }
     $url.=(($url=~/\?/)?'&':'?').'symb='.&Apache::lonnet::escape($symb);      if ($is_random_order) {
  }   $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');
     }      }
     my $parameterset='&nbsp;';      $r->print('<table class="LC_docs_editor">');
     if ($isfolder) {      foreach my $res (@LONCAPA::map::order) {
  my $foldername=&Apache::lonnet::escape($foldertitle);   my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
  my $folderpath=$env{'form.folderpath'};   $name=&LONCAPA::map::qtescape($name);
  if ($folderpath) { $folderpath.='&' };   $url=&LONCAPA::map::qtescape($url);
  $folderpath.=$folderarg.'&'.$foldername;   unless ($name) {  $name=(split(/\//,$url))[-1]; }
  $url.='folderpath='.&Apache::lonnet::escape($folderpath).$cpinfo;   unless ($name) { $idx++; next; }
  $parameterset='<label>'.&mt('Randomly Pick: ').   $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,
     '<input type="text" size="4" onChange="this.form.submit()" name="randpick_'.$orderidx.'" value="'.       $coursenum));
     (&Apache::lonratedt::getparameter($orderidx,   $idx++;
                                               'parameter_randompick'))[0].   $shown++;
                                               '" />'.      }
 '<font size="-2"><a href="javascript:void(0)">'.&mt('Store').'</a></font></label>';      unless ($shown) {
           $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
     }      }
     if ($ispage) {      $r->print("\n</table>\n");
         my $pagename=&Apache::lonnet::escape($pagetitle);      if ($allowed) {
         my $pagepath;          &print_paste_buffer($r,$container);
         my $folderpath=$env{'form.folderpath'};      }
         if ($folderpath) { $pagepath = $folderpath.'&' };      return;
         $pagepath.=$pagearg.'&'.$pagename;  }
  my $symb=$env{'form.pagesymb'};  
  if (!$symb) {  sub process_file_upload {
     my $path='uploaded/'.      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.  # upload a file, if present
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';      my $parseaction;
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',     if ($env{'form.parserflag'}) {
        $residx,          $parseaction = 'parse';
        $path.$pagearg.'.page');      }
  }      my $phase_status;
  $url.='pagepath='.&Apache::lonnet::escape($pagepath).      my $folder=$env{'form.folder'};
     '&pagesymb='.&Apache::lonnet::escape($symb).$cpinfo;      if ($folder eq '') {
     }          $folder='default';
     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.      }
  '" border="0"></a></td>'.      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
         "<td bgcolor='#FFFFBB'><a href='$url'>$title</a></td>";          my $errtext='';
     if (($allowed) && ($folder!~/^supplemental/)) {          my $fatal=0;
   my %lt=&Apache::lonlocal::texthash(          my $container='sequence';
        'hd' => 'Hidden',          if ($env{'form.pagepath'}) {
        'ec' => 'URL hidden');              $container='page';
  my $enctext=          }
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');          ($errtext,$fatal)=
  my $hidtext=                &mapread($coursenum,$coursedom,$folder.'.'.$container);
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');          if ($#LONCAPA::map::order<1) {
  $line.=(<<ENDPARMS);              $LONCAPA::map::order[0]=1;
 <td bgcolor="#BBBBFF"><font size='-2'>              $LONCAPA::map::resources[1]='';
 <nobr><label><input type="checkbox" name="hidprs_$orderidx" onClick="this.form.submit()" $hidtext /> $lt{'hd'}</label></nobr></td>          }
 <td bgcolor="#BBBBFF"><font size='-2'>          if ($fatal) {
 <nobr><label><input type="checkbox" name="encprs_$orderidx" onClick="this.form.submit()" $enctext /> $lt{'ec'}</label></nobr></td>              return 'failed';
 <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>          }
 ENDPARMS          my $destination = 'docs/';
     }          if ($folder =~ /^supplemental/) {
     $line.="</form></tr>";              $destination = 'supplemental/';
     return $line;          }
 }          if (($folder eq 'default') || ($folder eq 'supplemental')) {
               $destination .= 'default/';
 # ---------------------------------------------------------------- tie the hash          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
               $destination .=  $2.'/';
 sub tiehash {          }
     my ($mode)=@_;  # this is for a course, not a user, so set coursedoc flag
     $hashtied=0;  # probably the only place in the system where this should be "1"
     if ($env{'request.course.fn'}) {          my $newidx=&LONCAPA::map::getresidx();
  if ($mode eq 'write') {          $destination .= $newidx;
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",          my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
     &GDBM_WRCREAT(),0640)) {   $parseaction,$allfiles,
                 $hashtied=2;   $codebase);
     }          my $ext='false';
  } else {          if ($url=~m{^http://}) { $ext='true'; }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",   $url     = &LONCAPA::map::qtunescape($url);
     &GDBM_READER(),0640)) {          my $comment=$env{'form.comment'};
                 $hashtied=1;   $comment = &LONCAPA::map::qtunescape($comment);
     }          if ($folder=~/^supplemental/) {
  }                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     }                        $env{'user.domain'}.'___&&&___'.$comment;
 }          }
   
 sub untiehash {          $LONCAPA::map::resources[$newidx]=
     if ($hashtied) { untie %hash; }      $comment.':'.$url.':'.$ext.':normal:res';
     $hashtied=0;          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
 }          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
       $folder.'.'.$container);
 # --------------------------------------------------------------- check on this          if ($fatal) {
               $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';
 sub checkonthis {              return 'failed';
     my ($r,$url,$level,$title)=@_;          } else {
     $url=&Apache::lonnet::unescape($url);              if ($parseaction eq 'parse') {
     $alreadyseen{$url}=1;                  my $total_embedded = keys(%{$allfiles});
     $r->rflush();                  if ($total_embedded > 0) {
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {                      my $num = 0;
        $r->print("\n<br />");      my $state = '
        for (my $i=0;$i<=$level*5;$i++) {     <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
            $r->print('&nbsp;');     <input type="hidden" name="cmd" value="upload_embedded" />
        }     <input type="hidden" name="newidx" value="'.$newidx.'" />
        $r->print('<a href="'.$url.'" target="cat">'.     <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
  ($title?$title:$url).'</a> ');     <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
        if ($url=~/^\/res\//) {      $phase_status = 'phasetwo';
   my $result=&Apache::lonnet::repcopy(  
                               &Apache::lonnet::filelocation('',$url));                      $$upload_output .=
           if ($result eq 'ok') {   'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.
              $r->print('<font color="green">'.&mt('ok').'</font>');   &Apache::loncommon::ask_for_embedded_content(
              $r->rflush();                              '/adm/coursedocs',$state,$allfiles,$codebase);
              &Apache::lonnet::countacc($url);                  } else {
              $url=~/\.(\w+)$/;                      $$upload_output .= 'No embedded items identified<br />';
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {                  }
  $r->print('<br />');              }
                  $r->rflush();          }
                  for (my $i=0;$i<=$level*5;$i++) {      }
                      $r->print('&nbsp;');      return $phase_status;
                  }  }
                  $r->print('- '.&mt('Rendering').': ');  
  my ($errorcount,$warningcount)=split(/:/,  sub process_secondary_uploads {
        &Apache::lonnet::ssi_body($url,      my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
        ('grade_target'=>'web',      my $folder=$env{'form.folder'};
  'return_only_error_and_warning_counts' => 1)));      my $destination = 'docs/';
                  if (($errorcount) ||      if ($folder =~ /^supplemental/) {
                      ($warningcount)) {          $destination = 'supplemental/';
      if ($errorcount) {      }
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.      if (($folder eq 'default') || ($folder eq 'supplemental')) {
   $errorcount.' '.          $destination .= 'default/';
   &mt('error(s)').'</b></font> ');      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
                      }          $destination .=  $2.'/';
      if ($warningcount) {      }
                         $r->print('<font color="blue">'.      $destination .= $newidx;
   $warningcount.' '.      my ($url,$filename);
   &mt('warning(s)').'</font>');      $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
                      }      ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});
                  } else {      return $filename;
                      $r->print('<font color="green">'.&mt('ok').'</font>');  }
                  }  
                  $r->rflush();  sub is_supplemental_title {
              }      my ($title) = @_;
      my $dependencies=      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
                 &Apache::lonnet::metadata($url,'dependencies');  }
              foreach (split(/\,/,$dependencies)) {  
  if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {  sub parse_supplemental_title {
                     &checkonthis($r,$_,$level+1);      my ($title) = @_;
                  }  
              }      my ($foldertitle,$renametitle);
           } elsif ($result eq 'unavailable') {      if ($title =~ /&amp;&amp;&amp;/) {
              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');   $title = &HTML::Entites::decode($title);
           } elsif ($result eq 'not_found') {      }
       unless ($url=~/\$/) {   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
   $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');   $renametitle=$4;
       } else {   my ($time,$uname,$udom) = ($1,$2,$3);
   $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
       }   my $name =  &Apache::loncommon::plainname($uname,$udom);
           } else {   $name = &HTML::Entities::encode($name,'"<>&\'');
              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
           }      $name.': <br />'.$foldertitle;
       }      }
    }      if (wantarray) {
 }   return ($title,$foldertitle,$renametitle);
       }
       return $title;
 #  }
 # -------------------------------------------------------------- Verify Content  
 #   # --------------------------------------------------------------- An entry line
 sub verifycontent {  
    my $r=shift;   sub entryline {
    my $loaderror=&Apache::lonnet::overloaderror($r);      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
    if ($loaderror) { return $loaderror; }  
    my $html=&Apache::lonxml::xmlbegin();      my ($foldertitle,$pagetitle,$renametitle);
    $r->print($html.'<head><title>Verify Content</title></head>'.      if (&is_supplemental_title($title)) {
               &Apache::loncommon::bodytag('Verify Course Documents'));   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
    $hashtied=0;   $pagetitle = $foldertitle;
    undef %alreadyseen;      } else {
    %alreadyseen=();   $title=&HTML::Entities::encode($title,'"<>&\'');
    &tiehash();   $renametitle=$title;
    foreach (keys %hash) {   $foldertitle=$title;
        if ($hash{$_}=~/\.(page|sequence)$/) {   $pagetitle=$title;
    if (($_=~/^src_/) && ($alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {      }
        $r->print('<hr /><font color="red">'.  
  &mt('The following sequence or page is included more than once in your course: ').      my $orderidx=$LONCAPA::map::order[$index];
  &Apache::lonnet::unescape($hash{$_}).'</font><br />'.     
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));  
    }      $renametitle=~s/\\/\\\\/g;
        }      $renametitle=~s/\&quot\;/\\\"/g;
        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {      $renametitle=~s/ /%20/g;
            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});      my $line='<tr>';
        }      my ($form_start,$form_end);
    }  # Edit commands
    &untiehash();      my ($container, $type, $esc_path, $path, $symb);
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.      if ($env{'form.folderpath'}) {
      &mt('Return to DOCS').'</a>');   $type = 'folder';
 }          $container = 'sequence';
    $esc_path=&escape($env{'form.folderpath'});
    $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 # -------------------------------------------------------------- Check Versions   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
       }
 sub devalidateversioncache {      if ($env{'form.pagepath'}) {
     my $src=shift;          $type = $container = 'page';
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.          $esc_path=&escape($path = $env{'form.pagepath'});
   &Apache::lonnet::clutter($src));   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
 }          $symb=&escape($env{'form.pagesymb'});
       }
 sub checkversions {      my $cpinfo='';
     my $r=shift;      if ($allowed) {
     my $html=&Apache::lonxml::xmlbegin();   my $incindex=$index+1;
     $r->print($html.'<head><title>Check Versions</title></head>'.   my $selectbox='';
               &Apache::loncommon::bodytag('Check Course Document Versions'));   if (($folder!~/^supplemental/) &&
     my $header='';      ($#LONCAPA::map::order>0) &&
     my $startsel='';      ((split(/\:/,
     my $monthsel='';       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
     my $weeksel='';       ne '') &&
     my $daysel='';      ((split(/\:/,
     my $allsel='';       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
     my %changes=();       ne '')) {
     my $starttime=0;      $selectbox=
     my $haschanged=0;   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
     my %setversions=&Apache::lonnet::dump('resourceversions',   '<select name="newpos" onChange="this.form.submit()">';
   $env{'course.'.$env{'request.course.id'}.'.domain'},      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
   $env{'course.'.$env{'request.course.id'}.'.num'});   if ($i==$incindex) {
       $selectbox.='<option value="" selected="1">('.$i.')</option>';
     $hashtied=0;   } else {
     &tiehash();      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
     my %newsetversions=();   }
     if ($env{'form.setmostrecent'}) {      }
  $haschanged=1;      $selectbox.='</select>';
  foreach (keys %hash) {   }
     if ($_=~/^ids\_(\/res\/.+)$/) {   my %lt=&Apache::lonlocal::texthash(
  $newsetversions{$1}='mostrecent';                  'up' => 'Move Up',
                 &devalidateversioncache($1);   'dw' => 'Move Down',
     }   'rm' => 'Remove',
  }                  'ct' => 'Cut',
     } elsif ($env{'form.setcurrent'}) {   'rn' => 'Rename',
  $haschanged=1;   'cp' => 'Copy');
  foreach (keys %hash) {   my $nocopy=0;
     if ($_=~/^ids\_(\/res\/.+)$/) {          my $nocut=0;
  my $getvers=&Apache::lonnet::getversion($1);          if ($url=~/\.(page|sequence)$/) {
  if ($getvers>0) {      if ($url =~ m{/res/}) {
     $newsetversions{$1}=$getvers;   # no copy for published maps
     &devalidateversioncache($1);   $nocopy = 1;
  }      } else {
     }   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
  }      my ($title,$url,$ext,$type)=split(/\:/,$item);
     } elsif ($env{'form.setversions'}) {      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
  $haschanged=1;   $nocopy=1;
  foreach (keys %env) {   last;
     if ($_=~/^form\.set_version_(.+)$/) {      }
  my $src=$1;   }
  if (($env{$_}) && ($env{$_} ne $setversions{$src})) {      }
     $newsetversions{$src}=$env{$_};   }
     &devalidateversioncache($src);          if ($url=~/^\/res\/lib\/templates\//) {
  }             $nocopy=1;
     }             $nocut=1;
  }          }
     }          my $copylink='&nbsp;';
     if ($haschanged) {          my $cutlink='&nbsp;';
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,  
   $env{'course.'.$env{'request.course.id'}.'.domain'},   my $skip_confirm = 0;
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {   if ( $folder =~ /^supplemental/
     $r->print('<h1>'.&mt('Your Version Settings have been Stored').'</h1>');       || ($url =~ m{( /smppg$
  } else {      |/syllabus$
     $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Store your Version Settings').'</font></h1>');      |/aboutme$
  }      |/navmaps$
  &mark_hash_old();      |/bulletinboard$
     }      |\.html$
     &changewarning($r,'');      |^/adm/wrapper/ext)}x)) {
     if ($env{'form.timerange'} eq 'all') {      $skip_confirm = 1;
 # show all documents   }
  $header=&mt('All Documents in Course');  
  $allsel=1;   if (!$nocopy) {
  foreach (keys %hash) {      $copylink=(<<ENDCOPY);
     if ($_=~/^ids\_(\/res\/.+)$/) {  <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
  my $src=$1;  ENDCOPY
  $changes{$src}=1;          }
     }   if (!$nocut) {
  }      $cutlink=(<<ENDCUT);
     } else {  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
 # show documents which changed  ENDCUT
  %changes=&Apache::lonnet::dump          }
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},   $form_start = (<<END);
                      $env{'course.'.$env{'request.course.id'}.'.num'});     <form  action="/adm/coursedocs" method="post">
  my $firstkey=(keys %changes)[0];     <input type="hidden" name="${type}path" value="$path" />
  unless ($firstkey=~/^error\:/) {     <input type="hidden" name="${type}symb" value="$symb" />
     unless ($env{'form.timerange'}) {     <input type="hidden" name="setparms" value="$orderidx" />
  $env{'form.timerange'}=604800;     <input type="hidden" name="changeparms" value="0" />
     }  END
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '          $form_end = '</form>';
  .&mt('seconds');   $line.=(<<END);
     if ($env{'form.timerange'}==-1) {  <td>
  $seltext='since start of course';     <table class="LC_docs_entry_move">
  $startsel='selected';        <tr>
  $env{'form.timerange'}=time;           <td>
     }              <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" /></a>
     $starttime=time-$env{'form.timerange'};           </td>
     if ($env{'form.timerange'}==2592000) {        </tr>
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';        <tr>
  $monthsel='selected';          <td>
     } elsif ($env{'form.timerange'}==604800) {             <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" /></a>
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';          </td>
  $weeksel='selected';        </tr>
     } elsif ($env{'form.timerange'}==86400) {      </table>
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  </td>
  $daysel='selected';  <td>
     }     $form_start
     $header=&mt('Content changed').' '.$seltext;     $selectbox
  } else {     $form_end
     $header=&mt('No content modifications yet.');  </td>
  }  <td class="LC_docs_entry_commands">
     }     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     %setversions=&Apache::lonnet::dump('resourceversions',  $cutlink
   $env{'course.'.$env{'request.course.id'}.'.domain'},     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
   $env{'course.'.$env{'request.course.id'}.'.num'});  $copylink
     my %lt=&Apache::lonlocal::texthash  </td>
       ('st' => 'Version changes since start of Course',  END
        'lm' => 'Version changes since last Month',  
        'lw' => 'Version changes since last Week',      }
        'sy' => 'Version changes since Yesterday',  # Figure out what kind of a resource this is
                'al' => 'All Resources (possibly large output)',      my ($extension)=($url=~/\.(\w+)$/);
        'sd' => 'Display',      my $uploaded=($url=~/^\/*uploaded\//);
        'fi' => 'File',      my $icon=&Apache::loncommon::icon($url);
        'md' => 'Modification Date',      my $isfolder=0;
                'mr' => 'Most recently published Version',      my $ispage=0;
        've' => 'Version used in Course',      my $folderarg;
                'vu' => 'Set Version to be used in Course',      my $pagearg;
 'sv' => 'Set Versions to be used in Course according to Selections below',      my $pagefile;
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      if ($uploaded) {
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',   if ($extension eq 'sequence') {
        'di' => 'Differences');      $icon=$iconpath.'/folder_closed.gif';
     $r->print(<<ENDHEADERS);      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
 <form action="/adm/coursedocs" method="post">      $url='/adm/coursedocs?';
 <input type="hidden" name="versions" value="1" />      $folderarg=$1;
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />      $isfolder=1;
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />          } elsif ($extension eq 'page') {
 <select name="timerange">              $icon=$iconpath.'/page.gif';
 <option value='all' $allsel>$lt{'al'}</option>              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
 <option value="-1" $startsel>$lt{'st'}</option>              $pagearg=$1;
 <option value="2592000" $monthsel>$lt{'lm'}</option>              $url='/adm/coursedocs?';
 <option value="604800" $weeksel>$lt{'lw'}</option>              $ispage=1;
 <option value="86400" $daysel>$lt{'sy'}</option>   } else {
 </select>      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 <input type="submit" name="display" value="$lt{'sd'}" />   }
 <h3>$header</h3>      }
 <input type="submit" name="setversions" value="$lt{'sv'}" />     
 <table border="0">      my $orig_url = $url;
 ENDHEADERS      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
     foreach (sort keys %changes) {      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
  if ($changes{$_}>$starttime) {   my $symb=&Apache::lonnet::symbclean(
     my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);            &Apache::lonnet::declutter('uploaded/'.
     my $currentversion=&Apache::lonnet::getversion($_);             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
     if ($currentversion<0) {             $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
  $currentversion=&mt('Could not be determined.');             '.sequence').
     }             '___'.$residx.'___'.
     my $linkurl=&Apache::lonnet::clutter($_);     &Apache::lonnet::declutter($url));
     $r->print(   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.   $url=&Apache::lonnet::clutter($url);
       &Apache::lonnet::gettitle($linkurl).   if ($url=~/^\/*uploaded\//) {
                       '</b></font></td></tr>'.      $url=~/\.(\w+)$/;
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      my $embstyle=&Apache::loncommon::fileembstyle($1);
                       '<td colspan="4">'.      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.   $url='/adm/wrapper'.$url;
       '</a></td></tr>'.      } elsif ($embstyle eq 'ssi') {
                       '<tr><td></td>'.   #do nothing with these
                       '<td title="'.$lt{'md'}.'">'.      } elsif ($url!~/\.(sequence|page)$/) {
       &Apache::lonlocal::locallocaltime(   $url='/adm/coursedocs/showdoc'.$url;
                            &Apache::lonnet::metadata($root.'.'.$extension,      }
                                                      'lastrevisiondate')   } elsif ($url=~m|^/ext/|) {
                                                         ).      $url='/adm/wrapper'.$url;
                       '</td>'.      $external = 1;
                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.   }
                       '<font size="+1">'.$currentversion.'</font>'.          if (&Apache::lonnet::symbverify($symb,$url)) {
                       '</nobr></td>'.      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
                       '<td title="'.$lt{'ve'}.'"><nobr>In Course: '.          } else {
                       '<font size="+1">');              $url='';
 # Used in course          }
     my $usedversion=$hash{'version_'.$linkurl};   if ($container eq 'page') {
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      my $symb=$env{'form.pagesymb'};
  $r->print($usedversion);          
     } else {      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
  $r->print($currentversion);      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
     }   }
     $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.      }
                       '<nobr>Use: ');      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
 # Set version      if ($isfolder || $extension eq 'sequence') {
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},   my $foldername=&escape($foldertitle);
       'set_version_'.$linkurl,   my $folderpath=$env{'form.folderpath'};
       ('select_form_order' =>   if ($folderpath) { $folderpath.='&' };
        ['',1..$currentversion,'mostrecent'],  # Append randompick number, hidden, and encrypted with ":" to foldername,
        '' => '',  # so it gets transferred between levels
        'mostrecent' => 'most recent',   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
        map {$_,$_} (1..$currentversion))));                                                'parameter_randompick'))[0]
     $r->print('</nobr></td></tr><tr><td></td>');                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     my $lastold=1;                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  my $url=$root.'.'.$prevvers.'.'.$extension;                                                'parameter_encrypturl'))[0]=~/^yes$/i)
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     $starttime) {                                                'parameter_randomorder'))[0]=~/^yes$/i);
     $lastold=$prevvers;   $url.='folderpath='.&escape($folderpath).$cpinfo;
  }   $parameterset='<label>'.&mt('Randomly Pick: ').
     }      '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
             #       (&LONCAPA::map::getparameter($orderidx,
             # Code to figure out how many version entries should go in                                                'parameter_randompick'))[0].
             # each of the four columns                                                '" />'.
             my $entries_per_col = 0;  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
             my $num_entries = ($currentversion-$lastold);      my $ro_set=
             if ($num_entries % 4 == 0) {      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
                 $entries_per_col = $num_entries/4;   $rand_order_text ='
             } else {  <span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" onClick="this.form.changeparms.value=\'randomorder\';this.form.submit()" '.$ro_set.' /> '.&mt('Random Order').' </label></span>';  
                 $entries_per_col = $num_entries/4 + 1;      }
             }      if ($ispage) {
             my $entries_count = 0;          my $pagename=&escape($pagetitle);
             $r->print('<td valign="top"><font size="-2">');           my $pagepath;
             my $cols_output = 1;          my $folderpath=$env{'form.folderpath'};
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {          if ($folderpath) { $pagepath = $folderpath.'&' };
  my $url=$root.'.'.$prevvers.'.'.$extension;          $pagepath.=$pagearg.'&'.$pagename;
  $r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).   my $symb=$env{'form.pagesymb'};
   '">'.&mt('Version').' '.$prevvers.'</a> ('.   if (!$symb) {
   &Apache::lonlocal::locallocaltime(      my $path='uploaded/'.
                                 &Apache::lonnet::metadata($url,   $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
                                                           'lastrevisiondate')   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
                                                             ).      $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
   ')');         $residx,
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {         $path.$pagearg.'.page');
                     $r->print(' <a href="/adm/diff?filename='.   }
       &Apache::lonnet::clutter($root.'.'.$extension).   $url.='pagepath='.&escape($pagepath).
       '&versionone='.$prevvers.      '&amp;pagesymb='.&escape($symb).$cpinfo;
       '">'.&mt('Diffs').'</a>');      }
  }      if ($external) {
  $r->print('</nobr><br />');   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
                 if (++$entries_count % $entries_per_col == 0) {   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
                     $r->print('</font></td>');      } else {
                     if ($cols_output != 4) {   undef($external);
                         $r->print('<td valign="top"><font size="-2">');      }
                         $cols_output++;      $line.='
                     }    <td class="LC_docs_entry_icon">
                 }      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
     }    </td>
             while($cols_output++ < 4) {    <td class="LC_docs_entry_title">
                 $r->print('</font></td><td><font>')      '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."
             }    </td>";
     $r->print('</font></td></tr>'."\n");      if (($allowed) && ($folder!~/^supplemental/)) {
  }    my %lt=&Apache::lonlocal::texthash(
     }         'hd' => 'Hidden',
     $r->print('</table></form>');         'ec' => 'URL hidden');
     $r->print('<h1>'.&mt('Done').'.</h1>');   my $enctext=
       ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
     &untiehash();   my $hidtext=
 }      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
    $line.=(<<ENDPARMS);
 sub mark_hash_old {    <td class="LC_docs_entry_parameter">
     my $retie_hash=0;      $form_start
     if ($hashtied) {      <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
  $retie_hash=1;      $form_end
  &untiehash();    </td>
     }    <td class="LC_docs_entry_parameter">
     &tiehash('write');      $form_start
     $hash{'old'}=1;      <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
     &untiehash();      $form_end
     if ($retie_hash) { &tiehash(); }    </td>
 }    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
     <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
 sub is_hash_old {  ENDPARMS
     my $untie_hash=0;      }
     if (!$hashtied) {      $line.="</tr>";
  $untie_hash=1;      return $line;
  &tiehash();  }
     }  
     my $return=$hash{'old'};  =pod
     if ($untie_hash) { &untiehash(); }  
     return $return;  =item tiehash()
 }  
   tie the hash
 sub changewarning {  
     my ($r,$postexec,$message,$url)=@_;  =cut
     if (!&is_hash_old()) { return; }  
     my $pathvar='folderpath';  sub tiehash {
     my $path=&Apache::lonnet::escape($env{'form.folderpath'});      my ($mode)=@_;
     if (!defined($url)) {      $hashtied=0;
  if (defined($env{'form.pagepath'})) {      if ($env{'request.course.fn'}) {
     $pathvar='pagepath';   if ($mode eq 'write') {
     $path=&Apache::lonnet::escape($env{'form.pagepath'});      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     $path.='&amp;pagesymb='.&Apache::lonnet::escape($env{'form.pagesymb'});      &GDBM_WRCREAT(),0640)) {
  }                  $hashtied=2;
  $url='/adm/coursedocs?'.$pathvar.'='.$path;      }
     }   } else {
     if (!defined($message)) {      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  $message='Changes will become active for your current session after [_1], or the next time you log in.';      &GDBM_READER(),0640)) {
     }                  $hashtied=1;
     $r->print("\n\n".      }
 '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".    }
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.      }    
 '<input type="hidden" name="orgurl" value="'.$url.  }
 '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.  
 &mt($message,' <input type="hidden" name="'.  sub untiehash {
     $env{'request.role'}.'" value="1" /><input type="button" value="'.      if ($hashtied) { untie %hash; }
     &mt('re-initializing course').'" onClick="reinit(this.form)" />').      $hashtied=0;
 $help{'Caching'}.'</font></h3></form>'."\n\n");      return OK;
 }  }
   
 # ================================================================ Main Handler  
 sub handler {  
     my $r = shift;  
     &Apache::loncommon::content_type($r,'text/html');  sub checkonthis {
     $r->send_http_header;      my ($r,$url,$level,$title)=@_;
     return OK if $r->header_only;      $url=&unescape($url);
       $alreadyseen{$url}=1;
 # --------------------------------------------- Initialize help topics for this      $r->rflush();
   foreach ('Adding_Course_Doc','Main_Course_Documents',      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
            'Adding_External_Resource','Navigate_Content',         $r->print("\n<br />");
            'Adding_Folders','Docs_Overview', 'Load_Map',         if ($level==0) {
            'Supplemental','Score_Upload_Form','Adding_Pages',             $r->print("<br />");
            'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',         }
    'Check_Resource_Versions','Verify_Content') {         for (my $i=0;$i<=$level*5;$i++) {
       $help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);             $r->print('&nbsp;');
   }         }
     # Composite help files         $r->print('<a href="'.$url.'" target="cat">'.
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(   ($title?$title:$url).'</a> ');
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');         if ($url=~/^\/res\//) {
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(    my $result=&Apache::lonnet::repcopy(
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');                                &Apache::lonnet::filelocation('',$url));
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(            if ($result eq 'ok') {
     'Option_Response_Simple');               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(               $r->rflush();
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');               &Apache::lonnet::countacc($url);
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(               $url=~/\.(\w+)$/;
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');   $r->print('<br />');
                    $r->rflush();
   if ($env{'form.verify'}) {                   for (my $i=0;$i<=$level*5;$i++) {
       &verifycontent($r);                       $r->print('&nbsp;');
   } elsif ($env{'form.versions'}) {                   }
       &checkversions($r);                   $r->print('- '.&mt('Rendering:').' ');
   } elsif ($env{'form.dumpcourse'}) {   my ($errorcount,$warningcount)=split(/:/,
       &dumpcourse($r);         &Apache::lonnet::ssi_body($url,
   } elsif ($env{'form.exportcourse'}) {         ('grade_target'=>'web',
       &exportcourse($r);   'return_only_error_and_warning_counts' => 1)));
   } else {                   if (($errorcount) ||
 # is this a standard course?                       ($warningcount)) {
        if ($errorcount) {
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);                          $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.
     my $forcestandard = 0;                            &mt('[quant,_1,error]',$errorcount).'</span>');
     my $forcesupplement;                       }
     my $script='';       if ($warningcount) {
     my $allowed;                          $r->print('<span class="LC_warning">'.
     my $events='';                            &mt('[quant,_1,warning]',$warningcount).'</span>');
     my $showdoc=0;                       }
     my $containertag;                   } else {
     my $uploadtag;                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                   }
     ['folderpath','pagepath','pagesymb','markedcopy_url','markedcopy_title']);                   $r->rflush();
     if ($env{'form.folderpath'}) {               }
  my (@folderpath)=split('&',$env{'form.folderpath'});       my $dependencies=
  $env{'form.foldername'}=&Apache::lonnet::unescape(pop(@folderpath));                  &Apache::lonnet::metadata($url,'dependencies');
  $env{'form.folder'}=pop(@folderpath);               foreach my $dep (split(/\,/,$dependencies)) {
     }   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
     if ($env{'form.pagepath'}) {                      &checkonthis($r,$dep,$level+1);
         my (@pagepath)=split('&',$env{'form.pagepath'});                   }
         $env{'form.pagename'}=&Apache::lonnet::unescape(pop(@pagepath));               }
         $env{'form.folder'}=pop(@pagepath);            } elsif ($result eq 'unavailable') {
         $containertag = '<input type="hidden" name="pagepath" value="" />'.               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
     '<input type="hidden" name="pagesymb" value="" />';            } elsif ($result eq 'not_found') {
         $uploadtag = '<input type="hidden" name="pagepath" value="'.$env{'form.pagepath'}.'" />'.        unless ($url=~/\$/) {
     '<input type="hidden" name="pagesymb" value="'.$env{'form.pagesymb'}.'" />';    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
     }        } else {
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {    $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');
        $showdoc='/'.$1;        }
     }            } else {
     unless ($showdoc) { # got called from remote               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
        if (($env{'form.folder'}=~/^default_/) ||             }
           ($env{'form.folder'} =~ m#^\d+/(pages|sequences)/#)) {         }
            $forcestandard = 1;      }
        }   }
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);  
   
 # does this user have privileges to post, etc?  
        $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});  =pod
        if ($allowed) {   
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);  =item list_symbs()
          $script=&Apache::lonratedt::editscript('simple');   
        }  List Symbs
     } else { # got called in sequence from course  
        $allowed=0;  =cut
        $script='</script>'.&Apache::lonmenu::registerurl(1,undef).'<script>';  
        $events='onLoad="'.&Apache::lonmenu::loadevents.  sub list_symbs {
            '" onUnload="'.&Apache::lonmenu::unloadevents.'"';      my ($r) = @_;
     }  
       my $type = &Apache::loncommon::course_type();
 # get course data      $r->print(&Apache::loncommon::start_page('Symb List'));
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};      my $navmap = Apache::lonnavmaps::navmap->new();
       if (!defined($navmap)) {
 # get personal data          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
                      '<div class="LC_error">'.
     my $uname=$env{'user.name'};                    &mt('Unable to retrieve information about course contents').
     my $udom=$env{'user.domain'};                    '</div>');
     my $plainname=&Apache::lonnet::escape(          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
                      &Apache::loncommon::plainname($uname,$udom));      } else {
           $r->print("<pre>\n");
 # graphics settings          foreach my $res ($navmap->retrieveResources()) {
       $r->print($res->compTitle()."\t".$res->symb()."\n");
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");          }
           $r->print("\n</pre>\n");
     my $now=time;      }
       $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
 # print screen  }
        my $html=&Apache::lonxml::xmlbegin();  
     $r->print(<<ENDDOCUMENT);  
 $html  sub verifycontent {
 <head>      my ($r) = @_;
 <title>The LearningOnline Network with CAPA</title>      my $type = &Apache::loncommon::course_type();
 <script>     my $loaderror=&Apache::lonnet::overloaderror($r);
 $script     if ($loaderror) { return $loaderror; }
 </script>     $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
 ENDDOCUMENT     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));
    if ($allowed) {     $hashtied=0;
     $r->print(<<ENDNEWSCRIPT);     undef %alreadyseen;
 <script>     %alreadyseen=();
 function makenewfolder(targetform,folderseq) {     &tiehash();
     var foldername=prompt('Name of New Folder','New Folder');     foreach my $key (keys(%hash)) {
     if (foldername) {         if ($hash{$key}=~/\.(page|sequence)$/) {
  targetform.importdetail.value=foldername+"="+folderseq;     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
         targetform.submit();         $r->print('<hr /><span class="LC_error">'.
     }   &mt('The following sequence or page is included more than once in your '.$type.': ').
 }   &unescape($hash{$key}).'</span><br />'.
    &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
 function makenewpage(targetform,folderseq) {     }
     var pagename=prompt('Name of New Page','New Page');         }
     if (pagename) {         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
         targetform.importdetail.value=pagename+"="+folderseq;             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
         targetform.submit();         }
     }     }
 }     &untiehash();
      $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
 function makenewext(targetname) {       &mt('Return to DOCS').'</a>');
     this.document.forms.extimport.useform.value=targetname;  }
     window.open('/adm/rat/extpickframe.html');  
 }  
   sub devalidateversioncache {
 function makeexamupload() {      my $src=shift;
    var title=prompt('Listed Title for the Uploaded Score');      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
    if (title) {     &Apache::lonnet::clutter($src));
     this.document.forms.newexamupload.importdetail.value=  }
  title+'=/res/lib/templates/examupload.problem';  
     this.document.forms.newexamupload.submit();  sub checkversions {
    }      my ($r) = @_;
 }      my $type = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
 function makesmppage() {      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));
    var title=prompt('Listed Title for the Page');      my $header='';
    if (title) {       my $startsel='';
     this.document.forms.newsmppg.importdetail.value=      my $monthsel='';
  title+'=/adm/$udom/$uname/$now/smppg';      my $weeksel='';
     this.document.forms.newsmppg.submit();      my $daysel='';
    }      my $allsel='';
 }      my %changes=();
       my $starttime=0;
 function makesmpproblem() {      my $haschanged=0;
    var title=prompt('Listed Title for the Problem');      my %setversions=&Apache::lonnet::dump('resourceversions',
    if (title) {     $env{'course.'.$env{'request.course.id'}.'.domain'},
     this.document.forms.newsmpproblem.importdetail.value=    $env{'course.'.$env{'request.course.id'}.'.num'});
  title+'=/res/lib/templates/simpleproblem.problem';  
     this.document.forms.newsmpproblem.submit();      $hashtied=0;
    }      &tiehash();
 }      my %newsetversions=();
       if ($env{'form.setmostrecent'}) {
 function makebulboard() {   $haschanged=1;
    var title=prompt('Listed Title for the Bulletin Board');   foreach my $key (keys(%hash)) {
    if (title) {      if ($key=~/^ids\_(\/res\/.+)$/) {
     this.document.forms.newbul.importdetail.value=   $newsetversions{$1}='mostrecent';
  title+'=/adm/$udom/$uname/$now/bulletinboard';                  &devalidateversioncache($1);
     this.document.forms.newbul.submit();      }
    }   }
 }      } elsif ($env{'form.setcurrent'}) {
    $haschanged=1;
 function makeabout() {   foreach my $key (keys(%hash)) {
    var user=prompt("Enter user\@domain for User's 'About Me' Page");      if ($key=~/^ids\_(\/res\/.+)$/) {
    if (user) {   my $getvers=&Apache::lonnet::getversion($1);
        var comp=new Array();   if ($getvers>0) {
        comp=user.split('\@');      $newsetversions{$1}=$getvers;
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {      &devalidateversioncache($1);
    if ((comp[0]) && (comp[1])) {   }
        this.document.forms.newaboutsomeone.importdetail.value=      }
    'About '+user+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';   }
        this.document.forms.newaboutsomeone.submit();      } elsif ($env{'form.setversions'}) {
    } else {   $haschanged=1;
                alert("Not a valid user\@domain");   foreach my $key (keys(%env)) {
            }      if ($key=~/^form\.set_version_(.+)$/) {
        } else {   my $src=$1;
            alert("Please enter both user and domain in the format user\@domain");    if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
        }      $newsetversions{$src}=$env{$key};
    }      &devalidateversioncache($src);
 }   }
       }
 function makeims() {   }
     var caller = document.forms.ims.folder.value;      }
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";      if ($haschanged) {
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
     newWindow.location.href = newlocation;    $env{'course.'.$env{'request.course.id'}.'.domain'},
 }    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
       $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
    } else {
 function finishpick() {      $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
     var title=this.document.forms.extimport.title.value;   }
     var url=this.document.forms.extimport.url.value;   &mark_hash_old();
     var form=this.document.forms.extimport.useform.value;      }
     eval      &changewarning($r,'');
      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+      if ($env{'form.timerange'} eq 'all') {
     '";this.document.forms.'+form+'.submit();');  # show all documents
 }   $header=&mt('All Documents in '.$type);
    $allsel=1;
 function changename(folderpath,index,oldtitle,container,pagesymb) {   foreach my $key (keys(%hash)) {
     var title=prompt('New Title',oldtitle);      if ($key=~/^ids\_(\/res\/.+)$/) {
     if (title) {   my $src=$1;
  this.document.forms.renameform.title.value=title;   $changes{$src}=1;
  this.document.forms.renameform.cmd.value='rename_'+index;      }
         if (container == 'sequence') {   }
     this.document.forms.renameform.folderpath.value=folderpath;      } else {
         }  # show documents which changed
         if (container == 'page') {   %changes=&Apache::lonnet::dump
             this.document.forms.renameform.pagepath.value=folderpath;   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
             this.document.forms.renameform.pagesymb.value=pagesymb;                       $env{'course.'.$env{'request.course.id'}.'.num'});
         }   my $firstkey=(keys(%changes))[0];
         this.document.forms.renameform.submit();   unless ($firstkey=~/^error\:/) {
     }      unless ($env{'form.timerange'}) {
 }   $env{'form.timerange'}=604800;
       }
 function removeres(folderpath,index,oldtitle,container,pagesymb) {      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
     if (confirm('WARNING: Removing a resource makes associated grades and scores inaccessible!\\nRemove "'+oldtitle+'"?')) {   .&mt('seconds');
  this.document.forms.renameform.cmd.value='del_'+index;      if ($env{'form.timerange'}==-1) {
         if (container == 'sequence') {   $seltext='since start of course';
             this.document.forms.renameform.folderpath.value=folderpath;   $startsel='selected';
         }   $env{'form.timerange'}=time;
         if (container == 'page') {      }
             this.document.forms.renameform.pagepath.value=folderpath;      $starttime=time-$env{'form.timerange'};
             this.document.forms.renameform.pagesymb.value=pagesymb;      if ($env{'form.timerange'}==2592000) {
         }   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
         this.document.forms.renameform.submit();   $monthsel='selected';
     }      } elsif ($env{'form.timerange'}==604800) {
 }   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $weeksel='selected';
 function cutres(folderpath,index,oldtitle,container,pagesymb) {      } elsif ($env{'form.timerange'}==86400) {
     if (confirm('WARNING: Cutting a resource makes associated grades and scores inaccessible!\\nGrades remain inaccessible if resource is pasted into another folder.\\nCut "'+oldtitle+'"?')) {   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  this.document.forms.renameform.cmd.value='cut_'+index;   $daysel='selected';
  this.document.forms.renameform.markcopy.value=index;      }
         if (container == 'sequence') {      $header=&mt('Content changed').' '.$seltext;
             this.document.forms.renameform.folderpath.value=folderpath;   } else {
         }      $header=&mt('No content modifications yet.');
         if (container == 'page') {   }
             this.document.forms.renameform.pagepath.value=folderpath;      }
             this.document.forms.renameform.pagesymb.value=pagesymb;      %setversions=&Apache::lonnet::dump('resourceversions',
         }    $env{'course.'.$env{'request.course.id'}.'.domain'},
         this.document.forms.renameform.submit();    $env{'course.'.$env{'request.course.id'}.'.num'});
     }      my %lt=&Apache::lonlocal::texthash
 }        ('st' => 'Version changes since start of '.$type,
          'lm' => 'Version changes since last Month',
 function markcopy(folderpath,index,oldtitle,container,pagesymb) {         'lw' => 'Version changes since last Week',
     this.document.forms.renameform.markcopy.value=index;         'sy' => 'Version changes since Yesterday',
     if (container == 'sequence') {                 'al' => 'All Resources (possibly large output)',
  this.document.forms.renameform.folderpath.value=folderpath;         'sd' => 'Display',
     }         'fi' => 'File',
     if (container == 'page') {         'md' => 'Modification Date',
  this.document.forms.renameform.pagepath.value=folderpath;                 'mr' => 'Most recently published Version',
  this.document.forms.renameform.pagesymb.value=pagesymb;         've' => 'Version used in '.$type,
     }                 'vu' => 'Set Version to be used in '.$type,
     this.document.forms.renameform.submit();  'sv' => 'Set Versions to be used in '.$type.' according to Selections below',
 }  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
   'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 </script>         'di' => 'Differences');
       $r->print(<<ENDHEADERS);
 ENDNEWSCRIPT  <form action="/adm/coursedocs" method="post">
   }  <input type="hidden" name="versions" value="1" />
 # -------------------------------------------------------------------- Body tag  <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
   $r->print('</head>'.  <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
             &Apache::loncommon::bodytag('Course Documents','',$events,  <select name="timerange">
  '','',$showdoc).  <option value='all' $allsel>$lt{'al'}</option>
     &Apache::loncommon::help_open_menu('','','','',273,'RAT'));  <option value="-1" $startsel>$lt{'st'}</option>
   my %allfiles = ();  <option value="2592000" $monthsel>$lt{'lm'}</option>
   my %codebase = ();  <option value="604800" $weeksel>$lt{'lw'}</option>
   my ($upload_result,$upload_output);  <option value="86400" $daysel>$lt{'sy'}</option>
   if ($allowed) {  </select>
       if (($env{'form.uploaddoc.filename'}) &&                                               ($env{'form.cmd'}=~/^upload_(\w+)/)) {  <input type="submit" name="display" value="$lt{'sd'}" />
 # Process file upload - phase one - upload and parse primary file.    <h3>$header</h3>
           $upload_result = &process_file_upload(\$upload_output,$coursenum,  <input type="submit" name="setversions" value="$lt{'sv'}" />
  $coursedom,\%allfiles,  <table border="0">
  \%codebase,$1);  ENDHEADERS
           if ($upload_result eq 'phasetwo') {      foreach my $key (sort(keys(%changes))) {
               $r->print($upload_output);   if ($changes{$key}>$starttime) {
           }      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
       } elsif ($env{'form.phasetwo'}) {      my $currentversion=&Apache::lonnet::getversion($key);
           my %newname = ();      if ($currentversion<0) {
           my %origname = ();   $currentversion=&mt('Could not be determined.');
           my %attribs = ();      }
           my $updateflag = 0;      my $linkurl=&Apache::lonnet::clutter($key);
           my $residx = $env{'form.newidx'};      $r->print(
           my $primary_url = &Apache::lonnet::unescape($env{'form.primaryurl'});        '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
 # Process file upload - phase two - gather secondary files.        &Apache::lonnet::gettitle($linkurl).
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {                        '</b></font></td></tr>'.
               if ($env{'form.embedded_item_'.$i.'.filename'}) {                        '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
                   my $javacodebase;                        '<td colspan="4">'.
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);                        '<a href="'.$linkurl.'" target="cat">'.$linkurl.
                   $origname{$i} = &Apache::lonnet::unescape($env{'form.embedded_orig_'.$i});        '</a></td></tr>'.
                   if (exists($env{'form.embedded_codebase_'.$i})) {                        '<tr><td></td>'.
                       $javacodebase =  &Apache::lonnet::unescape($env{'form.embedded_codebase_'.$i});                          '<td title="'.$lt{'md'}.'">'.
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;         &Apache::lonlocal::locallocaltime(
                   }                             &Apache::lonnet::metadata($root.'.'.$extension,
                   my @attributes = ();                                                       'lastrevisiondate')
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {                                                          ).
                       @attributes = split/:/,$env{'form.embedded_attrib_'.$i};                        '</td>'.
                   } else {                        '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
                       @attributes = ($env{'form.embedded_attrib_'.$i});                        '<font size="+1">'.$currentversion.'</font>'.
                   }                        '</span></td>'.
                   foreach (@attributes) {                        '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.
                       push(@{$attribs{$i}},&Apache::lonnet::unescape($_));                        '<font size="+1">');
                   }  # Used in course
                   if ($javacodebase) {      my $usedversion=$hash{'version_'.$linkurl};
                       $codebase{$i} = $javacodebase;      if (($usedversion) && ($usedversion ne 'mostrecent')) {
                       $codebase{$i} =~ s#/$##;   $r->print($usedversion);
                       $updateflag = 1;      } else {
                   }   $r->print($currentversion);
               }      }
               unless ($newname{$i} eq $origname{$i}) {      $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
                   $updateflag = 1;                        '<span class="LC_nobreak">Use: ');
               }  # Set version
           }      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
 # Process file upload - phase three - modify primary file        'set_version_'.$linkurl,
           if ($updateflag) {        ('select_form_order' =>
               my ($content,$rtncode);         ['',1..$currentversion,'mostrecent'],
               my $updateflag = 0;         '' => '',
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);         'mostrecent' => 'most recent',
               if ($getstatus eq 'ok') {         map {$_,$_} (1..$currentversion))));
                   foreach my $item (keys %newname) {      $r->print('</span></td></tr><tr><td></td>');
                       if ($newname{$item} ne $origname{$item}) {      my $lastold=1;
                           my $attrib_regexp = '';      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
                           if (@{$attribs{$item}} > 1) {   my $url=$root.'.'.$prevvers.'.'.$extension;
                               $attrib_regexp = join('|',@{$attribs{$item}});   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
                           } else {      $starttime) {
                               $attrib_regexp = $attribs{$item}[0];      $lastold=$prevvers;
                           }   }
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {      }
                           }               #
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;               # Code to figure out how many version entries should go in
                       }              # each of the four columns
                       if (exists($codebase{$item})) {              my $entries_per_col = 0;
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i;              my $num_entries = ($currentversion-$lastold);
                       }              if ($num_entries % 4 == 0) {
                   }                  $entries_per_col = $num_entries/4;
 # Save edited file.              } else {
                   my $saveresult;                  $entries_per_col = $num_entries/4 + 1;
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};              }
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};              my $entries_count = 0;
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);              $r->print('<td valign="top"><font size="-2">');
               } else {              my $cols_output = 1;
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);               for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
               }   my $url=$root.'.'.$prevvers.'.'.$extension;
           }   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
       }    '">'.&mt('Version').' '.$prevvers.'</a> ('.
   }    &Apache::lonlocal::locallocaltime(
                                   &Apache::lonnet::metadata($url,
   unless ($showdoc ||  $upload_result eq 'phasetwo') {                                                            'lastrevisiondate')
 # -----------------------------------------------------------------------------                                                              ).
        my %lt=&Apache::lonlocal::texthash(    ')');
                 'uplm' => 'Upload a new main course document',   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
                 'upls' => 'Upload a new supplemental course document',                      $r->print(' <a href="/adm/diff?filename='.
                 'impp' => 'Import a document',        &Apache::lonnet::clutter($root.'.'.$extension).
                 'pubd' => 'Published documents',        '&versionone='.$prevvers.
  'copm' => 'All documents out of a published map into this folder',        '">'.&mt('Diffs').'</a>');
                 'spec' => 'Special documents',   }
                 'upld' => 'Upload Document',   $r->print('</span><br />');
                 'srch' => 'Search',                  if (++$entries_count % $entries_per_col == 0) {
                 'impo' => 'Import',                      $r->print('</font></td>');
                 'selm' => 'Select Map',                      if ($cols_output != 4) {
                 'load' => 'Load Map',                          $r->print('<td valign="top"><font size="-2">');
                 'reco' => 'Recover Deleted Resources',                          $cols_output++;
                 'newf' => 'New Folder',                      }
                 'newp' => 'New Composite Page',                  }
                 'extr' => 'External Resource',      }
                 'syll' => 'Syllabus',              while($cols_output++ < 4) {
                 'navc' => 'Navigate Contents',                  $r->print('</font></td><td><font>')
                 'sipa' => 'Simple Page',              }
                 'sipr' => 'Simple Problem',      $r->print('</font></td></tr>'."\n");
                 'scuf' => 'Score Upload Form',   }
                 'bull' => 'Bulletin Board',      }
                 'mypi' => 'My Personal Info',      $r->print('</table></form>');
  'abou' => 'About User',      $r->print('<h1>'.&mt('Done').'.</h1>');
                 'imsf' => 'Import IMS package',  
                 'file' =>  'File',      &untiehash();
                 'title' => 'Title',  }
                 'comment' => 'Comment',  
                 'parse' => 'If HTML file, upload embedded images/multimedia files'  sub mark_hash_old {
   );      my $retie_hash=0;
 # -----------------------------------------------------------------------------      if ($hashtied) {
     if ($allowed) {   $retie_hash=1;
        my $dumpbut=&dumpbutton();   &untiehash();
        my $exportbut=&exportbutton();      }
        my %lt=&Apache::lonlocal::texthash(      &tiehash('write');
  'vc' => 'Verify Content',      $hash{'old'}=1;
  'cv' => 'Check/Set Resource Versions',      &untiehash();
   );      if ($retie_hash) { &tiehash(); }
   }
        my $folderpath=$env{'form.folderpath'};  
        if (!$folderpath) {  sub is_hash_old {
    if ($env{'form.folder'} eq '' ||      my $untie_hash=0;
        $env{'form.folder'} eq 'supplemental') {      if (!$hashtied) {
        $folderpath='default&'.   $untie_hash=1;
    &Apache::lonnet::escape(&mt('Main Course Documents'));   &tiehash();
    }      }
        }      my $return=$hash{'old'};
        unless ($env{'form.pagepath'}) {      if ($untie_hash) { &untiehash(); }
            $containertag = '<input type="hidden" name="folderpath" value="" />';      return $return;
            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';  }
        }  
   sub changewarning {
        $r->print(<<ENDCOURSEVERIFY);      my ($r,$postexec,$message,$url)=@_;
 <form name="renameform" method="post" action="/adm/coursedocs">      if (!&is_hash_old()) { return; }
 <input type="hidden" name="title" />      my $pathvar='folderpath';
 <input type="hidden" name="cmd" />      my $path=&escape($env{'form.folderpath'});
 <input type="hidden" name="markcopy" />      if (!defined($url)) {
 $containertag   if (defined($env{'form.pagepath'})) {
 </form>      $pathvar='pagepath';
 <form name="simpleedit" method="post" action="/adm/coursedocs">      $path=&escape($env{'form.pagepath'});
 <input type=hidden name="importdetail" value="">      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
 $uploadtag   }
 </form>   $url='/adm/coursedocs?'.$pathvar.'='.$path;
 <form action="/adm/coursedocs" method="post" name="courseverify">      }
 <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">      my $course_type = &Apache::loncommon::course_type();
 <tr><td bgcolor="#DDDDCC">      if (!defined($message)) {
 <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}   $message='Changes will become active for your current session after [_1], or the next time you log in.';
 </td><td bgcolor="#DDDDCC">      }
     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}      $r->print("\n\n".
 $dumpbut  '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".
 $exportbut  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 </td></tr></table>  '<input type="hidden" name="orgurl" value="'.$url.
 </form>  '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.
 ENDCOURSEVERIFY  &mt($message,' <input type="hidden" name="'.
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',      $env{'request.role'}.'" value="1" /><input type="button" value="'.
      &mt('Editing the Table of Contents for your Course')));      &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
     }  $help{'Caching'}.'</span></h3></form>'."\n\n");
 # --------------------------------------------------------- Standard documents  }
     $r->print('<table border=2 cellspacing=4 cellpadding=4>');  
     if (($standard) && ($allowed) && (!$forcesupplement)) {  
  $r->print('<tr><td bgcolor="#BBBBBB">');  sub init_breadcrumbs {
 #  '<h2>'.&mt('Main Course Documents').      my ($form,$text)=@_;
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');      &Apache::lonhtmlcommon::clear_breadcrumbs();
        my $folder=$env{'form.folder'};      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
        if ($folder eq '' || $folder eq 'supplemental') {      text=>"Edit ".&Apache::loncommon::course_type(),
            $folder='default';      faq=>273,
    $env{'form.folderpath'}='default&'.&Apache::lonnet::escape(&mt('Main Course Documents'));      bug=>'Instructor Interface',
        }                                              help => 'Docs_Adding_Course_Doc'});
        my $postexec='';      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
        if ($folder eq 'default') {      text=>$text,
    $r->print('<script>this.window.name="loncapaclient";</script>');      faq=>273,
        } else {      bug=>'Instructor Interface'});
            #$postexec='self.close();';  }
        }  
        $hadchanges=0;  
        &editor($r,$coursenum,$coursedom,$folder,$allowed,$upload_output);  
        if ($hadchanges) {  
    &mark_hash_old()  sub handler {
        }      my $r = shift;
        &changewarning($r,$postexec);      &Apache::loncommon::content_type($r,'text/html');
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      $r->send_http_header;
                      '.sequence';      return OK if $r->header_only;
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      my $type = &Apache::loncommon::course_type();
                      '.page';  
  my $container='sequence';  
  if ($env{'form.pagepath'}) {  # --------------------------------------------- Initialize help topics for this
     $container='page';      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
  }                 'Adding_External_Resource','Navigate_Content',
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;                 'Adding_Folders','Docs_Overview', 'Load_Map',
        $r->print(<<ENDFORM);                 'Supplemental','Score_Upload_Form','Adding_Pages',
 <table cellspacing=4 cellpadding=4><tr>                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
 <th bgcolor="#DDDDDD">$lt{'uplm'}</th>                 'Check_Resource_Versions','Verify_Content') {
 <th bgcolor="#DDDDDD">$lt{'impp'}</th>   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>      }
 </tr>      # Composite help files
 <tr><td bgcolor="#DDDDDD">      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 $lt{'file'}:<br />      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 <input type="file" name="uploaddoc" size="40">      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 <br />      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 $lt{'title'}:<br />      'Option_Response_Simple');
 <input type="text" size="50" name="comment">      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 $uploadtag      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 <input type="hidden" name="cmd" value="upload_default">      $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
 <br />    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 <nobr>      $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 <label>$lt{'parse'}?      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 <input type="checkbox" name="parserflag" />  
 </label>  # does this user have privileges to modify docs
 </nobr>      my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 <br />    if ($allowed && $env{'form.verify'}) {
 <br />        &init_breadcrumbs('verify','Verify Content');
 <nobr>        &verifycontent($r);
 <input type="submit" value="$lt{'upld'}">    } elsif ($allowed && $env{'form.listsymbs'}) {
  $help{'Uploading_From_Harddrive'}        &init_breadcrumbs('listsymbs','List Symbs');
 </nobr>        &list_symbs($r);
 </form>    } elsif ($allowed && $env{'form.docslog'}) {
 </td>        &init_breadcrumbs('docslog','Show Log');
 <td bgcolor="#DDDDDD">        &docs_change_log($r);
 <form action="/adm/coursedocs" method="post" name="simpleeditdefault">    } elsif ($allowed && $env{'form.versions'}) {
 $lt{'pubd'}<br />        &init_breadcrumbs('versions','Check/Set Resource Versions');
 $uploadtag        &checkversions($r);
 <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}">    } elsif ($allowed && $env{'form.dumpcourse'}) {
 <nobr>        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
 <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}">        &dumpcourse($r);
 $help{'Importing_LON-CAPA_Resource'}    } elsif ($allowed && $env{'form.exportcourse'}) {
 </nobr>        &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');
 <p>        &exportcourse($r);
 <hr />    } else {
 $lt{'copm'}<br />  # is this a standard course?
 <input type="text" size="40" name="importmap"><br />  
 <nobr><input type=button       my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      my $forcestandard = 0;
 value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">      my $forcesupplement;
 $help{'Load_Map'}</nobr>      my $script='';
 </p>      my $showdoc=0;
 </form>      my $containertag;
 <hr />      my $uploadtag;
 <form action="/adm/groupsort" method="post" name="recover">  
 <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1)" value="$lt{'reco'}" />  
 </form>      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 ENDFORM      ['folderpath','pagepath',
        unless ($env{'form.pagepath'}) {       'pagesymb']);
    $r->print(<<ENDFORM);  # No folderpath, no pagepath, see if we have something stored
 <hr />      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
 <form action="/adm/coursedocs" method="post" name="newext">          &Apache::loncommon::restore_course_settings('docs_folderpath',
 $uploadtag                                                {'folderpath' => 'scalar'});
 <input type=hidden name="importdetail" value="">      }
 <nobr>      if (!$env{'form.folderpath'}) {
 <input name="newext" type="button" onClick="javascript:makenewext('newext');"          &Apache::loncommon::restore_course_settings('docs_folderpath',
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}                                                {'pagepath' => 'scalar'});
 </nobr>      }
 </form>      if ($env{'form.pagepath'}) {
 <form action="/adm/imsimportdocs" method="post" name="ims">         $env{'form.folderpath'}='';
 <input type="hidden" name="folder" value="$folder" />      }
 <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 </nobr>          $env{'form.folderpath'} = 'supplemental&'.
 </form>                                    &escape(&mt('Supplemental '.$type.' Documents')).'&'.
 ENDFORM                                    $env{'form.folderpath'};
        }      }
        $r->print('</td><td bgcolor="#DDDDDD">');      &Apache::loncommon::store_course_settings('docs_folderpath',
        unless ($env{'form.pagepath'}) {                                                  {'pagepath' => 'scalar',
            $r->print(<<ENDFORM);                                                   'folderpath' => 'scalar'});
 <form action="/adm/coursedocs" method="post" name="newfolder">      if ($env{'form.folderpath'}) {
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   my (@folderpath)=split('&',$env{'form.folderpath'});
 <input type=hidden name="importdetail" value="">   $env{'form.foldername'}=&unescape(pop(@folderpath));
 <nobr>   $env{'form.folder'}=pop(@folderpath);
 <input name="newfolder" type="button"      }
 onClick="javascript:makenewfolder(this.form,'$folderseq');"      if ($env{'form.pagepath'}) {
 value="$lt{'newf'}" />$help{'Adding_Folders'}          my (@pagepath)=split('&',$env{'form.pagepath'});
 </nobr>          $env{'form.pagename'}=&unescape(pop(@pagepath));
 </form>          $env{'form.folder'}=pop(@pagepath);
 <form action="/adm/coursedocs" method="post" name="newpage">          $containertag = '<input type="hidden" name="pagepath" value="" />'.
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      '<input type="hidden" name="pagesymb" value="" />';
 <input type=hidden name="importdetail" value="">          $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
 <nobr>      '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';
 <input name="newpage" type="button"      }
 onClick="javascript:makenewpage(this.form,'$pageseq');"      if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 value="$lt{'newp'}" />$help{'Adding_Pages'}         $showdoc='/'.$1;
 </nobr>      }
 </form>      unless ($showdoc) { # got called from remote
 <form action="/adm/coursedocs" method="post" name="newsyl">         if (($env{'form.folder'}=~/^(?:group|default)_/) ||
 $uploadtag            ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
 <input type=hidden name="importdetail"              $forcestandard = 1;
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">         }
 <nobr>         $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
 <input name="newsyl" type="submit" value="$lt{'syll'}" />   
  $help{'Syllabus'}         if ($allowed) {
 </nobr>           &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
 </form>           $script=&Apache::lonratedt::editscript('simple');
 <form action="/adm/coursedocs" method="post" name="newnav">         }
 $uploadtag      } else { # got called in sequence from course
 <input type=hidden name="importdetail"          $allowed=0;
 value="Navigate Content=/adm/navmaps">      }
 <nobr>  
 <input name="newnav" type="submit" value="$lt{'navc'}" />  # get course data
 $help{'Navigate_Content'}      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 </nobr>      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 </form>  
 <form action="/adm/coursedocs" method="post" name="newsmppg">  # get personal data
 $uploadtag      my $uname=$env{'user.name'};
 <input type=hidden name="importdetail" value="">      my $udom=$env{'user.domain'};
 <nobr>      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 <input name="newsmppg" type="button" value="$lt{'sipa'}"  
 onClick="javascript:makesmppage();" /> $help{'Simple Page'}  # graphics settings
 </nobr>  
 </form>      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">  
 $uploadtag      if ($allowed) {
 <input type=hidden name="importdetail" value="">   $script .= &editing_js($udom,$uname);
 <nobr>      }
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"  # -------------------------------------------------------------------- Body tag
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}      $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
 </nobr>      my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];
 </form>      $r->print(&Apache::loncommon::start_page("$type Documents", $script,
 <form action="/adm/coursedocs" method="post" name="newexamupload">      {'force_register' => $showdoc,
 $uploadtag                                       'bread_crumbs' => $brcrum}).
 <input type=hidden name="importdetail" value="">        &Apache::loncommon::help_open_menu('','',273,'RAT'));
 <nobr>   
 <input name="newexamupload" type="button" value="$lt{'scuf'}"    my %allfiles = ();
 onClick="javascript:makeexamupload();" />    my %codebase = ();
 $help{'Score_Upload_Form'}    my ($upload_result,$upload_output);
 </nobr>    if ($allowed) {
 </form>        if (($env{'form.uploaddoc.filename'}) &&
 <form action="/adm/coursedocs" method="post" name="newbul">    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 $uploadtag  # Process file upload - phase one - upload and parse primary file.  
 <input type=hidden name="importdetail" value="">    undef($hadchanges);
 <nobr>            $upload_result = &process_file_upload(\$upload_output,$coursenum,
 <input name="newbulletin" type="button" value="$lt{'bull'}"   $coursedom,\%allfiles,
 onClick="javascript:makebulboard();" />   \%codebase,$1);
 $help{'Bulletin Board'}    if ($hadchanges) {
 </nobr>        &mark_hash_old();
 </form>    }
 <form action="/adm/coursedocs" method="post" name="newaboutme">            if ($upload_result eq 'phasetwo') {
 $uploadtag                $r->print($upload_output);
 <input type=hidden name="importdetail"             }
 value="$plainname=/adm/$udom/$uname/aboutme">        } elsif ($env{'form.phasetwo'}) {
 <nobr>            my %newname = ();
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />            my %origname = ();
 $help{'My Personal Info'}            my %attribs = ();
 </nobr>            my $updateflag = 0;
 </form>            my $residx = $env{'form.newidx'};
 <form action="/adm/coursedocs" method="post" name="newaboutsomeone">            my $primary_url = &unescape($env{'form.primaryurl'});
 $uploadtag  # Process file upload - phase two - gather secondary files.
 <input type=hidden name="importdetail" value="">            for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
 <nobr>                if ($env{'form.embedded_item_'.$i.'.filename'}) {
 <input name="newaboutsomeone" type="button" value="$lt{'abou'}"                     my $javacodebase;
 onClick="javascript:makeabout();" />                    $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
 </nobr>                    $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
 </form>                    if (exists($env{'form.embedded_codebase_'.$i})) {
 ENDFORM                        $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
        }                        $origname{$i} =~ s#^\Q$javacodebase\E/##;
        if ($env{'form.pagepath'}) {                    }
            $r->print(<<ENDBLOCK);                    my @attributes = ();
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">                    if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
 $uploadtag                        @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
 <input type=hidden name="importdetail" value="">                    } else {
 <nobr>                        @attributes = ($env{'form.embedded_attrib_'.$i});
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"                    }
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}                    foreach my $attr (@attributes) {
 </nobr>                        push(@{$attribs{$i}},&unescape($attr));
 </form>                    }
 <form action="/adm/coursedocs" method="post" name="newexamupload">                    if ($javacodebase) {
 $uploadtag                        $codebase{$i} = $javacodebase;
 <input type=hidden name="importdetail" value="">                        $codebase{$i} =~ s#/$##;
 <nobr>                        $updateflag = 1;
 <input name="newexamupload" type="button" value="$lt{'scuf'}"                    }
 onClick="javascript:makeexamupload();" />                }
 $help{'Score_Upload_Form'}                unless ($newname{$i} eq $origname{$i}) {
 </nobr>                    $updateflag = 1;
 </form>                }
 ENDBLOCK            }
        }  # Process file upload - phase three - modify primary file
        $r->print('</td></tr>'."\n".            if ($updateflag) {
 '</table>');                my ($content,$rtncode);
        $r->print('</td></tr>');                my $updateflag = 0;
     }                my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
 # ----------------------------------------------------- Supplemental documents                if ($getstatus eq 'ok') {
     if (!$forcestandard) {                    foreach my $item (keys(%newname)) {
        $r->print('<tr><td bgcolor="#BBBBBB">');                        if ($newname{$item} ne $origname{$item}) {
 # '<h2>'.&mt('Supplemental Course Documents').                            my $attrib_regexp = '';
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');                            if (@{$attribs{$item}} > 1) {
        my $folder=$env{'form.folder'};                                $attrib_regexp = join('|',@{$attribs{$item}});
        unless ($folder=~/^supplemental/) {                            } else {
    $folder='supplemental';                                $attrib_regexp = $attribs{$item}[0];
        }                            }
        if ($folder =~ /^supplemental$/ &&                            if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
    $env{'form.folderpath'} =~ /^default\&/) {                            }
    $env{'form.folderpath'}='supplemental&'.                            $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;
        &Apache::lonnet::escape(&mt('Supplemental Course Documents'));                        }
        }                        if (exists($codebase{$item})) {
        &editor($r,$coursenum,$coursedom,$folder,$allowed);                            $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
        if ($allowed) {                        }
        my $folderseq=                    }
                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.  # Save edited file.
                      '.sequence';                    my $saveresult;
                     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
           $r->print(<<ENDSUPFORM);                    my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 <table cellspacing=4 cellpadding=4><tr>                    my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
 <th bgcolor="#DDDDDD">$lt{'upls'}</th>                } else {
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>                    &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
 </tr>                }
 <tr><td bgcolor="#DDDDDD">            }
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">        }
 <input type="file" name="uploaddoc" size="40">    }
 <br />  
 <br />    unless ($showdoc ||  $upload_result eq 'phasetwo') {
 <nobr>  # -----------------------------------------------------------------------------
 <label>$lt{'parse'}?         my %lt=&Apache::lonlocal::texthash(
 <input type="checkbox" name="parserflag" />                  'uplm' => 'Upload a new main '.lc($type).' document',
 </label>                  'upls' => 'Upload a new supplemental '.lc($type).' document',
 </nobr>                  'impp' => 'Import a document',
 <br /><br />                  'pubd' => 'Published Documents',
 $lt{'comment'}:<br />   'copm' => 'All documents out of a published map into this folder',
 <textarea cols=50 rows=4 name='comment'>                  'upld' => 'Upload Document',
 </textarea>                  'srch' => 'Search',
 <br />                  'impo' => 'Import',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   'book' => 'Import Bookmarks',
 <input type="hidden" name="cmd" value="upload_supplemental">                  'selm' => 'Select Map',
 <nobr>                  'load' => 'Load Map',
 <input type="submit" value="$lt{'upld'}">                  'reco' => 'Recover Deleted Resources',
  $help{'Uploading_From_Harddrive'}                  'newf' => 'New Folder',
 </nobr>                  'newp' => 'New Composite Page',
 </form>                  'extr' => 'External Resource',
 </td>                  'syll' => 'Syllabus',
 <td bgcolor="#DDDDDD">                  'navc' => 'Navigate Contents',
 <form action="/adm/coursedocs" method="post" name="supnewfolder">                  'sipa' => 'Simple Page',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                  'sipr' => 'Simple Problem',
 <input type=hidden name="importdetail" value="">                  'drbx' => 'Drop Box',
 <nobr>                  'scuf' => 'Score Upload Form',
 <input name="newfolder" type="button"                  'bull' => 'Bulletin Board',
 onClick="javascript:makenewfolder(this.form,'$folderseq');"                  'mypi' => 'My Personal Info',
 value="$lt{'newf'}" /> $help{'Adding_Folders'}                  'grpo' => 'Group Files',
 </nobr>                  'rost' => 'Course Roster',
 </form>   'abou' => 'About User',
 <form action="/adm/coursedocs" method="post" name="supnewext">                  'imsf' => 'Import IMS package',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                  'file' =>  'File',
 <input type=hidden name="importdetail" value="">                  'title' => 'Title',
 <nobr>                  'comment' => 'Comment',
 <input name="newext" type="button"                   'parse' => 'Upload embedded images/multimedia files if HTML file!',
 onClick="javascript:makenewext('supnewext');"   'nd' => 'New Document',
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   'pm' => 'Published Map',
 </nobr>   'sd' => 'Special Document',
 </form>   'mo' => 'More Options',
 <form action="/adm/coursedocs" method="post" name="supnewsyl">   'hao' => 'Hide all Options'
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />    );
 <input type=hidden name="importdetail"   # -----------------------------------------------------------------------------
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">   my $fileupload=(<<FIUP);
 <nobr>   $lt{'file'}:<br />
 <input name="newsyl" type="submit" value="$lt{'syll'}" />   <input type="file" name="uploaddoc" size="40" />
 $help{'Syllabus'}  FIUP
 </nobr>  
 </form>   my $checkbox=(<<CHBO);
 <form action="/adm/coursedocs" method="post" name="subnewaboutme">   <!-- <label>$lt{'parse'}?
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   <input type="checkbox" name="parserflag" />
 <input type=hidden name="importdetail"    </label> -->
 value="$plainname=/adm/$udom/$uname/aboutme">   <label>
 <nobr>   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />   </label>
 $help{'My Personal Info'}  CHBO
 </nobr>  
 </form>   my $fileuploadform=(<<FUFORM);
 </td></tr>   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 </table></td></tr>   $fileupload
 ENDSUPFORM   <br />
        }   $lt{'title'}:<br />
     }   <input type="text" size="50" name="comment" />
     if ($allowed) {   $uploadtag
  $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>');   <input type="hidden" name="cmd" value="upload_default" />
     }   <br />
     $r->print('</table>');   <span class="LC_nobreak">
   } else {   $checkbox
       unless ($upload_result eq 'phasetwo') {   </span>
 # -------------------------------------------------------- This is showdoc mode   <br />
           $r->print("<h1>".&mt('Uploaded Document').' - '.   <br />
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.   <span class="LC_nobreak">
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".   <input type="submit" value="$lt{'upld'}" />
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');   $help{'Uploading_From_Harddrive'}
       }   </span>
   }   </form>
  }  FUFORM
  $r->print('</body></html>');  
  return OK;   my $simpleeditdefaultform=(<<SEDFFORM);
 }    <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
    $lt{'pubd'}<br />
 1;   $uploadtag
 __END__   <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />
    <br />
    <span class="LC_nobreak">
    <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />
    $help{'Importing_LON-CAPA_Resource'}
    </span>
    <br />
    <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
    <hr />
    <p>
    $lt{'copm'}<br />
    <input type="text" size="40" name="importmap" /><br />
    <span class="LC_nobreak"><input type="button"
    onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
    value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
    $help{'Load_Map'}</span>
    </p>
    </form>
   SEDFFORM
   
    my $extresourcesform=(<<ERFORM);
    <form action="/adm/coursedocs" method="post" name="newext">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newext" type="button" onClick="javascript:makenewext('newext');"
    value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
    </span>
    </form>
   ERFORM
   
       if ($allowed) {
    &update_paste_buffer($coursenum,$coursedom);
          my %lt=&Apache::lonlocal::texthash(
    'vc' => 'Verify Content',
    'cv' => 'Check/Set Resource Versions',
    'ls' => 'List Symbs',
                                            'sl' => 'Show Log'
     );
   
          my $folderpath=$env{'form.folderpath'};
          if (!$folderpath) {
      if ($env{'form.folder'} eq '' ||
          $env{'form.folder'} eq 'supplemental') {
          $folderpath='default&'.
      &escape(&mt('Main '.$type.' Documents'));
      }
          }
          unless ($env{'form.pagepath'}) {
              $containertag = '<input type="hidden" name="folderpath" value="" />';
              $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
          }
          $r->print(&generate_admin_options($containertag,$uploadtag,\%lt,\%help,\%env));
          $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',
        &mt('Editing the Table of Contents for your '.$type)));
       }
   # --------------------------------------------------------- Standard documents
       $r->print('<table class="LC_docs_documents">');
   
       if (($standard) && ($allowed) && (!$forcesupplement)) {
    $r->print('<tr><td class="LC_docs_document">');
   #  '<h2>'.&mt('Main Course Documents').
   #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');
          my $folder=$env{'form.folder'};
          if ($folder eq '' || $folder eq 'supplemental') {
              $folder='default';
      $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));
              $uploadtag = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
          my $postexec='';
          if ($folder eq 'default') {
      $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');
          } else {
              #$postexec='self.close();';
          }
          $hadchanges=0;
          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,
      $upload_output,$type);
          if ($error) {
      $r->print('<p><span class="LC_error">'.$error.'</span></p>');
          }
          if ($hadchanges) {
      &mark_hash_old();
          }
          &changewarning($r,$postexec);
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                        '.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                        '.page';
    my $container='sequence';
    if ($env{'form.pagepath'}) {
       $container='page';
    }
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
   
   
   
    my $recoverform=(<<RFORM);
    <form action="/adm/groupsort" method="post" name="recover">
    <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />
    </form>
   RFORM
   
    my $imspform=(<<IMSPFORM);
    <form action="/adm/imsimportdocs" method="post" name="ims">
    <input type="hidden" name="folder" value="$folder" />
    <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />
    </form>
   IMSPFORM
   
    my $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'navc'}=/adm/navmaps" />
    <span class="LC_nobreak">
    <input name="newnav" type="submit" value="$lt{'navc'}" />
    $help{'Navigate_Content'}
    </span>
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newsmppg" type="button" value="$lt{'sipa'}"
    onClick="javascript:makesmppage();" /> $help{'Simple Page'}
    </span>
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newsmpproblem" type="button" value="$lt{'sipr'}"
    onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}
    </span>
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    $uploadtag      
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">          
    <input name="newdropbox" type="button" value="$lt{'drbx'}"
    onClick="javascript:makedropbox();" />
    </span>        
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newexamupload" type="button" value="$lt{'scuf'}"
    onClick="javascript:makeexamupload();" />
    $help{'Score_Upload_Form'}
    </span>
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newbulletin" type="button" value="$lt{'bull'}"
    onClick="javascript:makebulboard();" />
    $help{'Bulletin Board'}
    </span>
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <span class="LC_nobreak">
    <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
    $help{'My Personal Info'}
    </span>
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newaboutsomeone" type="button" value="$lt{'abou'}"
    onClick="javascript:makeabout();" />
    </span>
    </form>
   NASOFORM
   
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'rost'}=/adm/viewclasslist" />
    <span class="LC_nobreak">
    <input name="newroster" type="submit" value="$lt{'rost'}" />
    $help{'Course Roster'}
    </span>
    </form>
   NROSTFORM
   
          $r->print(<<ENDFORM);
   
   <ul class="LC_TabContent">
   <li>$lt{'nd'}</li>
   <li>$lt{'pm'}</li>
   <li>$lt{'pubd'}</li>
   <li>$lt{'sd'}</li>
   <li>$lt{'mo'}</li>
   <li>$lt{'hao'}</li>
   </ul>
   
   <table class="LC_docs_adddocs">
   <!-- <tr>
   <th>$lt{'uplm'}</th>
   <th>$lt{'impp'}</th>
   <th>$lt{'spec'}</th>
   </tr> -->
   <tr>
   <td>
   $fileuploadform
   </td>
   <td>
   $simpleeditdefaultform
   <hr />
   $recoverform
   ENDFORM
          unless ($env{'form.pagepath'}) {
      $r->print(<<ENDFORM);
   <hr />
   $extresourcesform
    <br />
   $imspform
   ENDFORM
          }
          $r->print('</td><td>');
          unless ($env{'form.pagepath'}) {
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
   
   
    my $newpageform=(<<NPFORM);
    <form action="/adm/coursedocs" method="post" name="newpage">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newpage" type="button"
    onClick="javascript:makenewpage(this.form,'$pageseq');"
    value="$lt{'newp'}" />$help{'Adding_Pages'}
    </span>
    </form>
   NPFORM
   
    my $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newfolder" type="button"
    onClick="javascript:makenewfolder(this.form,'$folderseq');"
    value="$lt{'newf'}" />$help{'Adding_Folders'}
    </span>
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <span class="LC_nobreak">
    <input name="newsyl" type="submit" value="$lt{'syll'}" />
    $help{'Syllabus'}
    </span>
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <span class="LC_nobreak">
    <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />
    $help{'Group Files'}
    </span>
    </form>
   NGFFORM
   
   
              $r->print(<<ENDFORM);
   <br />
   $newfolderform
   <br />
   $newpageform
   <br />
   $newsylform
   <br />
   $newnavform
   <br />
   $newsmppageform
   <br />
   $newsmpproblemform
   <br />
   $newdropboxform
   <br />
   $newexuploadform
   <br />
   $newbulform
   <br />
   $newaboutmeform
   <br />
   $newaboutsomeoneform
   <br />
   $newgroupfileform
   <br />
   $newrosterform
   ENDFORM
          }
          if ($env{'form.pagepath'}) {
              $r->print(<<ENDBLOCK);
   $newsmpproblemform
   <br />
   $newexuploadform
   ENDBLOCK
          }
          $r->print('</td></tr>'."\n".
   '</table>');
          $r->print('</td></tr>');
       }
   # ----------------------------------------------------- Supplemental documents
       if (!$forcestandard) {
          $r->print('<tr><td class="LC_docs_document">');
   # '<h2>'.&mt('Supplemental Course Documents').
   #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');
          my $folder=$env{'form.folder'};
          unless ($folder=~/^supplemental/) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = 'supplemental&'.
                                       &escape(&mt('Supplemental '.$type.' Documents'));
          }
          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);
          if ($error) {
      $r->print('<p><span class="LC_error">'.$error.'</span></p>');
          }
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
          '.sequence';
   
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $supupdocform=(<<SUPDOCFORM);
    <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">
    $fileupload
    <br />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br /><br />
    $lt{'comment'}:<br />
    <textarea cols=50 rows=4 name='comment'>
    </textarea>
    <br />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="cmd" value="upload_supplemental" />
    <span class="LC_nobreak">
    <input type="submit" value="$lt{'upld'}" />
    $help{'Uploading_From_Harddrive'}
    </span>
    </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newfolder" type="button"
    onClick="javascript:makenewfolder(this.form,'$folderseq');"
    value="$lt{'newf'}" /> $help{'Adding_Folders'}
    </span>
    </form>
   SNFFORM
   
   
    my $supnewextform=(<<SNEFORM);
    <form action="/adm/coursedocs" method="post" name="supnewext">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newext" type="button"
    onClick="javascript:makenewext('supnewext');"
    value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
    </span>
    </form>
   SNEFORM
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail"
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <span class="LC_nobreak">
    <input name="newsyl" type="submit" value="$lt{'syll'}" />
    $help{'Syllabus'}
    </span>
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="subnewaboutme">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail"
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <span class="LC_nobreak">
    <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
    $help{'My Personal Info'}
    </span>
    </form>
   SNAMFORM
   
      $r->print(<<ENDSUPFORM);
   <ul class="LC_TabContent">
   <li>$lt{'nd'}</li>
   <li>$lt{'sd'}</li>
   <li>$lt{'hao'}</li>
   </ul>
   <table class="LC_docs_adddocs">
   <tr><td>
   $supupdocform
   </td>
   <td>
   $supnewfolderform
   <br />
   $supnewextform
   <br />
   $supnewsylform
   <br />
   $supnewaboutmeform
   </td></tr>
   </table></td></tr>
   ENDSUPFORM
          }
       }
       $r->print('</table>');
       if ($allowed) {
    $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" />
     <input type="hidden" name="residx" />
   </form>');
       }
     } else {
         unless ($upload_result eq 'phasetwo') {
   # -------------------------------------------------------- This is showdoc mode
             $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p>'.
   &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
             &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
         }
     }
    }
    $r->print(&Apache::loncommon::end_page());
    return OK;
   }
   
   sub generate_admin_options {
     my ($containertag,$uploadtag,$lt_ref,$help_ref,$env_ref) = @_;
     my %lt = %{$lt_ref};
     my %help = %{$help_ref};
     my %env = %{$env_ref};
     my $dumpbut=&dumpbutton();
     my $exportbut=&exportbutton();
     return (<<ENDOPTIONFORM);
    <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
      <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
      <input type="hidden" name="copyfolder" />
      $containertag
    </form>
    <form name="simpleedit" method="post" action="/adm/coursedocs">
      <input type="hidden" name="importdetail" value="" />
      $uploadtag
    </form>
    <form action="/adm/coursedocs" method="post" name="courseverify">
      <ul style="list-style-type:none">
          <li>
              <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}
          </li>
          <li>
              <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}
          </li>
          <li>
              $dumpbut
          </li>
          <li>
              $exportbut
          </li>
          <li>
             <input type="submit" name="listsymbs" value="$lt{'ls'}" />
           </li>
           <li>
             <input type="hidden" name="folder" value="$env{'form.folder'}" />
             <input type="submit" name="docslog" value="$lt{'sl'}" />
           </li>
      </ul>
    </form>
    <div style="clear: both; height: 0px;">&nbsp;</div>
   ENDOPTIONFORM
   }
   
   sub generate_edit_table {
       my ($optionhash_ref,$namehash_ref,$orderhash_ref) = @_;
       my %optionhash = %{$optionhash_ref};         #id verlinkt mit inhalt
       my %namehash = %{$namehash_ref};             #name verlinkt mit id
       my %orderhash = %{$orderhash_ref};           #name mit kürzel verlinkt mit name
       my $form;
       $form = '<div class="LC_ContentBoxSpecial"><h4 class="LC_hcell">'.&mt('Upload Course Documents').'<h4>';
       $form .= '<ul class="LC_TabContent">';
       foreach my $name (sort(keys(%orderhash))){
           if($name eq 'zz_hide'){
               $form .= '<li><a onclick="hideAllSection();" href="#">'.&mt($orderhash{$name}).'</a></li>';
           }else{
               $form .= '<li><a onclick="popUpSection(\''.$namehash{$orderhash{$name}}.'\');" href="#">'.&mt($orderhash{$name}).'</a></li>';
           }
       }
       foreach my $field (keys(%optionhash)){
           $form .= '<div id="'.$field.'" class="LC_ContentBox LC_hideThis">'.$optionhash{$field}.'</div>';
       }
       $form .= '</div>';
       return $form;
   }
   
   sub editing_js {
       my ($udom,$uname) = @_;
       my $now = time();
       my %lt = &Apache::lonlocal::texthash(
                                             p_mnf => 'Name of New Folder',
                                             t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
                                             t_mnp => 'New Page',
                                             p_mxu => 'Title for the Uploaded Score',
                                             p_msp => 'Title for the Page',
                                             p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Bulletin Board',
                                             p_mab => "Enter user:domain for User's 'About Me' Page",
                                             p_mab2 => "About [_99]",
                                             p_mab_alrt1 => 'Not a valid user:domain',
                                             p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                             p_chn => 'New Title',
                                             p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
                                             p_rmr2a => 'Remove[_99]',
                                             p_rmr2b => '?[_99]',
                                             p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                             p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                             p_ctr2a => 'Cut[_98]',
                                             p_ctr2b => '?[_98]'
                                           );
   
       return <<ENDNEWSCRIPT;
   function makenewfolder(targetform,folderseq) {
       var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
       if (foldername) {
          targetform.importdetail.value=escape(foldername)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makenewpage(targetform,folderseq) {
       var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
       if (pagename) {
           targetform.importdetail.value=escape(pagename)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makenewext(targetname) {
       this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.title.value='';
       this.document.forms.extimport.url.value='';
       this.document.forms.extimport.residx.value='';
       window.open('/adm/rat/extpickframe.html');
   }
   
   function edittext(targetname,residx,title,url) {
       this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.residx.value=residx;
       this.document.forms.extimport.url.value=url;
       this.document.forms.extimport.title.value=title;
       window.open('/adm/rat/extpickframe.html');
   }
   
   function makeexamupload() {
      var title=prompt('$lt{"p_mxu"}');
      if (title) {
       this.document.forms.newexamupload.importdetail.value=
    escape(title)+'=/res/lib/templates/examupload.problem';
       this.document.forms.newexamupload.submit();
      }
   }
   
   function makesmppage() {
      var title=prompt('$lt{"p_msp"}');
      if (title) {
       this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/smppg';
       this.document.forms.newsmppg.submit();
      }
   }
   
   function makesmpproblem() {
      var title=prompt('$lt{"p_msb"}');
      if (title) {
       this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
       this.document.forms.newsmpproblem.submit();
      }
   }
   
   function makedropbox() {
      var title=prompt('$lt{"p_mdb"}');
      if (title) {
       this.document.forms.newdropbox.importdetail.value=
           escape(title)+'=/res/lib/templates/DropBox.problem';
       this.document.forms.newdropbox.submit();
      }
   }
   
   function makebulboard() {
      var title=prompt('$lt{"p_mbb"}');
      if (title) {
       this.document.forms.newbul.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
       this.document.forms.newbul.submit();
      }
   }
   
   function makeabout() {
      var user=prompt("$lt{'p_mab'}");
      if (user) {
          var comp=new Array();
          comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
      if ((comp[0]) && (comp[1])) {
          this.document.forms.newaboutsomeone.importdetail.value=
      '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
          this.document.forms.newaboutsomeone.submit();
      } else {
                  alert("$lt{'p_mab_alrt1'}");
              }
          } else {
              alert("$lt{'p_mab_alrt2'}");
          }
      }
   }
   
   function makeims() {
       var caller = document.forms.ims.folder.value;
       var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
       newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");
       newWindow.location.href = newlocation;
   }
   
   
   function finishpick() {
       var title=this.document.forms.extimport.title.value;
       var url=this.document.forms.extimport.url.value;
       var form=this.document.forms.extimport.useform.value;
       var residx=this.document.forms.extimport.residx.value;
       eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');
   }
   
   function changename(folderpath,index,oldtitle,container,pagesymb) {
       var title=prompt('$lt{"p_chn"}',oldtitle);
       if (title) {
    this.document.forms.renameform.markcopy.value=-1;
    this.document.forms.renameform.title.value=title;
    this.document.forms.renameform.cmd.value='rename_'+index;
           if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {
       if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
    this.document.forms.renameform.markcopy.value=-1;
    this.document.forms.renameform.cmd.value='del_'+index;
           if (container == 'sequence') {
               this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {
       if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
    this.document.forms.renameform.cmd.value='cut_'+index;
    this.document.forms.renameform.markcopy.value=index;
    this.document.forms.renameform.copyfolder.value=folder+'.'+container;
           if (container == 'sequence') {
               this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
       this.document.forms.renameform.markcopy.value=index;
       this.document.forms.renameform.copyfolder.value=folder+'.'+container;
       if (container == 'sequence') {
    this.document.forms.renameform.folderpath.value=folderpath;
       }
       if (container == 'page') {
    this.document.forms.renameform.pagepath.value=folderpath;
    this.document.forms.renameform.pagesymb.value=pagesymb;
       }
       this.document.forms.renameform.submit();
   }
   
   
   ENDNEWSCRIPT
   }
   1;
   __END__
   
   
   =head1 NAME
   
   Apache::londocs.pm
   
   =head1 SYNOPSIS
   
   This is part of the LearningOnline Network with CAPA project
   described at http://www.lon-capa.org.
   
   =head1 SUBROUTINES
   
   =over
   
   =item %help=()
   
   Available help topics
   
   =item mapread()
   
   Mapread read maps into LONCAPA::map:: global arrays
   @order and @resources, determines status
   sets @order - pointer to resources in right order
   sets @resources - array with the resources with correct idx
   
   =item authorhosts()
   
   Return hash with valid author names
   
   =item dumpbutton()
   
   Generate "dump" button
   
   =item clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   
   =item exportbutton()
   
       Generate "export" button
   
   =item exportcourse()
   
   =item create_ims_store()
   
   =item build_package()
   
   =item get_dependencies()
   
   =item process_content()
   
   =item replicate_content()
   
   =item extract_media()
   
   =item store_template()
   
   =item group_import()
   
       Imports the given (name, url) resources into the course
       coursenum, coursedom, and folder must precede the list
   
   =item breadcrumbs()
   
   =item log_docs()
   
   =item docs_change_log()
   
   =item update_paste_buffer()
   
   =item print_paste_buffer()
   
   =item do_paste_from_buffer()
   
   =item update_parameter()
   
   =item handle_edit_cmd()
   
   =item editor()
   
   =item process_file_upload()
   
   =item process_secondary_uploads()
   
   =item is_supplemental_title()
   
   =item parse_supplemental_title()
   
   =item entryline()
   
   =item tiehash()
   
   =item untiehash()
   
   =item checkonthis()
   
   check on this
   
   =item verifycontent()
   
   Verify Content
   
   =item devalidateversioncache() & checkversions()
   
   Check Versions
   
   =item mark_hash_old()
   
   =item is_hash_old()
   
   =item changewarning()
   
   =item init_breadcrumbs()
   
   Breadcrumbs for special functions
   
   =back
   
   =cut

Removed from v.1.203  
changed lines
  Added in v.1.328


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