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

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


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