Diff for /loncom/interface/londocs.pm between versions 1.227 and 1.327

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


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