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

version 1.256, 2006/11/22 14:07:13 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 %lt=('hiddenresource' => 'Resources hidden',  
     'encrypturl'     => 'URL hidden',  
     'randompick'     => 'Randomly pick',  
     'set'            => 'set to',  
     'del'            => 'deleted');  
   sub docs_change_log {
     my $countselect =      my ($r)=@_;
         &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,      my $folder=$env{'form.folder'};
                                     (&mt('all'),10,20,50,100,1000,10000));      $r->print(&Apache::loncommon::start_page('Course Document Change Log'));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));
     $r->print('<nobr>'.&mt('[_1] Records',$countselect).'</nobr>'.      my %docslog=&Apache::lonnet::dump('nohist_docslog',
               '<input type="submit" value="'.&mt('Display').'" /></form>');                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().                                        $env{'course.'.$env{'request.course.id'}.'.num'});
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.  
               &mt('After').'</th>'.      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
               &Apache::loncommon::end_data_table_header_row());  
     my $shown=0;      $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {                '<input type="hidden" name="docslog" value="1" />');
         my @changes=keys(%{$docslog{$id}{'logentry'}});  
         my $count = 0;      my %saveable_parameters = ('show' => 'scalar',);
         my $time =      &Apache::loncommon::store_course_settings('docs_log',
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});                                                \%saveable_parameters);
         my $plainname =      &Apache::loncommon::restore_course_settings('docs_log',
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},                                                  \%saveable_parameters);
                                           $docslog{$id}{'exe_udom'});      if (!$env{'form.show'}) { $env{'form.show'}=10; }
         my $about_me_link =      my %lt=('hiddenresource' => 'Resources hidden',
             &Apache::loncommon::aboutmewrapper($plainname,      'encrypturl'     => 'URL hidden',
                                                $docslog{$id}{'exe_uname'},      'randompick'     => 'Randomly pick',
                                                $docslog{$id}{'exe_udom'});      'randomorder'    => 'Randomly ordered',
         my $send_msg_link='';      'set'            => 'set to',
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})      'del'            => 'deleted');
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {      $r->print(&Apache::loncommon::display_filter().
             $send_msg_link ='<br />'.                '<input type="hidden" name="folder" value="'.$folder.'" />'.
                 &Apache::loncommon::messagewrapper(&mt('Send message'),                '<input type="submit" value="'.&mt('Display').'" /></form>');
                                                    $docslog{$id}{'exe_uname'},      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
                                                    $docslog{$id}{'exe_udom'});                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
         }                &mt('After').'</th>'.
         $r->print(&Apache::loncommon::start_data_table_row());                &Apache::loncommon::end_data_table_header_row());
         $r->print('<td>'.$time.'</td>      my $shown=0;
                        <td>'.$about_me_link.      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.   if ($env{'form.displayfilter'} eq 'currentfolder') {
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
                   $send_msg_link.'</td><td>'.   }
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');          my @changes=keys(%{$docslog{$id}{'logentry'}});
 # Before          if ($env{'form.displayfilter'} eq 'containing') {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];      foreach my $key (@changes) {
     if ($oldname ne $newname) {   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
  $r->print(&LONCAPA::map::qtescape($oldname));      }
     }      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }        
  }   }
  $r->print('<ul>');          my $count = 0;
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          my $time =
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');          my $plainname =
     }              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
  }                                            $docslog{$id}{'exe_udom'});
  $r->print('</ul>');          my $about_me_link =
 # After              &Apache::loncommon::aboutmewrapper($plainname,
         $r->print('</td><td>');                                                 $docslog{$id}{'exe_uname'},
                                                  $docslog{$id}{'exe_udom'});
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          my $send_msg_link='';
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
     if ($oldname ne $newname) {              $send_msg_link ='<br />'.
  $r->print(&LONCAPA::map::qtescape($newname));                  &Apache::loncommon::messagewrapper(&mt('Send message'),
     }                                                     $docslog{$id}{'exe_uname'},
  }                                                             $docslog{$id}{'exe_udom'});
  $r->print('<ul>');          }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          $r->print(&Apache::loncommon::start_data_table_row());
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {          $r->print('<td>'.$time.'</td>
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');                         <td>'.$about_me_link.
     }                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
  }                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
  $r->print('</ul>');                    $send_msg_link.'</td><td>'.
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');  # Before
     foreach my $parameter ('randompick','hiddenresource','encrypturl') {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     $r->print('<li>'.      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',      if ($oldname ne $newname) {
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})   $r->print(&LONCAPA::map::qtescape($oldname));
       .'</li>');      }
  }   }
     }   $r->print('<ul>');
     $r->print('</ul>');   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  }              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
 # End   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());      }
         $shown++;   }
         if (!($env{'form.show'} eq &mt('all')   $r->print('</ul>');
               || $shown<=$env{'form.show'})) { last; }  # After
     }          $r->print('</td><td>');
     $r->print(&Apache::loncommon::end_data_table());  
     $r->print(&Apache::loncommon::end_page());   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 }      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
       my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
 sub editor {      if ($oldname ne '' && $oldname ne $newname) {
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output)=@_;   $r->print(&LONCAPA::map::qtescape($newname));
     my $errtext='';      }
     my $fatal=0;   }        
     my $container='sequence';   $r->print('<ul>');
     if ($env{'form.pagepath'}) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
         $container='page';              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
     }   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
     ($errtext,$fatal)=      }
               &mapread($coursenum,$coursedom,$folder.'.'.$container);   }
     if ($#LONCAPA::map::order<1) {   $r->print('</ul>');
  my $idx=&LONCAPA::map::getresidx();   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
  if ($idx<=0) { $idx=1; }      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
         $LONCAPA::map::order[0]=$idx;      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
         $LONCAPA::map::resources[$idx]='';   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
     }      $r->print('<li>'.
     if (defined($env{'form.markcopy'})) {        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
 # Mark for copying    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
  my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);        .'</li>');
  $env{'form.markedcopy_title'}=$title;   }
  $env{'form.markedcopy_url'}=$url;      }
     }      $r->print('</ul>');
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain)=&breadcrumbs($folder);   }
     $r->print($breadcrumbtrail);  # End
     if ($fatal) {          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
    $r->print('<p><font color="red">'.$errtext.'</font></p>');          $shown++;
     } else {          if (!($env{'form.show'} eq &mt('all')
 # ------------------------------------------------------------ Process commands                || $shown<=$env{'form.show'})) { last; }
       }
 # ---------------- if they are for this folder and user allowed to make changes      $r->print(&Apache::loncommon::end_data_table());
  if (($allowed) && ($env{'form.folder'} eq $folder)) {  }
 # set parameters and change order  
             &snapshotbefore();  sub update_paste_buffer {
     if ($env{'form.changeparms'}) {      my ($coursenum,$coursedom) = @_;
  my $idx=$env{'form.setparms'};  
 # set parameters      return if (!defined($env{'form.markcopy'}));
  if ($env{'form.randpick_'.$idx}) {      return if (!defined($env{'form.copyfolder'}));
     &LONCAPA::map::storeparameter($idx,'parameter_randompick',$env{'form.randpick_'.$idx},'int_pos');      return if ($env{'form.markcopy'} < 0);
                     &remember_parms($idx,'randompick','set',$env{'form.randpick_'.$idx});  
  } else {      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
     &LONCAPA::map::delparameter($idx,'parameter_randompick');      $env{'form.copyfolder'});
                     &remember_parms($idx,'randompick','del');     
  }      return if ($fatal);
  if ($env{'form.hidprs_'.$idx}) {  
     &LONCAPA::map::storeparameter($idx,'parameter_hiddenresource','yes','string_yesno');  # Mark for copying
                     &remember_parms($idx,'hiddenresource','set',$env{'form.hidprs_'.$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_hiddenresource');          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
                     &remember_parms($idx,'hiddenresource','del');   ($title) = &parse_supplemental_title($title);
   }      } elsif ($env{'docs.markedcopy_supplemental'}) {
  if ($env{'form.encprs_'.$idx}) {          &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');
     &LONCAPA::map::storeparameter($idx,'parameter_encrypturl','yes','string_yesno');      }
                     &remember_parms($idx,'encrypturl','set',$env{'form.encprs_'.$idx});      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
   } else {  
     &LONCAPA::map::delparameter($idx,'parameter_encrypturl');      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
                     &remember_parms($idx,'encrypturl','del');      'docs.markedcopy_url'   => $url});
   }      delete($env{'form.markcopy'});
 # store the changed version  }
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);  
  if ($fatal) {  sub print_paste_buffer {
     $r->print('<p><font color="red">'.$errtext.'</font></p>');      my ($r,$container) = @_;
     return;      return if (!defined($env{'docs.markedcopy_url'}));
  }  
     }      $r->print(<<ENDPASTE);
   <form name="pasteform" action="/adm/coursedocs" method="post"><p>
     if ($env{'form.newpos'}) {  ENDPASTE
 # change order      $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');
  my $newpos=$env{'form.newpos'}-1;  
  my $currentpos=$env{'form.currentpos'}-1;      my $type;
  my $i;      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
  my @neworder=();   $type = &mt('External Resource');
  if ($newpos>$currentpos) {   $r->print($type.': '.
 # moving stuff up    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
     for ($i=0;$i<$currentpos;$i++) {    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
  $neworder[$i]=$LONCAPA::map::order[$i];      }  else {
     }   my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
     for ($i=$currentpos;$i<$newpos;$i++) {   my $icon = &Apache::loncommon::icon($extension);
  $neworder[$i]=$LONCAPA::map::order[$i+1];   if ($extension eq 'sequence' &&
     }      $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
     $neworder[$newpos]=$LONCAPA::map::order[$currentpos];      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     for ($i=$newpos+1;$i<=$#LONCAPA::map::order;$i++) {      $icon .= '/folder_closed.gif';
  $neworder[$i]=$LONCAPA::map::order[$i];   }
     }   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
  } else {   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
 # moving stuff down      }
     for ($i=0;$i<$newpos;$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'},'<>&"').'" />
     $neworder[$newpos]=$LONCAPA::map::order[$currentpos];   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
     for ($i=$newpos+1;$i<$currentpos+1;$i++) {  ');
  $neworder[$i]=$LONCAPA::map::order[$i-1];      } else {
     }   $r->print('
     for ($i=$currentpos+1;$i<=$#LONCAPA::map::order;$i++) {          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
  $neworder[$i]=$LONCAPA::map::order[$i];  ');
     }      }
  }      $r->print('</p></form>');
  @LONCAPA::map::order=@neworder;  }
 # store the changed version  
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);  sub do_paste_from_buffer {
  if ($fatal) {      my ($coursenum,$coursedom,$folder) = @_;
     $r->print('<p><font color="red">'.$errtext.'</font></p>');  
     return;      if (!$env{'form.pastemarked'}) {
  }          return;
     }      }
   
     if ($env{'form.pastemarked'}) {  # paste resource to end of list
 # paste resource to end of list      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
                 my $url=$env{'form.markedcopy_url'};      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
  my $title=$env{'form.markedcopy_title'};  # Maps need to be copied first
 # Maps need to be copied first      if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
  if (($url=~/\.(page|sequence)$/) || ($url=~/^\/uploaded\//)) {   $title=&mt('Copy of').' '.$title;
     $title=&mt('Copy of').' '.$title;   my $newid=$$.int(rand(100)).time;
                     my $newid=$$.time;   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
     $url=~/^(.+)\.(\w+)$/;          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
     my $newurl=$1.$newid.'.'.$2;              my $path = $1;
     my $storefn=$newurl;              my $prefix = $2;
                     $storefn=~s/^\/\w+\/\w+\/\w+\///;              my $ancestor = $3;
     &Apache::lonclonecourse::writefile              if (length($ancestor) > 10) {
  ($env{'request.course.id'},$storefn,                  $ancestor = substr($ancestor,-10,10);
  &Apache::lonnet::getfile($url));              }
     $url=$newurl;              $oldid = $path.$prefix.$ancestor;
  }          }
  $title=~s/\</\&lt\;/g;          my $counter = 0;
  $title=~s/\>/\&gt\;/g;          my $newurl=$oldid.$newid.'.'.$ext;
  $title=~s/\:/\&colon;/g;          my $is_unique = &uniqueness_check($newurl);
  my $ext='false';          while (!$is_unique && $counter < 100) {
  if ($url=~/^http\:\/\//) { $ext='true'; }              $counter ++;
  $url=~s/\:/\&colon;/g;              $newid ++;
 # Now insert the URL at the bottom              $newurl = $oldid.$newid;
                 my $newidx=&LONCAPA::map::getresidx($url);              $is_unique = &uniqueness_check($newurl);
  $LONCAPA::map::resources[$newidx]=          }
     $title.':'.$url.':'.$ext.':normal:res';          if (!$is_unique) {
  $LONCAPA::map::order[1+$#LONCAPA::map::order]=$newidx;              if ($url=~/\.page$/) {
 # Store the result                  return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);              } else {
  if ($fatal) {                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
     $r->print('<p><font color="red">'.$errtext.'</font></p>');              }
     return;          }
  }   my $storefn=$newurl;
    $storefn=~s{^/\w+/$match_domain/$match_username/}{};
     }   my $paste_map_result =
             $r->print($upload_output);              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
     if ($env{'form.cmd'}) {         &Apache::lonnet::getfile($url));
                 my ($cmd,$idx)=split(/\_/,$env{'form.cmd'});          if ($paste_map_result eq '/adm/notfound.html') {
                 if ($cmd eq 'del') {              if ($url=~/\.page$/) {
     my (undef,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$idx]]);                  return &mt('Paste failed: an error occurred saving the composite page');
     if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&              } else {
  ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {                  return &mt('Paste failed: an error occurred saving the folder');
  &Apache::lonnet::removeuploadedurl($url);              }
     } else {          }
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);   $url = $newurl;
     }      }
     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 'cut') {      if ($url=~ m{/smppg$}) {
     my (undef,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$idx]]);   my $db_name = &Apache::lonsimplepage::get_db_name($url);
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);   if ($db_name =~ /^smppage_/) {
     for (my $i=$idx;$i<$#LONCAPA::map::order;$i++) {      #simple pages, need to copy the db contents to a new one.
                         $LONCAPA::map::order[$i] = $LONCAPA::map::order[$i+1];      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
                     }      my $now = time();
                     $#LONCAPA::map::order--;      $db_name =~ s{_\d*$ }{_$now}x;
                 } elsif ($cmd eq 'up') {      my $result=&Apache::lonnet::put($db_name,\%contents,
   if (($idx) && (defined($LONCAPA::map::order[$idx-1]))) {      $coursedom,$coursenum);
                     my $i=$LONCAPA::map::order[$idx-1];      $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
                     $LONCAPA::map::order[$idx-1] = $LONCAPA::map::order[$idx];      $title=&mt('Copy of').' '.$title;
                     $LONCAPA::map::order[$idx] = $i;   }
    }      }
                 } elsif ($cmd eq 'down') {      $title = &LONCAPA::map::qtunescape($title);
    if (defined($LONCAPA::map::order[$idx+1])) {      my $ext='false';
                     my $i=$LONCAPA::map::order[$idx+1];      if ($url=~m{^http(|s)://}) { $ext='true'; }
                     $LONCAPA::map::order[$idx+1] = $LONCAPA::map::order[$idx];      $url       = &LONCAPA::map::qtunescape($url);
                     $LONCAPA::map::order[$idx] = $i;  # Now insert the URL at the bottom
    }      my $newidx = &LONCAPA::map::getresidx($url);
                 } elsif ($cmd eq 'rename') {      if ($env{'docs.markedcopy_supplemental'}) {
                     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];          if ($folder =~ /^supplemental/) {
                     my ($rtitle,@rrest)=split(/\:/,              $title = $env{'docs.markedcopy_supplemental'};
                        $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]);          } else {
                     my $comment=              (undef,undef,$title) =
                      &HTML::Entities::decode($env{'form.title'});                  &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
                     $comment=~s/\</\&lt\;/g;          }
                     $comment=~s/\>/\&gt\;/g;      } else {
                     $comment=~s/\:/\&colon;/g;          if ($folder=~/^supplemental/) {
     if ($comment=~/\S/) {             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=                    $env{'user.domain'}.'___&&&___'.$title;
     $comment.':'.join(':',@rrest);          }
     }      }
 # Devalidate title cache  
                     my $renamed_url=$rrest[0];      $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
 # Has the &colon;-escaping      push(@LONCAPA::map::order, $newidx);
                     $renamed_url=~s/\&colon\;/\:/g;      return 'ok';
     &Apache::lonnet::devalidate_title_cache($renamed_url);  # Store the result
                 }  }
 # Store the changed version  
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,  sub uniqueness_check {
     $folder.'.'.$container);      my ($newurl) = @_;
  if ($fatal) {      my $unique = 1;
     $r->print('<p><font color="red">'.$errtext.'</font></p>');      foreach my $res (@LONCAPA::map::order) {
     return;          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
  }          $url=&LONCAPA::map::qtescape($url);
             }          if ($newurl eq $url) {
 # Group import/search              $unique = 0;
     if ($env{'form.importdetail'}) {              last;    
  my @imports;          }
 # &Apache::lonnet::logthis("imp detail ".$env{'form.importdetail'});      }
  foreach (split(/\&/,$env{'form.importdetail'})) {      return $unique;
     if (defined($_)) {  }
  my ($name,$url)=split(/\=/,$_);  
  $name=&unescape($name);  my %parameter_type = ( 'randompick'     => 'int_pos',
  $url=&unescape($url);         'hiddenresource' => 'string_yesno',
  push @imports, $name, $url;         'encrypturl'     => 'string_yesno',
     }         'randomorder'    => 'string_yesno',);
  }  my $valid_parameters_re = join('|',keys(%parameter_type));
 # Store the changed version  # set parameters
  ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,  sub update_parameter {
        $container,'londocs',@imports);  
  if ($fatal) {      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     $r->print('<p><font color="red">'.$errtext.'</font></p>');  
     return;      my $which = $env{'form.changeparms'};
  }      my $idx = $env{'form.setparms'};
             }      if ($env{'form.'.$which.'_'.$idx}) {
 # Loading a complete map   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
    if ($env{'form.loadmap'}) {                                       : 'yes';
                if ($env{'form.importmap'}=~/\w/) {   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
           foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {        $parameter_type{$which});
       my ($title,$url,$ext,$type)=split(/\:/,$_);   &remember_parms($idx,$which,'set',$value);
                       my $idx=&LONCAPA::map::getresidx($url);      } else {
                       $LONCAPA::map::resources[$idx]=$_;   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
                       $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;  
           }   &remember_parms($idx,$which,'del');
 # Store the changed version      }
            ($errtext,$fatal)=&storemap($coursenum,$coursedom,      return 1;
    $folder.'.'.$container);  }
           if ($fatal) {  
       $r->print('<p><font color="red">'.$errtext.'</font></p>');  
       return;  sub handle_edit_cmd {
           }      my ($coursenum,$coursedom) =@_;
                } else {  
                    $r->print('<p><font color="red">'.&mt('No map selected.').'</font></p>');      my ($cmd,$idx)=split('_',$env{'form.cmd'});
                }  
            }      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
            &log_differences($plain);      my ($title, $url, @rrest) = split(':', $ratstr);
        }  
 # ---------------------------------------------------------------- End commands      if ($cmd eq 'del') {
 # ---------------------------------------------------------------- Print screen   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
         my $idx=0;      ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
  my $shown=0;      &Apache::lonnet::removeuploadedurl($url);
         if (($ishidden) || ($isencrypted) || ($randompick>=0)) {   } else {
            $r->print('<p>'.&mt('Parameters').':<ul>'.      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
                      ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').   }
                      ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').   splice(@LONCAPA::map::order, $idx, 1);
                      ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').  
                      '</ul></p>');      } elsif ($cmd eq 'cut') {
         }                                                                                                        &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
         if ($randompick>=0) {   splice(@LONCAPA::map::order, $idx, 1);
            $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>');  
         }      } elsif ($cmd eq 'up'
         $r->print('<table>');       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
         foreach (@LONCAPA::map::order) {   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
            my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$_]);  
    $name=&LONCAPA::map::qtescape($name);      } elsif ($cmd eq 'down'
    $url=&LONCAPA::map::qtescape($url);       && defined($LONCAPA::map::order[$idx+1])) {
            unless ($name) {  $name=(split(/\//,$url))[-1]; }   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
            unless ($name) { $idx++; next; }  
            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));      } elsif ($cmd eq 'rename') {
            $idx++;  
    $shown++;   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
         }   if ($comment=~/\S/) {
  unless ($shown) {      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
     $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');   $comment.':'.join(':', $url, @rrest);
  }   }
         $r->print("\n</table>\n");  # Devalidate title cache
  if ($env{'form.markedcopy_url'}) {   my $renamed_url=&LONCAPA::map::qtescape($url);
     $r->print(<<ENDPASTE);   &Apache::lonnet::devalidate_title_cache($renamed_url);
 <p><form name="pasteform" action="/adm/coursedocs" method="post">      } else {
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />   return 0;
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      }
 ENDPASTE      return 1;
             $r->print(  }
    '<input type="submit" name="pastemarked" value="'.&mt('Paste').  
       '" /> '.&Apache::loncommon::filedescription(  sub editor {
  (split(/\./,$env{'form.markedcopy_url'}))[-1]).': '.      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;
       $env{'form.markedcopy_title'});  
             if ($container eq 'page') {      my $container= ($env{'form.pagepath'}) ? 'page'
  $r->print(<<PAGEINFO);                             : 'sequence';
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />  
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 PAGEINFO      $folder.'.'.$container);
             } else {      return $errtext if ($fatal);
  $r->print(<<FOLDERINFO);  
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      if ($#LONCAPA::map::order<1) {
 FOLDERINFO   my $idx=&LONCAPA::map::getresidx();
     }   if ($idx<=0) { $idx=1; }
     $r->print('</form></p>');          $LONCAPA::map::order[0]=$idx;
  }          $LONCAPA::map::resources[$idx]='';
     }      }
 }     
       my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=
 sub process_file_upload {   &breadcrumbs($folder,$allowed,$type);
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;      $r->print($breadcrumbtrail);
 # upload a file, if present     
     my $parseaction;  # ------------------------------------------------------------ Process commands
    if ($env{'form.parserflag'}) {  
         $parseaction = 'parse';  # ---------------- if they are for this folder and user allowed to make changes
     }      if (($allowed) && ($env{'form.folder'} eq $folder)) {
     my $phase_status;  # set parameters and change order
     my $folder=$env{'form.folder'};   &snapshotbefore();
     if ($folder eq '') {  
         $folder='default';   if (&update_parameter()) {
     }      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {      return $errtext if ($fatal);
         my $errtext='';   }
         my $fatal=0;  
         my $container='sequence';   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
         if ($env{'form.pagepath'}) {  # change order
             $container='page';      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
         }      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
         ($errtext,$fatal)=  
               &mapread($coursenum,$coursedom,$folder.'.'.$container);      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
         if ($#LONCAPA::map::order<1) {      return $errtext if ($fatal);
             $LONCAPA::map::order[0]=1;   }
             $LONCAPA::map::resources[1]='';      
         }   if ($env{'form.pastemarked'}) {
         if ($fatal) {              my $paste_res =
             return 'failed';                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
         }              if ($paste_res eq 'ok') {
         my $destination = 'docs/';                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
         if ($folder =~ /^supplemental/) {                  return $errtext if ($fatal);
             $destination = 'supplemental/';              } elsif ($paste_res ne '') {
         }                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
         if (($folder eq 'default') || ($folder eq 'supplemental')) {              }
             $destination .= 'default/';   }
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {  
             $destination .=  $2.'/';   $r->print($upload_output);
         }  
 # this is for a course, not a user, so set coursedoc flag   if (&handle_edit_cmd()) {
 # probably the only place in the system where this should be "1"      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
         my $newidx=&LONCAPA::map::getresidx();      return $errtext if ($fatal);
         $destination .= $newidx;   }
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,  # Group import/search
  $parseaction,$allfiles,   if ($env{'form.importdetail'}) {
  $codebase);      my @imports;
         my $ext='false';      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
         if ($url=~/^http\:\/\//) { $ext='true'; }   if (defined($item)) {
         $url=~s/\:/\&colon;/g;      my ($name,$url,$residx)=
         my $comment=$env{'form.comment'};   map {&unescape($_)} split(/\=/,$item);
         $comment=~s/\</\&lt\;/g;      push(@imports, [$name, $url, $residx]);
         $comment=~s/\>/\&gt\;/g;   }
         $comment=~s/\:/\&colon;/g;      }
         if ($folder=~/^supplemental/) {      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.      $container,'londocs',@imports);
                   $env{'user.domain'}.'___&&&___'.$comment;      return $errtext if ($fatal);
         }   }
   # Loading a complete map
         $LONCAPA::map::resources[$newidx]=   if ($env{'form.loadmap'}) {
     $comment.':'.$url.':'.$ext.':normal:res';      if ($env{'form.importmap'}=~/\w/) {
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,      my ($title,$url,$ext,$type)=split(/\:/,$res);
     $folder.'.'.$container);      my $idx=&LONCAPA::map::getresidx($url);
         if ($fatal) {      $LONCAPA::map::resources[$idx]=$res;
             $$upload_output .= '<p><font color="red">'.$errtext.'</font></p>';      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
             return 'failed';   }
         } else {   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
             if ($parseaction eq 'parse') {      $folder.'.'.$container);
                 my $total_embedded = keys(%{$allfiles});   return $errtext if ($fatal);
                 if ($total_embedded > 0) {      } else {
                     my $num = 0;   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
                     $$upload_output .= 'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />  
    <form name="upload_embedded" action="/adm/coursedocs"      }
                   method="post" enctype="multipart/form-data">   }
    <input type="hidden" name="folderpath" value="'.$env{'form.folderpath'}.'" />   <input type="hidden" name="cmd" value="upload_embedded" />   &log_differences($plain);
    <input type="hidden" name="newidx" value="'.$newidx.'" />      }
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />  # ---------------------------------------------------------------- End commands
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';  # ---------------------------------------------------------------- Print screen
                     $$upload_output .= '<b>Upload embedded files</b>:<br />      my $idx=0;
    <table>';      my $shown=0;
                     foreach my $embed_file (keys(%{$allfiles})) {      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
                         $$upload_output .= '<tr><td>'.$embed_file.   $r->print('<p>'.&mt('Parameters').':<ul>'.
           '<input name="embedded_item_'.$num.'" type="file" />    ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
                         my $attrib;    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
                         if (@{$$allfiles{$embed_file}} > 1) {    '</ul></p>');
                             $attrib = join(':',@{$$allfiles{$embed_file}});      }                                                                                                    
                         } else {      if ($randompick>=0) {
                             $attrib = $$allfiles{$embed_file}[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 .=      if ($is_random_order) {
            '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.$attrib.'" />';   $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>');
                         if (exists($$codebase{$embed_file})) {      }
                             $$upload_output .=       $r->print('<table class="LC_docs_editor">');
           '<input name="codebase_'.$num.'" type="hidden" value="'.&escape($$codebase{$embed_file}).'" />';      foreach my $res (@LONCAPA::map::order) {
                         }   my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
                         $$upload_output .= '</td></tr>';   $name=&LONCAPA::map::qtescape($name);
                         $num ++;   $url=&LONCAPA::map::qtescape($url);
                     }   unless ($name) {  $name=(split(/\//,$url))[-1]; }
                     $phase_status = 'phasetwo';   unless ($name) { $idx++; next; }
                     $$upload_output .= '</table><br />   $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,
    <input type ="submit" value="Complete upload" />       $coursenum));
    </form>';   $idx++;
                 } else {   $shown++;
                     $$upload_output .= 'No embedded items identified<br />';      }
                 }      unless ($shown) {
             }   $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
         }      }
     }      $r->print("\n</table>\n");
     return $phase_status;      if ($allowed) {
 }          &print_paste_buffer($r,$container);
       }
 sub process_secondary_uploads {      return;
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;  }
     my $folder=$env{'form.folder'};  
     my $destination = 'docs/';  sub process_file_upload {
     if ($folder =~ /^supplemental/) {      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
         $destination = 'supplemental/';  # upload a file, if present
     }      my $parseaction;
     if (($folder eq 'default') || ($folder eq 'supplemental')) {     if ($env{'form.parserflag'}) {
         $destination .= 'default/';          $parseaction = 'parse';
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {      }
         $destination .=  $2.'/';      my $phase_status;
     }      my $folder=$env{'form.folder'};
     $destination .= $newidx;      if ($folder eq '') {
     my ($url,$filename);          $folder='default';
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);      }
     ($filename) = ($url =~ m-^/uploaded/$coursedom/$coursenum/$destination/(.+)$-);      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
     return $filename;          my $errtext='';
 }          my $fatal=0;
           my $container='sequence';
 # --------------------------------------------------------------- An entry line          if ($env{'form.pagepath'}) {
               $container='page';
 sub entryline {          }
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;          ($errtext,$fatal)=
     $title=~s/\&colon\;/\:/g;                &mapread($coursenum,$coursedom,$folder.'.'.$container);
     $title=&HTML::Entities::encode(&HTML::Entities::decode(          if ($#LONCAPA::map::order<1) {
      &unescape($title)),'"<>&\'');              $LONCAPA::map::order[0]=1;
     my $renametitle=$title;              $LONCAPA::map::resources[1]='';
     my $foldertitle=$title;          }
     my $pagetitle=$title;          if ($fatal) {
     my $orderidx=$LONCAPA::map::order[$index];              return 'failed';
     if ($title=~ /^(\d+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(.*)$/ ) {           }
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);          my $destination = 'docs/';
  $renametitle=$4;          if ($folder =~ /^supplemental/) {
  $title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.              $destination = 'supplemental/';
     &Apache::loncommon::plainname($2,$3).': <br />'.          }
     $foldertitle;          if (($folder eq 'default') || ($folder eq 'supplemental')) {
     }              $destination .= 'default/';
     $renametitle=~s/\\/\\\\/g;          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
     $renametitle=~s/\&quot\;/\\\"/g;              $destination .=  $2.'/';
     my $line='<tr>';          }
 # Edit commands  # this is for a course, not a user, so set coursedoc flag
     my $container;  # probably the only place in the system where this should be "1"
     my $folderpath;          my $newidx=&LONCAPA::map::getresidx();
     if ($env{'form.folderpath'}) {          $destination .= $newidx;
         $container = 'sequence';          my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
  $folderpath=&escape($env{'form.folderpath'});   $parseaction,$allfiles,
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');   $codebase);
     }          my $ext='false';
     my ($pagepath,$pagesymb);          if ($url=~m{^http://}) { $ext='true'; }
     if ($env{'form.pagepath'}) {   $url     = &LONCAPA::map::qtunescape($url);
         $container = 'page';          my $comment=$env{'form.comment'};
         $pagepath=&escape($env{'form.pagepath'});   $comment = &LONCAPA::map::qtunescape($comment);
         $pagesymb=&escape($env{'form.pagesymb'});          if ($folder=~/^supplemental/) {
     }                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     my $cpinfo='';                    $env{'user.domain'}.'___&&&___'.$comment;
     if ($env{'form.markedcopy_url'}) {          }
        $cpinfo='&markedcopy_url='.  
                &escape($env{'form.markedcopy_url'}).          $LONCAPA::map::resources[$newidx]=
                '&markedcopy_title='.      $comment.':'.$url.':'.$ext.':normal:res';
                &escape($env{'form.markedcopy_title'});          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     }          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     if ($allowed) {      $folder.'.'.$container);
  my $incindex=$index+1;          if ($fatal) {
  my $selectbox='';              $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';
  if (($folder!~/^supplemental/) &&              return 'failed';
     ($#LONCAPA::map::order>0) &&           } else {
     ((split(/\:/,              if ($parseaction eq 'parse') {
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]                   my $total_embedded = keys(%{$allfiles});
      ne '') &&                   if ($total_embedded > 0) {
     ((split(/\:/,                      my $num = 0;
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]       my $state = '
      ne '')) {     <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
     $selectbox=     <input type="hidden" name="cmd" value="upload_embedded" />
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.     <input type="hidden" name="newidx" value="'.$newidx.'" />
  '<select name="newpos" onChange="this.form.submit()">';     <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {     <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
  if ($i==$incindex) {      $phase_status = 'phasetwo';
     $selectbox.='<option value="" selected="1">('.$i.')</option>';  
  } else {                      $$upload_output .=
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';   'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.
  }   &Apache::loncommon::ask_for_embedded_content(
     }                              '/adm/coursedocs',$state,$allfiles,$codebase);
     $selectbox.='</select>';                  } else {
  }                      $$upload_output .= 'No embedded items identified<br />';
  my %lt=&Apache::lonlocal::texthash(                  }
                 'up' => 'Move Up',              }
  'dw' => 'Move Down',          }
  'rm' => 'Remove',      }
                 'ct' => 'Cut',      return $phase_status;
  'rn' => 'Rename',  }
  'cp' => 'Copy');  
  my $nocopy=0;  sub process_secondary_uploads {
         if ($url=~/\.(page|sequence)$/) {      my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
     foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url))) {      my $folder=$env{'form.folder'};
  my ($title,$url,$ext,$type)=split(/\:/,$_);      my $destination = 'docs/';
  if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {      if ($folder =~ /^supplemental/) {
     $nocopy=1;          $destination = 'supplemental/';
     last;      }
  }      if (($folder eq 'default') || ($folder eq 'supplemental')) {
     }          $destination .= 'default/';
  }      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
         my $copylink='&nbsp;';          $destination .=  $2.'/';
         if ($env{'form.pagepath'}) {      }
            unless ($nocopy) {      $destination .= $newidx;
                $copylink=(<<ENDCOPY);      my ($url,$filename);
 <a href='javascript:markcopy("$pagepath","$index","$renametitle","page","$pagesymb");'>      $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>      ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});
 ENDCOPY      return $filename;
             }  }
             $line.=(<<END);  
 <form name="entry_$index" action="/adm/coursedocs" method="post">  sub is_supplemental_title {
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />      my ($title) = @_;
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />  }
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />  
 <input type="hidden" name="setparms" value="$orderidx" />  sub parse_supplemental_title {
 <input type="hidden" name="changeparms" value="0" />      my ($title) = @_;
 <td><table border='0' cellspacing='2' cellpadding='0'>  
 <tr><td bgcolor="#DDDDDD">      my ($foldertitle,$renametitle);
 <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>      if ($title =~ /&amp;&amp;&amp;/) {
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>   $title = &HTML::Entites::decode($title);
 <tr><td bgcolor="#DDDDDD">      }
 <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>   $renametitle=$4;
 </table></td>   my ($time,$uname,$udom) = ($1,$2,$3);
 <td>$selectbox   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
 </td><td bgcolor="#DDDDDD">   my $name =  &Apache::loncommon::plainname($uname,$udom);
 <a href='javascript:removeres("$pagepath","$index","$renametitle","page","$pagesymb");'>   $name = &HTML::Entities::encode($name,'"<>&\'');
 <font size="-2" color="#990000">$lt{'rm'}</font></a>   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
 <a href='javascript:cutres("$pagepath","$index","$renametitle","page","$pagesymb");'>      $name.': <br />'.$foldertitle;
 <font size="-2" color="#550044">$lt{'ct'}</font></a>      }
 <a href='javascript:changename("$pagepath","$index","$renametitle","page","$pagesymb");'>      if (wantarray) {
 <font size="-2" color="#009900">$lt{'rn'}</font></a>   return ($title,$foldertitle,$renametitle);
 $copylink      }
 END      return $title;
         } else {  }
            unless ($nocopy) {  
                $copylink=(<<ENDCOPY);  # --------------------------------------------------------------- An entry line
 <a href='javascript:markcopy("$folderpath","$index","$renametitle","sequence");'>  
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>  sub entryline {
 ENDCOPY      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
             }  
             $line.=(<<END);       my ($foldertitle,$pagetitle,$renametitle);
 <form name="entry_$index" action="/adm/coursedocs" method="post">      if (&is_supplemental_title($title)) {
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />   $pagetitle = $foldertitle;
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      } else {
 <input type="hidden" name="setparms" value="$orderidx" />   $title=&HTML::Entities::encode($title,'"<>&\'');
 <input type="hidden" name="changeparms" value="0" />   $renametitle=$title;
 <td><table border='0' cellspacing='2' cellpadding='0'>   $foldertitle=$title;
 <tr><td bgcolor="#DDDDDD">   $pagetitle=$title;
 <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath$cpinfo'>      }
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>  
 <tr><td bgcolor="#DDDDDD">      my $orderidx=$LONCAPA::map::order[$index];
 <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath$cpinfo'>     
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>  
 </table></td>      $renametitle=~s/\\/\\\\/g;
 <td>$selectbox      $renametitle=~s/\&quot\;/\\\"/g;
 </td><td bgcolor="#DDDDDD">      $renametitle=~s/ /%20/g;
 <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>      my $line='<tr>';
 <font size="-2" color="#990000">$lt{'rm'}</font></a>      my ($form_start,$form_end);
 <a href='javascript:cutres("$folderpath","$index","$renametitle","sequence");'>  # Edit commands
 <font size="-2" color="#550044">$lt{'ct'}</font></a>      my ($container, $type, $esc_path, $path, $symb);
 <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>      if ($env{'form.folderpath'}) {
 <font size="-2" color="#009900">$lt{'rn'}</font></a>   $type = 'folder';
 $copylink          $container = 'sequence';
 END   $esc_path=&escape($env{'form.folderpath'});
         }   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
     }   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 # Figure out what kind of a resource this is      }
     my ($extension)=($url=~/\.(\w+)$/);      if ($env{'form.pagepath'}) {
     my $uploaded=($url=~/^\/*uploaded\//);          $type = $container = 'page';
     my $icon=&Apache::loncommon::icon($url);          $esc_path=&escape($path = $env{'form.pagepath'});
     my $isfolder=0;   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
     my $ispage=0;          $symb=&escape($env{'form.pagesymb'});
     my $folderarg;      }
     my $pagearg;      my $cpinfo='';
     my $pagefile;      if ($allowed) {
     if ($uploaded) {   my $incindex=$index+1;
  if ($extension eq 'sequence') {   my $selectbox='';
     $icon=$iconpath.'/folder_closed.gif';   if (($folder!~/^supplemental/) &&
     $url=~/$coursenum\/([\/\w]+)\.sequence$/;      ($#LONCAPA::map::order>0) &&
     $url='/adm/coursedocs?';      ((split(/\:/,
     $folderarg=$1;       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
     $isfolder=1;       ne '') &&
         } elsif ($extension eq 'page') {      ((split(/\:/,
             $icon=$iconpath.'/page.gif';       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
             $url=~/$coursenum\/([\/\w]+)\.page$/;       ne '')) {
             $pagearg=$1;      $selectbox=
             $url='/adm/coursedocs?';   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
             $ispage=1;   '<select name="newpos" onChange="this.form.submit()">';
  } else {      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);   if ($i==$incindex) {
  }      $selectbox.='<option value="" selected="1">('.$i.')</option>';
     }   } else {
     $url=~s-^http(\&colon\;|:)//-/adm/wrapper/ext/-;      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {   }
  my $symb=&Apache::lonnet::symbclean(      }
           &Apache::lonnet::declutter('uploaded/'.      $selectbox.='</select>';
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.   }
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.   my %lt=&Apache::lonlocal::texthash(
            '.sequence').                  'up' => 'Move Up',
            '___'.$residx.'___'.   'dw' => 'Move Down',
    &Apache::lonnet::declutter($url));   'rm' => 'Remove',
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);                  'ct' => 'Cut',
  $url=&Apache::lonnet::clutter($url);   'rn' => 'Rename',
  if ($url=~/^\/*uploaded\//) {   'cp' => 'Copy');
     $url=~/\.(\w+)$/;   my $nocopy=0;
     my $embstyle=&Apache::loncommon::fileembstyle($1);          my $nocut=0;
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {          if ($url=~/\.(page|sequence)$/) {
  $url='/adm/wrapper'.$url;      if ($url =~ m{/res/}) {
     } elsif ($embstyle eq 'ssi') {   # no copy for published maps
  #do nothing with these   $nocopy = 1;
     } elsif ($url!~/\.(sequence|page)$/) {      } else {
  $url='/adm/coursedocs/showdoc'.$url;   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
     }      my ($title,$url,$ext,$type)=split(/\:/,$item);
  } elsif ($url=~m|^/ext/|) {       if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
     $url='/adm/wrapper'.$url;   $nocopy=1;
  }   last;
         if (&Apache::lonnet::symbverify($symb,$url)) {      }
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);   }
         } else {      }
             $url='';   }
         }          if ($url=~/^\/res\/lib\/templates\//) {
  if ($container eq 'page') {             $nocopy=1;
     my $symb=$env{'form.pagesymb'};             $nocut=1;
                   }
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);          my $copylink='&nbsp;';
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);          my $cutlink='&nbsp;';
  }  
     }   my $skip_confirm = 0;
     my $parameterset='&nbsp;';   if ( $folder =~ /^supplemental/
     if ($isfolder || $extension eq 'sequence') {       || ($url =~ m{( /smppg$
  my $foldername=&escape($foldertitle);      |/syllabus$
  my $folderpath=$env{'form.folderpath'};      |/aboutme$
  if ($folderpath) { $folderpath.='&' };      |/navmaps$
 # Append randompick number, hidden, and encrypted with ":" to foldername,       |/bulletinboard$
 # so it gets transferred between levels      |\.html$
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,      |^/adm/wrapper/ext)}x)) {
                                               'parameter_randompick'))[0]      $skip_confirm = 1;
                                                .':'.((&LONCAPA::map::getparameter($orderidx,   }
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)  
                                                .':'.((&LONCAPA::map::getparameter($orderidx,   if (!$nocopy) {
                                               'parameter_encrypturl'))[0]=~/^yes$/i);      $copylink=(<<ENDCOPY);
  $url.='folderpath='.&escape($folderpath).$cpinfo;  <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
  $parameterset='<label>'.&mt('Randomly Pick: ').  ENDCOPY
     '<input type="text" size="4" onChange="this.form.changeparms.value=1;this.form.submit()" name="randpick_'.$orderidx.'" value="'.          }
     (&LONCAPA::map::getparameter($orderidx,   if (!$nocut) {
                                               'parameter_randompick'))[0].      $cutlink=(<<ENDCUT);
                                               '" />'.  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
 '<font size="-2"><a href="javascript:void(0)">'.&mt('Store').'</a></font></label>';  ENDCUT
                  }
     }   $form_start = (<<END);
     if ($ispage) {     <form  action="/adm/coursedocs" method="post">
         my $pagename=&escape($pagetitle);     <input type="hidden" name="${type}path" value="$path" />
         my $pagepath;     <input type="hidden" name="${type}symb" value="$symb" />
         my $folderpath=$env{'form.folderpath'};     <input type="hidden" name="setparms" value="$orderidx" />
         if ($folderpath) { $pagepath = $folderpath.'&' };     <input type="hidden" name="changeparms" value="0" />
         $pagepath.=$pagearg.'&'.$pagename;  END
  my $symb=$env{'form.pagesymb'};          $form_end = '</form>';
  if (!$symb) {   $line.=(<<END);
     my $path='uploaded/'.  <td>
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.     <table class="LC_docs_entry_move">
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';        <tr>
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',           <td>
        $residx,              <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>
        $path.$pagearg.'.page');           </td>
  }        </tr>
  $url.='pagepath='.&escape($pagepath).        <tr>
     '&pagesymb='.&escape($symb).$cpinfo;          <td>
     }             <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>
     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.          </td>
  '" border="0"></a></td>'.        </tr>
         "<td bgcolor='#FFFFBB'>".($url?"<a href=\"$url\">":'').$title.      </table>
         ($url?'</a>':' <font size="-2">'.&mt('(re-initialize course to access)').'</font>')."</td>";  </td>
     if (($allowed) && ($folder!~/^supplemental/)) {  <td>
   my %lt=&Apache::lonlocal::texthash(     $form_start
        'hd' => 'Hidden',     $selectbox
        'ec' => 'URL hidden');     $form_end
  my $enctext=  </td>
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');  <td class="LC_docs_entry_commands">
  my $hidtext=     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');  $cutlink
  $line.=(<<ENDPARMS);     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
 <td bgcolor="#BBBBFF"><font size='-2'>  $copylink
 <nobr><label><input type="checkbox" name="hidprs_$orderidx" onClick="this.form.changeparms.value=1;this.form.submit()" $hidtext /> $lt{'hd'}</label></nobr></td>  </td>
 <td bgcolor="#BBBBFF"><font size='-2'>  END
 <nobr><label><input type="checkbox" name="encprs_$orderidx" onClick="this.form.changeparms.value=1;this.form.submit()" $enctext /> $lt{'ec'}</label></nobr></td>  
 <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>      }
 ENDPARMS  # Figure out what kind of a resource this is
     }      my ($extension)=($url=~/\.(\w+)$/);
     $line.="</form></tr>";      my $uploaded=($url=~/^\/*uploaded\//);
     return $line;      my $icon=&Apache::loncommon::icon($url);
 }      my $isfolder=0;
       my $ispage=0;
 # ---------------------------------------------------------------- tie the hash      my $folderarg;
       my $pagearg;
 sub tiehash {      my $pagefile;
     my ($mode)=@_;      if ($uploaded) {
     $hashtied=0;   if ($extension eq 'sequence') {
     if ($env{'request.course.fn'}) {      $icon=$iconpath.'/folder_closed.gif';
  if ($mode eq 'write') {      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      $url='/adm/coursedocs?';
     &GDBM_WRCREAT(),0640)) {      $folderarg=$1;
                 $hashtied=2;      $isfolder=1;
     }          } elsif ($extension eq 'page') {
  } else {              $icon=$iconpath.'/page.gif';
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
     &GDBM_READER(),0640)) {              $pagearg=$1;
                 $hashtied=1;              $url='/adm/coursedocs?';
     }              $ispage=1;
  }   } else {
     }          &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 }   }
       }
 sub untiehash {     
     if ($hashtied) { untie %hash; }      my $orig_url = $url;
     $hashtied=0;      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
     return OK;      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
 }   my $symb=&Apache::lonnet::symbclean(
             &Apache::lonnet::declutter('uploaded/'.
 # --------------------------------------------------------------- check on this             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
              $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
 sub checkonthis {             '.sequence').
     my ($r,$url,$level,$title)=@_;             '___'.$residx.'___'.
     $url=&unescape($url);     &Apache::lonnet::declutter($url));
     $alreadyseen{$url}=1;   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
     $r->rflush();   $url=&Apache::lonnet::clutter($url);
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {   if ($url=~/^\/*uploaded\//) {
        $r->print("\n<br />");      $url=~/\.(\w+)$/;
        for (my $i=0;$i<=$level*5;$i++) {      my $embstyle=&Apache::loncommon::fileembstyle($1);
            $r->print('&nbsp;');      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
        }   $url='/adm/wrapper'.$url;
        $r->print('<a href="'.$url.'" target="cat">'.      } elsif ($embstyle eq 'ssi') {
  ($title?$title:$url).'</a> ');   #do nothing with these
        if ($url=~/^\/res\//) {      } elsif ($url!~/\.(sequence|page)$/) {
   my $result=&Apache::lonnet::repcopy(   $url='/adm/coursedocs/showdoc'.$url;
                               &Apache::lonnet::filelocation('',$url));      }
           if ($result eq 'ok') {   } elsif ($url=~m|^/ext/|) {
              $r->print('<font color="green">'.&mt('ok').'</font>');      $url='/adm/wrapper'.$url;
              $r->rflush();      $external = 1;
              &Apache::lonnet::countacc($url);   }
              $url=~/\.(\w+)$/;          if (&Apache::lonnet::symbverify($symb,$url)) {
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  $r->print('<br />');          } else {
                  $r->rflush();              $url='';
                  for (my $i=0;$i<=$level*5;$i++) {          }
                      $r->print('&nbsp;');   if ($container eq 'page') {
                  }      my $symb=$env{'form.pagesymb'};
                  $r->print('- '.&mt('Rendering').': ');          
  my ($errorcount,$warningcount)=split(/:/,      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
        &Apache::lonnet::ssi_body($url,      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
        ('grade_target'=>'web',   }
  'return_only_error_and_warning_counts' => 1)));      }
                  if (($errorcount) ||      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
                      ($warningcount)) {      if ($isfolder || $extension eq 'sequence') {
      if ($errorcount) {   my $foldername=&escape($foldertitle);
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.   my $folderpath=$env{'form.folderpath'};
   $errorcount.' '.   if ($folderpath) { $folderpath.='&' };
   &mt('error(s)').'</b></font> ');  # Append randompick number, hidden, and encrypted with ":" to foldername,
                      }  # so it gets transferred between levels
      if ($warningcount) {   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
                         $r->print('<font color="blue">'.                                                'parameter_randompick'))[0]
   $warningcount.' '.                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
   &mt('warning(s)').'</font>');                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
                      }                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                  } else {                                                'parameter_encrypturl'))[0]=~/^yes$/i)
                      $r->print('<font color="green">'.&mt('ok').'</font>');                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                  }                                                'parameter_randomorder'))[0]=~/^yes$/i);
                  $r->rflush();   $url.='folderpath='.&escape($folderpath).$cpinfo;
              }   $parameterset='<label>'.&mt('Randomly Pick: ').
      my $dependencies=      '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
                 &Apache::lonnet::metadata($url,'dependencies');      (&LONCAPA::map::getparameter($orderidx,
              foreach (split(/\,/,$dependencies)) {                                                'parameter_randompick'))[0].
  if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {                                                '" />'.
                     &checkonthis($r,$_,$level+1);  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
                  }      my $ro_set=
              }      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
           } elsif ($result eq 'unavailable') {   $rand_order_text ='
              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');  <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>';  
           } elsif ($result eq 'not_found') {      }
       unless ($url=~/\$/) {      if ($ispage) {
   $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');          my $pagename=&escape($pagetitle);
       } else {          my $pagepath;
   $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');          my $folderpath=$env{'form.folderpath'};
       }          if ($folderpath) { $pagepath = $folderpath.'&' };
           } else {          $pagepath.=$pagearg.'&'.$pagename;
              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');   my $symb=$env{'form.pagesymb'};
           }   if (!$symb) {
       }      my $path='uploaded/'.
    }   $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 }   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
       $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
          $residx,
 #         $path.$pagearg.'.page');
 # ----------------------------------------------------------------- List Symbs   }
 #    $url.='pagepath='.&escape($pagepath).
 sub list_symbs {      '&amp;pagesymb='.&escape($symb).$cpinfo;
     my ($r) = @_;      }
       if ($external) {
     $r->print(&Apache::loncommon::start_page('Symb List'));   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
     my $navmap = Apache::lonnavmaps::navmap->new();   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
     $r->print("<pre>\n");      } else {
     foreach my $res ($navmap->retrieveResources()) {   undef($external);
  $r->print($res->compTitle()."\t".$res->symb()."\n");      }
     }      $line.='
     $r->print("\n</pre>\n");    <td class="LC_docs_entry_icon">
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
 }    </td>
     <td class="LC_docs_entry_title">
       '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."
 #    </td>";
 # -------------------------------------------------------------- Verify Content      if (($allowed) && ($folder!~/^supplemental/)) {
 #     my %lt=&Apache::lonlocal::texthash(
 sub verifycontent {         'hd' => 'Hidden',
     my ($r) = @_;         'ec' => 'URL hidden');
     my $type = &Apache::loncommon::course_type();   my $enctext=
    my $loaderror=&Apache::lonnet::overloaderror($r);      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
    if ($loaderror) { return $loaderror; }   my $hidtext=
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
    $hashtied=0;   $line.=(<<ENDPARMS);
    undef %alreadyseen;    <td class="LC_docs_entry_parameter">
    %alreadyseen=();      $form_start
    &tiehash();      <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
    foreach (keys %hash) {      $form_end
        if ($hash{$_}=~/\.(page|sequence)$/) {    </td>
    if (($_=~/^src_/) && ($alreadyseen{&unescape($hash{$_})})) {    <td class="LC_docs_entry_parameter">
        $r->print('<hr /><font color="red">'.      $form_start
  &mt('The following sequence or page is included more than once in your '.$type.': ').      <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
  &unescape($hash{$_}).'</font><br />'.      $form_end
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));    </td>
    }    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
        }    <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$_})})) {  ENDPARMS
            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});      }
        }      $line.="</tr>";
    }      return $line;
    &untiehash();  }
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.  
      &mt('Return to DOCS').'</a>');  =pod
 }  
   =item tiehash()
   
 # -------------------------------------------------------------- Check Versions  tie the hash
   
 sub devalidateversioncache {  =cut
     my $src=shift;  
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.  sub tiehash {
   &Apache::lonnet::clutter($src));      my ($mode)=@_;
 }      $hashtied=0;
       if ($env{'request.course.fn'}) {
 sub checkversions {   if ($mode eq 'write') {
     my ($r) = @_;      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     my $type = &Apache::loncommon::course_type();      &GDBM_WRCREAT(),0640)) {
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));                  $hashtied=2;
     my $header='';      }
     my $startsel='';   } else {
     my $monthsel='';      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     my $weeksel='';      &GDBM_READER(),0640)) {
     my $daysel='';                  $hashtied=1;
     my $allsel='';      }
     my %changes=();   }
     my $starttime=0;      }    
     my $haschanged=0;  }
     my %setversions=&Apache::lonnet::dump('resourceversions',  
   $env{'course.'.$env{'request.course.id'}.'.domain'},  sub untiehash {
   $env{'course.'.$env{'request.course.id'}.'.num'});      if ($hashtied) { untie %hash; }
       $hashtied=0;
     $hashtied=0;      return OK;
     &tiehash();  }
     my %newsetversions=();  
     if ($env{'form.setmostrecent'}) {  
  $haschanged=1;  
  foreach (keys %hash) {  
     if ($_=~/^ids\_(\/res\/.+)$/) {  sub checkonthis {
  $newsetversions{$1}='mostrecent';      my ($r,$url,$level,$title)=@_;
                 &devalidateversioncache($1);      $url=&unescape($url);
     }      $alreadyseen{$url}=1;
  }      $r->rflush();
     } elsif ($env{'form.setcurrent'}) {      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
  $haschanged=1;         $r->print("\n<br />");
  foreach (keys %hash) {         if ($level==0) {
     if ($_=~/^ids\_(\/res\/.+)$/) {             $r->print("<br />");
  my $getvers=&Apache::lonnet::getversion($1);         }
  if ($getvers>0) {         for (my $i=0;$i<=$level*5;$i++) {
     $newsetversions{$1}=$getvers;             $r->print('&nbsp;');
     &devalidateversioncache($1);         }
  }         $r->print('<a href="'.$url.'" target="cat">'.
     }   ($title?$title:$url).'</a> ');
  }         if ($url=~/^\/res\//) {
     } elsif ($env{'form.setversions'}) {    my $result=&Apache::lonnet::repcopy(
  $haschanged=1;                                &Apache::lonnet::filelocation('',$url));
  foreach (keys %env) {            if ($result eq 'ok') {
     if ($_=~/^form\.set_version_(.+)$/) {               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  my $src=$1;               $r->rflush();
  if (($env{$_}) && ($env{$_} ne $setversions{$src})) {               &Apache::lonnet::countacc($url);
     $newsetversions{$src}=$env{$_};               $url=~/\.(\w+)$/;
     &devalidateversioncache($src);               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
  }   $r->print('<br />');
     }                   $r->rflush();
  }                   for (my $i=0;$i<=$level*5;$i++) {
     }                       $r->print('&nbsp;');
     if ($haschanged) {                   }
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,                   $r->print('- '.&mt('Rendering:').' ');
   $env{'course.'.$env{'request.course.id'}.'.domain'},   my ($errorcount,$warningcount)=split(/:/,
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {         &Apache::lonnet::ssi_body($url,
     $r->print('<h1>'.&mt('Your Version Settings have been Stored').'</h1>');         ('grade_target'=>'web',
  } else {   'return_only_error_and_warning_counts' => 1)));
     $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Store your Version Settings').'</font></h1>');                   if (($errorcount) ||
  }                       ($warningcount)) {
  &mark_hash_old();       if ($errorcount) {
     }                          $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.
     &changewarning($r,'');                            &mt('[quant,_1,error]',$errorcount).'</span>');
     if ($env{'form.timerange'} eq 'all') {                       }
 # show all documents       if ($warningcount) {
  $header=&mt('All Documents in '.$type);                          $r->print('<span class="LC_warning">'.
  $allsel=1;                            &mt('[quant,_1,warning]',$warningcount).'</span>');
  foreach (keys %hash) {                       }
     if ($_=~/^ids\_(\/res\/.+)$/) {                   } else {
  my $src=$1;                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  $changes{$src}=1;                   }
     }                   $r->rflush();
  }               }
     } else {       my $dependencies=
 # show documents which changed                  &Apache::lonnet::metadata($url,'dependencies');
  %changes=&Apache::lonnet::dump               foreach my $dep (split(/\,/,$dependencies)) {
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
                      $env{'course.'.$env{'request.course.id'}.'.num'});                      &checkonthis($r,$dep,$level+1);
  my $firstkey=(keys %changes)[0];                   }
  unless ($firstkey=~/^error\:/) {               }
     unless ($env{'form.timerange'}) {            } elsif ($result eq 'unavailable') {
  $env{'form.timerange'}=604800;               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
     }            } elsif ($result eq 'not_found') {
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '        unless ($url=~/\$/) {
  .&mt('seconds');    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
     if ($env{'form.timerange'}==-1) {        } else {
  $seltext='since start of course';    $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');
  $startsel='selected';        }
  $env{'form.timerange'}=time;            } else {
     }               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
     $starttime=time-$env{'form.timerange'};            }
     if ($env{'form.timerange'}==2592000) {         }
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      }
  $monthsel='selected';  }
     } elsif ($env{'form.timerange'}==604800) {  
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  
  $weeksel='selected';  
     } elsif ($env{'form.timerange'}==86400) {  =pod
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  
  $daysel='selected';  =item list_symbs()
     }  
     $header=&mt('Content changed').' '.$seltext;  List Symbs
  } else {  
     $header=&mt('No content modifications yet.');  =cut
  }  
     }  sub list_symbs {
     %setversions=&Apache::lonnet::dump('resourceversions',      my ($r) = @_;
   $env{'course.'.$env{'request.course.id'}.'.domain'},  
   $env{'course.'.$env{'request.course.id'}.'.num'});      my $type = &Apache::loncommon::course_type();
     my %lt=&Apache::lonlocal::texthash      $r->print(&Apache::loncommon::start_page('Symb List'));
       ('st' => 'Version changes since start of '.$type,      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
        'lm' => 'Version changes since last Month',      my $navmap = Apache::lonnavmaps::navmap->new();
        'lw' => 'Version changes since last Week',      if (!defined($navmap)) {
        'sy' => 'Version changes since Yesterday',          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
                'al' => 'All Resources (possibly large output)',                    '<div class="LC_error">'.
        'sd' => 'Display',                    &mt('Unable to retrieve information about course contents').
        'fi' => 'File',                    '</div>');
        'md' => 'Modification Date',          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
                'mr' => 'Most recently published Version',      } else {
        've' => 'Version used in '.$type,          $r->print("<pre>\n");
                'vu' => 'Set Version to be used in '.$type,          foreach my $res ($navmap->retrieveResources()) {
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      $r->print($res->compTitle()."\t".$res->symb()."\n");
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',          }
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',          $r->print("\n</pre>\n");
        'di' => 'Differences');      }
     $r->print(<<ENDHEADERS);      $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
 <form action="/adm/coursedocs" method="post">  }
 <input type="hidden" name="versions" value="1" />  
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />  
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />  sub verifycontent {
 <select name="timerange">      my ($r) = @_;
 <option value='all' $allsel>$lt{'al'}</option>      my $type = &Apache::loncommon::course_type();
 <option value="-1" $startsel>$lt{'st'}</option>     my $loaderror=&Apache::lonnet::overloaderror($r);
 <option value="2592000" $monthsel>$lt{'lm'}</option>     if ($loaderror) { return $loaderror; }
 <option value="604800" $weeksel>$lt{'lw'}</option>     $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
 <option value="86400" $daysel>$lt{'sy'}</option>     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));
 </select>     $hashtied=0;
 <input type="submit" name="display" value="$lt{'sd'}" />     undef %alreadyseen;
 <h3>$header</h3>     %alreadyseen=();
 <input type="submit" name="setversions" value="$lt{'sv'}" />     &tiehash();
 <table border="0">     foreach my $key (keys(%hash)) {
 ENDHEADERS         if ($hash{$key}=~/\.(page|sequence)$/) {
     foreach (sort keys %changes) {     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
  if ($changes{$_}>$starttime) {         $r->print('<hr /><span class="LC_error">'.
     my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);   &mt('The following sequence or page is included more than once in your '.$type.': ').
     my $currentversion=&Apache::lonnet::getversion($_);   &unescape($hash{$key}).'</span><br />'.
     if ($currentversion<0) {   &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
  $currentversion=&mt('Could not be determined.');     }
     }         }
     my $linkurl=&Apache::lonnet::clutter($_);         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
     $r->print(             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.         }
       &Apache::lonnet::gettitle($linkurl).     }
                       '</b></font></td></tr>'.     &untiehash();
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.     $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
                       '<td colspan="4">'.       &mt('Return to DOCS').'</a>');
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.  }
       '</a></td></tr>'.  
                       '<tr><td></td>'.  
                       '<td title="'.$lt{'md'}.'">'.  sub devalidateversioncache {
       &Apache::lonlocal::locallocaltime(      my $src=shift;
                            &Apache::lonnet::metadata($root.'.'.$extension,      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
                                                      'lastrevisiondate')    &Apache::lonnet::clutter($src));
                                                         ).  }
                       '</td>'.  
                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.  sub checkversions {
                       '<font size="+1">'.$currentversion.'</font>'.      my ($r) = @_;
                       '</nobr></td>'.      my $type = &Apache::loncommon::course_type();
                       '<td title="'.$lt{'ve'}.'"><nobr>In '.$type.': '.      $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
                       '<font size="+1">');      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));
 # Used in course      my $header='';
     my $usedversion=$hash{'version_'.$linkurl};      my $startsel='';
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      my $monthsel='';
  $r->print($usedversion);      my $weeksel='';
     } else {      my $daysel='';
  $r->print($currentversion);      my $allsel='';
     }      my %changes=();
     $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.      my $starttime=0;
                       '<nobr>Use: ');      my $haschanged=0;
 # Set version      my %setversions=&Apache::lonnet::dump('resourceversions',
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},    $env{'course.'.$env{'request.course.id'}.'.domain'},
       'set_version_'.$linkurl,    $env{'course.'.$env{'request.course.id'}.'.num'});
       ('select_form_order' =>  
        ['',1..$currentversion,'mostrecent'],      $hashtied=0;
        '' => '',      &tiehash();
        'mostrecent' => 'most recent',      my %newsetversions=();
        map {$_,$_} (1..$currentversion))));      if ($env{'form.setmostrecent'}) {
     $r->print('</nobr></td></tr><tr><td></td>');   $haschanged=1;
     my $lastold=1;   foreach my $key (keys(%hash)) {
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {      if ($key=~/^ids\_(\/res\/.+)$/) {
  my $url=$root.'.'.$prevvers.'.'.$extension;   $newsetversions{$1}='mostrecent';
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                  &devalidateversioncache($1);
     $starttime) {      }
     $lastold=$prevvers;   }
  }      } elsif ($env{'form.setcurrent'}) {
     }   $haschanged=1;
             #    foreach my $key (keys(%hash)) {
             # Code to figure out how many version entries should go in      if ($key=~/^ids\_(\/res\/.+)$/) {
             # each of the four columns   my $getvers=&Apache::lonnet::getversion($1);
             my $entries_per_col = 0;   if ($getvers>0) {
             my $num_entries = ($currentversion-$lastold);      $newsetversions{$1}=$getvers;
             if ($num_entries % 4 == 0) {      &devalidateversioncache($1);
                 $entries_per_col = $num_entries/4;   }
             } else {      }
                 $entries_per_col = $num_entries/4 + 1;   }
             }      } elsif ($env{'form.setversions'}) {
             my $entries_count = 0;   $haschanged=1;
             $r->print('<td valign="top"><font size="-2">');    foreach my $key (keys(%env)) {
             my $cols_output = 1;      if ($key=~/^form\.set_version_(.+)$/) {
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {   my $src=$1;
  my $url=$root.'.'.$prevvers.'.'.$extension;   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
  $r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).      $newsetversions{$src}=$env{$key};
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      &devalidateversioncache($src);
   &Apache::lonlocal::locallocaltime(   }
                                 &Apache::lonnet::metadata($url,      }
                                                           'lastrevisiondate')   }
                                                             ).      }
   ')');      if ($haschanged) {
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
                     $r->print(' <a href="/adm/diff?filename='.    $env{'course.'.$env{'request.course.id'}.'.domain'},
       &Apache::lonnet::clutter($root.'.'.$extension).    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
       '&versionone='.$prevvers.      $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
       '">'.&mt('Diffs').'</a>');   } else {
  }      $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
  $r->print('</nobr><br />');   }
                 if (++$entries_count % $entries_per_col == 0) {   &mark_hash_old();
                     $r->print('</font></td>');      }
                     if ($cols_output != 4) {      &changewarning($r,'');
                         $r->print('<td valign="top"><font size="-2">');      if ($env{'form.timerange'} eq 'all') {
                         $cols_output++;  # show all documents
                     }   $header=&mt('All Documents in '.$type);
                 }   $allsel=1;
     }   foreach my $key (keys(%hash)) {
             while($cols_output++ < 4) {      if ($key=~/^ids\_(\/res\/.+)$/) {
                 $r->print('</font></td><td><font>')   my $src=$1;
             }   $changes{$src}=1;
     $r->print('</font></td></tr>'."\n");      }
  }   }
     }      } else {
     $r->print('</table></form>');  # show documents which changed
     $r->print('<h1>'.&mt('Done').'.</h1>');   %changes=&Apache::lonnet::dump
    ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
     &untiehash();                       $env{'course.'.$env{'request.course.id'}.'.num'});
 }   my $firstkey=(keys(%changes))[0];
    unless ($firstkey=~/^error\:/) {
 sub mark_hash_old {      unless ($env{'form.timerange'}) {
     my $retie_hash=0;   $env{'form.timerange'}=604800;
     if ($hashtied) {      }
  $retie_hash=1;      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
  &untiehash();   .&mt('seconds');
     }      if ($env{'form.timerange'}==-1) {
     &tiehash('write');   $seltext='since start of course';
     $hash{'old'}=1;   $startsel='selected';
     &untiehash();   $env{'form.timerange'}=time;
     if ($retie_hash) { &tiehash(); }      }
 }      $starttime=time-$env{'form.timerange'};
       if ($env{'form.timerange'}==2592000) {
 sub is_hash_old {   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
     my $untie_hash=0;   $monthsel='selected';
     if (!$hashtied) {      } elsif ($env{'form.timerange'}==604800) {
  $untie_hash=1;   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  &tiehash();   $weeksel='selected';
     }      } elsif ($env{'form.timerange'}==86400) {
     my $return=$hash{'old'};   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
     if ($untie_hash) { &untiehash(); }   $daysel='selected';
     return $return;      }
 }      $header=&mt('Content changed').' '.$seltext;
    } else {
 sub changewarning {      $header=&mt('No content modifications yet.');
     my ($r,$postexec,$message,$url)=@_;   }
     if (!&is_hash_old()) { return; }      }
     my $pathvar='folderpath';      %setversions=&Apache::lonnet::dump('resourceversions',
     my $path=&escape($env{'form.folderpath'});    $env{'course.'.$env{'request.course.id'}.'.domain'},
     if (!defined($url)) {    $env{'course.'.$env{'request.course.id'}.'.num'});
  if (defined($env{'form.pagepath'})) {      my %lt=&Apache::lonlocal::texthash
     $pathvar='pagepath';        ('st' => 'Version changes since start of '.$type,
     $path=&escape($env{'form.pagepath'});         'lm' => 'Version changes since last Month',
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});         'lw' => 'Version changes since last Week',
  }         'sy' => 'Version changes since Yesterday',
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                 'al' => 'All Resources (possibly large output)',
     }         'sd' => 'Display',
     my $course_type = &Apache::loncommon::course_type();         'fi' => 'File',
     if (!defined($message)) {         'md' => 'Modification Date',
  $message='Changes will become active for your current session after [_1], or the next time you log in.';                 'mr' => 'Most recently published Version',
     }         've' => 'Version used in '.$type,
     $r->print("\n\n".                 'vu' => 'Set Version to be used in '.$type,
 '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".   'sv' => 'Set Versions to be used in '.$type.' according to Selections below',
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 '<input type="hidden" name="orgurl" value="'.$url.  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.         'di' => 'Differences');
 &mt($message,' <input type="hidden" name="'.      $r->print(<<ENDHEADERS);
     $env{'request.role'}.'" value="1" /><input type="button" value="'.  <form action="/adm/coursedocs" method="post">
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').  <input type="hidden" name="versions" value="1" />
 $help{'Caching'}.'</font></h3></form>'."\n\n");  <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
 }  <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
   <select name="timerange">
 # ================================================================ Main Handler  <option value='all' $allsel>$lt{'al'}</option>
 sub handler {  <option value="-1" $startsel>$lt{'st'}</option>
     my $r = shift;  <option value="2592000" $monthsel>$lt{'lm'}</option>
     &Apache::loncommon::content_type($r,'text/html');  <option value="604800" $weeksel>$lt{'lw'}</option>
     $r->send_http_header;  <option value="86400" $daysel>$lt{'sy'}</option>
     return OK if $r->header_only;  </select>
     my $type = &Apache::loncommon::course_type();  <input type="submit" name="display" value="$lt{'sd'}" />
   <h3>$header</h3>
 # --------------------------------------------- Initialize help topics for this  <input type="submit" name="setversions" value="$lt{'sv'}" />
     foreach ('Adding_Course_Doc','Main_Course_Documents',  <table border="0">
      'Adding_External_Resource','Navigate_Content',  ENDHEADERS
      'Adding_Folders','Docs_Overview', 'Load_Map',      foreach my $key (sort(keys(%changes))) {
      'Supplemental','Score_Upload_Form','Adding_Pages',   if ($changes{$key}>$starttime) {
      'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
      'Check_Resource_Versions','Verify_Content') {      my $currentversion=&Apache::lonnet::getversion($key);
  $help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);      if ($currentversion<0) {
     }   $currentversion=&mt('Could not be determined.');
     # Composite help files      }
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(      my $linkurl=&Apache::lonnet::clutter($key);
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');      $r->print(
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(        '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');        &Apache::lonnet::gettitle($linkurl).
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(                        '</b></font></td></tr>'.
     'Option_Response_Simple');                        '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(                        '<td colspan="4">'.
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');                        '<a href="'.$linkurl.'" target="cat">'.$linkurl.
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(        '</a></td></tr>'.
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');                        '<tr><td></td>'.
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');                        '<td title="'.$lt{'md'}.'">'.
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');        &Apache::lonlocal::locallocaltime(
                              &Apache::lonnet::metadata($root.'.'.$extension,
 # does this user have privileges to modify docs                                                       'lastrevisiondate')
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});                                                          ).
                         '</td>'.
   if ($allowed && $env{'form.verify'}) {                        '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
       &verifycontent($r);                        '<font size="+1">'.$currentversion.'</font>'.
   } elsif ($allowed && $env{'form.listsymbs'}) {                        '</span></td>'.
       &list_symbs($r);                        '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.
   } elsif ($allowed && $env{'form.docslog'}) {                        '<font size="+1">');
       &docs_change_log($r);  # Used in course
   } elsif ($allowed && $env{'form.versions'}) {      my $usedversion=$hash{'version_'.$linkurl};
       &checkversions($r);      if (($usedversion) && ($usedversion ne 'mostrecent')) {
   } elsif ($allowed && $env{'form.dumpcourse'}) {   $r->print($usedversion);
       &dumpcourse($r);      } else {
   } elsif ($allowed && $env{'form.exportcourse'}) {   $r->print($currentversion);
       &exportcourse($r);      }
   } else {      $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
 # is this a standard course?                        '<span class="LC_nobreak">Use: ');
   # Set version
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
     my $forcestandard = 0;        'set_version_'.$linkurl,
     my $forcesupplement;        ('select_form_order' =>
     my $script='';         ['',1..$currentversion,'mostrecent'],
     my $showdoc=0;         '' => '',
     my $containertag;         'mostrecent' => 'most recent',
     my $uploadtag;         map {$_,$_} (1..$currentversion))));
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      $r->print('</span></td></tr><tr><td></td>');
     ['folderpath','pagepath',      my $lastold=1;
      'pagesymb','markedcopy_url',      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
      'markedcopy_title']);   my $url=$root.'.'.$prevvers.'.'.$extension;
     if ($env{'form.folderpath'}) {   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
  my (@folderpath)=split('&',$env{'form.folderpath'});      $starttime) {
  $env{'form.foldername'}=&unescape(pop(@folderpath));      $lastold=$prevvers;
  $env{'form.folder'}=pop(@folderpath);   }
     }      }
     if ($env{'form.pagepath'}) {              #
         my (@pagepath)=split('&',$env{'form.pagepath'});              # Code to figure out how many version entries should go in
         $env{'form.pagename'}=&unescape(pop(@pagepath));              # each of the four columns
         $env{'form.folder'}=pop(@pagepath);              my $entries_per_col = 0;
         $containertag = '<input type="hidden" name="pagepath" value="" />'.              my $num_entries = ($currentversion-$lastold);
     '<input type="hidden" name="pagesymb" value="" />';              if ($num_entries % 4 == 0) {
         $uploadtag = '<input type="hidden" name="pagepath" value="'.$env{'form.pagepath'}.'" />'.                  $entries_per_col = $num_entries/4;
     '<input type="hidden" name="pagesymb" value="'.$env{'form.pagesymb'}.'" />';              } else {
     }                  $entries_per_col = $num_entries/4 + 1;
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {              }
        $showdoc='/'.$1;              my $entries_count = 0;
     }              $r->print('<td valign="top"><font size="-2">');
     unless ($showdoc) { # got called from remote              my $cols_output = 1;
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||               for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {   my $url=$root.'.'.$prevvers.'.'.$extension;
            $forcestandard = 1;   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
        }     '">'.&mt('Version').' '.$prevvers.'</a> ('.
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);    &Apache::lonlocal::locallocaltime(
                                   &Apache::lonnet::metadata($url,
        if ($allowed) {                                                             'lastrevisiondate')
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);                                                              ).
          $script=&Apache::lonratedt::editscript('simple');     ')');
        }   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
     } else { # got called in sequence from course                      $r->print(' <a href="/adm/diff?filename='.
        $allowed=0;        &Apache::lonnet::clutter($root.'.'.$extension).
     }        '&versionone='.$prevvers.
         '">'.&mt('Diffs').'</a>');
 # get course data   }
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};   $r->print('</span><br />');
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};                  if (++$entries_count % $entries_per_col == 0) {
                       $r->print('</font></td>');
 # get personal data                       if ($cols_output != 4) {
     my $uname=$env{'user.name'};                          $r->print('<td valign="top"><font size="-2">');
     my $udom=$env{'user.domain'};                          $cols_output++;
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));                      }
                   }
 # graphics settings      }
               while($cols_output++ < 4) {
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");                  $r->print('</font></td><td><font>')
               }
     if ($allowed) {      $r->print('</font></td></tr>'."\n");
  $script .= &editing_js($udom,$uname);   }
     }      }
 # -------------------------------------------------------------------- Body tag      $r->print('</table></form>');
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';      $r->print('<h1>'.&mt('Done').'.</h1>');
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,  
      {'force_register' => $showdoc,}).      &untiehash();
       &Apache::loncommon::help_open_menu('','',273,'RAT'));  }
     
   my %allfiles = ();  sub mark_hash_old {
   my %codebase = ();      my $retie_hash=0;
   my ($upload_result,$upload_output);      if ($hashtied) {
   if ($allowed) {   $retie_hash=1;
       if (($env{'form.uploaddoc.filename'}) &&                                               ($env{'form.cmd'}=~/^upload_(\w+)/)) {   &untiehash();
 # Process file upload - phase one - upload and parse primary file.        }
           $upload_result = &process_file_upload(\$upload_output,$coursenum,      &tiehash('write');
  $coursedom,\%allfiles,      $hash{'old'}=1;
  \%codebase,$1);      &untiehash();
           if ($upload_result eq 'phasetwo') {      if ($retie_hash) { &tiehash(); }
               $r->print($upload_output);  }
           }  
       } elsif ($env{'form.phasetwo'}) {  sub is_hash_old {
           my %newname = ();      my $untie_hash=0;
           my %origname = ();      if (!$hashtied) {
           my %attribs = ();   $untie_hash=1;
           my $updateflag = 0;   &tiehash();
           my $residx = $env{'form.newidx'};      }
           my $primary_url = &unescape($env{'form.primaryurl'});      my $return=$hash{'old'};
 # Process file upload - phase two - gather secondary files.      if ($untie_hash) { &untiehash(); }
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {      return $return;
               if ($env{'form.embedded_item_'.$i.'.filename'}) {  }
                   my $javacodebase;  
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);  sub changewarning {
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});      my ($r,$postexec,$message,$url)=@_;
                   if (exists($env{'form.embedded_codebase_'.$i})) {      if (!&is_hash_old()) { return; }
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});        my $pathvar='folderpath';
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;       my $path=&escape($env{'form.folderpath'});
                   }      if (!defined($url)) {
                   my @attributes = ();   if (defined($env{'form.pagepath'})) {
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {      $pathvar='pagepath';
                       @attributes = split/:/,$env{'form.embedded_attrib_'.$i};      $path=&escape($env{'form.pagepath'});
                   } else {      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
                       @attributes = ($env{'form.embedded_attrib_'.$i});   }
                   }   $url='/adm/coursedocs?'.$pathvar.'='.$path;
                   foreach (@attributes) {      }
                       push(@{$attribs{$i}},&unescape($_));      my $course_type = &Apache::loncommon::course_type();
                   }      if (!defined($message)) {
                   if ($javacodebase) {   $message='Changes will become active for your current session after [_1], or the next time you log in.';
                       $codebase{$i} = $javacodebase;      }
                       $codebase{$i} =~ s#/$##;      $r->print("\n\n".
                       $updateflag = 1;  '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".
                   }  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
               }  '<input type="hidden" name="orgurl" value="'.$url.
               unless ($newname{$i} eq $origname{$i}) {  '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.
                   $updateflag = 1;  &mt($message,' <input type="hidden" name="'.
               }      $env{'request.role'}.'" value="1" /><input type="button" value="'.
           }      &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
 # Process file upload - phase three - modify primary file  $help{'Caching'}.'</span></h3></form>'."\n\n");
           if ($updateflag) {  }
               my ($content,$rtncode);  
               my $updateflag = 0;  
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);  sub init_breadcrumbs {
               if ($getstatus eq 'ok') {      my ($form,$text)=@_;
                   foreach my $item (keys %newname) {      &Apache::lonhtmlcommon::clear_breadcrumbs();
                       if ($newname{$item} ne $origname{$item}) {      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
                           my $attrib_regexp = '';      text=>"Edit ".&Apache::loncommon::course_type(),
                           if (@{$attribs{$item}} > 1) {      faq=>273,
                               $attrib_regexp = join('|',@{$attribs{$item}});      bug=>'Instructor Interface',
                           } else {                                              help => 'Docs_Adding_Course_Doc'});
                               $attrib_regexp = $attribs{$item}[0];      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
                           }      text=>$text,
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {      faq=>273,
                           }       bug=>'Instructor Interface'});
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;   }
                       }  
                       if (exists($codebase{$item})) {  
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs  
                       }  
                   }  sub handler {
 # Save edited file.      my $r = shift;
                   my $saveresult;      &Apache::loncommon::content_type($r,'text/html');
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};      $r->send_http_header;
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};      return OK if $r->header_only;
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);      my $type = &Apache::loncommon::course_type();
               } else {  
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);   
               }  # --------------------------------------------- Initialize help topics for this
           }      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
       }                 'Adding_External_Resource','Navigate_Content',
   }                 'Adding_Folders','Docs_Overview', 'Load_Map',
                  'Supplemental','Score_Upload_Form','Adding_Pages',
   unless ($showdoc ||  $upload_result eq 'phasetwo') {                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
 # -----------------------------------------------------------------------------                 'Check_Resource_Versions','Verify_Content') {
        my %lt=&Apache::lonlocal::texthash(   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
                 'uplm' => 'Upload a new main '.lc($type).' document',      }
                 'upls' => 'Upload a new supplemental '.lc($type).' document',      # Composite help files
                 'impp' => 'Import a document',      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
                 'pubd' => 'Published documents',      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
  'copm' => 'All documents out of a published map into this folder',      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
                 'spec' => 'Special documents',      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
                 'upld' => 'Upload Document',      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
                 'srch' => 'Search',      'Option_Response_Simple');
                 'impo' => 'Import',      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
  'book' => 'Import Bookmarks',      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
                 'selm' => 'Select Map',      $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
                 'load' => 'Load Map',    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
                 'reco' => 'Recover Deleted Resources',      $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
                 'newf' => 'New Folder',      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
                 'newp' => 'New Composite Page',  
                 'extr' => 'External Resource',  # does this user have privileges to modify docs
                 'syll' => 'Syllabus',      my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                 'navc' => 'Navigate Contents',    if ($allowed && $env{'form.verify'}) {
                 'sipa' => 'Simple Page',        &init_breadcrumbs('verify','Verify Content');
                 'sipr' => 'Simple Problem',        &verifycontent($r);
                 'drbx' => 'Drop Box',    } elsif ($allowed && $env{'form.listsymbs'}) {
                 'scuf' => 'Score Upload Form',        &init_breadcrumbs('listsymbs','List Symbs');
                 'bull' => 'Bulletin Board',        &list_symbs($r);
                 'mypi' => 'My Personal Info',    } elsif ($allowed && $env{'form.docslog'}) {
                 'grpo' => 'Group Files',        &init_breadcrumbs('docslog','Show Log');
  'abou' => 'About User',        &docs_change_log($r);
                 'imsf' => 'Import IMS package',    } elsif ($allowed && $env{'form.versions'}) {
                 'file' =>  'File',        &init_breadcrumbs('versions','Check/Set Resource Versions');
                 'title' => 'Title',        &checkversions($r);
                 'comment' => 'Comment',    } elsif ($allowed && $env{'form.dumpcourse'}) {
                 'parse' => 'If HTML file, upload embedded images/multimedia files'        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
   );        &dumpcourse($r);
 # -----------------------------------------------------------------------------    } elsif ($allowed && $env{'form.exportcourse'}) {
     if ($allowed) {        &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');
        my $dumpbut=&dumpbutton();        &exportcourse($r);
        my $exportbut=&exportbutton();    } else {
        my %lt=&Apache::lonlocal::texthash(  # is this a standard course?
  'vc' => 'Verify Content',  
  'cv' => 'Check/Set Resource Versions',      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
  'ls' => 'List Symbs',      my $forcestandard = 0;
                                          'sl' => 'Show Log'      my $forcesupplement;
   );      my $script='';
       my $showdoc=0;
        my $folderpath=$env{'form.folderpath'};      my $containertag;
        if (!$folderpath) {      my $uploadtag;
    if ($env{'form.folder'} eq '' ||  
        $env{'form.folder'} eq 'supplemental') {  
        $folderpath='default&'.      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
    &escape(&mt('Main '.$type.' Documents'));      ['folderpath','pagepath',
    }       'pagesymb']);
        }  # No folderpath, no pagepath, see if we have something stored
        unless ($env{'form.pagepath'}) {      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
            $containertag = '<input type="hidden" name="folderpath" value="" />';          &Apache::loncommon::restore_course_settings('docs_folderpath',
            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';                                                {'folderpath' => 'scalar'});
        }      }
       if (!$env{'form.folderpath'}) {
        $r->print(<<ENDCOURSEVERIFY);          &Apache::loncommon::restore_course_settings('docs_folderpath',
 <form name="renameform" method="post" action="/adm/coursedocs">                                                {'pagepath' => 'scalar'});
 <input type="hidden" name="title" />      }
 <input type="hidden" name="cmd" />      if ($env{'form.pagepath'}) {
 <input type="hidden" name="markcopy" />         $env{'form.folderpath'}='';
 $containertag      }
 </form>      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 <form name="simpleedit" method="post" action="/adm/coursedocs">          $env{'form.folderpath'} = 'supplemental&'.
 <input type="hidden" name="importdetail" value="" />                                    &escape(&mt('Supplemental '.$type.' Documents')).'&'.
 $uploadtag                                    $env{'form.folderpath'};
 </form>      }
 <form action="/adm/coursedocs" method="post" name="courseverify">      &Apache::loncommon::store_course_settings('docs_folderpath',
 <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">                                                  {'pagepath' => 'scalar',
 <tr><td bgcolor="#DDDDCC">                                                   'folderpath' => 'scalar'});
 <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}      if ($env{'form.folderpath'}) {
 </td><td bgcolor="#DDDDCC">   my (@folderpath)=split('&',$env{'form.folderpath'});
     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}   $env{'form.foldername'}=&unescape(pop(@folderpath));
 $dumpbut   $env{'form.folder'}=pop(@folderpath);
 $exportbut      }
 </td><td bgcolor="#DDDDCC">      if ($env{'form.pagepath'}) {
     <input type="submit" name="listsymbs" value="$lt{'ls'}" />          my (@pagepath)=split('&',$env{'form.pagepath'});
 </td><td bgcolor="#DDDDCC">          $env{'form.pagename'}=&unescape(pop(@pagepath));
     <input type="submit" name="docslog" value="$lt{'sl'}" />          $env{'form.folder'}=pop(@pagepath);
 </td></tr></table>          $containertag = '<input type="hidden" name="pagepath" value="" />'.
 </form>      '<input type="hidden" name="pagesymb" value="" />';
 ENDCOURSEVERIFY          $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',      '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';
      &mt('Editing the Table of Contents for your '.$type)));      }
     }      if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 # --------------------------------------------------------- Standard documents         $showdoc='/'.$1;
     $r->print('<table border=2 cellspacing=4 cellpadding=4>');      }
     if (($standard) && ($allowed) && (!$forcesupplement)) {      unless ($showdoc) { # got called from remote
  $r->print('<tr><td bgcolor="#BBBBBB">');         if (($env{'form.folder'}=~/^(?:group|default)_/) ||
 #  '<h2>'.&mt('Main Course Documents').            ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');             $forcestandard = 1;
        my $folder=$env{'form.folder'};         }
        if ($folder eq '' || $folder eq 'supplemental') {         $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
            $folder='default';  
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));         if ($allowed) {
        }           &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
        my $postexec='';           $script=&Apache::lonratedt::editscript('simple');
        if ($folder eq 'default') {         }
    $r->print('<script>this.window.name="loncapaclient";</script>');      } else { # got called in sequence from course
        } else {         $allowed=0;
            #$postexec='self.close();';      }
        }  
        $hadchanges=0;  # get course data
        &editor($r,$coursenum,$coursedom,$folder,$allowed,$upload_output);      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
        if ($hadchanges) {      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
    &mark_hash_old()  
        }  # get personal data
        &changewarning($r,$postexec);      my $uname=$env{'user.name'};
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      my $udom=$env{'user.domain'};
                      '.sequence';      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  
                      '.page';  # graphics settings
  my $container='sequence';  
  if ($env{'form.pagepath'}) {      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
     $container='page';  
  }      if ($allowed) {
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;   $script .= &editing_js($udom,$uname);
        $r->print(<<ENDFORM);      }
 <table cellspacing=4 cellpadding=4><tr>  # -------------------------------------------------------------------- Body tag
 <th bgcolor="#DDDDDD">$lt{'uplm'}</th>      $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
 <th bgcolor="#DDDDDD">$lt{'impp'}</th>      my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>      $r->print(&Apache::loncommon::start_page("$type Documents", $script,
 </tr>      {'force_register' => $showdoc,
 <tr><td bgcolor="#DDDDDD">                                       'bread_crumbs' => $brcrum}).
 $lt{'file'}:<br />        &Apache::loncommon::help_open_menu('','',273,'RAT'));
 <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">   
 <input type="file" name="uploaddoc" size="40">    my %allfiles = ();
 <br />    my %codebase = ();
 $lt{'title'}:<br />    my ($upload_result,$upload_output);
 <input type="text" size="50" name="comment">    if ($allowed) {
 $uploadtag        if (($env{'form.uploaddoc.filename'}) &&
 <input type="hidden" name="cmd" value="upload_default">    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 <br />  # Process file upload - phase one - upload and parse primary file.  
 <nobr>    undef($hadchanges);
 <label>$lt{'parse'}?            $upload_result = &process_file_upload(\$upload_output,$coursenum,
 <input type="checkbox" name="parserflag" />   $coursedom,\%allfiles,
 </label>   \%codebase,$1);
 </nobr>    if ($hadchanges) {
 <br />        &mark_hash_old();
 <br />    }
 <nobr>            if ($upload_result eq 'phasetwo') {
 <input type="submit" value="$lt{'upld'}">                $r->print($upload_output);
  $help{'Uploading_From_Harddrive'}            }
 </nobr>        } elsif ($env{'form.phasetwo'}) {
 </form>            my %newname = ();
 </td>            my %origname = ();
 <td bgcolor="#DDDDDD">            my %attribs = ();
 <form action="/adm/coursedocs" method="post" name="simpleeditdefault">            my $updateflag = 0;
 $lt{'pubd'}<br />            my $residx = $env{'form.newidx'};
 $uploadtag            my $primary_url = &unescape($env{'form.primaryurl'});
 <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}" />  # Process file upload - phase two - gather secondary files.
 <br />            for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
 <nobr>                if ($env{'form.embedded_item_'.$i.'.filename'}) {
 <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}" />                    my $javacodebase;
 $help{'Importing_LON-CAPA_Resource'}                    $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
 </nobr>                    $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
 <br />                    if (exists($env{'form.embedded_codebase_'.$i})) {
 <input type=button onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />                        $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
 <p>                        $origname{$i} =~ s#^\Q$javacodebase\E/##;
 <hr />                    }
 $lt{'copm'}<br />                    my @attributes = ();
 <input type="text" size="40" name="importmap"><br />                    if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
 <nobr><input type=button                         @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
 onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"                    } else {
 value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">                        @attributes = ($env{'form.embedded_attrib_'.$i});
 $help{'Load_Map'}</nobr>                    }
 </p>                    foreach my $attr (@attributes) {
 </form>                        push(@{$attribs{$i}},&unescape($attr));
 <hr />                    }
 <form action="/adm/groupsort" method="post" name="recover">                    if ($javacodebase) {
 <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />                        $codebase{$i} = $javacodebase;
 </form>                        $codebase{$i} =~ s#/$##;
 ENDFORM                        $updateflag = 1;
        unless ($env{'form.pagepath'}) {                    }
    $r->print(<<ENDFORM);                }
 <hr />                unless ($newname{$i} eq $origname{$i}) {
 <form action="/adm/coursedocs" method="post" name="newext">                    $updateflag = 1;
 $uploadtag                }
 <input type="hidden" name="importdetail" value="" />            }
 <nobr>  # Process file upload - phase three - modify primary file
 <input name="newext" type="button" onClick="javascript:makenewext('newext');"            if ($updateflag) {
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}                my ($content,$rtncode);
 </nobr>                my $updateflag = 0;
 </form>                my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
 <br /><form action="/adm/imsimportdocs" method="post" name="ims">                if ($getstatus eq 'ok') {
 <input type="hidden" name="folder" value="$folder" />                    foreach my $item (keys(%newname)) {
 <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />                        if ($newname{$item} ne $origname{$item}) {
 </nobr>                            my $attrib_regexp = '';
 </form>                            if (@{$attribs{$item}} > 1) {
 ENDFORM                                $attrib_regexp = join('|',@{$attribs{$item}});
        }                            } else {
        $r->print('</td><td bgcolor="#DDDDDD">');                                $attrib_regexp = $attribs{$item}[0];
        unless ($env{'form.pagepath'}) {                            }
            $r->print(<<ENDFORM);                            if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
 <br /><form action="/adm/coursedocs" method="post" name="newfolder">                            }
 <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="newfolder" type="button"                            $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
 onClick="javascript:makenewfolder(this.form,'$folderseq');"                        }
 value="$lt{'newf'}" />$help{'Adding_Folders'}                    }
 </nobr>  # Save edited file.
 </form>                    my $saveresult;
 <br /><form action="/adm/coursedocs" method="post" name="newpage">                    my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                    my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 <input type="hidden" name="importdetail" value="" />                    my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
 <nobr>                } else {
 <input name="newpage" type="button"                    &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
 onClick="javascript:makenewpage(this.form,'$pageseq');"                }
 value="$lt{'newp'}" />$help{'Adding_Pages'}            }
 </nobr>        }
 </form>    }
 <br /><form action="/adm/coursedocs" method="post" name="newsyl">  
 $uploadtag    unless ($showdoc ||  $upload_result eq 'phasetwo') {
 <input type="hidden" name="importdetail"   # -----------------------------------------------------------------------------
 value="Syllabus=/public/$coursedom/$coursenum/syllabus" />         my %lt=&Apache::lonlocal::texthash(
 <nobr>                  'uplm' => 'Upload a new main '.lc($type).' document',
 <input name="newsyl" type="submit" value="$lt{'syll'}" />                   'upls' => 'Upload a new supplemental '.lc($type).' document',
  $help{'Syllabus'}                  '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="newnav">                  'upld' => 'Upload Document',
 $uploadtag                  'srch' => 'Search',
 <input type="hidden" name="importdetail"                   'impo' => 'Import',
 value="Navigate Content=/adm/navmaps" />   'book' => 'Import Bookmarks',
 <nobr>                  'selm' => 'Select Map',
 <input name="newnav" type="submit" value="$lt{'navc'}" />                  'load' => 'Load Map',
 $help{'Navigate_Content'}                  'reco' => 'Recover Deleted Resources',
 </nobr>                  'newf' => 'New Folder',
 </form>                  'newp' => 'New Composite Page',
 <br /><form action="/adm/coursedocs" method="post" name="newsmppg">                  'extr' => 'External Resource',
 $uploadtag                  'syll' => 'Syllabus',
 <input type="hidden" name="importdetail" value="" />                  'navc' => 'Navigate Contents',
 <nobr>                  'sipa' => 'Simple Page',
 <input name="newsmppg" type="button" value="$lt{'sipa'}"                  'sipr' => 'Simple Problem',
 onClick="javascript:makesmppage();" /> $help{'Simple Page'}                  'drbx' => 'Drop Box',
 </nobr>                  'scuf' => 'Score Upload Form',
 </form>                  'bull' => 'Bulletin Board',
 <br /><form action="/adm/coursedocs" method="post" name="newsmpproblem">                  'mypi' => 'My Personal Info',
 $uploadtag                  'grpo' => 'Group Files',
 <input type="hidden" name="importdetail" value="" />                  'rost' => 'Course Roster',
 <nobr>   'abou' => 'About User',
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"                  'imsf' => 'Import IMS package',
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}                  'file' =>  'File',
 </nobr>                  'title' => 'Title',
 </form>                  'comment' => 'Comment',
 <br /><form action="/adm/coursedocs" method="post" name="newdropbox">                  'parse' => 'Upload embedded images/multimedia files if HTML file!',
 $uploadtag         'nd' => 'New Document',
 <input type="hidden" name="importdetail" value="" />   'pm' => 'Published Map',
 <nobr>             'sd' => 'Special Document',
 <input name="newdropbox" type="button" value="$lt{'drbx'}"   'mo' => 'More Options',
 onClick="javascript:makedropbox();" />   'hao' => 'Hide all Options'
 </nobr>             );
 </form>   # -----------------------------------------------------------------------------
 <br /><form action="/adm/coursedocs" method="post" name="newexamupload">   my $fileupload=(<<FIUP);
 $uploadtag   $lt{'file'}:<br />
 <input type="hidden" name="importdetail" value="" />   <input type="file" name="uploaddoc" size="40" />
 <nobr>  FIUP
 <input name="newexamupload" type="button" value="$lt{'scuf'}"  
 onClick="javascript:makeexamupload();" />   my $checkbox=(<<CHBO);
 $help{'Score_Upload_Form'}   <!-- <label>$lt{'parse'}?
 </nobr>   <input type="checkbox" name="parserflag" />
 </form>   </label> -->
 <br /><form action="/adm/coursedocs" method="post" name="newbul">   <label>
 $uploadtag   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
 <input type="hidden" name="importdetail" value="" />   </label>
 <nobr>  CHBO
 <input name="newbulletin" type="button" value="$lt{'bull'}"  
 onClick="javascript:makebulboard();" />   my $fileuploadform=(<<FUFORM);
 $help{'Bulletin Board'}   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 </nobr>   $fileupload
 </form>   <br />
 <br /><form action="/adm/coursedocs" method="post" name="newaboutme">   $lt{'title'}:<br />
 $uploadtag   <input type="text" size="50" name="comment" />
 <input type="hidden" name="importdetail"    $uploadtag
 value="$plainname=/adm/$udom/$uname/aboutme" />   <input type="hidden" name="cmd" value="upload_default" />
 <nobr>   <br />
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />   <span class="LC_nobreak">
 $help{'My Personal Info'}   $checkbox
 </nobr>   </span>
 </form>   <br />
 <br /><form action="/adm/coursedocs" method="post" name="newaboutsomeone">   <br />
 $uploadtag   <span class="LC_nobreak">
 <input type="hidden" name="importdetail" value="" />   <input type="submit" value="$lt{'upld'}" />
 <nobr>   $help{'Uploading_From_Harddrive'}
 <input name="newaboutsomeone" type="button" value="$lt{'abou'}"    </span>
 onClick="javascript:makeabout();" />   </form>
 </nobr>  FUFORM
 </form>  
 <br /><form action="/adm/coursedocs" method="post" name="newgroupfiles">   my $simpleeditdefaultform=(<<SEDFFORM);
 $uploadtag   <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
 <input type="hidden" name="importdetail"   $lt{'pubd'}<br />
 value="Group Files=/adm/$coursedom/$coursenum/aboutme" />   $uploadtag
 <nobr>   <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />
 <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />   <br />
 $help{'Group Files'}   <span class="LC_nobreak">
 </nobr>   <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />
 </form>   $help{'Importing_LON-CAPA_Resource'}
 ENDFORM   </span>
        }   <br />
        if ($env{'form.pagepath'}) {   <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
            $r->print(<<ENDBLOCK);   <hr />
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">   <p>
 $uploadtag   $lt{'copm'}<br />
 <input type="hidden" name="importdetail" value="" />   <input type="text" size="40" name="importmap" /><br />
 <nobr>   <span class="LC_nobreak"><input type="button"
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"   onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}   value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
 </nobr>   $help{'Load_Map'}</span>
 </form>   </p>
 <br /><form action="/adm/coursedocs" method="post" name="newexamupload">   </form>
 $uploadtag  SEDFFORM
 <input type="hidden" name="importdetail" value="" />  
 <nobr>   my $extresourcesform=(<<ERFORM);
 <input name="newexamupload" type="button" value="$lt{'scuf'}"   <form action="/adm/coursedocs" method="post" name="newext">
 onClick="javascript:makeexamupload();" />   $uploadtag
 $help{'Score_Upload_Form'}   <input type="hidden" name="importdetail" value="" />
 </nobr>   <span class="LC_nobreak">
 </form>   <input name="newext" type="button" onClick="javascript:makenewext('newext');"
 ENDBLOCK   value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
        }   </span>
        $r->print('</td></tr>'."\n".   </form>
 '</table>');  ERFORM
        $r->print('</td></tr>');  
     }      if ($allowed) {
 # ----------------------------------------------------- Supplemental documents   &update_paste_buffer($coursenum,$coursedom);
     if (!$forcestandard) {         my $dumpbut=&dumpbutton();
        $r->print('<tr><td bgcolor="#BBBBBB">');         my $exportbut=&exportbutton();
 # '<h2>'.&mt('Supplemental Course Documents').         my %lt=&Apache::lonlocal::texthash(
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');   'vc' => 'Verify Content',
        my $folder=$env{'form.folder'};   'cv' => 'Check/Set Resource Versions',
        unless ($folder=~/^supplemental/) {   'ls' => 'List Symbs',
    $folder='supplemental';                                           'sl' => 'Show Log'
        }    );
        if ($folder =~ /^supplemental$/ &&  
    $env{'form.folderpath'} =~ /^default\&/) {         my $folderpath=$env{'form.folderpath'};
    $env{'form.folderpath'}='supplemental&'.         if (!$folderpath) {
        &escape(&mt('Supplemental '.$type.' Documents'));     if ($env{'form.folder'} eq '' ||
        }         $env{'form.folder'} eq 'supplemental') {
        &editor($r,$coursenum,$coursedom,$folder,$allowed);         $folderpath='default&'.
        if ($allowed) {     &escape(&mt('Main '.$type.' Documents'));
        my $folderseq=     }
                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.         }
                      '.sequence';         unless ($env{'form.pagepath'}) {
              $containertag = '<input type="hidden" name="folderpath" value="" />';
           $r->print(<<ENDSUPFORM);             $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
 <table cellspacing=4 cellpadding=4><tr>         }
 <th bgcolor="#DDDDDD">$lt{'upls'}</th>  
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>         $r->print(<<ENDCOURSEVERIFY);
 </tr>  <form name="renameform" method="post" action="/adm/coursedocs">
 <tr><td bgcolor="#DDDDDD">    <input type="hidden" name="title" />
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">    <input type="hidden" name="cmd" />
 <input type="file" name="uploaddoc" size="40">    <input type="hidden" name="markcopy" />
 <br />    <input type="hidden" name="copyfolder" />
 <br />    $containertag
 <nobr>  </form>
 <label>$lt{'parse'}?  <form name="simpleedit" method="post" action="/adm/coursedocs">
 <input type="checkbox" name="parserflag" />    <input type="hidden" name="importdetail" value="" />
 </label>    $uploadtag
 </nobr>  </form>
 <br /><br />  <form action="/adm/coursedocs" method="post" name="courseverify">
 $lt{'comment'}:<br />    <div class="LC_docs_course_commands">
 <textarea cols=50 rows=4 name='comment'>  
 </textarea>        <div>
 <br />          <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />        </div>
 <input type="hidden" name="cmd" value="upload_supplemental">        <div>
 <nobr>          <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}
 <input type="submit" value="$lt{'upld'}">        </div>
  $help{'Uploading_From_Harddrive'}          $dumpbut
 </nobr>          $exportbut
 </form>        <div>
 </td>          <input type="submit" name="listsymbs" value="$lt{'ls'}" />
 <td bgcolor="#DDDDDD">        </div>
 <form action="/adm/coursedocs" method="post" name="supnewfolder">        <div>
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />          <input type="hidden" name="folder" value="$env{'form.folder'}" />
 <input type="hidden" name="importdetail" value="" />          <input type="submit" name="docslog" value="$lt{'sl'}" />
 <nobr>        </div>
 <input name="newfolder" type="button"    </div>
 onClick="javascript:makenewfolder(this.form,'$folderseq');"  </form>
 value="$lt{'newf'}" /> $help{'Adding_Folders'}  <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="supnewext">       &mt('Editing the Table of Contents for your '.$type)));
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      }
 <input type="hidden" name="importdetail" value="" />  # --------------------------------------------------------- Standard documents
 <nobr>      $r->print('<table class="LC_docs_documents">');
 <input name="newext" type="button"   
 onClick="javascript:makenewext('supnewext');"      if (($standard) && ($allowed) && (!$forcesupplement)) {
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   $r->print('<tr><td class="LC_docs_document">');
 </nobr>  #  '<h2>'.&mt('Main Course Documents').
 </form>  #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');
 <br /><form action="/adm/coursedocs" method="post" name="supnewsyl">         my $folder=$env{'form.folder'};
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />         if ($folder eq '' || $folder eq 'supplemental') {
 <input type="hidden" name="importdetail"              $folder='default';
 value="Syllabus=/public/$coursedom/$coursenum/syllabus" />     $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));
 <nobr>             $uploadtag = '<input type="hidden" name="folderpath" value="'.
 <input name="newsyl" type="submit" value="$lt{'syll'}" />         &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 $help{'Syllabus'}         }
 </nobr>         my $postexec='';
 </form>         if ($folder eq 'default') {
 <br /><form action="/adm/coursedocs" method="post" name="subnewaboutme">     $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />         } else {
 <input type="hidden" name="importdetail"              #$postexec='self.close();';
 value="$plainname=/adm/$udom/$uname/aboutme" />         }
 <nobr>         $hadchanges=0;
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />         my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,
 $help{'My Personal Info'}     $upload_output,$type);
 </nobr>         if ($error) {
 </form>     $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 </td></tr>         }
 </table></td></tr>         if ($hadchanges) {
 ENDSUPFORM     &mark_hash_old();
        }         }
     }         &changewarning($r,$postexec);
     if ($allowed) {         my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
  $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>');                       '.sequence';
     }         my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
     $r->print('</table>');                       '.page';
   } else {   my $container='sequence';
       unless ($upload_result eq 'phasetwo') {   if ($env{'form.pagepath'}) {
 # -------------------------------------------------------- This is showdoc mode      $container='page';
           $r->print("<h1>".&mt('Uploaded Document').' - '.   }
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.   my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".  
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');  
       }  
   }   my $recoverform=(<<RFORM);
  }   <form action="/adm/groupsort" method="post" name="recover">
  $r->print(&Apache::loncommon::end_page());   <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />
  return OK;   </form>
 }   RFORM
   
    my $imspform=(<<IMSPFORM);
 sub editing_js {   <form action="/adm/imsimportdocs" method="post" name="ims">
     my ($udom,$uname) = @_;   <input type="hidden" name="folder" value="$folder" />
     my $now = time();   <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />
    </form>
     return <<ENDNEWSCRIPT;  IMSPFORM
 function makenewfolder(targetform,folderseq) {  
     var foldername=prompt('Name of New Folder','New Folder');   my $newnavform=(<<NNFORM);
     if (foldername) {   <form action="/adm/coursedocs" method="post" name="newnav">
        targetform.importdetail.value=escape(foldername)+"="+folderseq;   $uploadtag
         targetform.submit();   <input type="hidden" name="importdetail"
     }   value="$lt{'navc'}=/adm/navmaps" />
 }   <span class="LC_nobreak">
    <input name="newnav" type="submit" value="$lt{'navc'}" />
 function makenewpage(targetform,folderseq) {   $help{'Navigate_Content'}
     var pagename=prompt('Name of New Page','New Page');   </span>
     if (pagename) {   </form>
         targetform.importdetail.value=escape(pagename)+"="+folderseq;  NNFORM
         targetform.submit();   my $newsmppageform=(<<NSPFORM);
     }   <form action="/adm/coursedocs" method="post" name="newsmppg">
 }   $uploadtag
    <input type="hidden" name="importdetail" value="" />
 function makenewext(targetname) {   <span class="LC_nobreak">
     this.document.forms.extimport.useform.value=targetname;   <input name="newsmppg" type="button" value="$lt{'sipa'}"
     window.open('/adm/rat/extpickframe.html');   onClick="javascript:makesmppage();" /> $help{'Simple Page'}
 }   </span>
    </form>
 function makeexamupload() {  NSPFORM
    var title=prompt('Listed Title for the Uploaded Score');  
    if (title) {    my $newsmpproblemform=(<<NSPROBFORM);
     this.document.forms.newexamupload.importdetail.value=   <form action="/adm/coursedocs" method="post" name="newsmpproblem">
  escape(title)+'=/res/lib/templates/examupload.problem';   $uploadtag
     this.document.forms.newexamupload.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 makesmppage() {   </span>
    var title=prompt('Listed Title for the Page');   </form>
    if (title) {   
     this.document.forms.newsmppg.importdetail.value=  NSPROBFORM
  escape(title)+'=/adm/$udom/$uname/$now/smppg';  
     this.document.forms.newsmppg.submit();   my $newdropboxform=(<<NDBFORM);
    }   <form action="/adm/coursedocs" method="post" name="newdropbox">
 }   $uploadtag      
    <input type="hidden" name="importdetail" value="" />
 function makesmpproblem() {   <span class="LC_nobreak">          
    var title=prompt('Listed Title for the Problem');   <input name="newdropbox" type="button" value="$lt{'drbx'}"
    if (title) {    onClick="javascript:makedropbox();" />
     this.document.forms.newsmpproblem.importdetail.value=   </span>        
  escape(title)+'=/res/lib/templates/simpleproblem.problem';   </form>
     this.document.forms.newsmpproblem.submit();  NDBFORM
    }  
 }   my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
 function makedropbox() {   $uploadtag
    var title=prompt('Listed Title for the Drop Box');   <input type="hidden" name="importdetail" value="" />
    if (title) {    <span class="LC_nobreak">
     this.document.forms.newdropbox.importdetail.value=   <input name="newexamupload" type="button" value="$lt{'scuf'}"
         escape(title)+'=/res/lib/templates/DropBox.problem';   onClick="javascript:makeexamupload();" />
     this.document.forms.newdropbox.submit();   $help{'Score_Upload_Form'}
    }   </span>
 }   </form>
   NEXUFORM
 function makebulboard() {  
    var title=prompt('Listed Title for the Bulletin Board');   my $newbulform=(<<NBFORM);
    if (title) {   <form action="/adm/coursedocs" method="post" name="newbul">
     this.document.forms.newbul.importdetail.value=   $uploadtag
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';   <input type="hidden" name="importdetail" value="" />
     this.document.forms.newbul.submit();   <span class="LC_nobreak">
    }   <input name="newbulletin" type="button" value="$lt{'bull'}"
 }   onClick="javascript:makebulboard();" />
    $help{'Bulletin Board'}
 function makeabout() {   </span>
    var user=prompt("Enter user:domain for User's 'About Me' Page");   </form>
    if (user) {  NBFORM
        var comp=new Array();  
        comp=user.split(':');   my $newaboutmeform=(<<NAMFORM);
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {   <form action="/adm/coursedocs" method="post" name="newaboutme">
    if ((comp[0]) && (comp[1])) {   $uploadtag
        this.document.forms.newaboutsomeone.importdetail.value=   <input type="hidden" name="importdetail"
    'About '+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';   value="$plainname=/adm/$udom/$uname/aboutme" />
        this.document.forms.newaboutsomeone.submit();   <span class="LC_nobreak">
    } else {   <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
                alert("Not a valid user:domain");   $help{'My Personal Info'}
            }   </span>
        } else {   </form>
            alert("Please enter both user and domain in the format user:domain");   NAMFORM
        }  
    }   my $newaboutsomeoneform=(<<NASOFORM);
 }   <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    $uploadtag
 function makeims() {   <input type="hidden" name="importdetail" value="" />
     var caller = document.forms.ims.folder.value;   <span class="LC_nobreak">
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";   <input name="newaboutsomeone" type="button" value="$lt{'abou'}"
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");   onClick="javascript:makeabout();" />
     newWindow.location.href = newlocation;   </span>
 }   </form>
   NASOFORM
   
 function finishpick() {  
     var title=this.document.forms.extimport.title.value;   my $newrosterform=(<<NROSTFORM);
     var url=this.document.forms.extimport.url.value;   <form action="/adm/coursedocs" method="post" name="newroster">
     var form=this.document.forms.extimport.useform.value;   $uploadtag
     eval   <input type="hidden" name="importdetail"
      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+   value="$lt{'rost'}=/adm/viewclasslist" />
     '";this.document.forms.'+form+'.submit();');   <span class="LC_nobreak">
 }   <input name="newroster" type="submit" value="$lt{'rost'}" />
    $help{'Course Roster'}
 function changename(folderpath,index,oldtitle,container,pagesymb) {   </span>
     var title=prompt('New Title',oldtitle);   </form>
     if (title) {  NROSTFORM
  this.document.forms.renameform.title.value=title;  
  this.document.forms.renameform.cmd.value='rename_'+index;         $r->print(<<ENDFORM);
         if (container == 'sequence') {  
     this.document.forms.renameform.folderpath.value=folderpath;  <ul class="LC_TabContent">
         }  <li>$lt{'nd'}</li>
         if (container == 'page') {  <li>$lt{'pm'}</li>
             this.document.forms.renameform.pagepath.value=folderpath;  <li>$lt{'pubd'}</li>
             this.document.forms.renameform.pagesymb.value=pagesymb;  <li>$lt{'sd'}</li>
         }  <li>$lt{'mo'}</li>
         this.document.forms.renameform.submit();  <li>$lt{'hao'}</li>
     }  </ul>
 }  
   <table class="LC_docs_adddocs">
 function removeres(folderpath,index,oldtitle,container,pagesymb) {  <!-- <tr>
     if (confirm('WARNING: Removing a resource makes associated grades and scores inaccessible!\\nRemove "'+oldtitle+'"?')) {  <th>$lt{'uplm'}</th>
  this.document.forms.renameform.cmd.value='del_'+index;  <th>$lt{'impp'}</th>
         if (container == 'sequence') {  <th>$lt{'spec'}</th>
             this.document.forms.renameform.folderpath.value=folderpath;  </tr> -->
         }  <tr>
         if (container == 'page') {  <td>
             this.document.forms.renameform.pagepath.value=folderpath;  $fileuploadform
             this.document.forms.renameform.pagesymb.value=pagesymb;  </td>
         }  <td>
         this.document.forms.renameform.submit();  $simpleeditdefaultform
     }  <hr />
 }  $recoverform
   ENDFORM
 function cutres(folderpath,index,oldtitle,container,pagesymb) {         unless ($env{'form.pagepath'}) {
     if (confirm('WARNING: Cutting a resource makes associated grades and scores inaccessible!\\nGrades remain inaccessible if resource is pasted into another folder.\\nCut "'+oldtitle+'"?')) {     $r->print(<<ENDFORM);
  this.document.forms.renameform.cmd.value='cut_'+index;  <hr />
  this.document.forms.renameform.markcopy.value=index;  $extresourcesform
         if (container == 'sequence') {   <br />
             this.document.forms.renameform.folderpath.value=folderpath;  $imspform
         }  ENDFORM
         if (container == 'page') {         }
             this.document.forms.renameform.pagepath.value=folderpath;         $r->print('</td><td>');
             this.document.forms.renameform.pagesymb.value=pagesymb;         unless ($env{'form.pagepath'}) {
         }     my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
         this.document.forms.renameform.submit();  
     }  
 }  
    my $newpageform=(<<NPFORM);
 function markcopy(folderpath,index,oldtitle,container,pagesymb) {   <form action="/adm/coursedocs" method="post" name="newpage">
     this.document.forms.renameform.markcopy.value=index;   <input type="hidden" name="folderpath" value="$path" />
     if (container == 'sequence') {   <input type="hidden" name="importdetail" value="" />
  this.document.forms.renameform.folderpath.value=folderpath;   <span class="LC_nobreak">
     }   <input name="newpage" type="button"
     if (container == 'page') {   onClick="javascript:makenewpage(this.form,'$pageseq');"
  this.document.forms.renameform.pagepath.value=folderpath;   value="$lt{'newp'}" />$help{'Adding_Pages'}
  this.document.forms.renameform.pagesymb.value=pagesymb;   </span>
     }   </form>
     this.document.forms.renameform.submit();  NPFORM
 }  
    my $newfolderform=(<<NFFORM);
 ENDNEWSCRIPT   <form action="/adm/coursedocs" method="post" name="newfolder">
 }   <input type="hidden" name="folderpath" value="$path" />
 1;   <input type="hidden" name="importdetail" value="" />
 __END__   <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.256  
changed lines
  Added in v.1.326


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