Diff for /loncom/interface/londocs.pm between versions 1.252 and 1.326

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


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