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

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

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


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