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

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


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