Diff for /loncom/interface/londocs.pm between versions 1.327 and 1.502

version 1.327, 2009/01/28 12:56:08 version 1.502, 2012/11/01 01:01:13
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;
   
 package Apache::londocs;  use strict;
   use Apache::Constants qw(:common :http);
 use strict;  use Apache::imsexport;
 use Apache::Constants qw(:common :http);  use Apache::lonnet;
 use Apache::imsexport;  use Apache::loncommon;
 use Apache::lonnet;  use Apache::lonhtmlcommon;
 use Apache::loncommon;  use LONCAPA::map();
 use LONCAPA::map();  use Apache::lonratedt();
 use Apache::lonratedt();  use Apache::lonxml;
 use Apache::lonxml;  use Apache::lonclonecourse;
 use Apache::lonclonecourse;  use Apache::lonnavmaps;
 use Apache::lonnavmaps;  use Apache::lonnavdisplay();
 use HTML::Entities;  use Apache::lonuserstate();
 use GDBM_File;  use HTML::Entities;
 use Apache::lonlocal;  use HTML::TokeParser;
 use Cwd;  use GDBM_File;
 use LONCAPA qw(:DEFAULT :match);  use Apache::lonlocal;
   use Cwd;
 my $iconpath;  use LONCAPA qw(:DEFAULT :match);
   
 my %hash;  my $iconpath;
   
 my $hashtied;  my %hash;
 my %alreadyseen=();  
   my $hashtied;
 my $hadchanges;  my %alreadyseen=();
   
   my $hadchanges;
 my %help=();  
   
   my %help=();
 sub mapread {  
     my ($coursenum,$coursedom,$map)=@_;  
     return  sub mapread {
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map)=@_;
      $map);      return
 }        &LONCAPA::map::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,$contentchg)=@_;
       $map,1);      my $report;
     if ($errtext) { return ($errtext,2); }      if (($contentchg) && ($map =~ /^default/)) {
             $report = 1;
     $hadchanges=1;      }
     return ($errtext,0);      my ($outtext,$errtext)=
 }        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1,$report);
       if ($errtext) { return ($errtext,2); }
   
 sub authorhosts {      $hadchanges=1;
     my %outhash=();      return ($errtext,0);
     my $home=0;  }
     my $other=0;  
     foreach my $key (keys(%env)) {  
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {  
     my $role=$1;  sub authorhosts {
     my $realm=$2;      my %outhash=();
     my ($start,$end)=split(/\./,$env{$key});      my $home=0;
     if (($start) && ($start>time)) { next; }      my $other=0;
     if (($end) && (time>$end)) { next; }      foreach my $key (keys(%env)) {
     my ($ca,$cd);   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     if ($1 eq 'au') {      my $role=$1;
  $ca=$env{'user.name'};      my $realm=$2;
  $cd=$env{'user.domain'};      my ($start,$end)=split(/\./,$env{$key});
     } else {      if (($start) && ($start>time)) { next; }
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);      if (($end) && (time>$end)) { next; }
     }      my ($ca,$cd);
     my $allowed=0;      if ($1 eq 'au') {
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);   $ca=$env{'user.name'};
     my @ids=&Apache::lonnet::current_machine_ids();   $cd=$env{'user.domain'};
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      } else {
     if ($allowed) {   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  $home++;      }
  $outhash{'home_'.$ca.'@'.$cd}=1;      my $allowed=0;
     } else {      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      my @ids=&Apache::lonnet::current_machine_ids();
  $other++;      foreach my $id (@ids) {
     }                  if ($id eq $myhome) {
  }                      $allowed=1;
     }                      last;
     return ($home,$other,%outhash);                  }
 }              }
       if ($allowed) {
    $home++;
 sub dumpbutton {   $outhash{'home_'.$ca.':'.$cd}=1;
     my ($home,$other,%outhash)=&authorhosts();      } else {
     my $type = &Apache::loncommon::course_type();   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
     if ($home+$other==0) { return ''; }   $other++;
     if ($home) {      }
  return '<input type="submit" name="dumpcourse" value="'.   }
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      }
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');      return ($home,$other,%outhash);
     } else {  }
  return '<div>'.  
      &mt('Dump '.$type.  
  ' DOCS to Construction Space: available on other servers').  sub clean {
  '</div>';      my ($title)=@_;
     }      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
 }      return $title;
   }
 sub clean {  
     my ($title)=@_;  
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;  
     return $title;  sub dumpcourse {
 }      my ($r) = @_;
       my $crstype = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
                 &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
 sub dumpcourse {      $r->print(&startContentScreen('tools'));
     my ($r) = @_;      my ($home,$other,%outhash)=&authorhosts();
     my $type = &Apache::loncommon::course_type();      unless ($home) {
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').          $r->print(&endContentScreen());
       '<form name="dumpdoc" method="post">');          return '';
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      }
     my ($home,$other,%outhash)=&authorhosts();      my $origcrsid=$env{'request.course.id'};
     unless ($home) { return ''; }      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my $origcrsid=$env{'request.course.id'};      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);  # Do the dumping
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
 # Do the dumping              $r->print(&endContentScreen());
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }              return '';
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});          }
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
  my $title=$env{'form.authorfolder'};   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  $title=&clean($title);   my $title=$env{'form.authorfolder'};
  my %replacehash=();   $title=&clean($title);
  foreach my $key (keys(%env)) {   my %replacehash=();
     if ($key=~/^form\.namefor\_(.+)/) {   foreach my $key (keys(%env)) {
  $replacehash{$1}=$env{$key};      if ($key=~/^form\.namefor\_(.+)/) {
     }   $replacehash{$1}=$env{$key};
  }      }
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   }
  $crs=~s/\_/\//g;   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  foreach my $item (keys(%replacehash)) {   $crs=~s/\_/\//g;
     my $newfilename=$title.'/'.$replacehash{$item};   foreach my $item (keys(%replacehash)) {
     $newfilename=~s/\.(\w+)$//;      my $newfilename=$title.'/'.$replacehash{$item};
     my $ext=$1;      $newfilename=~s/\.(\w+)$//;
     $newfilename=&clean($newfilename);      my $ext=$1;
     $newfilename.='.'.$ext;      $newfilename=&clean($newfilename);
     my @dirs=split(/\//,$newfilename);      $newfilename.='.'.$ext;
     my $path='/home/'.$ca.'/public_html';      my @dirs=split(/\//,$newfilename);
     my $makepath=$path;      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
     my $fail=0;      my $makepath=$path;
     for (my $i=0;$i<$#dirs;$i++) {      my $fail=0;
  $makepath.='/'.$dirs[$i];      for (my $i=0;$i<$#dirs;$i++) {
  unless (-e $makepath) {   $makepath.='/'.$dirs[$i];
     unless(mkdir($makepath,0777)) { $fail=1; }   unless (-e $makepath) {
  }      unless(mkdir($makepath,0777)) { $fail=1; }
     }   }
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      }
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     print $fh &Apache::lonclonecourse::rewritefile(   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),      print $fh &Apache::lonclonecourse::rewritefile(
      (%replacehash,$crs => '')           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
     );       (%replacehash,$crs => '')
  } else {      );
     print $fh   } else {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);      print $fh
        }           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  $fh->close();         }
     } else {   $fh->close();
  $fail=1;      } else {
     }   $fail=1;
     if ($fail) {      }
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');      if ($fail) {
     } else {   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      } else {
     }   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  }      }
     } else {   }
 # Input form      } else {
  unless ($home==1) {          $r->print(&mt('Searching ...').'<br />');
     $r->print(          $r->rflush();
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');  # Input form
  }          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
  foreach my $key (sort(keys(%outhash))) {   unless ($home==1) {
     if ($key=~/^home_(.+)$/) {      $r->print('<div class="LC_left_float">'.
  if ($home==1) {        '<fieldset><legend>'.
     $r->print(                        &mt('Select the Authoring Space').
   '<input type="hidden" name="authorspace" value="'.$1.'" />');                        '</legend><select name="authorspace">');
  } else {   }
     $r->print('<option value="'.$1.'">'.$1.' - '.   foreach my $key (sort(keys(%outhash))) {
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');      if ($key=~/^home_(.+)$/) {
  }   if ($home==1) {
     }      $r->print(
  }    '<input type="hidden" name="authorspace" value="'.$1.'" />');
  unless ($home==1) {   } else {
     $r->print('</select>');      $r->print('<option value="'.$1.'">'.$1.' - '.
  }        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
  my $title=$origcrsdata{'description'};   }
  $title=~s/[\/\s]+/\_/gs;      }
  $title=&clean($title);   }
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'   unless ($home==1) {
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');      $r->print('</select></fieldset></div>'."\n");
  &tiehash();   }
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'   my $title=$origcrsdata{'description'};
                  .&Apache::loncommon::start_data_table()   $title=~s/[\/\s]+/\_/gs;
                  .&Apache::loncommon::start_data_table_header_row()   $title=&clean($title);
                  .'<th>'.&mt('Internal Filename').'</th>'   $r->print('<div class="LC_left_float">'.
                  .'<th>'.&mt('Title').'</th>'                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
                  .'<th>'.&mt('Save as ...').'</th>'                    '<input type="text" size="50" name="authorfolder" value="'.
                  .&Apache::loncommon::end_data_table_header_row());                    $title.'" />'.
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {                    '</fieldset></div><br clear="all" />'."\n");
     $r->print(&Apache::loncommon::start_data_table_row()   &tiehash();
                      .'<td>'.$file.'</td>');   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
     my ($ext)=($file=~/\.(\w+)$/);                   .&Apache::loncommon::start_data_table()
     my $title=$hash{'title_'.$hash{                   .&Apache::loncommon::start_data_table_header_row()
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                   .'<th>'.&mt('Internal Filename').'</th>'
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');                   .'<th>'.&mt('Title').'</th>'
     if (!$title) {                   .'<th>'.&mt('Save as ...').'</th>'
  $title=$file;                   .&Apache::loncommon::end_data_table_header_row());
     } else {   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  $title=~s|/|_|g;      $r->print(&Apache::loncommon::start_data_table_row()
     }                       .'<td>'.$file.'</td>');
     $title=~s/\.(\w+)$//;      my ($ext)=($file=~/\.(\w+)$/);
     $title=&clean($title);      my $title=$hash{'title_'.$hash{
     $title.='.'.$ext;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
                      .&Apache::loncommon::end_data_table_row());      if (!$title) {
  }   $title=$file;
  $r->print(&Apache::loncommon::end_data_table());      } else {
  &untiehash();   $title=~s|/|_|g;
  $r->print(      }
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      $title=~s/\.(\w+)$//;
     }      $title=&clean($title);
 }      $title.='.'.$ext;
       $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
                        .&Apache::loncommon::end_data_table_row());
    }
 sub exportbutton {   $r->print(&Apache::loncommon::end_data_table());
     my $type = &Apache::loncommon::course_type();   &untiehash();
     return '<input type="submit" name="exportcourse" value="'.   $r->print(
             &mt('Export '.$type.' to IMS').'" />'.    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');      }
 }      $r->print(&endContentScreen());
   }
   
   sub group_import {
 sub exportcourse {      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
     my $r=shift;  
     my $type = &Apache::loncommon::course_type();      while (@files) {
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',   my ($name, $url, $residx) = @{ shift(@files) };
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
     my $numdisc = keys(%discussiontime);       && ($caller eq 'londocs')
     my $navmap = Apache::lonnavmaps::navmap->new();       && (!&Apache::lonnet::stat_file($url))) {
     if (!defined($navmap)) {  
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').              my $errtext = '';
                   '<h2>IMS Export Failed</h2>'.              my $fatal = 0;
                   '<div class="LC_error">'.              my $newmapstr = '<map>'."\n".
                   &mt('Unable to retrieve information about course contents').                              '<resource id="1" src="" type="start"></resource>'."\n".
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');                              '<link from="1" to="2" index="1"></link>'."\n".
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                              '<resource id="2" src="" type="finish"></resource>'."\n".
         return;                              '</map>';
     }              $env{'form.output'}=$newmapstr;
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
     my $curRes;                                                  'output',$1.$2);
     my $outcome;              if ($result != m|^/uploaded/|) {
                   $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                  $fatal = 2;
                                             ['finishexport']);              }
     if ($env{'form.finishexport'}) {              if ($fatal) {
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                  return ($errtext,$fatal);
                                             ['archive','discussion']);              }
           }
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');   if ($url) {
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');      if (!$residx
         if (@exportitems == 0 && @discussions == 0) {   || defined($LONCAPA::map::zombies[$residx])) {
             $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';   $residx = &LONCAPA::map::getresidx($url,$residx);
         } else {   push(@LONCAPA::map::order, $residx);
             my $now = time;      }
             my %symbs;      my $ext = 'false';
             my $manifestok = 0;      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
             my $imsresources;      $url  = &LONCAPA::map::qtunescape($url);
             my $tempexport;      $name = &LONCAPA::map::qtunescape($name);
             my $copyresult;      $LONCAPA::map::resources[$residx] =
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);   join(':', ($name, $url, $ext, 'normal', 'res'));
             if ($manifestok) {   }
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);      }
                 close($ims_manifest);      return &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
   }
 #Create zip file in prtspool  
                 my $imszipfile = '/prtspool/'.  sub breadcrumbs {
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.      my ($allowed,$crstype)=@_;
                    time.'_'.rand(1000000000).'.zip';      &Apache::lonhtmlcommon::clear_breadcrumbs();
                 my $cwd = &Cwd::getcwd();      my (@folders);
                 my $imszip = '/home/httpd/'.$imszipfile;      if ($env{'form.pagepath'}) {
                 chdir $tempexport;          @folders = split('&',$env{'form.pagepath'});
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");      } else {
                 close(OUTPUT);          @folders=split('&',$env{'form.folderpath'});
                 chdir $cwd;      }
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      my $folderpath;
                 if ($copyresult) {      my $plain='';
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);      my $randompick=-1;
                 }      my $isencrypted=0;
             } else {      my $ishidden=0;
                 $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 />';      my $is_random_order=0;
             }      while (@folders) {
         }   my $folder=shift(@folders);
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));      my $foldername=shift(@folders);
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));   if ($folderpath) {$folderpath.='&';}
         $r->print($outcome);   $folderpath.=$folder.'&'.$foldername;
         $r->print(&Apache::loncommon::end_page());          my $url;
     } else {          if ($allowed) {
         my $display;              $url = '/adm/coursedocs?folderpath=';
         $display = '<form name="exportdoc" method="post">'."\n";          } else {
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');              $url = '/adm/supplemental?folderpath=';
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.          }
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.   $url .= &escape($folderpath);
                     '<input type="button" value="check all" '.   my $name=&unescape($foldername);
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.  # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.    $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.   if ($1 ne '') {
                     '<td>&nbsp;</td><td>&nbsp;</td>'.             $randompick=$1;
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.          } else {
                     '</b></legend><input type="button" value="check all"'.             $randompick=-1;
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.          }
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.          if ($2) { $ishidden=1; }
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.          if ($3) { $isencrypted=1; }
                     '</tr></table>';   if ($4 ne '') { $is_random_order = 1; }
         my $curRes;          if ($folder eq 'supplemental') {
         my $depth = 0;              $name = &mt('Supplemental '.$crstype.' Content');
         my $count = 0;          }
         my $boards = 0;   &Apache::lonhtmlcommon::add_breadcrumb(
         my $startcount = 5;        {'href'=>$url,
         my %parent = ();         'title'=>$name,
         my %children = ();         'text'=>$name,
         my $lastcontainer = $startcount;         'no_mt'=>1,
         my @bgcolors = ('#F6F6F6','#FFFFFF');         });
         $display .= '<table cellspacing="0"><tr>'.   $plain.=$name.' &gt; ';
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";      }
         if ($numdisc > 0) {      $plain=~s/\&gt\;\s*$//;
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";      return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
         }         undef, undef, 1 ),$randompick,$ishidden,
         $display.='&nbsp;</td></tr>';                                                 $isencrypted,$plain,$is_random_order);
         while ($curRes = $it->next()) {  }
             if (ref($curRes)) {  
                 $count ++;  sub log_docs {
             }      return &Apache::lonnet::write_log('course','docslog',@_);
             if ($curRes == $it->BEGIN_MAP()) {  }
                 $depth++;  
                 $parent{$depth} = $lastcontainer;  {
             }      my @oldresources=();
             if ($curRes == $it->END_MAP()) {      my @oldorder=();
                 $depth--;      my $parmidx;
                 $lastcontainer = $parent{$depth};      my %parmaction=();
             }      my %parmvalue=();
             if (ref($curRes)) {      my $changedflag;
                 my $symb = $curRes->symb();  
                 my $ressymb = $symb;      sub snapshotbefore {
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {          @oldresources=@LONCAPA::map::resources;
                     unless ($ressymb =~ m|adm/wrapper/adm|) {          @oldorder=@LONCAPA::map::order;
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';          $parmidx=undef;
                     }          %parmaction=();
                 }          %parmvalue=();
                 my $color = $count%2;          $changedflag=0;
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".      }
                     '<input type="checkbox" name="archive" value="'.$count.'" ';  
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {      sub remember_parms {
                     my $checkitem = $count + $boards + $startcount;          my ($idx,$parameter,$action,$value)=@_;
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';          $parmidx=$idx;
                 }          $parmaction{$parameter}=$action;
                 $display .= ' />'."\n";          $parmvalue{$parameter}=$value;
                 for (my $i=0; $i<$depth; $i++) {          $changedflag=1;
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";      }
                 }  
                 if ($curRes->is_sequence()) {      sub log_differences {
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";          my ($plain)=@_;
                     $lastcontainer = $count + $startcount + $boards;          my %storehash=('folder' => $plain,
                 } elsif ($curRes->is_page()) {                         'currentfolder' => $env{'form.folder'});
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";          if ($parmidx) {
                     $lastcontainer = $count + $startcount + $boards;             $storehash{'parameter_res'}=$oldresources[$parmidx];
                 }             foreach my $parm (keys(%parmaction)) {
                 my $currelem = $count+$boards+$startcount;                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
                 $children{$parent{$depth}} .= $currelem.':';                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
                 $display .= '&nbsp;'.$curRes->title().'</td>';             }
                 if ($discussiontime{$ressymb} > 0) {          }
                     $boards ++;          my $maxidx=$#oldresources;
                     $currelem = $count+$boards+$startcount;          if ($#LONCAPA::map::resources>$#oldresources) {
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";             $maxidx=$#LONCAPA::map::resources;
                 } else {          }
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";          for (my $idx=0; $idx<=$maxidx; $idx++) {
                 }             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
             }                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
         }                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
         my $scripttag = qq|                $changedflag=1;
 <script>             }
              if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
 function checkAll(field) {                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
     if (field.length > 0) {                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
         for (i = 0; i < field.length; i++) {                $changedflag=1;
             field[i].checked = true ;             }
         }          }
     } else {   $storehash{'maxidx'}=$maxidx;
         field.checked = true          if ($changedflag) { &log_docs(\%storehash); }
     }      }
 }  }
                                                                                  
 function uncheckAll(field) {  sub docs_change_log {
     if (field.length > 0) {      my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
         for (i = 0; i < field.length; i++) {      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
             field[i].checked = false ;      my $js = '<script type="text/javascript">'."\n".
         }               '// <![CDATA['."\n".
     } else {               &Apache::loncommon::display_filter_js('docslog')."\n".
         field.checked = false ;               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
     }               &history_tab_js()."\n".
 }               &Apache::lonratedt::editscript('simple')."\n".
                '// ]]>'."\n".
 function propagateCheck(item) {               '</script>'."\n";
     if (document.exportdoc.elements[item].checked == true) {      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
         containerCheck(item)      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
     }      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
 }      my %orderhash;
       my $container='sequence';
 function containerCheck(item) {      my $pathitem;
     document.exportdoc.elements[item].checked = true      if ($env{'form.pagepath'}) {
     var numitems = $count + $boards + $startcount          $container='page';
     var parents = new Array(numitems)          $pathitem = '<input type="hidden" name="pagepath" value="'.
     for (var i=$startcount; i<numitems; i++) {                      &HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />';
         parents[i] = new Array      } else {
     }          my $folderpath=$env{'form.folderpath'};
         |;          if ($folderpath eq '') {
               $folderpath = 'default&'.&escape(&mt('Main '.$crstype.' Documents'));
         foreach my $container (sort { $a <=> $b } (keys(%children))) {          }
             my @contents = split(/:/,$children{$container});          $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
             for (my $i=0; $i<@contents; $i ++) {      }
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
             }      my $jumpto = $readfile;
         }      $jumpto =~ s{^/}{};
       my $tid = 1;
         $scripttag .= qq|      if ($supplementalflag) {
     if (parents[item].length > 0) {          $tid = 2;
         for (var j=0; j<parents[item].length; j++) {      }
             containerCheck(parents[item][j])      my ($breadcrumbtrail) = &breadcrumbs($allowed,$crstype);
         }      $r->print($breadcrumbtrail.
      }                  &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
 }                $readfile));
       my %docslog=&Apache::lonnet::dump('nohist_docslog',
 </script>                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
         |;                                        $env{'course.'.$env{'request.course.id'}.'.num'});
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',  
  $scripttag));      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));  
  $r->print($display.'</table>'.      my %saveable_parameters = ('show' => 'scalar',);
                   '<p><input type="hidden" name="finishexport" value="1">'.      &Apache::loncommon::store_course_settings('docs_log',
                   '<input type="submit" name="exportcourse" value="'.                                                \%saveable_parameters);
                   &mt('Export '.$type.' DOCS').'" /></p></form>');      &Apache::loncommon::restore_course_settings('docs_log',
     }                                                  \%saveable_parameters);
 }      if (!$env{'form.show'}) { $env{'form.show'}=10; }
   # FIXME: internationalization seems wrong here
 sub create_ims_store {      my %lt=('hiddenresource' => 'Resources hidden',
     my ($now,$manifestok,$outcome,$tempexport) = @_;      'encrypturl'     => 'URL hidden',
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';      'randompick'     => 'Randomly pick',
     my $ims_manifest;      'randomorder'    => 'Randomly ordered',
     if (!-e $$tempexport) {      'set'            => 'set to',
         mkdir($$tempexport,0700);      'del'            => 'deleted');
     }      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
     $$tempexport .= '/'.$now;                   $pathitem."\n".
     if (!-e $$tempexport) {                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
         mkdir($$tempexport,0700);                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
     }      $r->print('<div class="LC_left_float">'.
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
     if (!-e $$tempexport) {                &makedocslogform($filter,1).
         mkdir($$tempexport,0700);                '</fieldset></div><br clear="all" />');
     }      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     if (!-e "$$tempexport/resources") {                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
         mkdir("$$tempexport/resources",0700);                &mt('After').'</th>'.
     }                &Apache::loncommon::end_data_table_header_row());
 # open manifest file      my $shown=0;
     my $manifest = '/imsmanifest.xml';      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     my $manifestfilename = $$tempexport.$manifest;   if ($env{'form.displayfilter'} eq 'currentfolder') {
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
         $$manifestok=1;   }
         print $ims_manifest          my @changes=keys(%{$docslog{$id}{'logentry'}});
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".          if ($env{'form.displayfilter'} eq 'containing') {
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.      foreach my $key (@changes) {
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.      }
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
 '  <metadata>   }
     <schema></schema>          my $count = 0;
     <imsmd:lom>          my $time =
       <imsmd:general>              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>          my $plainname =
         <imsmd:title>              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>                                            $docslog{$id}{'exe_udom'});
         </imsmd:title>          my $about_me_link =
       </imsmd:general>              &Apache::loncommon::aboutmewrapper($plainname,
     </imsmd:lom>                                                 $docslog{$id}{'exe_uname'},
   </metadata>'."\n".                                                 $docslog{$id}{'exe_udom'});
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".          my $send_msg_link='';
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
 ' structure="hierarchical">'."\n".               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'              $send_msg_link ='<br />'.
     } else {                  &Apache::loncommon::messagewrapper(&mt('Send message'),
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'                                                     $docslog{$id}{'exe_uname'},
 ;                                                     $docslog{$id}{'exe_udom'});
     }          }
     return $ims_manifest;          $r->print(&Apache::loncommon::start_data_table_row());
 }          $r->print('<td>'.$time.'</td>
                          <td>'.$about_me_link.
 sub build_package {                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
 # first iterator to look for dependencies                    $send_msg_link.'</td><td>'.
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
     my $curRes;          my $is_supp = 0; 
     my $count = 0;          if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
     my $depth = 0;              $is_supp = 1;
     my $lastcontainer = 0;          }
     my %parent = ();  # Before
     my @dependencies = ();   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
     while ($curRes = $it->next()) {      if ($oldname ne $newname) {
         if (ref($curRes)) {                  my $shown = &LONCAPA::map::qtescape($oldname);
             $count ++;                  if ($is_supp) {
         }                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
         if ($curRes == $it->BEGIN_MAP()) {                  }
             $depth++;                  $r->print($shown);
             $parent{$depth} = $lastcontainer;      }
         }   }
         if ($curRes == $it->END_MAP()) {   $r->print('<ul>');
             $depth--;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
             $lastcontainer = $parent{$depth};              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
         }                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
         if (ref($curRes)) {                  if ($is_supp) {
             if ($curRes->is_sequence() || $curRes->is_page()) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                 $lastcontainer = $count;                  }
             }   $r->print('<li>'.$shown.'</li>');
             if (grep(/^$count$/,@$exportitems)) {      }
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);   }
             }   $r->print('</ul>');
         }  # After
     }          $r->print('</td><td>');
 # second iterator to build manifest and store resources  
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     $depth = 0;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     my $prevdepth;      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
     $count = 0;      if ($oldname ne '' && $oldname ne $newname) {
     my $imsresources;                  my $shown = &LONCAPA::map::qtescape($newname);
     my $pkgdepth;                  if ($is_supp) {
     while ($curRes = $it->next()) {                      $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
         if ($curRes == $it->BEGIN_MAP()) {                  }
             $prevdepth = $depth;                  $r->print($shown);
             $depth++;      }
         }   }
         if ($curRes == $it->END_MAP()) {   $r->print('<ul>');
             $prevdepth = $depth;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
             $depth--;              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
         }                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
                   if ($is_supp) {
         if (ref($curRes)) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
             $count ++;                  }
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {                  $r->print('<li>'.$shown.'</li>');
                 my $symb = $curRes->symb();      }
                 my $isvisible = 'true';   }
                 my $resourceref;   $r->print('</ul>');
                 if ($curRes->randomout()) {   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                     $isvisible = 'false';      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
                 }      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
                 unless ($curRes->is_sequence()) {   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';  # FIXME: internationalization seems wrong here
                 }      $r->print('<li>'.
                 my $step = $prevdepth - $depth;        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
                 if (($step >= 0) && ($count > 1)) {    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
                     while ($step >= 0) {        .'</li>');
                         print $ims_manifest "\n".'  </item>'."\n";   }
                         $step --;      }
                     }      $r->print('</ul>');
                 }   }
                 $prevdepth = $depth;  # End
           $r->print('</td>'.&Apache::loncommon::end_data_table_row());
                 my $itementry =          $shown++;
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.          if (!($env{'form.show'} eq &mt('all')
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.                || $shown<=$env{'form.show'})) { last; }
               '<title>'.$curRes->title().'</title>';      }
                 print $ims_manifest "\n".$itementry;      $r->print(&Apache::loncommon::end_data_table()."\n".
                 &makesimpleeditform($pathitem)."\n".
                 unless ($curRes->is_sequence()) {                '</div></div>');
                     my $content_file;      $r->print(&endContentScreen());
                     my @hrefs = ();  }
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);  
                     if ($content_file) {  sub update_paste_buffer {
                         $imsresources .= "\n".      my ($coursenum,$coursedom,$folder) = @_;
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.  
                      '" type="webcontent" href="'.$content_file.'">'."\n".      return if (!defined($env{'form.markcopy'}));
                      '       <file href="'.$content_file.'" />'."\n";      return if (!defined($env{'form.copyfolder'}));
                         foreach my $item (@hrefs) {      return if ($env{'form.markcopy'} < 0);
                             $imsresources .=  
                      '        <file href="'.$item.'" />'."\n";      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                         }      $env{'form.copyfolder'});
                         if (grep(/^$count$/,@$discussions)) {  
                             my $ressymb = $symb;      return if ($fatal);
                             my $mode;  
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {  # Mark for copying
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';      if (&is_supplemental_title($title)) {
                                 }          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
                                 $mode = 'board';   ($title) = &Apache::loncommon::parse_supplemental_title($title);
                             }      } elsif ($env{'docs.markedcopy_supplemental'}) {
                             my %extras = (          &Apache::lonnet::delenv('docs.markedcopy_supplemental');
                                           caller => 'imsexport',      }
                                           tempexport => $tempexport.'/resources',      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
                                           count => $count  
                                          );      (my $cmd,undef)=split('_',$env{'form.cmd'});
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);  
                         }      my %addtoenv = (
                         $imsresources .= '    </resource>'."\n";                      'docs.markedcopy_title' => $title,
                     }                      'docs.markedcopy_url'   => $url,
                 }                      'docs.markedcopy_cmd'   => $cmd,
                 $pkgdepth = $depth;                     );
             }      &Apache::lonnet::delenv('docs.markedcopy_nested');
         }      &Apache::lonnet::delenv('docs.markedcopy_nestednames');
     }      if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
     while ($pkgdepth > 0) {          my $prefix = $1;
         print $ims_manifest "    </item>\n";          my $subdir =$2;
         $pkgdepth --;          if ($subdir eq '') {
     }              $subdir = $prefix;
     my $resource_text = qq|          }
     </organization>          my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
   </organizations>          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
   <resources>                               \%hierarchy,\%titles,\%allmaps);
     $imsresources          if (ref($hierarchy{$url}) eq 'HASH') {
   </resources>              my ($nested,$nestednames);
 </manifest>              &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
     |;              $nested =~ s/\&$//;
     print $ims_manifest $resource_text;              $nestednames =~ s/\Q___&&&___\E$//;
 }              if ($nested ne '') {
                   $addtoenv{'docs.markedcopy_nested'} = $nested;
 sub get_dependencies {              }
     my ($exportitems,$parent,$depth,$dependencies) = @_;              if ($nestednames ne '') {
     if ($depth > 1) {                  $addtoenv{'docs.markedcopy_nestednames'} = $nestednames;
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {              }
             push(@{$dependencies},$$parent{$depth});          }
             if ($depth > 2) {      }
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);      &Apache::lonnet::appenv(\%addtoenv);
             }      delete($env{'form.markcopy'});
         }  }
     }  
 }  sub recurse_uploaded_maps {
       my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
 sub process_content {      if (ref($hierarchy->{$url}) eq 'HASH') {
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;          my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
     my $content_type;          my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
     my $message;          my (@uploaded,@names,%shorter);
     my @uploads = ();          for (my $i=0; $i<@maps; $i++) {
     if ($curRes->is_sequence()) {              my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
         $content_type = 'sequence';              if ($inner ne '') {
     } elsif ($curRes->is_page()) {                  push(@uploaded,$inner);
         $content_type = 'page'; # need to handle individual items in pages.                  push(@names,&escape($titles[$i]));
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {                  $shorter{$maps[$i]} = $inner;
         $content_type = 'syllabus';              }
         my $contents = &Apache::imsexport::templatedpage($content_type);          }
         if ($contents) {          $$nestref .= "$dir:".join(',',@uploaded).'&';
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
         }          foreach my $map (@maps) {
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {              if ($shorter{$map} ne '') {
         $content_type = 'external';                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
         my $title = $curRes->title;              }
         my $contents =  &Apache::imsexport::external($symb,$title);          }
         if ($contents) {      }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      return;
         }  }
     } elsif ($symb =~ m-adm/navmaps$-) {  
         $content_type =  'navmap';  sub print_paste_buffer {
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
         $content_type = 'simplepage';      return if (!defined($env{'docs.markedcopy_url'}));
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);  
         if ($contents) {      my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
         }      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {          $is_external = 1;
         $content_type = 'simpleproblem';      }
         my $contents =  &Apache::imsexport::simpleproblem($symb);  
         if ($contents) {      my ($canpaste,$nopaste,$othercrs,$areachange,$is_uploaded_map);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      if ($folder =~ /^supplemental/) {
         }          $canpaste = &supp_pasteable($env{'docs.markedcopy_url'});
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {          unless ($canpaste) {
         $content_type = 'examupload';              $nopaste = &mt('Paste into Supplemental Content unavailable for this type of content.');
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {          } 
         $content_type = 'bulletinboard';      } else {
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);          $canpaste = 1;
         if ($contents) {      }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);  
         }      if ($canpaste) {
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {          if ($env{'docs.markedcopy_url'} =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
         $content_type = 'aboutme';              my $srcdom = $1;
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);              my $srcnum = $2;
         if ($contents) {              my $rem = $3;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
         }                  $othercourse = 1;
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {                  if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                      if ($canpaste) {
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {                          $othercrs = '<br />'.&mt('(from another course).');  
         my $canedit = 0;                      }
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {                  } else {
             $canedit= 1;                      $canpaste = 0;
         }                      $nopaste = &mt('Paste from another course unavailable.') 
 # only include problem code where current user is author                  }
         if ($canedit) {              }
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');              if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
         } else {                  my $prefix = $1;
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');                  $parent = $2;
         }                  if ($folder !~ /^\Q$prefix\E/) {
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {                      $areachange = 1;
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                  }
     }                  $is_uploaded_map = 1;
     if (@uploads > 0) {              }
         foreach my $item (@uploads) {          }
             my $uploadmsg = '';      }
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');  
             if ($uploadmsg) {      $r->print('<fieldset>'
                 $$copyresult .= $uploadmsg."\n";               .'<legend>'.&mt('Clipboard').'</legend>');
             }      my ($type,$buffer);
         }      if ($is_external) {
     }          $type = &mt('External Resource');
     if ($message) {          $buffer = $type.': '.
         $$copyresult .= $message."\n";                    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
     }                    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')';
 }      }  else {
           my $icon = &Apache::loncommon::icon($extension);
 sub replicate_content {          if ($extension eq 'sequence' &&
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;              $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
     my ($map,$ind,$url);              $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     if ($caller eq 'templateupload') {              $icon .= '/navmap.folder.closed.gif';
         $url = $symb;          }
         $url =~ s#//#/#g;          $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
     } else {          $buffer = $icon.$type.': '.  &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'}));
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);      }
     }      if ($canpaste) {
     my $content;          $r->print('<form name="pasteform" action="/adm/coursedocs" method="post">'.$buffer);
     my $filename;          if (($is_uploaded_map) && (!$areachange)) {
     my $repstatus;              if ((!$othercourse) && ($env{'docs.markedcopy_cmd'} eq 'cut')) {
     my $content_name;                  $r->print(('&nbsp;'x 4).'<span id="pasteoptionstext">'.
     if ($url =~ m-/([^/]+)$-) {                            '<a href="javascript:showPasteOptions();" class="LC_menubuttons_link">'.
         $filename = $1;                            &mt('Show Paste Options').'</a></span><br />'.
         if (!-e $tempexport.'/resources') {                            '<div id="pasteoptions" class="LC_dccid">'.('&nbsp;'x 4).
             mkdir($tempexport.'/resources',0700);                            '<label>'.
         }                            '<input type="radio" name="docs.markedcopy_options" value="new" checked="checked" />'.
         if (!-e $tempexport.'/resources/'.$count) {                            &mt('Copy to new folder').'</label>'.('&nbsp;' x2).
             mkdir($tempexport.'/resources/'.$count,0700);                            '<label>'.   
         }                            '<input type="radio" name="docs.markedcopy_options" value="move" />'.
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;                            &mt('Move old folder').'</label><br />');
         my $copiedfile;                  if ($env{'docs.markedcopy_nested'}) {
         if ($copiedfile = Apache::File->new('>'.$destination)) {                      $r->print('<br />'.&mt('Folder to paste contains sub-folders').
             my $content;                                '<br /><table border="0">');
             if ($caller eq 'resource') {                      my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested'});
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                      my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames'});
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);                      my $lastdir = $parent;
                 $content = &Apache::lonnet::getfile($filepath);                      my %depths = (
                 if ($content eq -1) {                                     $lastdir => 0,
                     $$message = 'Could not copy file '.$filename;                                   );
                 } else {                      my (%display,%deps); 
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');                      for (my $i=0; $i<@pastemaps; $i++) {
                     $repstatus = 'ok';                          ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
                 }                          my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {                          my @subfolders = split(/,/,$subfolderstr);
                 my $rtncode;                          $deps{$lastdir} = \@subfolders;
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);                          my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
                 if ($repstatus eq 'ok') {                          my $depth = $depths{$lastdir} + 1;
                     if ($url =~ /\.html?$/i) {                          my $offset = int($depth * 4);
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');                          my $indent = ('&nbsp;' x $offset);
                     }                          for (my $j=0; $j<@subfolders; $j++) {
                 } else {                              $depths{$subfolders[$j]} = $depth;
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";                              $display{$subfolders[$j]} = 
                 }                                    '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
             } elsif ($caller eq 'noedit') {                                    '<td><label>'.
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
                 $repstatus = 'ok';                                    '<label>'.
                 $content = 'Not the owner of this resource';                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="move" />'.
             }                                    &mt('Move old').'</label>'.
             if ($repstatus eq 'ok') {                                    '</td></tr>';
                 print $copiedfile $content;                          }
             }                      }
             close($copiedfile);                      &recurse_print($r,$parent,\%deps,\%display);
         } else {                      $r->print('</table>');
             $$message = 'Could not open destination file for '.$filename."<br />\n";                  }
         }                  $r->print('</div>');
     } else {              }
         $$message = 'Could not determine name of file for '.$symb."<br />\n";          }
     }          $r->print('<br /><input type="submit" name="pastemarked" value="'.&mt('Paste').'" />'.$othercrs);
     if ($repstatus eq 'ok') {          if ($container eq 'page') {
         $content_name = 'resources/'.$count.'/'.$filename;              $r->print('
     }          <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
     return $content_name;          <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
 }  ');
           } else {
 sub extract_media {              $r->print('
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
     my ($dirpath,$container);  ');
     my %allfiles = ();          }
     my %codebase = ();          $r->print('</form>');
     if ($url =~ m-(.*/)([^/]+)$-) {      } else {
         $dirpath = $1;          $r->print(&mt('Paste buffer contains:').' '.$buffer.
         $container = $2;                    '<br /><p class="LC_info">'.$nopaste.'</p>');
     } else {      }
         $dirpath = $url;      $r->print('</fieldset>');
         $container = '';  }
     }  
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);  sub recurse_print {
     foreach my $embed_file (keys(%allfiles)) {      my ($r,$dir,$deps,$display) = @_;
         my $filename;      $r->print($display->{$dir}."\n");
         if ($embed_file =~ m#([^/]+)$#) {      if (ref($deps->{$dir}) eq 'ARRAY') {
             $filename = $1;          foreach my $subdir (@{$deps->{$dir}}) {
         } else {              &recurse_print($r,$subdir,$deps,$display);
             $filename = $embed_file;          }
         }      }
         my $newname = 'res/'.$filename;  }
         my ($rtncode,$embed_content,$repstatus);  
         my $embed_url;  sub supp_pasteable {
         if ($embed_file =~ m-^/-) {      my ($url) = @_;
             $embed_url = $embed_file;           # points to absolute path      if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
         } else {          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
             if ($embed_file =~ m-https?://-) {          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
                 next;                           # points to url          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
             } else {          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
                 $embed_url = $dirpath.$embed_file;  # points to relative path          return 1;
             }      }
         }      return;
         if ($caller eq 'resource') {  }
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';    
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);  sub paste_popup_js {
             $embed_content = &Apache::lonnet::getfile($embed_path);      my %lt = &Apache::lonlocal::texthash(
             unless ($embed_content eq -1) {                                            show => 'Show Paste Options',
                 $repstatus = 'ok';                                            hide => 'Hide Paste Options',
             }                                          );
         } elsif ($caller eq 'uploaded') {      return <<"END";
              
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);  function showPasteOptions() {
         }      document.getElementById('pasteoptions').style.display='block';
         if ($repstatus eq 'ok') {      document.getElementById('pasteoptions').style.textAlign='left';
             my $destination = $tempexport.'/resources/'.$count.'/res';      document.getElementById('pasteoptions').style.textFace='normal';
             if (!-e "$destination") {      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:hidePasteOptions();" class="LC_menubuttons_link">$lt{'hide'}</a><br />';
                 mkdir($destination,0755);      return;
             }  }
             $destination .= '/'.$filename;  
             my $copiedfile;  function hidePasteOptions() {
             if ($copiedfile = Apache::File->new('>'.$destination)) {      document.getElementById('pasteoptions').style.display='none';
                 print $copiedfile $embed_content;      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:showPasteOptions()" class="LC_menubuttons_link">$lt{'show'}</a>';
                 push(@{$href},'resources/'.$count.'/res/'.$filename);      return;
                 my $attrib_regexp = '';  }
                 if (@{$allfiles{$embed_file}} > 1) {  
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});  END
                 } else {  
                     $attrib_regexp = $allfiles{$embed_file}[0];  }
                 }  
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;  
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {  sub do_paste_from_buffer {
                     $$content =~ s#\Q$embed_file\E#$newname#gi;      my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
                 }  
             }  # Early out if paste buffer is empty
         } else {      if (!$env{'form.pastemarked'}) {
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";          return ();
         }      }
     }  
     return;  # Supplemental content may only include certain types of content
 }  # Early out if pasted content is not supported in Supplemental area
       if ($folder =~ /^supplemental/) {
 sub store_template {          unless (&supp_pasteable($env{'docs.markedcopy_url'})) {
     my ($contents,$tempexport,$count,$content_type) = @_;              return (&mt('Paste failed: content type is not supported within Supplemental Content'));
     if ($contents) {          }
         if ($tempexport) {      }
             if (!-e $tempexport.'/resources') {  
                 mkdir($tempexport.'/resources',0700);  # Prepare to paste resource at end of list
             }      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
             if (!-e $tempexport.'/resources/'.$count) {      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
                 mkdir($tempexport.'/resources/'.$count,0700);  
             }      my ($is_map,$srcdom,$srcnum,$prefixchg,%before,%after,%mapchanges,%tomove);
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';      if ($url=~/\.(page|sequence)$/) {
             my $storetemplate;          $is_map = 1; 
             if ($storetemplate = Apache::File->new('>'.$destination)) {      }
                 print $storetemplate $contents;      if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/([^/]+)}) {
                 close($storetemplate);          $srcdom = $1;
             }          $srcnum = $2;
             if ($content_type eq 'external') {          my $oldprefix = $3;
                 return 'resources/'.$count.'/'.$content_type.'.html';  # When paste buffer was populated using an active role in a different course
             } else {  # check for mdc privilege in the course from which the resource was pasted 
                 return 'resources/'.$count.'/'.$content_type.'.xml';          if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
             }              unless ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         }                  return (&mt('Paste failed: Item is from a different course which you do not have rights to edit.'));
     }              }
 }          }
   # When pasting content from Main Content to Supplemental Content and vice versa 
   # URLs will contain different paths (which depend on whether pasted item is
 sub group_import {  # a folder/page or a document.   
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;          if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
               $prefixchg = 1;
     while (@files) {              %before = ( map => 'default',
  my ($name, $url, $residx) = @{ shift(@files) };                          doc => 'docs');
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})              %after =  ( map => 'supplemental',
      && ($caller eq 'londocs')                          doc => 'supplemental' );
      && (!&Apache::lonnet::stat_file($url))) {          } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
                   $prefixchg = 1;
             my $errtext = '';              %before = ( map => 'supplemental',
             my $fatal = 0;                          doc => 'supplemental');
             my $newmapstr = '<map>'."\n".              %after  = ( map => 'default',
                             '<resource id="1" src="" type="start"></resource>'."\n".                          doc => 'docs');
                             '<link from="1" to="2" index="1"></link>'."\n".          }
                             '<resource id="2" src="" type="finish"></resource>'."\n".  
                             '</map>';  # If pasting an uploaded map, get list of contained uploaded maps.
             $env{'form.output'}=$newmapstr;          my @nested;
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,          if ($env{'docs.markedcopy_nested'}) {
                                                 'output',$1.$2);              my ($type) = ($oldprefix =~ /^(default|supplemental)/);
             if ($result != m|^/uploaded/|) {              my @items = split(/\&/,$env{'docs.markedcopy_nested'});
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';              my @deps = map { /\d+:([\d,]+$)/ } @items;
                 $fatal = 2;              foreach my $dep (@deps) {
             }                  if ($dep =~ /,/) {
             if ($fatal) {                      push(@nested,split(/,/,$dep));
                 return ($errtext,$fatal);                  } else {
             }                      push(@nested,$dep);
         }                  }
  if ($url) {              }
     if (!$residx              foreach my $item (@nested) {
  || defined($LONCAPA::map::zombies[$residx])) {                  if ($env{'form.docs.markedcopy_'.$item} eq 'move') {
  $residx = &LONCAPA::map::getresidx($url,$residx);                      $tomove{$type.'_'.$item} = 1;
  push(@LONCAPA::map::order, $residx);                  }
     }              }
     my $ext = 'false';          }
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }      }
     $url  = &LONCAPA::map::qtunescape($url);  
     $name = &LONCAPA::map::qtunescape($name);  # Maps need to be copied first
     $LONCAPA::map::resources[$residx] =      my ($oldurl,%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
  join(':', ($name, $url, $ext, 'normal', 'res'));          %dbcopies,%zombies,%params,%docmoves,%mapmoves,%newsubdir,%newurls);
  }      $oldurl = $url;
     }      if ($is_map) {
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);          if ($folder =~ /^default/) {
 }              my $lastchange = &Apache::lonnet::get_coursechange($coursedom,$coursenum);
               if ($lastchange > $env{'request.course.tied'}) {
 sub breadcrumbs {                  &reinit_role($coursedom,$coursenum,$env{"course.$env{'request.course.id'}.home"}); 
     my ($where,$allowed,$type)=@_;              }
     &Apache::lonhtmlcommon::clear_breadcrumbs();          }
     my (@folders);  # If pasting a map, check if map contains other maps
     if ($env{'form.pagepath'}) {          my (%allmaps,%hierarchy,%titles);
         @folders = split('&',$env{'form.pagepath'});          if ($folder =~ /^default/) {
     } else {              my $navmap = Apache::lonnavmaps::navmap->new();
         @folders=split('&',$env{'form.folderpath'});              if (defined($navmap)) {
     }                  foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
     my $folderpath;                      $allmaps{$res->src()} = 1;
     my $cpinfo='';                  }
     my $plain='';              }
     my $randompick=-1;          }
     my $isencrypted=0;          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
     my $ishidden=0;                               \%addedmaps,\%hierarchy,\%titles,\%allmaps);
     my $is_random_order=0;          if ($url=~ m{^/uploaded/}) {
     while (@folders) {              my $newurl;
  my $folder=shift(@folders);              unless ($env{'form.docs.markedcopy_options'} eq 'move') {
     my $foldername=shift(@folders);                  ($newurl,my $error) = 
  if ($folderpath) {$folderpath.='&';}                      &get_newmap_url($url,$folder,$prefixchg,$coursedom,$coursenum,
  $folderpath.=$folder.'&'.$foldername;                                      $srcdom,$srcnum,\$title,\%allmaps,\%newurls);
  my $url='/adm/coursedocs?folderpath='.                  if ($error) {
     &escape($folderpath);                      return ($error);
     my $name=&unescape($foldername);                  }
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername                  if ($newurl ne '') {
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;                      if ($newurl ne $url) {
     if ($1 ne '') {                          if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
                $randompick=$1;                              $newsubdir{$url} = $1;
             } else {                          }
                $randompick=-1;                          $mapchanges{$url} = 1;
             }                      }
             if ($2) { $ishidden=1; }                  }
             if ($3) { $isencrypted=1; }              }
     if ($4 ne '') { $is_random_order = 1; }              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum) || ($prefixchg) ||
             if ($folder eq 'supplemental') {                  (($newurl ne '') && ($newurl ne $url))) {
                 if ($allowed) {                  unless (&url_paste_fixups($url,$folder,$prefixchg,$coursedom,$coursenum,
                     $name = &mt('Supplemental '.$type.' Documents');                                            \%allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
                 } else {                                            \%zombies,\%params,\%mapmoves,\%mapchanges,\%tomove,
                     $name = &mt($type.' Documents');                                            \%newsubdir,\%newurls)) {
                 }                      $mapmoves{$url} = 1;
             }                  }
     &Apache::lonhtmlcommon::add_breadcrumb(                  $url = $newurl;
       {'href'=>$url.$cpinfo,              } elsif ($env{'docs.markedcopy_nested'}) {
        'title'=>$name,                  &url_paste_fixups($url,$folder,$prefixchg,$coursedom,$coursenum,\%allmaps,\%rewrites,
        'text'=>'<font size="+1">'.                                    \%retitles,\%copies,\%dbcopies,\%zombies,\%params,\%mapmoves,
    $name.'</font>',                                    \%mapchanges,\%tomove,\%newsubdir,\%newurls); 
        'no_mt'=>1,              }
        });          } elsif ($url=~m {^/res/}) {
  $plain.=$name.' &gt; ';  # published maps can only exists once, so remove it from paste buffer when done
     }              &Apache::lonnet::delenv('docs.markedcopy');
     $plain=~s/\&gt\;\s*$//;  # if pasting published map (main content are only) check map is not already in course
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',              if ($folder =~ /^default/) {
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);                  if ($allmaps{$url}) {
 }                      return (&mt('Paste failed: only one instance of a particular published sequence or page is allowed within each course.'));
                   }
 sub log_docs {              }
     return &Apache::lonnet::instructor_log('docslog',@_);          }
 }      }
       if ($url=~ m{/smppg$}) {
 {   my $db_name = &Apache::lonsimplepage::get_db_name($url);
     my @oldresources=();   if ($db_name =~ /^smppage_/) {
     my @oldorder=();      #simple pages, need to copy the db contents to a new one.
     my $parmidx;      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
     my %parmaction=();      my $now = time();
     my %parmvalue=();      $db_name =~ s{_\d*$ }{_$now}x;
     my $changedflag;      my $dbresult=&Apache::lonnet::put($db_name,\%contents,
       $coursedom,$coursenum);
     sub snapshotbefore {              if ($dbresult eq 'ok') {
         @oldresources=@LONCAPA::map::resources;                  $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
         @oldorder=@LONCAPA::map::order;                  $title=&mt('Copy of').' '.$title;
         $parmidx=undef;              } else {
         %parmaction=();                  return (&mt('Paste failed: An error occurred when copying the simple page.'));
         %parmvalue=();              }
         $changedflag=0;   }
     }      }
       $title = &LONCAPA::map::qtunescape($title);
     sub remember_parms {      my $ext='false';
         my ($idx,$parameter,$action,$value)=@_;      if ($url=~m{^http(|s)://}) { $ext='true'; }
         $parmidx=$idx;      $url       = &LONCAPA::map::qtunescape($url);
         $parmaction{$parameter}=$action;  
         $parmvalue{$parameter}=$value;  # For uploaded files (excluding pages/sequences) path in copied file is changed
         $changedflag=1;  # if paste is from Main to Supplemental (or vice versa), or if pasting between
     }  # courses.
   
     sub log_differences {      my $newidx;
         my ($plain)=@_;      unless ($is_map) {
         my %storehash=('folder' => $plain,  # Now insert the URL at the bottom
                        'currentfolder' => $env{'form.folder'});          $newidx = &LONCAPA::map::getresidx($url);
         if ($parmidx) {          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
            $storehash{'parameter_res'}=$oldresources[$parmidx];              my $relpath = $1;
            foreach my $parm (keys(%parmaction)) {              if ($relpath ne '') {
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};                  my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};                  my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
            }                  my $newprefix = $newloc;
         }                  if ($newloc eq 'default') {
         my $maxidx=$#oldresources;                      $newprefix = 'docs';
         if ($#LONCAPA::map::resources>$#oldresources) {                  }
            $maxidx=$#LONCAPA::map::resources;                  if ($newdocsdir eq '') {
         }                      $newdocsdir = 'default';
         for (my $idx=0; $idx<=$maxidx; $idx++) {                  }
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {                  if (($prefixchg) || ($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];                      my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];                      $url =
               $changedflag=1;                          &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
            }                                                             &Apache::lonnet::getfile($oldurl));
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {                      if ($url eq '/adm/notfound.html') {
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];                          return (&mt('Paste failed: an error occurred saving the file.'));
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];                      } else {
               $changedflag=1;                          my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
            }                          $newsubpath =~ s{/+$}{/};
         }                          $docmoves{$oldurl} = $newsubpath;
  $storehash{'maxidx'}=$maxidx;                      }
         if ($changedflag) { &log_docs(\%storehash); }                  }
     }              }
 }          }
       }
   # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
       my ($result,$save_err);
       $result =
           &apply_fixups($folder,$is_map,$prefixchg,$coursedom,$coursenum,$oldurl,
 sub docs_change_log {                        $url,\%removefrommap,\%removeparam,\%rewrites,\%retitles,
     my ($r)=@_;                        \%copies,\%dbcopies,\%zombies,\%params,\%docmoves,
     my $folder=$env{'form.folder'};                        \%mapmoves,\%newsubdir,$errors,\%before,\%after);
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));      if ($result eq 'ok') {
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));          if ($is_map) { 
     my %docslog=&Apache::lonnet::dump('nohist_docslog',              my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},                                              $folder.'.'.$container);
                                       $env{'course.'.$env{'request.course.id'}.'.num'});              return $errtext if ($fatal);
   
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }              if ($#LONCAPA::map::order<1) {
                   my $idx=&LONCAPA::map::getresidx();
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.                  if ($idx<=0) { $idx=1; }
               '<input type="hidden" name="docslog" value="1" />');                  $LONCAPA::map::order[0]=$idx;
                   $LONCAPA::map::resources[$idx]='';
     my %saveable_parameters = ('show' => 'scalar',);              }
     &Apache::loncommon::store_course_settings('docs_log',              $newidx = &LONCAPA::map::getresidx($url);
                                               \%saveable_parameters);          }
     &Apache::loncommon::restore_course_settings('docs_log',          if ($env{'docs.markedcopy_supplemental'}) {
                                                 \%saveable_parameters);              if ($folder !~ /^supplemental/) {
     if (!$env{'form.show'}) { $env{'form.show'}=10; }                  (undef,undef,$title) =
     my %lt=('hiddenresource' => 'Resources hidden',                      &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental'});
     'encrypturl'     => 'URL hidden',              }
     'randompick'     => 'Randomly pick',          } else {
     'randomorder'    => 'Randomly ordered',              if ($folder=~/^supplemental/) {
     'set'            => 'set to',                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     'del'            => 'deleted');                         $env{'user.domain'}.'___&&&___'.$title;
     $r->print(&Apache::loncommon::display_filter().              }
               '<input type="hidden" name="folder" value="'.$folder.'" />'.          }
               '<input type="submit" value="'.&mt('Display').'" /></form>');          $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().          push(@LONCAPA::map::order, $newidx);
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.  
               &mt('After').'</th>'.  # Store the result
               &Apache::loncommon::end_data_table_header_row());          my ($errtext,$fatal) = 
     my $shown=0;              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {          if ($fatal) {
  if ($env{'form.displayfilter'} eq 'currentfolder') {              $save_err = $errtext;
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }          }
  }      }
         my @changes=keys(%{$docslog{$id}{'logentry'}});     
         if ($env{'form.displayfilter'} eq 'containing') {      if ($env{'form.docs.markedcopy_options'} eq 'move') {
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.          &Apache::lonnet::delenv('docs.markedcopy');
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});          &Apache::lonnet::delenv('docs.markedcopy_nested');
     foreach my $key (@changes) {          &Apache::lonnet::delenv('docs.markedcopy_nestednames');
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};      }
     }      return ($result,$save_err);
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }          }
  }  
         my $count = 0;  sub get_newmap_url {
         my $time =      my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});          $titleref,$allmaps,$newurls) = @_;
         my $plainname =      my $newurl;
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},      if ($url=~ m{^/uploaded/}) {
                                           $docslog{$id}{'exe_udom'});          $$titleref=&mt('Copy of').' '.$$titleref;
         my $about_me_link =      }
             &Apache::loncommon::aboutmewrapper($plainname,      my $now = time;
                                                $docslog{$id}{'exe_uname'},      my $suffix=$$.int(rand(100)).$now;
                                                $docslog{$id}{'exe_udom'});      my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
         my $send_msg_link='';      if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})          my $path = $1;
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {          my $prefix = $2;
             $send_msg_link ='<br />'.          my $ancestor = $3;
                 &Apache::loncommon::messagewrapper(&mt('Send message'),          if (length($ancestor) > 10) {
                                                    $docslog{$id}{'exe_uname'},              $ancestor = substr($ancestor,-10,10);
                                                    $docslog{$id}{'exe_udom'});          }
         }          my $newid;
         $r->print(&Apache::loncommon::start_data_table_row());          if ($prefixchg) {
         $r->print('<td>'.$time.'</td>              if ($folder =~ /^supplemental/) {
                        <td>'.$about_me_link.                  $prefix =~ s/^default/supplemental/;
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.              } else {
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.                  $prefix =~ s/^supplemental/default/;
                   $send_msg_link.'</td><td>'.              }
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');          }
 # Before          if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];          } else {
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];              $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
     if ($oldname ne $newname) {          }
  $r->print(&LONCAPA::map::qtescape($oldname));          my $counter = 0;
     }          my $is_unique = &uniqueness_check($newurl);
  }          if ($folder =~ /^default/) {
  $r->print('<ul>');              if ($allmaps->{$newurl}) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  $is_unique = 0;
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {              }
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');          }
     }          while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
  }              $counter ++;
  $r->print('</ul>');              $suffix ++;
 # After              if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
         $r->print('</td><td>');                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
               } else {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];              }
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];              $is_unique = &uniqueness_check($newurl);
     if ($oldname ne '' && $oldname ne $newname) {          }
  $r->print(&LONCAPA::map::qtescape($newname));          if ($is_unique) {
     }              $newurls->{$newurl} = 1;
  }                  } else {
  $r->print('<ul>');              if ($url=~/\.page$/) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {              } else {
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
     }              }
  }          }
  $r->print('</ul>');      }
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {      return ($newurl);
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');  }
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {  
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {  sub dbcopy {
     $r->print('<li>'.      my ($url,$coursedom,$coursenum) = @_;
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',      if ($url=~ m{/smppg$}) {
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})          my $db_name = &Apache::lonsimplepage::get_db_name($url);
       .'</li>');          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);
     $r->print('</ul>');              my $now = time();
  }              $db_name =~ s{_\d*$ }{_$now}x;
 # End              my $result=&Apache::lonnet::put($db_name,\%contents,
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());                                              $coursedom,$coursenum);
         $shown++;              $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
         if (!($env{'form.show'} eq &mt('all')          }
               || $shown<=$env{'form.show'})) { last; }      }
     }      return $url;
     $r->print(&Apache::loncommon::end_data_table());  }
 }  
   sub uniqueness_check {
 sub update_paste_buffer {      my ($newurl) = @_;
     my ($coursenum,$coursedom) = @_;      my $unique = 1;
       foreach my $res (@LONCAPA::map::order) {
     return if (!defined($env{'form.markcopy'}));          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     return if (!defined($env{'form.copyfolder'}));          $url=&LONCAPA::map::qtescape($url);
     return if ($env{'form.markcopy'} < 0);          if ($newurl eq $url) {
               $unique = 0;
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,              last;
     $env{'form.copyfolder'});          }
          }
     return if ($fatal);      return $unique;
   }
 # Mark for copying  
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);  sub contained_map_check {
     if (&is_supplemental_title($title)) {      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});          $allmaps) = @_;
  ($title) = &parse_supplemental_title($title);      my $content = &Apache::lonnet::getfile($url);
     } elsif ($env{'docs.markedcopy_supplemental'}) {      unless ($content eq '-1') {
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');          my $parser = HTML::TokeParser->new(\$content);
     }          $parser->attr_encoded(1);
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};          while (my $token = $parser->get_token) {
               next if ($token->[0] ne 'S');
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,              if ($token->[1] eq 'resource') {
     'docs.markedcopy_url'   => $url});                  next if ($token->[2]->{'type'} eq 'zombie');
     delete($env{'form.markcopy'});                  my $ressrc = $token->[2]->{'src'};
 }                  if ($folder =~ /^supplemental/) {
                       unless (&supp_pasteable($ressrc)) {
 sub print_paste_buffer {                          $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     my ($r,$container) = @_;                          next;
     return if (!defined($env{'docs.markedcopy_url'}));                      }
                   }
     $r->print(<<ENDPASTE);                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>                      if ($1 eq 'uploaded') {
 ENDPASTE                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');                          $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
                       } else {
     my $type;                          if ($allmaps->{$ressrc}) {
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc; 
  $type = &mt('External Resource');                          } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
  $r->print($type.': '.                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.                          } else {
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');                              $addedmaps->{$ressrc} = [$url];
     }  else {                          }
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];                      }
  my $icon = &Apache::loncommon::icon($extension);                      &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
  if ($extension eq 'sequence' &&                                           $addedmaps,$hierarchy,$titles,$allmaps);
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {                  }
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));              } elsif ($token->[1] eq 'param') {
     $icon .= '/folder_closed.gif';                  if ($folder =~ /^supplemental/) {
  }                      if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';                          push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));                      } else {
     }                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
     if ($container eq 'page') {                      }
  $r->print('                  }
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />              }
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />          }
 ');      }
     } else {      return;
  $r->print('  }
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />  
 ');  sub reinit_role {
     }      my ($cdom,$cnum,$chome) = @_;
     $r->print('</p></form>');      my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
 }      unless ($ferr) {
           &Apache::loncommon::update_content_constraints($cdom,$cnum,$chome,$cdom.'_'.$cnum);
 sub do_paste_from_buffer {      }
     my ($coursenum,$coursedom,$folder) = @_;      return;
   }
     if (!$env{'form.pastemarked'}) {  
         return;  sub url_paste_fixups {
     }      my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$allmaps,$rewrites,$retitles,$copies,
           $dbcopies,$zombies,$params,$mapmoves,$mapchanges,$tomove,$newsubdir,$newurls) = @_;
 # paste resource to end of list      my $checktitle;
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});      if (($prefixchg) &&
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});          ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
 # Maps need to be copied first          $checktitle = 1;
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {      }
  $title=&mt('Copy of').' '.$title;      my $skip;
  my $newid=$$.int(rand(100)).time;      if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);          my $mapid = $1.$2;
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {          if ($tomove->{$mapid}) {
             my $path = $1;              $skip = 1;
             my $prefix = $2;          }
             my $ancestor = $3;      }
             if (length($ancestor) > 10) {      my $file = &Apache::lonnet::getfile($oldurl);
                 $ancestor = substr($ancestor,-10,10);      return if ($file eq '-1');
             }      my $parser = HTML::TokeParser->new(\$file);
             $oldid = $path.$prefix.$ancestor;      $parser->attr_encoded(1);
         }      my $changed = 0;
         my $counter = 0;      while (my $token = $parser->get_token) {
         my $newurl=$oldid.$newid.'.'.$ext;          next if ($token->[0] ne 'S');
         my $is_unique = &uniqueness_check($newurl);          if ($token->[1] eq 'resource') {
         while (!$is_unique && $counter < 100) {              my $ressrc = $token->[2]->{'src'};
             $counter ++;              next if ($ressrc eq '');
             $newid ++;              my $id = $token->[2]->{'id'};
             $newurl = $oldid.$newid;              my $title = $token->[2]->{'title'};
             $is_unique = &uniqueness_check($newurl);              if ($checktitle) {
         }                  if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
         if (!$is_unique) {                      $retitles->{$oldurl}{$ressrc} = $id;
             if ($url=~/\.page$/) {                  }
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');              }
             } else {              next if ($token->[2]->{'type'} eq 'external');
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');              if ($token->[2]->{'type'} eq 'zombie') {
             }                  next if ($skip);  
         }                  $zombies->{$oldurl}{$ressrc} = $id;
  my $storefn=$newurl;                  $changed = 1;
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};              } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
  my $paste_map_result =                  my $srcdom = $1;
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,                  my $srcnum = $2;
        &Apache::lonnet::getfile($url));                  my $rem = $3;
         if ($paste_map_result eq '/adm/notfound.html') {                  my $newurl;
             if ($url=~/\.page$/) {                  my $mapname;
                 return &mt('Paste failed: an error occurred saving the composite page');                  if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
             } else {                      my $prefix = $1;
                 return &mt('Paste failed: an error occurred saving the folder');                      $mapname = $prefix.$2;
             }                      if ($tomove->{$mapname}) {
         }                          &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,$allmaps,
  $url = $newurl;                                            $rewrites,$retitles,$copies,$dbcopies,$zombies,
     }                                            $params,$mapmoves,$mapchanges,$tomove,$newsubdir,
 # published maps can only exists once, so remove it from paste buffer when done                                            $newurls);
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {                          next;
  &Apache::lonnet::delenv('docs\\.markedcopy');                      } else {
     }                          ($newurl,my $error) =
     if ($url=~ m{/smppg$}) {                              &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
  my $db_name = &Apache::lonsimplepage::get_db_name($url);                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
  if ($db_name =~ /^smppage_/) {                          if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
     #simple pages, need to copy the db contents to a new one.                              $newsubdir->{$ressrc} = $1;
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);                          }
     my $now = time();                          if ($error) {
     $db_name =~ s{_\d*$ }{_$now}x;                              next;
     my $result=&Apache::lonnet::put($db_name,\%contents,                          }
     $coursedom,$coursenum);                      }
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;                  }
     $title=&mt('Copy of').' '.$title;                  if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
  }                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
     }                     
     $title = &LONCAPA::map::qtunescape($title);                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
     my $ext='false';                          $rewrites->{$oldurl}{$ressrc} = $id;
     if ($url=~m{^http(|s)://}) { $ext='true'; }                          $mapchanges->{$ressrc} = 1;
     $url       = &LONCAPA::map::qtunescape($url);                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,$allmaps,
 # Now insert the URL at the bottom                                                    $rewrites,$retitles,$copies,$dbcopies,$zombies,
     my $newidx = &LONCAPA::map::getresidx($url);                                                    $params,$mapmoves,$mapchanges,$tomove,$newsubdir,
     if ($env{'docs.markedcopy_supplemental'}) {                                                    $newurls)) {
         if ($folder =~ /^supplemental/) {                              $mapmoves->{$ressrc} = 1;
             $title = $env{'docs.markedcopy_supplemental'};                          }
         } else {                          $changed = 1;
             (undef,undef,$title) =                      } else {
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});                          $rewrites->{$oldurl}{$ressrc} = $id;
         }                          $copies->{$oldurl}{$ressrc} = $id;
     } else {                          $changed = 1;
         if ($folder=~/^supplemental/) {                      }
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                  }
                   $env{'user.domain'}.'___&&&___'.$title;              } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/(.+)$}) {
         }                  next if ($skip);  
     }                  my $srcdom = $1;
                   my $srcnum = $2;
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
     push(@LONCAPA::map::order, $newidx);                      $rewrites->{$oldurl}{$ressrc} = $id;
     return 'ok';                      $dbcopies->{$oldurl}{$ressrc} = $id;
 # Store the result                      $changed = 1;
 }                  }
               } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
 sub uniqueness_check {                  next if ($skip);
     my ($newurl) = @_;                  my $srcdom = $1;
     my $unique = 1;                  my $srcnum = $2;
     foreach my $res (@LONCAPA::map::order) {                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                      $rewrites->{$oldurl}{$ressrc} = $id;
         $url=&LONCAPA::map::qtescape($url);                      $dbcopies->{$oldurl}{$ressrc} = $id;
         if ($newurl eq $url) {                      $changed = 1;
             $unique = 0;                  }
             last;                  }
         }          } elsif ($token->[1] eq 'param') {
     }              next if ($skip);
     return $unique;              my $to = $token->[2]->{'to'}; 
 }              if ($to ne '') {
                   if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
 my %parameter_type = ( 'randompick'     => 'int_pos',                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
        'hiddenresource' => 'string_yesno',                  } else {
        'encrypturl'     => 'string_yesno',                      @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
        'randomorder'    => 'string_yesno',);                  }
 my $valid_parameters_re = join('|',keys(%parameter_type));              }
 # set parameters          }
 sub update_parameter {      }
       return $changed;
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);  }
   
     my $which = $env{'form.changeparms'};  sub apply_fixups {
     my $idx = $env{'form.setparms'};      my ($folder,$is_map,$prefixchg,$cdom,$cnum,$oldurl,$url,$removefrommap,
     if ($env{'form.'.$which.'_'.$idx}) {          $removeparam,$rewrites,$retitles,$copies,$dbcopies,$zombies,$params,
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}          $docmoves,$mapmoves,$newsubdir,$errors,$before,$after) = @_;
                                      : 'yes';      foreach my $key (keys(%{$copies}),keys(%{$docmoves})) {
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,          my @allcopies;
       $parameter_type{$which});          if (ref($copies->{$key}) eq 'HASH') {
  &remember_parms($idx,$which,'set',$value);              my %added;
     } else {              foreach my $innerkey (keys(%{$copies->{$key}})) {
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);                  if (($innerkey ne '') && (!$added{$innerkey})) {
                       push(@allcopies,$innerkey);
  &remember_parms($idx,$which,'del');                      $added{$innerkey} = 1;
     }                  }
     return 1;              }
 }              undef(%added);
           }
           if ($key eq $oldurl) {
 sub handle_edit_cmd {              if ((exists($docmoves->{$key}))) {
     my ($coursenum,$coursedom) =@_;                  unless (grep(/^\Q$oldurl\E/,@allcopies)) {
                       push(@allcopies,$oldurl);
     my ($cmd,$idx)=split('_',$env{'form.cmd'});                  }
               }
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];          }
     my ($title, $url, @rrest) = split(':', $ratstr);          if (@allcopies > 0) {
               foreach my $item (@allcopies) {
     if ($cmd eq 'del') {                  my ($relpath,$oldsubdir,$fname) = 
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {                  if ($fname ne '') {
     &Apache::lonnet::removeuploadedurl($url);                      my $content = &Apache::lonnet::getfile($item);
  } else {                      unless ($content eq '-1') {
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                          my $storefn;
  }                          if (($key eq $oldurl) && (ref($docmoves) eq 'HASH') && (exists($docmoves->{$key}))) {
  splice(@LONCAPA::map::order, $idx, 1);                              $storefn = $docmoves->{$key};
                           } else {
     } elsif ($cmd eq 'cut') {                              $storefn = $relpath;
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
  splice(@LONCAPA::map::order, $idx, 1);                              if ($prefixchg) {
                                   $storefn =~ s/^\Q$before->{'doc'}\E/$after->{'doc'}/;
     } elsif ($cmd eq 'up'                              }
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {                              if ($newsubdir->{$key}) {
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];                                  $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir->{$key}#;
                               }
     } elsif ($cmd eq 'down'                          }
      && defined($LONCAPA::map::order[$idx+1])) {                          &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];                          my $copyurl = 
                               &Apache::lonclonecourse::writefile($env{'request.course.id'},
     } elsif ($cmd eq 'rename') {                                                                 $storefn.$fname,$content);
                           if ($copyurl eq '/adm/notfound.html') {
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});                              if ((ref($docmoves) eq 'HASH') && (exists($docmoves->{$oldurl}))) {
  if ($comment=~/\S/) {                                  return &mt('Paste failed: an error occurred copying the file.');
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=                              } elsif (ref($errors) eq 'HASH') {
  $comment.':'.join(':', $url, @rrest);                                  $errors->{$item} = 1;
  }                              }
 # Devalidate title cache                          }
  my $renamed_url=&LONCAPA::map::qtescape($url);                      }
  &Apache::lonnet::devalidate_title_cache($renamed_url);                  }
     } else {              }
  return 0;          }
     }      }
     return 1;      foreach my $key (keys(%{$mapmoves})) {
 }          my $storefn=$key;
           $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 sub editor {          if ($prefixchg) {
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;              $storefn =~ s/^\Q$before->{'map'}\E/$after->{'map'}/;
           }
     my $container= ($env{'form.pagepath'}) ? 'page'          if ($newsubdir->{$key}) {
                            : 'sequence';              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir->{$key}/;
           }
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,          my $mapcontent = &Apache::lonnet::getfile($key);
     $folder.'.'.$container);          if ($mapcontent eq '-1') {
     return $errtext if ($fatal);              if (ref($errors) eq 'HASH') {
                   $errors->{$key} = 1;
     if ($#LONCAPA::map::order<1) {              }
  my $idx=&LONCAPA::map::getresidx();          } else {
  if ($idx<=0) { $idx=1; }              my $newmap =
         $LONCAPA::map::order[0]=$idx;                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
         $LONCAPA::map::resources[$idx]='';                                                     $mapcontent);
     }              if ($newmap eq '/adm/notfound.html') {
                      if (ref($errors) eq 'HASH') {
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=                      $errors->{$key} = 1;
  &breadcrumbs($folder,$allowed,$type);                  }
     $r->print($breadcrumbtrail);              }
              }
 # ------------------------------------------------------------ Process commands      }
       my %updates;
 # ---------------- if they are for this folder and user allowed to make changes      if ($is_map) {
     if (($allowed) && ($env{'form.folder'} eq $folder)) {          foreach my $key (keys(%{$rewrites})) {
 # set parameters and change order              $updates{$key} = 1;
  &snapshotbefore();          }
           foreach my $key (keys(%{$zombies})) {
  if (&update_parameter()) {              $updates{$key} = 1;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          }
     return $errtext if ($fatal);          foreach my $key (keys(%{$removefrommap})) {
  }              $updates{$key} = 1;
           }
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {          foreach my $key (keys(%{$removeparam})) {
 # change order              $updates{$key} = 1;
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);          }
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);          foreach my $key (keys(%{$dbcopies})) {
               $updates{$key} = 1;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          }
     return $errtext if ($fatal);          foreach my $key (keys(%{$retitles})) {
  }              $updates{$key} = 1;
               }
  if ($env{'form.pastemarked'}) {          foreach my $key (keys(%updates)) {
             my $paste_res =              my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);              if (ref($rewrites->{$key}) eq 'HASH') {
             if ($paste_res eq 'ok') {                  %torewrite = %{$rewrites->{$key}};
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);              }
                 return $errtext if ($fatal);              if (ref($retitles->{$key}) eq 'HASH') {
             } elsif ($paste_res ne '') {                  %toretitle = %{$retitles->{$key}};
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');              }
             }              if (ref($removefrommap->{$key}) eq 'HASH') {
  }                  %toremove = %{$removefrommap->{$key}};
               }
  $r->print($upload_output);              if (ref($removeparam->{$key}) eq 'HASH') {
                   %remparam = %{$removeparam->{$key}};
  if (&handle_edit_cmd()) {              }
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);              if (ref($zombies->{$key}) eq 'HASH') {
     return $errtext if ($fatal);                  %zombie = %{$zombies->{$key}};
  }              }
 # Group import/search              if (ref($dbcopies->{$key}) eq 'HASH') {
  if ($env{'form.importdetail'}) {                  foreach my $item (keys(%{$dbcopies->{$key}})) {
     my @imports;                      $newdb{$item} = &dbcopy($item);
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {                  }
  if (defined($item)) {              }
     my ($name,$url,$residx)=              if (ref($params->{$key}) eq 'HASH') {
  map {&unescape($_)} split(/\=/,$item);                  %currparam = %{$params->{$key}};
     push(@imports, [$name, $url, $residx]);              }
  }              my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
     }              if ($fatal) {
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,                  return $errtext;
     $container,'londocs',@imports);              }
     return $errtext if ($fatal);              for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
  }                  if (defined($LONCAPA::map::zombies[$i])) {
 # Loading a complete map                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
  if ($env{'form.loadmap'}) {                      if ($zombie{$src} eq $i) {
     if ($env{'form.importmap'}=~/\w/) {                          undef($LONCAPA::map::zombies[$i]);
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {                      }
     my ($title,$url,$ext,$type)=split(/\:/,$res);                  }
     my $idx=&LONCAPA::map::getresidx($url);              }
     $LONCAPA::map::resources[$idx]=$res;              for (my $i=0; $i<@LONCAPA::map::resources; $i++) {
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;                  if (defined($LONCAPA::map::resources[$i])) {
  }                      my $changed;
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$i]);
     $folder.'.'.$container);                      if ($toremove{$src} eq $i) {
  return $errtext if ($fatal);                          splice(@LONCAPA::map::order,$i,1);
     } else {                          if (ref($currparam{$i}) eq 'ARRAY') {
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');                              foreach my $name (@{$currparam{$i}}) {
                                   &LONCAPA::map::delparameter($i,'parameter_'.$name);
     }                              }
  }                          }
  &log_differences($plain);                          next;
     }                      }
 # ---------------------------------------------------------------- End commands                      my $origsrc = $src;
 # ---------------------------------------------------------------- Print screen                      if ((exists($toretitle{$src})) && ($toretitle{$src} eq $i)) {
     my $idx=0;                          if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
     my $shown=0;                              $changed = 1;
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {                          }
  $r->print('<p>'.&mt('Parameters').':<ul>'.                      }
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').                      if ((exists($torewrite{$src})) && ($torewrite{$src} eq $i)) {
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').                          if ($origsrc =~ m{^/uploaded/}) {
   '</ul></p>');                              if ($prefixchg) {
     }                                                                                                                                      if ($src =~ /\.(page|sequence)$/) {
     if ($randompick>=0) {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before->{'map'}\E#$1$after->{'map'}#;
  $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>');                                  } else {
     }                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before->{'doc'}\E#$1$after->{'doc'}#;
     if ($is_random_order) {                                  }
  $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');                              }
     }                              if ($newsubdir->{$origsrc}) {
     $r->print('<table class="LC_docs_editor">');                                  if ($src =~ /\.(page|sequence)$/) {
     foreach my $res (@LONCAPA::map::order) {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir->{$origsrc}#;
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                                  } else {
  $name=&LONCAPA::map::qtescape($name);                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir->{$origsrc}#;
  $url=&LONCAPA::map::qtescape($url);                                  }
  unless ($name) {  $name=(split(/\//,$url))[-1]; }                              }
  unless ($name) { $idx++; next; }                          }
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,                          $changed = 1;
      $coursenum));                      } elsif ($newdb{$src} ne '') {
  $idx++;                          $src = $newdb{$src};
  $shown++;                          $changed = 1;
     }                      }
     unless ($shown) {                      if ($changed) {
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');                          $LONCAPA::map::resources[$i] = join(':',($title,$src,$ext,$type));
     }                      }
     $r->print("\n</table>\n");                  }
     if ($allowed) {              }
         &print_paste_buffer($r,$container);              foreach my $idx (keys(%remparam)) {
     }                  if (ref($remparam{$idx}) eq 'ARRAY') {
     return;                      foreach my $name (@{$remparam{$idx}}) {   
 }                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
                       }
 sub process_file_upload {                  }
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;              }
 # upload a file, if present              my $storefn;
     my $parseaction;              if ($key eq $oldurl) {
    if ($env{'form.parserflag'}) {                  $storefn = $url;
         $parseaction = 'parse';                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     }              } else {
     my $phase_status;                  $storefn = $key;
     my $folder=$env{'form.folder'};                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     if ($folder eq '') {                  if ($prefixchg) {
         $folder='default';                      $storefn =~ s/^\Q$before->{'map'}\E/$after->{'map'}/;
     }                  }
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {                  if ($newsubdir->{$key}) {
         my $errtext='';                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir->{$key}/;
         my $fatal=0;                  }
         my $container='sequence';              }
         if ($env{'form.pagepath'}) {              my $report;
             $container='page';              if ($folder !~ /^supplemental/) {
         }                  $report = 1;
         ($errtext,$fatal)=              }
               &mapread($coursenum,$coursedom,$folder.'.'.$container);              my ($outtext,$errtext) =
         if ($#LONCAPA::map::order<1) {                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
             $LONCAPA::map::order[0]=1;              if ($errtext) {
             $LONCAPA::map::resources[1]='';                  return &mt('Paste failed: an error occurred saving the folder or page.');
         }              }
         if ($fatal) {          }
             return 'failed';      }
         }      return 'ok';
         my $destination = 'docs/';  }
         if ($folder =~ /^supplemental/) {  
             $destination = 'supplemental/';  sub copy_dependencies {
         }      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
         if (($folder eq 'default') || ($folder eq 'supplemental')) {      my $content;
             $destination .= 'default/';      if (ref($contentref)) {
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {          $content = $$contentref;
             $destination .=  $2.'/';      } else {
         }          $content = &Apache::lonnet::getfile($item);
 # this is for a course, not a user, so set coursedoc flag      }
 # probably the only place in the system where this should be "1"      unless ($content eq '-1') {
         my $newidx=&LONCAPA::map::getresidx();          my $mm = new File::MMagic;
         $destination .= $newidx;          my $mimetype = $mm->checktype_contents($content);
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,          if ($mimetype eq 'text/html') {
  $parseaction,$allfiles,              my (%allfiles,%codebase,$state);
  $codebase);              my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
         my $ext='false';              if ($res eq 'ok') {
         if ($url=~m{^http://}) { $ext='true'; }                  my ($numexisting,$numpathchanges,$existing);
  $url     = &LONCAPA::map::qtunescape($url);                  (undef,$numexisting,$numpathchanges,$existing) =
         my $comment=$env{'form.comment'};                      &Apache::loncommon::ask_for_embedded_content(
  $comment = &LONCAPA::map::qtunescape($comment);                          '/adm/coursedocs',$state,\%allfiles,\%codebase,
         if ($folder=~/^supplemental/) {                          {'error_on_invalid_names'   => 1,
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                           'ignore_remote_references' => 1,
                   $env{'user.domain'}.'___&&&___'.$comment;                           'docs_url'                 => $item,
         }                           'context'                  => 'paste'});
                   if ($numexisting > 0) {
         $LONCAPA::map::resources[$newidx]=                      if (ref($existing) eq 'HASH') {
     $comment.':'.$url.':'.$ext.':normal:res';                          foreach my $dep (keys(%{$existing})) {
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;                              my $depfile = $dep;
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,                              unless ($depfile =~ m{^\Q$relpath\E}) {
     $folder.'.'.$container);                                  $depfile = $relpath.$dep;
         if ($fatal) {                              }
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';                              my $depcontent = &Apache::lonnet::getfile($depfile);
             return 'failed';                              unless ($depcontent eq '-1') {
         } else {                                  my $storedep = $dep;
             if ($parseaction eq 'parse') {                                  $storedep =~ s{^\Q$relpath\E}{};
                 my $total_embedded = keys(%{$allfiles});                                  my $dep_url =
                 if ($total_embedded > 0) {                                      &Apache::lonclonecourse::writefile(
                     my $num = 0;                                          $env{'request.course.id'},
     my $state = '                                          $storefn.$storedep,$depcontent);
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />                                  if ($dep_url eq '/adm/notfound.html') {
    <input type="hidden" name="cmd" value="upload_embedded" />                                      if (ref($errors) eq 'HASH') {
    <input type="hidden" name="newidx" value="'.$newidx.'" />                                          $errors->{$depfile} = 1;
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />                                      }
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';                                  } else {
     $phase_status = 'phasetwo';                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
                                   }
                     $$upload_output .=                              }
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.                          }
  &Apache::loncommon::ask_for_embedded_content(                      }
                             '/adm/coursedocs',$state,$allfiles,$codebase);                  }
                 } else {              }
                     $$upload_output .= 'No embedded items identified<br />';          }
                 }      }
             }      return;
         }  }
     }  
     return $phase_status;  my %parameter_type = ( 'randompick'     => 'int_pos',
 }         'hiddenresource' => 'string_yesno',
          'encrypturl'     => 'string_yesno',
 sub process_secondary_uploads {         'randomorder'    => 'string_yesno',);
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;  my $valid_parameters_re = join('|',keys(%parameter_type));
     my $folder=$env{'form.folder'};  # set parameters
     my $destination = 'docs/';  sub update_parameter {
     if ($folder =~ /^supplemental/) {  
         $destination = 'supplemental/';      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     }  
     if (($folder eq 'default') || ($folder eq 'supplemental')) {      my $which = $env{'form.changeparms'};
         $destination .= 'default/';      my $idx = $env{'form.setparms'};
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {      if ($env{'form.'.$which.'_'.$idx}) {
         $destination .=  $2.'/';   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
     }                                       : 'yes';
     $destination .= $newidx;   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
     my ($url,$filename);        $parameter_type{$which});
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);   &remember_parms($idx,$which,'set',$value);
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});      } else {
     return $filename;   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
 }  
    &remember_parms($idx,$which,'del');
 sub is_supplemental_title {      }
     my ($title) = @_;      return 1;
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);  }
 }  
   
 sub parse_supplemental_title {  sub handle_edit_cmd {
     my ($title) = @_;      my ($coursenum,$coursedom) =@_;
       my ($cmd,$idx)=split('_',$env{'form.cmd'});
     my ($foldertitle,$renametitle);  
     if ($title =~ /&amp;&amp;&amp;/) {      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  $title = &HTML::Entites::decode($title);      my ($title, $url, @rrest) = split(':', $ratstr);
     }  
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {      if ($cmd eq 'del') {
  $renametitle=$4;   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  my ($time,$uname,$udom) = ($1,$2,$3);      ($url!~/$LONCAPA::assess_page_seq_re/)) {
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);      &Apache::lonnet::removeuploadedurl($url);
  my $name =  &Apache::loncommon::plainname($uname,$udom);   } else {
  $name = &HTML::Entities::encode($name,'"<>&\'');      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.   }
     $name.': <br />'.$foldertitle;   splice(@LONCAPA::map::order, $idx, 1);
     }  
     if (wantarray) {      } elsif ($cmd eq 'cut') {
  return ($title,$foldertitle,$renametitle);   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     }   splice(@LONCAPA::map::order, $idx, 1);
     return $title;  
 }      } elsif ($cmd eq 'up'
        && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
 # --------------------------------------------------------------- An entry line   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
   
 sub entryline {      } elsif ($cmd eq 'down'
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;       && defined($LONCAPA::map::order[$idx+1])) {
    @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
     my ($foldertitle,$pagetitle,$renametitle);  
     if (&is_supplemental_title($title)) {      } elsif ($cmd eq 'rename') {
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);  
  $pagetitle = $foldertitle;   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
     } else {   if ($comment=~/\S/) {
  $title=&HTML::Entities::encode($title,'"<>&\'');      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
  $renametitle=$title;   $comment.':'.join(':', $url, @rrest);
  $foldertitle=$title;   }
  $pagetitle=$title;  # Devalidate title cache
     }   my $renamed_url=&LONCAPA::map::qtescape($url);
    &Apache::lonnet::devalidate_title_cache($renamed_url);
     my $orderidx=$LONCAPA::map::order[$index];      } else {
       return 0;
       }
     $renametitle=~s/\\/\\\\/g;      return 1;
     $renametitle=~s/\&quot\;/\\\"/g;  }
     $renametitle=~s/ /%20/g;  
     my $line='<tr>';  sub editor {
     my ($form_start,$form_end);      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 # Edit commands          $supplementalflag,$orderhash,$iconpath,$uploadtag)=@_;
     my ($container, $type, $esc_path, $path, $symb);      my $container= ($env{'form.pagepath'}) ? 'page'
     if ($env{'form.folderpath'}) {                             : 'sequence';
  $type = 'folder';  
         $container = 'sequence';      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order) =
  $esc_path=&escape($env{'form.folderpath'});          &breadcrumbs($allowed,$crstype);
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      $r->print($breadcrumbtrail);
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');  
     }      my $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
     if ($env{'form.pagepath'}) {  
         $type = $container = 'page';      unless ($allowed) {
         $esc_path=&escape($path = $env{'form.pagepath'});          $randompick = -1;
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');      }
         $symb=&escape($env{'form.pagesymb'});  
     }      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
     my $cpinfo='';      $folder.'.'.$container);
     if ($allowed) {      return $errtext if ($fatal);
  my $incindex=$index+1;  
  my $selectbox='';      if ($#LONCAPA::map::order<1) {
  if (($folder!~/^supplemental/) &&   my $idx=&LONCAPA::map::getresidx();
     ($#LONCAPA::map::order>0) &&   if ($idx<=0) { $idx=1; }
     ((split(/\:/,          $LONCAPA::map::order[0]=$idx;
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]          $LONCAPA::map::resources[$idx]='';
      ne '') &&      }
     ((split(/\:/,  
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]  # ------------------------------------------------------------ Process commands
      ne '')) {  
     $selectbox=  # ---------------- if they are for this folder and user allowed to make changes
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.      if (($allowed) && ($env{'form.folder'} eq $folder)) {
  '<select name="newpos" onChange="this.form.submit()">';  # set parameters and change order
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {   &snapshotbefore();
  if ($i==$incindex) {  
     $selectbox.='<option value="" selected="1">('.$i.')</option>';   if (&update_parameter()) {
  } else {      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';      return $errtext if ($fatal);
  }   }
     }  
     $selectbox.='</select>';   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
  }  # change order
  my %lt=&Apache::lonlocal::texthash(      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
                 'up' => 'Move Up',      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
  'dw' => 'Move Down',  
  'rm' => 'Remove',      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                 'ct' => 'Cut',      return $errtext if ($fatal);
  'rn' => 'Rename',   }
  'cp' => 'Copy');  
  my $nocopy=0;   if ($env{'form.pastemarked'}) {
         my $nocut=0;              my %paste_errors;
         if ($url=~/\.(page|sequence)$/) {              my ($paste_res,$save_error) =
     if ($url =~ m{/res/}) {                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
  # no copy for published maps                                        \%paste_errors);
  $nocopy = 1;                  if ($save_error ne '') {
     } else {                      return $save_error; 
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {                  }
     my ($title,$url,$ext,$type)=split(/\:/,$item);              if ($paste_res ne 'ok') {
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
  $nocopy=1;              }
  last;              if (keys(%paste_errors) > 0) {
     }                  $r->print('<p span class="LC_warning">'."\n".
  }                            &mt('The following files are either dependencies of a web page or references within a folder and/or composite page which could not be copied during the paste operation:')."\n".
     }                            '<ul>'."\n");
  }                  foreach my $key (sort(keys(%paste_errors))) {
         if ($url=~/^\/res\/lib\/templates\//) {                      $r->print('<li>'.$key.'</li>'."\n");
            $nocopy=1;                  }
            $nocut=1;                  $r->print('</ul></p>'."\n");
         }              }
         my $copylink='&nbsp;';   }
         my $cutlink='&nbsp;';  
    $r->print($upload_output);
  my $skip_confirm = 0;  
  if ( $folder =~ /^supplemental/   if (&handle_edit_cmd()) {
      || ($url =~ m{( /smppg$              my $contentchg;
     |/syllabus$              if ($env{'form.cmd'} =~ /^(del|cut)_/) {
     |/aboutme$                  $contentchg = 1;
     |/navmaps$              }
     |/bulletinboard$      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
     |\.html$      return $errtext if ($fatal);
     |^/adm/wrapper/ext)}x)) {   }
     $skip_confirm = 1;  # Group import/search
  }   if ($env{'form.importdetail'}) {
       my @imports;
  if (!$nocopy) {      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
     $copylink=(<<ENDCOPY);   if (defined($item)) {
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>      my ($name,$url,$residx)=
 ENDCOPY   map {&unescape($_)} split(/\=/,$item);
         }      push(@imports, [$name, $url, $residx]);
  if (!$nocut) {   }
     $cutlink=(<<ENDCUT);      }
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
 ENDCUT      $container,'londocs',@imports);
         }      return $errtext if ($fatal);
  $form_start = (<<END);   }
    <form  action="/adm/coursedocs" method="post">  # Loading a complete map
    <input type="hidden" name="${type}path" value="$path" />   if ($env{'form.loadmap'}) {
    <input type="hidden" name="${type}symb" value="$symb" />      if ($env{'form.importmap'}=~/\w/) {
    <input type="hidden" name="setparms" value="$orderidx" />   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
    <input type="hidden" name="changeparms" value="0" />      my ($title,$url,$ext,$type)=split(/\:/,$res);
 END      my $idx=&LONCAPA::map::getresidx($url);
         $form_end = '</form>';      $LONCAPA::map::resources[$idx]=$res;
  $line.=(<<END);      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
 <td>   }
    <table class="LC_docs_entry_move">   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
       <tr>      $folder.'.'.$container,1);
          <td>   return $errtext if ($fatal);
             <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>      } else {
          </td>   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
       </tr>  
       <tr>      }
         <td>   }
            <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" /></a>   &log_differences($plain);
         </td>      }
       </tr>  # ---------------------------------------------------------------- End commands
     </table>  # ---------------------------------------------------------------- Print screen
 </td>      my $idx=0;
 <td>      my $shown=0;
    $form_start      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
    $selectbox   $r->print('<div class="LC_Box">'.
    $form_end            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
 </td>    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
 <td class="LC_docs_entry_commands">    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
 $cutlink    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>    '</ol>');
 $copylink          if ($randompick>=0) {
 </td>              $r->print('<p class="LC_warning">'
 END                   .&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'
 # Figure out what kind of a resource this is                       .' students see, resulting in spurious or missing credit'
     my ($extension)=($url=~/\.(\w+)$/);                       .' for completed problems, not limited to ones you'
     my $uploaded=($url=~/^\/*uploaded\//);                       .' modify. Do not modify the contents of this folder if'
     my $icon=&Apache::loncommon::icon($url);                       .' it is in active student use.')
     my $isfolder=0;                   .'</p>'
     my $ispage=0;              );
     my $folderarg;          }
     my $pagearg;          if ($is_random_order) {
     my $pagefile;              $r->print('<p class="LC_warning">'
     if ($uploaded) {                   .&mt('Caution: this folder is set to randomly order its'
  if ($extension eq 'sequence') {                       .' contents. Adding or removing resources from this folder'
     $icon=$iconpath.'/folder_closed.gif';                       .' will change the order of resources shown.')
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;                   .'</p>'
     $url='/adm/coursedocs?';              );
     $folderarg=$1;          }
     $isfolder=1;          $r->print('</div>');
         } elsif ($extension eq 'page') {      }
             $icon=$iconpath.'/page.gif';  
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;      my ($to_show,$output);
             $pagearg=$1;  
             $url='/adm/coursedocs?';      &Apache::loncommon::start_data_table_count(); #setup a row counter 
             $ispage=1;      foreach my $res (@LONCAPA::map::order) {
  } else {          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);          $name=&LONCAPA::map::qtescape($name);
  }          $url=&LONCAPA::map::qtescape($url);
     }          unless ($name) {  $name=(split(/\//,$url))[-1]; }
              unless ($name) { $idx++; next; }
     my $orig_url = $url;          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});                                $coursenum,$coursedom,$crstype,
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {                                $uploadtag,$supplementalflag);
  my $symb=&Apache::lonnet::symbclean(          $idx++;
           &Apache::lonnet::declutter('uploaded/'.          $shown++;
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.      }
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.      &Apache::loncommon::end_data_table_count();
            '.sequence').      
            '___'.$residx.'___'.      if ($shown) {
    &Apache::lonnet::declutter($url));          $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);                    .&Apache::loncommon::start_data_table(undef,'contentlist');
  $url=&Apache::lonnet::clutter($url);          if ($allowed) {
  if ($url=~/^\/*uploaded\//) {              $to_show .= &Apache::loncommon::start_data_table_header_row()
     $url=~/\.(\w+)$/;                       .'<th colspan="2">'.&mt('Move').'</th>'
     my $embstyle=&Apache::loncommon::fileembstyle($1);                       .'<th>'.&mt('Actions').'</th>'
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {                       .'<th colspan="2">'.&mt('Document').'</th>';
  $url='/adm/wrapper'.$url;              if ($folder !~ /^supplemental/) {
     } elsif ($embstyle eq 'ssi') {                  $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
  #do nothing with these              }
     } elsif ($url!~/\.(sequence|page)$/) {              $to_show .= &Apache::loncommon::end_data_table_header_row();
  $url='/adm/coursedocs/showdoc'.$url;          }
     }          $to_show .= $output.' '
  } elsif ($url=~m|^/ext/|) {                   .&Apache::loncommon::end_data_table()
     $url='/adm/wrapper'.$url;                   .'<br style="line-height:2px;" />'
     $external = 1;                   .&Apache::loncommon::end_scrollbox();
  }      } else {
         if (&Apache::lonnet::symbverify($symb,$url)) {          $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                   .'<div class="LC_info" id="contentlist">'
         } else {                   .&mt('Currently no documents.')
             $url='';                   .'</div>'
         }                   .&Apache::loncommon::end_scrollbox();
  if ($container eq 'page') {      }
     my $symb=$env{'form.pagesymb'};      my $tid = 1;
               if ($supplementalflag) {
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);          $tid = 2;
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);      }
  }      if ($allowed) {
     }          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,$jumpto,
     if ($isfolder || $extension eq 'sequence') {                                         $readfile));
  my $foldername=&escape($foldertitle);          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
  my $folderpath=$env{'form.folderpath'};      } else {
  if ($folderpath) { $folderpath.='&' };          if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 # Append randompick number, hidden, and encrypted with ":" to foldername,              #Function Box for Supplemental Content for users with mdc priv.
 # so it gets transferred between levels              my $funcname = &mt('Folder Editor');
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,              $r->print(
                                               'parameter_randompick'))[0]                  &Apache::loncommon::head_subbox(
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                      &Apache::lonhtmlcommon::start_funclist().
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)                      &Apache::lonhtmlcommon::add_item_funclist(
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                          '<a href="/adm/coursedocs?command=direct&forcesupplement=1&'.
                                               'parameter_encrypturl'))[0]=~/^yes$/i)                          'supppath='.&HTML::Entities::encode($env{'form.folderpath'}).'">'.
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                          '<img src="/res/adm/pages/docs.png" alt="'.$funcname.'" class="LC_icon" />'.
                                               'parameter_randomorder'))[0]=~/^yes$/i);                          '<span class="LC_menubuttons_inline_text">'.$funcname.'</span></a>').
  $url.='folderpath='.&escape($folderpath).$cpinfo;                            &Apache::lonhtmlcommon::end_funclist()));
  $parameterset='<label>'.&mt('Randomly Pick: ').          }
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.          $r->print($to_show);
     (&LONCAPA::map::getparameter($orderidx,      }
                                               'parameter_randompick'))[0].      return;
                                               '" />'.  }
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';  
     my $ro_set=  sub process_file_upload {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
  $rand_order_text ='  # upload a file, if present
 <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>';        my ($parseaction,$showupload,$nextphase,$mimetype);
     }      if ($env{'form.parserflag'}) {
     if ($ispage) {          $parseaction = 'parse';
         my $pagename=&escape($pagetitle);      }
         my $pagepath;      my $folder=$env{'form.folder'};
         my $folderpath=$env{'form.folderpath'};      if ($folder eq '') {
         if ($folderpath) { $pagepath = $folderpath.'&' };          $folder='default';
         $pagepath.=$pagearg.'&'.$pagename;      }
  my $symb=$env{'form.pagesymb'};      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  if (!$symb) {          my $errtext='';
     my $path='uploaded/'.          my $fatal=0;
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.          my $container='sequence';
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';          if ($env{'form.pagepath'}) {
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',              $container='page';
        $residx,          }
        $path.$pagearg.'.page');          ($errtext,$fatal)=
  }                &mapread($coursenum,$coursedom,$folder.'.'.$container);
  $url.='pagepath='.&escape($pagepath).          if ($#LONCAPA::map::order<1) {
     '&amp;pagesymb='.&escape($symb).$cpinfo;              $LONCAPA::map::order[0]=1;
     }              $LONCAPA::map::resources[1]='';
     if ($external) {          }
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';          if ($fatal) {
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('The uploaded file has not been stored as an error occurred reading the contents of the current folder.').'</div>';
     } else {              return;
  undef($external);          }
     }          my $destination = 'docs/';
     $line.='          if ($folder =~ /^supplemental/) {
   <td class="LC_docs_entry_icon">              $destination = 'supplemental/';
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'          }
   </td>          if (($folder eq 'default') || ($folder eq 'supplemental')) {
   <td class="LC_docs_entry_title">              $destination .= 'default/';
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
   </td>";              $destination .=  $2.'/';
     if (($allowed) && ($folder!~/^supplemental/)) {          }
   my %lt=&Apache::lonlocal::texthash(  # this is for a course, not a user, so set context to coursedoc.
        'hd' => 'Hidden',          my $newidx=&LONCAPA::map::getresidx();
        'ec' => 'URL hidden');          $destination .= $newidx;
  my $enctext=          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');   $parseaction,$allfiles,
  my $hidtext=   $codebase,undef,undef,undef,undef,
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');                                                  undef,undef,\$mimetype);
  $line.=(<<ENDPARMS);          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
   <td class="LC_docs_entry_parameter">              my $stored = $1;
     $form_start              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>                            $stored.'</span>').'</p>';
     $form_end          } else {
   </td>              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
   <td class="LC_docs_entry_parameter">              
     $form_start              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>              return;
     $form_end          }
   </td>          my $ext='false';
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>          if ($url=~m{^http://}) { $ext='true'; }
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>   $url     = &LONCAPA::map::qtunescape($url);
 ENDPARMS          my $comment=$env{'form.comment'};
     }   $comment = &LONCAPA::map::qtunescape($comment);
     $line.="</tr>";          if ($folder=~/^supplemental/) {
     return $line;                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 }                    $env{'user.domain'}.'___&&&___'.$comment;
           }
 =pod  
           $LONCAPA::map::resources[$newidx]=
 =item tiehash()      $comment.':'.$url.':'.$ext.':normal:res';
           $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
 tie the hash          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
       $folder.'.'.$container,1);
 =cut          if ($fatal) {
               $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
 sub tiehash {              return;
     my ($mode)=@_;          } else {
     $hashtied=0;              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
     if ($env{'request.course.fn'}) {                  $$upload_output = $showupload;
  if ($mode eq 'write') {                  my $total_embedded = scalar(keys(%{$allfiles}));
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                  if ($total_embedded > 0) {
     &GDBM_WRCREAT(),0640)) {                      my $uploadphase = 'upload_embedded';
                 $hashtied=2;                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
     }      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
  } else {                      my ($embedded,$num) = 
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                          &Apache::loncommon::ask_for_embedded_content(
     &GDBM_READER(),0640)) {                              '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
                 $hashtied=1;                      if ($embedded) {
     }                          if ($num) {
  }                              $$upload_output .=
     }               '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
 }                              $nextphase = $uploadphase;
                           } else {
 sub untiehash {                              $$upload_output .= $embedded;
     if ($hashtied) { untie %hash; }                          }
     $hashtied=0;                      } else {
     return OK;                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
 }                      }
                   } else {
                       $$upload_output .= &mt('No embedded items identified').'<br />';
                   }
                   $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
 sub checkonthis {              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
     my ($r,$url,$level,$title)=@_;                  $nextphase = 'decompress_uploaded';
     $url=&unescape($url);                  my $position = scalar(@LONCAPA::map::order)-1;
     $alreadyseen{$url}=1;                  my $noextract = &return_to_editor();
     $r->rflush();                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {                  my %archiveitems = (
        $r->print("\n<br />");                      folderpath => $env{'form.folderpath'},
        if ($level==0) {                      pagepath   => $env{'form.pagepath'},
            $r->print("<br />");                      cmd        => $nextphase,
        }                      newidx     => $newidx,
        for (my $i=0;$i<=$level*5;$i++) {                      position   => $position,
            $r->print('&nbsp;');                      phase      => $nextphase,
        }                      comment    => $comment,
        $r->print('<a href="'.$url.'" target="cat">'.                  );
  ($title?$title:$url).'</a> ');                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
        if ($url=~/^\/res\//) {                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
   my $result=&Apache::lonnet::repcopy(                  $$upload_output = $showupload.
                               &Apache::lonnet::filelocation('',$url));                                    &Apache::loncommon::decompress_form($mimetype,
           if ($result eq 'ok') {                                        $archiveurl,'/adm/coursedocs',$noextract,
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');                                        \%archiveitems,\@current);
              $r->rflush();              }
              &Apache::lonnet::countacc($url);          }
              $url=~/\.(\w+)$/;      }
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {      return $nextphase;
  $r->print('<br />');  }
                  $r->rflush();  
                  for (my $i=0;$i<=$level*5;$i++) {  sub get_dir_list {
                      $r->print('&nbsp;');      my ($url,$coursenum,$coursedom,$newidx) = @_;
                  }      my ($destination,$dir_root) = &embedded_destination();
                  $r->print('- '.&mt('Rendering:').' ');      my ($dirlistref,$listerror) =  
  my ($errorcount,$warningcount)=split(/:/,          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
        &Apache::lonnet::ssi_body($url,      my @dir_lines;
        ('grade_target'=>'web',      my $dirptr=16384;
  'return_only_error_and_warning_counts' => 1)));      if (ref($dirlistref) eq 'ARRAY') {
                  if (($errorcount) ||          foreach my $dir_line (sort
                      ($warningcount)) {                            {
      if ($errorcount) {                                my ($afile)=split('&',$a,2);
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.                                my ($bfile)=split('&',$b,2);
                           &mt('[quant,_1,error]',$errorcount).'</span>');                                return (lc($afile) cmp lc($bfile));
                      }                            } (@{$dirlistref})) {
      if ($warningcount) {              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
                         $r->print('<span class="LC_warning">'.              $filename =~ s/\s+$//;
                           &mt('[quant,_1,warning]',$warningcount).'</span>');              next if ($filename =~ /^\.\.?$/); 
                      }              my $isdir = 0;
                  } else {              if ($dirptr&$testdir) {
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');                  $isdir = 1;
                  }              }
                  $r->rflush();              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
              }          }
      my $dependencies=      }
                 &Apache::lonnet::metadata($url,'dependencies');      return @dir_lines;
              foreach my $dep (split(/\,/,$dependencies)) {  }
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {  
                     &checkonthis($r,$dep,$level+1);  sub is_supplemental_title {
                  }      my ($title) = @_;
              }      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
           } elsif ($result eq 'unavailable') {  }
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');  
           } elsif ($result eq 'not_found') {  # --------------------------------------------------------------- An entry line
       unless ($url=~/\$/) {  
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');  sub entryline {
       } else {      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');          $crstype,$uploadtag,$supplementalflag)=@_;
       }      my ($foldertitle,$pagetitle,$renametitle);
           } else {      if (&is_supplemental_title($title)) {
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
           }   $pagetitle = $foldertitle;
        }      } else {
     }   $title=&HTML::Entities::encode($title,'"<>&\'');
 }   $renametitle=$title;
    $foldertitle=$title;
    $pagetitle=$title;
       }
 =pod  
       my $orderidx=$LONCAPA::map::order[$index];
 =item list_symbs()  
       $renametitle=~s/\\/\\\\/g;
 List Symbs      $renametitle=~s/\&quot\;/\\\"/g;
       $renametitle=~s/ /%20/g;
 =cut      my $line=&Apache::loncommon::start_data_table_row();
       my ($form_start,$form_end,$form_common);
 sub list_symbs {  # Edit commands
     my ($r) = @_;      my ($container, $type, $esc_path, $path, $symb);
       if ($env{'form.folderpath'}) {
     my $type = &Apache::loncommon::course_type();   $type = 'folder';
     $r->print(&Apache::loncommon::start_page('Symb List'));          $container = 'sequence';
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));   $esc_path=&escape($env{'form.folderpath'});
     my $navmap = Apache::lonnavmaps::navmap->new();   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
     if (!defined($navmap)) {   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.      }
                   '<div class="LC_error">'.      if ($env{'form.pagepath'}) {
                   &mt('Unable to retrieve information about course contents').          $type = $container = 'page';
                   '</div>');          $esc_path=&escape($env{'form.pagepath'});
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
     } else {      }
         $r->print("<pre>\n");      if (!$supplementalflag && $residx) {
         foreach my $res ($navmap->retrieveResources()) {          my $currurl = $url;
     $r->print($res->compTitle()."\t".$res->symb()."\n");          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
         }          my $path = 'uploaded/'.
         $r->print("\n</pre>\n");                     $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
     }                     $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');          $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
 }                                               $residx,
                                                &Apache::lonnet::declutter($currurl));
       }
 sub verifycontent {      my %lt;
     my ($r) = @_;      if ($allowed) {
     my $type = &Apache::loncommon::course_type();   my $incindex=$index+1;
    my $loaderror=&Apache::lonnet::overloaderror($r);   my $selectbox='';
    if ($loaderror) { return $loaderror; }   if (($#LONCAPA::map::order>0) &&
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));      ((split(/\:/,
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
    $hashtied=0;       ne '') &&
    undef %alreadyseen;      ((split(/\:/,
    %alreadyseen=();       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
    &tiehash();       ne '')) {
    foreach my $key (keys(%hash)) {      $selectbox=
        if ($hash{$key}=~/\.(page|sequence)$/) {   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {   '<select name="newpos" onchange="this.form.submit()">';
        $r->print('<hr /><span class="LC_error">'.      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
  &mt('The following sequence or page is included more than once in your '.$type.': ').   if ($i==$incindex) {
  &unescape($hash{$key}).'</span><br />'.      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));   } else {
    }      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
        }   }
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {      }
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});      $selectbox.='</select>';
        }   }
    }   %lt=&Apache::lonlocal::texthash(
    &untiehash();                  'up' => 'Move Up',
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.   'dw' => 'Move Down',
      &mt('Return to DOCS').'</a>');   'rm' => 'Remove',
 }                  'ct' => 'Cut',
    'rn' => 'Rename',
    'cp' => 'Copy',
 sub devalidateversioncache {                  'ex' => 'External Resource',
     my $src=shift;                  'ed' => 'Edit',
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.                  'pr' => 'Preview',
   &Apache::lonnet::clutter($src));                  'sv' => 'Save',
 }                  'ul' => 'URL',
                   'ti' => 'Title', 
 sub checkversions {                  );
     my ($r) = @_;   my $nocopy=0;
     my $type = &Apache::loncommon::course_type();          my $nocut=0;
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));          my $noremove=0;
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));          if ($url=~ m{^/res/.+\.(page|sequence)$}) {
     my $header='';      # no copy for published maps
     my $startsel='';      $nocopy=1;
     my $monthsel='';   }
     my $weeksel='';          if ($url=~/^\/res\/lib\/templates\//) {
     my $daysel='';             $nocopy=1;
     my $allsel='';             $nocut=1;
     my %changes=();          }
     my $starttime=0;          my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
     my $haschanged=0;          my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
     my %setversions=&Apache::lonnet::dump('resourceversions',          if ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
   $env{'course.'.$env{'request.course.id'}.'.domain'},              if ($env{'form.folderpath'} =~ /^default&[^\&]+$/) {
   $env{'course.'.$env{'request.course.id'}.'.num'});                  my %curr_groups = &Apache::longroup::coursegroups();
                   if (keys(%curr_groups) > 0) {
     $hashtied=0;                      $noremove=1;
     &tiehash();                  }
     my %newsetversions=();                  $nocut=1;
     if ($env{'form.setmostrecent'}) {                  $nocopy=1;
  $haschanged=1;              }
  foreach my $key (keys(%hash)) {          } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
     if ($key=~/^ids\_(\/res\/.+)$/) {              my $group = $1;
  $newsetversions{$1}='mostrecent';              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
                 &devalidateversioncache($1);                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     }                  if (keys(%curr_group) > 0) {
  }                      $noremove=1;
     } elsif ($env{'form.setcurrent'}) {                  }
  $haschanged=1;              }
  foreach my $key (keys(%hash)) {              $nocut=1;
     if ($key=~/^ids\_(\/res\/.+)$/) {              $nocopy=1;
  my $getvers=&Apache::lonnet::getversion($1);          } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
  if ($getvers>0) {              my $group = $1;
     $newsetversions{$1}=$getvers;              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
     &devalidateversioncache($1);                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
  }                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
     }                  if (keys(%groupsettings) > 0) {
  }                      $noremove=1;
     } elsif ($env{'form.setversions'}) {                  }
  $haschanged=1;                  $nocut=1;
  foreach my $key (keys(%env)) {                  $nocopy=1;
     if ($key=~/^form\.set_version_(.+)$/) {              }
  my $src=$1;          } elsif ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {              my $group = $1;
     $newsetversions{$src}=$env{$key};              my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     &devalidateversioncache($src);              if ($url =~ /group_boards_\Q$group\E/) {
  }                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     }                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
  }                  if (keys(%groupsettings) > 0) {
     }                      if (ref($groupsettings{'functions'}) eq 'HASH') {
     if ($haschanged) {                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,                              $noremove=1;
   $env{'course.'.$env{'request.course.id'}.'.domain'},                          }
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {                      }
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');                  }
  } else {                  $nocut=1;
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');                  $nocopy=1;
  }              }
  &mark_hash_old();          }
     }          my $copylink='&nbsp;';
     &changewarning($r,'');          my $cutlink='&nbsp;';
     if ($env{'form.timerange'} eq 'all') {          my $removelink='&nbsp;';
 # show all documents  
  $header=&mt('All Documents in '.$type);   my $skip_confirm = 0;
  $allsel=1;   if ( $folder =~ /^supplemental/
  foreach my $key (keys(%hash)) {       || ($url =~ m{( /smppg$
     if ($key=~/^ids\_(\/res\/.+)$/) {      |/syllabus$
  my $src=$1;      |/aboutme$
  $changes{$src}=1;      |/navmaps$
     }      |/bulletinboard$
  }      |\.html$
     } else {      |^/adm/wrapper/ext)}x)) {
 # show documents which changed      $skip_confirm = 1;
  %changes=&Apache::lonnet::dump   }
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},  
                      $env{'course.'.$env{'request.course.id'}.'.num'});   if (!$nocopy) {
  my $firstkey=(keys(%changes))[0];      $copylink=(<<ENDCOPY);
  unless ($firstkey=~/^error\:/) {  <a href="javascript:markcopy('$esc_path','$index','$renametitle','$container','$symb','$folder');" class="LC_docs_copy">$lt{'cp'}</a>
     unless ($env{'form.timerange'}) {  ENDCOPY
  $env{'form.timerange'}=604800;          }
     }   if (!$nocut) {
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '      $cutlink=(<<ENDCUT);
  .&mt('seconds');  <a href="javascript:cutres('$esc_path','$index','$renametitle','$container','$symb','$folder',$skip_confirm);" class="LC_docs_cut">$lt{'ct'}</a>
     if ($env{'form.timerange'}==-1) {  ENDCUT
  $seltext='since start of course';          }
  $startsel='selected';          if (!$noremove) {
  $env{'form.timerange'}=time;              $removelink=(<<ENDREM);
     }  <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     $starttime=time-$env{'form.timerange'};  ENDREM
     if ($env{'form.timerange'}==2592000) {          }
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   $form_start = '
  $monthsel='selected';     <form action="/adm/coursedocs" method="post">
     } elsif ($env{'form.timerange'}==604800) {  ';
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';          $form_common=(<<END);
  $weeksel='selected';     <input type="hidden" name="${type}path" value="$path" />
     } elsif ($env{'form.timerange'}==86400) {     <input type="hidden" name="${type}symb" value="$symb" />
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';     <input type="hidden" name="setparms" value="$orderidx" />
  $daysel='selected';     <input type="hidden" name="changeparms" value="0" />
     }  END
     $header=&mt('Content changed').' '.$seltext;          $form_end = '</form>';
  } else {   $line.=(<<END);
     $header=&mt('No content modifications yet.');  <td>
  }  <div class="LC_docs_entry_move">
     }    <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
     %setversions=&Apache::lonnet::dump('resourceversions',      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
   $env{'course.'.$env{'request.course.id'}.'.domain'},    </a>
   $env{'course.'.$env{'request.course.id'}.'.num'});  </div>
     my %lt=&Apache::lonlocal::texthash  <div class="LC_docs_entry_move">
       ('st' => 'Version changes since start of '.$type,    <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
        'lm' => 'Version changes since last Month',      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
        'lw' => 'Version changes since last Week',    </a>
        'sy' => 'Version changes since Yesterday',  </div>
                'al' => 'All Resources (possibly large output)',  </td>
        'sd' => 'Display',  <td>
        'fi' => 'File',     $form_start
        'md' => 'Modification Date',     $form_common
                'mr' => 'Most recently published Version',     $selectbox
        've' => 'Version used in '.$type,     $form_end
                'vu' => 'Set Version to be used in '.$type,  </td>
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',  <td class="LC_docs_entry_commands">
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',  $removelink
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',  $cutlink
        'di' => 'Differences');     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
     $r->print(<<ENDHEADERS);  $copylink
 <form action="/adm/coursedocs" method="post">  </td>
 <input type="hidden" name="versions" value="1" />  END
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />  
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />      }
 <select name="timerange">  # Figure out what kind of a resource this is
 <option value='all' $allsel>$lt{'al'}</option>      my ($extension)=($url=~/\.(\w+)$/);
 <option value="-1" $startsel>$lt{'st'}</option>      my $uploaded=($url=~/^\/*uploaded\//);
 <option value="2592000" $monthsel>$lt{'lm'}</option>      my $icon=&Apache::loncommon::icon($url);
 <option value="604800" $weeksel>$lt{'lw'}</option>      my $isfolder=0;
 <option value="86400" $daysel>$lt{'sy'}</option>      my $ispage=0;
 </select>      my $folderarg;
 <input type="submit" name="display" value="$lt{'sd'}" />      my $pagearg;
 <h3>$header</h3>      my $pagefile;
 <input type="submit" name="setversions" value="$lt{'sv'}" />      if ($uploaded) {
 <table border="0">          if (($extension eq 'sequence') || ($extension eq 'page')) {
 ENDHEADERS              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
     foreach my $key (sort(keys(%changes))) {              my $containerarg = $1;
  if ($changes{$key}>$starttime) {      if ($extension eq 'sequence') {
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);          $icon=$iconpath.'navmap.folder.closed.gif';
     my $currentversion=&Apache::lonnet::getversion($key);                  $folderarg=$containerarg;
     if ($currentversion<0) {                  $isfolder=1;
  $currentversion=&mt('Could not be determined.');              } else {
     }                  $icon=$iconpath.'page.gif';
     my $linkurl=&Apache::lonnet::clutter($key);                  $pagearg=$containerarg;
     $r->print(                  $ispage=1;
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.              }
       &Apache::lonnet::gettitle($linkurl).              if ($allowed) {
                       '</b></font></td></tr>'.                  $url='/adm/coursedocs?';
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.              } else {
                       '<td colspan="4">'.                  $url='/adm/supplemental?';
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.              }
       '</a></td></tr>'.   } else {
                       '<tr><td></td>'.      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
                       '<td title="'.$lt{'md'}.'">'.   }
       &Apache::lonlocal::locallocaltime(      }
                            &Apache::lonnet::metadata($root.'.'.$extension,  
                                                      'lastrevisiondate')      my $editlink;
                                                         ).      my $orig_url = $url;
                       '</td>'.      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
                       '<font size="+1">'.$currentversion.'</font>'.      if (!$supplementalflag && $residx && $symb) {
                       '</span></td>'.          if ($container eq 'page') {
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.              $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                       '<font size="+1">');              $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
 # Used in course          } 
     my $usedversion=$hash{'version_'.$linkurl};          if ((!$isfolder) && (!$ispage)) {
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  $r->print($usedversion);      $url=&Apache::lonnet::clutter($url);
     } else {      if ($url=~/^\/*uploaded\//) {
  $r->print($currentversion);          $url=~/\.(\w+)$/;
     }          my $embstyle=&Apache::loncommon::fileembstyle($1);
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
                       '<span class="LC_nobreak">Use: ');      $url='/adm/wrapper'.$url;
 # Set version          } elsif ($embstyle eq 'ssi') {
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},      #do nothing with these
       'set_version_'.$linkurl,          } elsif ($url!~/\.(sequence|page)$/) {
       ('select_form_order' =>      $url='/adm/coursedocs/showdoc'.$url;
        ['',1..$currentversion,'mostrecent'],          }
        '' => '',      } elsif ($url=~m|^/ext/|) {
        'mostrecent' => 'most recent',          $url='/adm/wrapper'.$url;
        map {$_,$_} (1..$currentversion))));          $external = 1;
     $r->print('</span></td></tr><tr><td></td>');      }
     my $lastold=1;              if (&Apache::lonnet::symbverify($symb,$url)) {
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {          $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  my $url=$root.'.'.$prevvers.'.'.$extension;              } else {
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                  $url='';
     $starttime) {              }
     $lastold=$prevvers;   }
  }      }
     }      my ($rand_pick_text,$rand_order_text);
             #      if ($isfolder || $extension eq 'sequence') {
             # Code to figure out how many version entries should go in   my $foldername=&escape($foldertitle);
             # each of the four columns   my $folderpath=$env{'form.folderpath'};
             my $entries_per_col = 0;   if ($folderpath) { $folderpath.='&' };
             my $num_entries = ($currentversion-$lastold);  # Append randompick number, hidden, and encrypted with ":" to foldername,
             if ($num_entries % 4 == 0) {  # so it gets transferred between levels
                 $entries_per_col = $num_entries/4;   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
             } else {                                                'parameter_randompick'))[0]
                 $entries_per_col = $num_entries/4 + 1;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
             }                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
             my $entries_count = 0;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
             $r->print('<td valign="top"><font size="-2">');                                                'parameter_encrypturl'))[0]=~/^yes$/i)
             my $cols_output = 1;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {                                                'parameter_randomorder'))[0]=~/^yes$/i);
  my $url=$root.'.'.$prevvers.'.'.$extension;   $url.='folderpath='.&escape($folderpath);
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).          my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
   '">'.&mt('Version').' '.$prevvers.'</a> ('.                                                     'parameter_randompick'))[0];
   &Apache::lonlocal::locallocaltime(          my $rpckchk;
                                 &Apache::lonnet::metadata($url,          if ($rpicknum) {
                                                           'lastrevisiondate')              $rpckchk = ' checked="checked"';
                                                             ).          }
   ')');          my $formname = 'edit_rpick_'.$orderidx;
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {   $rand_pick_text = 
                     $r->print(' <a href="/adm/diff?filename='.  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
       &Apache::lonnet::clutter($root.'.'.$extension).  $form_common."\n".
       '&versionone='.$prevvers.  '<span class="LC_nobreak"><label><input type="checkbox" name="randpickon_'.$orderidx.'" id="rpick_'.$orderidx.'" onclick="'."updatePick(this.form,'$orderidx','check');".'"'.$rpckchk.' /> '.&mt('Randomly Pick').'</label><input type="hidden" name="randompick_'.$orderidx.'" id="rpicknum_'.$orderidx.'" value="'.$rpicknum.'" />';
       '">'.&mt('Diffs').'</a>');          if ($rpicknum ne '') {
  }              $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
  $r->print('</span><br />');          }
                 if (++$entries_count % $entries_per_col == 0) {          $rand_pick_text .= '</span></form>';
                     $r->print('</font></td>');      my $ro_set=
                     if ($cols_output != 4) {      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
                         $r->print('<td valign="top"><font size="-2">');   $rand_order_text = 
                         $cols_output++;  $form_start.
                     }  $form_common.'
                 }  <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></form>';
     }      }
             while($cols_output++ < 4) {      if ($ispage) {
                 $r->print('</font></td><td><font>')          my $pagename=&escape($pagetitle);
             }          my $pagepath;
     $r->print('</font></td></tr>'."\n");          my $folderpath=$env{'form.folderpath'};
  }          if ($folderpath) { $pagepath = $folderpath.'&' };
     }          $pagepath.=$pagearg.'&'.$pagename;
     $r->print('</table></form>');   $url.='pagepath='.&escape($pagepath).
     $r->print('<h1>'.&mt('Done').'.</h1>');      '&amp;pagesymb='.&escape($symb);
       }
     &untiehash();      if ($allowed) {
 }          my $fileloc = 
               &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
 sub mark_hash_old {  
     my $retie_hash=0;          if ($external) {
     if ($hashtied) {      $editlink = <<"EXTLNK";
  $retie_hash=1;              &nbsp;
  &untiehash();              <a class="LC_docs_ext_edit" href="javascript:editext('$residx');">
     }              $lt{'ed'}</a>
     &tiehash('write');              <form action="/adm/coursedocs" method="post" name="editext_$residx">
     $hash{'old'}=1;              <fieldset id="uploadext$residx" style="display: none;" />
     &untiehash();              <input type="hidden" name="active" value="aa" />
     if ($retie_hash) { &tiehash(); }              <span class="LC_nobreak">
 }              <span class="LC_docs_ext_edit">$lt{'ul'}&nbsp;</span>
               <input type="text" size="40" name="exturl" id="exturl_$residx" value="$orig_url" />&nbsp;
 sub is_hash_old {              <a class="LC_docs_ext_edit" href="javascript:extUrlPreview('exturl_$residx');">$lt{'pr'}</a></span>
     my $untie_hash=0;              </span><br />
     if (!$hashtied) {              <span class="LC_nobreak">
  $untie_hash=1;              <span class="LC_docs_ext_edit">$lt{'ti'}&nbsp;</span>
  &tiehash();              <input type="text" size="40" name="exttitle" value="$title" />
     }              $uploadtag
     my $return=$hash{'old'};              <input type="hidden" name="importdetail" value="" />
     if ($untie_hash) { &untiehash(); }              <input type="button" value="$lt{'sv'}" onclick="javascript:setExternal(this.form,'$residx')" />
     return $return;              </span>
 }              </fieldset>
               </form>
 sub changewarning {  EXTLNK
     my ($r,$postexec,$message,$url)=@_;          } else { 
     if (!&is_hash_old()) { return; }              my ($cfile,$home,$switchserver,$uploaded) = 
     my $pathvar='folderpath';                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom);
     my $path=&escape($env{'form.folderpath'});              if (($cfile ne '') && ($symb ne '')) {
     if (!defined($url)) {                  my $jscall = 
  if (defined($env{'form.pagepath'})) {                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
     $pathvar='pagepath';                                                              $switchserver,
     $path=&escape($env{'form.pagepath'});                                                              $uploaded,$symb);
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                  if ($jscall) {
  }                      $editlink = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:'.
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                                  $jscall.'" >'.&mt('Edit').'</a>';
     }                  }
     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.';      }
     }      my $reinit;
     $r->print("\n\n".      if ($crstype eq 'Community') {
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".          $reinit = &mt('(re-initialize community to access)');
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.      } else {
 '<input type="hidden" name="orgurl" value="'.$url.          $reinit = &mt('(re-initialize course to access)');
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.      }  
 &mt($message,' <input type="hidden" name="'.      $line.='<td>';
     $env{'request.role'}.'" value="1" /><input type="button" value="'.      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
 $help{'Caching'}.'</span></h3></form>'."\n\n");      } elsif ($url) {
 }         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
                                                '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
       } else {
 sub init_breadcrumbs {         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
     my ($form,$text)=@_;      }
     &Apache::lonhtmlcommon::clear_breadcrumbs();      $line.='</td><td>';
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
     text=>"Edit ".&Apache::loncommon::course_type(),         $line.='<a href="'.$url.'">'.$title.'</a>';
     faq=>273,      } elsif ($url) {
     bug=>'Instructor Interface',         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
                                             help => 'Docs_Adding_Course_Doc'});                                               $title,600,500);
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',      } else {
     text=>$text,         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
     faq=>273,      }
     bug=>'Instructor Interface'});      $line.=$editlink."</td>";
 }      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
       $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
       if (($allowed) && ($folder!~/^supplemental/)) {
     my %lt=&Apache::lonlocal::texthash(
          'hd' => 'Hidden',
 sub handler {         'ec' => 'URL hidden');
     my $r = shift;   my $enctext=
     &Apache::loncommon::content_type($r,'text/html');      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
     $r->send_http_header;   my $hidtext=
     return OK if $r->header_only;      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
     my $type = &Apache::loncommon::course_type();   $line.=(<<ENDPARMS);
     <td class="LC_docs_entry_parameter">
       $form_start
 # --------------------------------------------- Initialize help topics for this      $form_common
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',      <label><input type="checkbox" name="hiddenresource_$orderidx" onclick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
                'Adding_External_Resource','Navigate_Content',      $form_end
                'Adding_Folders','Docs_Overview', 'Load_Map',      <br />
                'Supplemental','Score_Upload_Form','Adding_Pages',      $form_start
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',      $form_common
                'Check_Resource_Versions','Verify_Content') {      <label><input type="checkbox" name="encrypturl_$orderidx" onclick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);      $form_end
     }    </td>
     # Composite help files    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(                                        $rand_order_text</td>
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');  ENDPARMS
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(      }
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');      $line.=&Apache::loncommon::end_data_table_row();
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(      return $line;
     'Option_Response_Simple');  }
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(  
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');  =pod
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(  
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');  =item tiehash()
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');  
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');  tie the hash
   
 # does this user have privileges to modify docs  =cut
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});  
   if ($allowed && $env{'form.verify'}) {  sub tiehash {
       &init_breadcrumbs('verify','Verify Content');      my ($mode)=@_;
       &verifycontent($r);      $hashtied=0;
   } elsif ($allowed && $env{'form.listsymbs'}) {      if ($env{'request.course.fn'}) {
       &init_breadcrumbs('listsymbs','List Symbs');   if ($mode eq 'write') {
       &list_symbs($r);      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
   } elsif ($allowed && $env{'form.docslog'}) {      &GDBM_WRCREAT(),0640)) {
       &init_breadcrumbs('docslog','Show Log');                  $hashtied=2;
       &docs_change_log($r);      }
   } elsif ($allowed && $env{'form.versions'}) {   } else {
       &init_breadcrumbs('versions','Check/Set Resource Versions');      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
       &checkversions($r);      &GDBM_READER(),0640)) {
   } elsif ($allowed && $env{'form.dumpcourse'}) {                  $hashtied=1;
       &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 {  sub untiehash {
 # is this a standard course?      if ($hashtied) { untie %hash; }
       $hashtied=0;
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);      return OK;
     my $forcestandard = 0;  }
     my $forcesupplement;  
     my $script='';  
     my $showdoc=0;  
     my $containertag;  
     my $uploadtag;  sub checkonthis {
       my ($r,$url,$level,$title)=@_;
       $url=&unescape($url);
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      $alreadyseen{$url}=1;
     ['folderpath','pagepath',      $r->rflush();
      'pagesymb']);      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 # No folderpath, no pagepath, see if we have something stored         $r->print("\n<br />");
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {         if ($level==0) {
         &Apache::loncommon::restore_course_settings('docs_folderpath',             $r->print("<br />");
                                               {'folderpath' => 'scalar'});         }
     }         for (my $i=0;$i<=$level*5;$i++) {
     if (!$env{'form.folderpath'}) {             $r->print('&nbsp;');
         &Apache::loncommon::restore_course_settings('docs_folderpath',         }
                                               {'pagepath' => 'scalar'});         $r->print('<a href="'.$url.'" target="cat">'.
     }   ($title?$title:$url).'</a> ');
     if ($env{'form.pagepath'}) {         if ($url=~/^\/res\//) {
        $env{'form.folderpath'}='';    my $result=&Apache::lonnet::repcopy(
     }                                &Apache::lonnet::filelocation('',$url));
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {            if ($result eq 'ok') {
         $env{'form.folderpath'} = 'supplemental&'.               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.               $r->rflush();
                                   $env{'form.folderpath'};               &Apache::lonnet::countacc($url);
     }               $url=~/\.(\w+)$/;
     &Apache::loncommon::store_course_settings('docs_folderpath',               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
                                                 {'pagepath' => 'scalar',   $r->print('<br />');
                                                  'folderpath' => 'scalar'});                   $r->rflush();
     if ($env{'form.folderpath'}) {                   for (my $i=0;$i<=$level*5;$i++) {
  my (@folderpath)=split('&',$env{'form.folderpath'});                       $r->print('&nbsp;');
  $env{'form.foldername'}=&unescape(pop(@folderpath));                   }
  $env{'form.folder'}=pop(@folderpath);                   $r->print('- '.&mt('Rendering:').' ');
     }   my ($errorcount,$warningcount)=split(/:/,
     if ($env{'form.pagepath'}) {         &Apache::lonnet::ssi_body($url,
         my (@pagepath)=split('&',$env{'form.pagepath'});         ('grade_target'=>'web',
         $env{'form.pagename'}=&unescape(pop(@pagepath));   'return_only_error_and_warning_counts' => 1)));
         $env{'form.folder'}=pop(@pagepath);                   if (($errorcount) ||
         $containertag = '<input type="hidden" name="pagepath" value="" />'.                       ($warningcount)) {
     '<input type="hidden" name="pagesymb" value="" />';       if ($errorcount) {
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';                            &mt('[quant,_1,error]',$errorcount).'</span>');
     }                       }
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {       if ($warningcount) {
        $showdoc='/'.$1;                          $r->print('<span class="LC_warning">'.
     }                            &mt('[quant,_1,warning]',$warningcount).'</span>');
     unless ($showdoc) { # got called from remote                       }
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||                   } else {
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
            $forcestandard = 1;                   }
        }                   $r->rflush();
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);               }
        my $dependencies=
        if ($allowed) {                  &Apache::lonnet::metadata($url,'dependencies');
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);               foreach my $dep (split(/\,/,$dependencies)) {
          $script=&Apache::lonratedt::editscript('simple');   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
        }                      &checkonthis($r,$dep,$level+1);
     } else { # got called in sequence from course                   }
        $allowed=0;               }
     }            } elsif ($result eq 'unavailable') {
                $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 # get course data            } elsif ($result eq 'not_found') {
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};        unless ($url=~/\$/) {
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
         } else {
 # get personal data    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
     my $uname=$env{'user.name'};        }
     my $udom=$env{'user.domain'};            } else {
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
             }
 # graphics settings         }
       }
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");  }
   
     if ($allowed) {  
  $script .= &editing_js($udom,$uname);  
     }  =pod
 # -------------------------------------------------------------------- Body tag  
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';  =item list_symbs()
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];  
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,  List Content Identifiers
     {'force_register' => $showdoc,  
                                      'bread_crumbs' => $brcrum}).  =cut
       &Apache::loncommon::help_open_menu('','',273,'RAT'));  
    sub list_symbs {
   my %allfiles = ();      my ($r) = @_;
   my %codebase = ();  
   my ($upload_result,$upload_output);      my $crstype = &Apache::loncommon::course_type();
   if ($allowed) {      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
       if (($env{'form.uploaddoc.filename'}) &&      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {      $r->print(&startContentScreen('tools'));
 # Process file upload - phase one - upload and parse primary file.        my $navmap = Apache::lonnavmaps::navmap->new();
   undef($hadchanges);      if (!defined($navmap)) {
           $upload_result = &process_file_upload(\$upload_output,$coursenum,          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
  $coursedom,\%allfiles,                    '<div class="LC_error">'.
  \%codebase,$1);                    &mt('Unable to retrieve information about course contents').
   if ($hadchanges) {                    '</div>');
       &mark_hash_old();          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
   }      } else {
           if ($upload_result eq 'phasetwo') {          $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
               $r->print($upload_output);                    &Apache::loncommon::start_data_table().
           }                    &Apache::loncommon::start_data_table_header_row().
       } elsif ($env{'form.phasetwo'}) {                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
           my %newname = ();                    &Apache::loncommon::end_data_table_header_row()."\n");
           my %origname = ();          my $count;
           my %attribs = ();          foreach my $res ($navmap->retrieveResources()) {
           my $updateflag = 0;              $r->print(&Apache::loncommon::start_data_table_row().
           my $residx = $env{'form.newidx'};                        '<td>'.$res->compTitle().'</td>'.
           my $primary_url = &unescape($env{'form.primaryurl'});                        '<td>'.$res->symb().'</td>'.
 # Process file upload - phase two - gather secondary files.                        &Apache::loncommon::start_data_table_row());
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {              $count ++;
               if ($env{'form.embedded_item_'.$i.'.filename'}) {          }
                   my $javacodebase;          if (!$count) {
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);              $r->print(&Apache::loncommon::start_data_table_row().
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});                        '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
                   if (exists($env{'form.embedded_codebase_'.$i})) {                        &Apache::loncommon::end_data_table_row()); 
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});            }
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;          $r->print(&Apache::loncommon::end_data_table());
                   }      }
                   my @attributes = ();  }
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {  
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});  
                   } else {  sub verifycontent {
                       @attributes = ($env{'form.embedded_attrib_'.$i});      my ($r) = @_;
                   }      my $crstype = &Apache::loncommon::course_type();
                   foreach my $attr (@attributes) {      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
                       push(@{$attribs{$i}},&unescape($attr));      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
                   }      $r->print(&startContentScreen('tools'));
                   if ($javacodebase) {      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
                       $codebase{$i} = $javacodebase;     $hashtied=0;
                       $codebase{$i} =~ s#/$##;     undef %alreadyseen;
                       $updateflag = 1;     %alreadyseen=();
                   }     &tiehash();
               }     
               unless ($newname{$i} eq $origname{$i}) {     foreach my $key (keys(%hash)) {
                   $updateflag = 1;         if ($hash{$key}=~/\.(page|sequence)$/) {
               }     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
           }         $r->print('<hr /><span class="LC_error">'.
 # Process file upload - phase three - modify primary file   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
           if ($updateflag) {   &unescape($hash{$key}).'</span><br />'.
               my ($content,$rtncode);   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
               my $updateflag = 0;     }
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);         }
               if ($getstatus eq 'ok') {         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
                   foreach my $item (keys(%newname)) {             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
                       if ($newname{$item} ne $origname{$item}) {         }
                           my $attrib_regexp = '';     }
                           if (@{$attribs{$item}} > 1) {     &untiehash();
                               $attrib_regexp = join('|',@{$attribs{$item}});     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
                           } else {  }
                               $attrib_regexp = $attribs{$item}[0];  
                           }  
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {  sub devalidateversioncache {
                           }      my $src=shift;
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
                       }    &Apache::lonnet::clutter($src));
                       if (exists($codebase{$item})) {  }
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs  
                       }  sub checkversions {
                   }      my ($r) = @_;
 # Save edited file.      my $crstype = &Apache::loncommon::course_type();
                   my $saveresult;      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};      $r->print(&startContentScreen('tools'));
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);  
               } else {      my $header='';
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);      my $startsel='';
               }      my $monthsel='';
           }      my $weeksel='';
       }      my $daysel='';
   }      my $allsel='';
       my %changes=();
   unless ($showdoc ||  $upload_result eq 'phasetwo') {      my $starttime=0;
 # -----------------------------------------------------------------------------      my $haschanged=0;
        my %lt=&Apache::lonlocal::texthash(      my %setversions=&Apache::lonnet::dump('resourceversions',
                 'uplm' => 'Upload a new main '.lc($type).' document',    $env{'course.'.$env{'request.course.id'}.'.domain'},
                 'upls' => 'Upload a new supplemental '.lc($type).' document',    $env{'course.'.$env{'request.course.id'}.'.num'});
                 'impp' => 'Import a document',  
                 'pubd' => 'Published Documents',      $hashtied=0;
  'copm' => 'All documents out of a published map into this folder',      &tiehash();
                 'upld' => 'Upload Document',      my %newsetversions=();
                 'srch' => 'Search',      if ($env{'form.setmostrecent'}) {
                 'impo' => 'Import',   $haschanged=1;
  'book' => 'Import Bookmarks',   foreach my $key (keys(%hash)) {
                 'selm' => 'Select Map',      if ($key=~/^ids\_(\/res\/.+)$/) {
                 'load' => 'Load Map',   $newsetversions{$1}='mostrecent';
                 'reco' => 'Recover Deleted Resources',                  &devalidateversioncache($1);
                 'newf' => 'New Folder',      }
                 'newp' => 'New Composite Page',   }
                 'extr' => 'External Resource',      } elsif ($env{'form.setcurrent'}) {
                 'syll' => 'Syllabus',   $haschanged=1;
                 'navc' => 'Navigate Contents',   foreach my $key (keys(%hash)) {
                 'sipa' => 'Simple Page',      if ($key=~/^ids\_(\/res\/.+)$/) {
                 'sipr' => 'Simple Problem',   my $getvers=&Apache::lonnet::getversion($1);
                 'drbx' => 'Drop Box',   if ($getvers>0) {
                 'scuf' => 'Score Upload Form',      $newsetversions{$1}=$getvers;
                 'bull' => 'Bulletin Board',      &devalidateversioncache($1);
                 'mypi' => 'My Personal Info',   }
                 'grpo' => 'Group Files',      }
                 'rost' => 'Course Roster',   }
  'abou' => 'About User',      } elsif ($env{'form.setversions'}) {
                 'imsf' => 'Import IMS package',   $haschanged=1;
                 'file' =>  'File',   foreach my $key (keys(%env)) {
                 'title' => 'Title',      if ($key=~/^form\.set_version_(.+)$/) {
                 'comment' => 'Comment',   my $src=$1;
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
  'nd' => 'New Document',      $newsetversions{$src}=$env{$key};
  'pm' => 'Published Map',      &devalidateversioncache($src);
  'sd' => 'Special Document',   }
  'mo' => 'More Options',      }
  'hao' => 'Hide all Options'   }
   );      }
 # -----------------------------------------------------------------------------      if ($haschanged) {
  my $fileupload=(<<FIUP);          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
  $lt{'file'}:<br />    $env{'course.'.$env{'request.course.id'}.'.domain'},
  <input type="file" name="uploaddoc" size="40" />    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 FIUP      $r->print(&Apache::loncommon::confirmwrapper(
                   &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
  my $checkbox=(<<CHBO);   } else {
  <!-- <label>$lt{'parse'}?      $r->print(&Apache::loncommon::confirmwrapper(
  <input type="checkbox" name="parserflag" />                  &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
  </label> -->   }
  <label>   &mark_hash_old();
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}      }
  </label>      &changewarning($r,'');
 CHBO      if ($env{'form.timerange'} eq 'all') {
   # show all documents
  my $fileuploadform=(<<FUFORM);   $header=&mt('All Documents in '.$crstype);
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">   $allsel=1;
  $fileupload   foreach my $key (keys(%hash)) {
  <br />      if ($key=~/^ids\_(\/res\/.+)$/) {
  $lt{'title'}:<br />   my $src=$1;
  <input type="text" size="50" name="comment" />   $changes{$src}=1;
  $uploadtag      }
  <input type="hidden" name="cmd" value="upload_default" />   }
  <br />      } else {
  <span class="LC_nobreak">  # show documents which changed
  $checkbox   %changes=&Apache::lonnet::dump
  </span>   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
  <br />                       $env{'course.'.$env{'request.course.id'}.'.num'});
  <br />   my $firstkey=(keys(%changes))[0];
  <span class="LC_nobreak">   unless ($firstkey=~/^error\:/) {
  <input type="submit" value="$lt{'upld'}" />      unless ($env{'form.timerange'}) {
  $help{'Uploading_From_Harddrive'}   $env{'form.timerange'}=604800;
  </span>      }
  </form>      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 FUFORM   .&mt('seconds');
       if ($env{'form.timerange'}==-1) {
  my $simpleeditdefaultform=(<<SEDFFORM);   $seltext='since start of course';
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">   $startsel='selected';
  $lt{'pubd'}<br />   $env{'form.timerange'}=time;
  $uploadtag      }
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />      $starttime=time-$env{'form.timerange'};
  <br />      if ($env{'form.timerange'}==2592000) {
  <span class="LC_nobreak">   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />   $monthsel='selected';
  $help{'Importing_LON-CAPA_Resource'}      } elsif ($env{'form.timerange'}==604800) {
  </span>   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  <br />   $weeksel='selected';
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />      } elsif ($env{'form.timerange'}==86400) {
  <hr />   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  <p>   $daysel='selected';
  $lt{'copm'}<br />      }
  <input type="text" size="40" name="importmap" /><br />      $header=&mt('Content changed').' '.$seltext;
  <span class="LC_nobreak"><input type="button"   } else {
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      $header=&mt('No content modifications yet.');
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />   }
  $help{'Load_Map'}</span>      }
  </p>      %setversions=&Apache::lonnet::dump('resourceversions',
  </form>    $env{'course.'.$env{'request.course.id'}.'.domain'},
 SEDFFORM    $env{'course.'.$env{'request.course.id'}.'.num'});
       my %lt=&Apache::lonlocal::texthash
  my $extresourcesform=(<<ERFORM);        ('st' => 'Version changes since start of '.$crstype,
  <form action="/adm/coursedocs" method="post" name="newext">         'lm' => 'Version changes since last Month',
  $uploadtag         'lw' => 'Version changes since last Week',
  <input type="hidden" name="importdetail" value="" />         'sy' => 'Version changes since Yesterday',
  <span class="LC_nobreak">                 'al' => 'All Resources (possibly large output)',
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"                 'cd' => 'Change display', 
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}         'sd' => 'Display',
  </span>         'fi' => 'File',
  </form>         'md' => 'Modification Date',
 ERFORM                 'mr' => 'Most recently published Version',
          've' => 'Version used in '.$crstype,
     if ($allowed) {                 'vu' => 'Set Version to be used in '.$crstype,
  &update_paste_buffer($coursenum,$coursedom);  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
        my $dumpbut=&dumpbutton();  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
        my $exportbut=&exportbutton();  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
        my %lt=&Apache::lonlocal::texthash(         'di' => 'Differences',
  'vc' => 'Verify Content',         'save' => 'Save changes',
  'cv' => 'Check/Set Resource Versions',                 'vers' => 'Version choice(s) for specific resources', 
  'ls' => 'List Symbs',         'act' => 'Actions');
                                          'sl' => 'Show Log'      $r->print(<<ENDHEADERS);
   );  <h4 class="LC_info">$header</h4>
   <form action="/adm/coursedocs" method="post">
        my $folderpath=$env{'form.folderpath'};  <input type="hidden" name="versions" value="1" />
        if (!$folderpath) {  <div class="LC_left_float">
    if ($env{'form.folder'} eq '' ||  <fieldset>
        $env{'form.folder'} eq 'supplemental') {  <legend>$lt{'cd'}</legend>
        $folderpath='default&'.  <select name="timerange">
    &escape(&mt('Main '.$type.' Documents'));  <option value='all' $allsel>$lt{'al'}</option>
    }  <option value="-1" $startsel>$lt{'st'}</option>
        }  <option value="2592000" $monthsel>$lt{'lm'}</option>
        unless ($env{'form.pagepath'}) {  <option value="604800" $weeksel>$lt{'lw'}</option>
            $containertag = '<input type="hidden" name="folderpath" value="" />';  <option value="86400" $daysel>$lt{'sy'}</option>
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';  </select>
        }  <input type="submit" name="display" value="$lt{'sd'}" />
        $r->print(&generate_admin_options($containertag,$uploadtag,\%lt,\%help,\%env));  </fieldset>
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',  </div>
      &mt('Editing the Table of Contents for your '.$type)));  <div class="LC_left_float">
     }  <fieldset>
 # --------------------------------------------------------- Standard documents  <legend>$lt{'act'}</legend>
     $r->print('<table class="LC_docs_documents">');  $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
   $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
     if (($standard) && ($allowed) && (!$forcesupplement)) {  </fieldset>
  $r->print('<tr><td class="LC_docs_document">');  </div>
 #  '<h2>'.&mt('Main Course Documents').  <br clear="all" />
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');  <hr />
        my $folder=$env{'form.folder'};  <h4>$lt{'vers'}</h4>
        if ($folder eq '' || $folder eq 'supplemental') {  <input type="submit" name="setversions" value="$lt{'save'}" />
            $folder='default';  <table border="0">
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));  ENDHEADERS
            $uploadtag = '<input type="hidden" name="folderpath" value="'.      #number of columns for version history
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';      my $num_ver_col = 1;
        }      $r->print(
        my $postexec='';      &Apache::loncommon::start_data_table().
        if ($folder eq 'default') {      &Apache::loncommon::start_data_table_header_row().
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');      '<th>'.&mt('Resources').'</th>'.
        } else {      "<th>$lt{'mr'}</th>".
            #$postexec='self.close();';      "<th>$lt{'ve'}</th>".
        }      "<th>$lt{'vu'}</th>".
        $hadchanges=0;      '<th colspan="'.$num_ver_col.'">'.&mt('History').'</th>'.
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,      '</b>');
    $upload_output,$type);      foreach my $key (sort(keys(%changes))) {
        if ($error) {          #excludes not versionable problems from resource version history:
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');          if ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/) {
        }      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
        if ($hadchanges) {      my $currentversion=&Apache::lonnet::getversion($key);
    &mark_hash_old();      if ($currentversion<0) {
        }                  $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
        &changewarning($r,$postexec);      }
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      my $linkurl=&Apache::lonnet::clutter($key);
                      '.sequence';          $r->print(
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.              &Apache::loncommon::end_data_table_header_row().
                      '.page';              &Apache::loncommon::start_data_table_row().
  my $container='sequence';              '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br>'.
  if ($env{'form.pagepath'}) {              '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
     $container='page';              '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br>('.
  }              &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;              '<td align="right">');
   # Used in course
       my $usedversion=$hash{'version_'.$linkurl};
       if (($usedversion) && ($usedversion ne 'mostrecent')) {
  my $recoverform=(<<RFORM);                  if($usedversion != $currentversion){
  <form action="/adm/groupsort" method="post" name="recover">                      $r->print('<span class="LC_warning">'.$usedversion.'</span>');
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />                  }else{
  </form>                      $r->print($usedversion);
 RFORM                  }
       } else {
  my $imspform=(<<IMSPFORM);   $r->print($currentversion);
  <form action="/adm/imsimportdocs" method="post" name="ims">      }
  <input type="hidden" name="folder" value="$folder" />      $r->print('</td><td title="'.$lt{'vu'}.'">');
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />  # Set version
  </form>      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
 IMSPFORM        'set_version_'.$linkurl,
         {'select_form_order' =>
  my $newnavform=(<<NNFORM);         ['',1..$currentversion,'mostrecent'],
  <form action="/adm/coursedocs" method="post" name="newnav">         '' => '',
  $uploadtag         'mostrecent' => &mt('most recent'),
  <input type="hidden" name="importdetail"         map {$_,$_} (1..$currentversion)}));
  value="$lt{'navc'}=/adm/navmaps" />      my $lastold=1;
  <span class="LC_nobreak">      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
  <input name="newnav" type="submit" value="$lt{'navc'}" />   my $url=$root.'.'.$prevvers.'.'.$extension;
  $help{'Navigate_Content'}   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
  </span>      $starttime) {
  </form>      $lastold=$prevvers;
 NNFORM   }
  my $newsmppageform=(<<NSPFORM);      }
  <form action="/adm/coursedocs" method="post" name="newsmppg">              #
  $uploadtag              # Code to figure out how many version entries should go in
  <input type="hidden" name="importdetail" value="" />              # each of the four columns
  <span class="LC_nobreak">              my $entries_per_col = 0;
  <input name="newsmppg" type="button" value="$lt{'sipa'}"              my $num_entries = ($currentversion-$lastold);
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}              if ($num_entries % $num_ver_col == 0) {
  </span>                  $entries_per_col = $num_entries/$num_ver_col;
  </form>              } else {
 NSPFORM                  $entries_per_col = $num_entries/$num_ver_col + 1;
               }
  my $newsmpproblemform=(<<NSPROBFORM);              my $entries_count = 0;
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">              $r->print('<td valign="top"><span class="LC_fontsize_medium">');
  $uploadtag              my $cols_output = 1;
  <input type="hidden" name="importdetail" value="" />              for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
  <span class="LC_nobreak">   my $url=$root.'.'.$prevvers.'.'.$extension;
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}    '">'.&mt('Version').' '.$prevvers.'</a> ('.
  </span>    &Apache::lonlocal::locallocaltime(
  </form>                                  &Apache::lonnet::metadata($url,
                                                             'lastrevisiondate')
 NSPROBFORM                                                              ).
     ')');
  my $newdropboxform=(<<NDBFORM);   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
  <form action="/adm/coursedocs" method="post" name="newdropbox">                      $r->print(' <a href="/adm/diff?filename='.
  $uploadtag              &Apache::lonnet::clutter($root.'.'.$extension).
  <input type="hidden" name="importdetail" value="" />        '&versionone='.$prevvers.
  <span class="LC_nobreak">                  '" target="diffs">'.&mt('Diffs').'</a>');
  <input name="newdropbox" type="button" value="$lt{'drbx'}"   }
  onClick="javascript:makedropbox();" />   $r->print('</span><br />');
  </span>                          if (++$entries_count % $entries_per_col == 0) {
  </form>                      $r->print('</span></td>');
 NDBFORM                      if ($cols_output != $num_ver_col) {
                           $r->print('<td valign="top"><span class="LC_fontsize_medium">');
  my $newexuploadform=(<<NEXUFORM);                          $cols_output++;
  <form action="/adm/coursedocs" method="post" name="newexamupload">                      }
  $uploadtag                  }
  <input type="hidden" name="importdetail" value="" />      }
  <span class="LC_nobreak">              while($cols_output++ < $num_ver_col) {
  <input name="newexamupload" type="button" value="$lt{'scuf'}"                  $r->print('</span></td><td>');
  onClick="javascript:makeexamupload();" />              }
  $help{'Score_Upload_Form'}   }
  </span>      }
  </form>      $r->print('</td>'.&Apache::loncommon::end_data_table_row().
 NEXUFORM              &Apache::loncommon::end_data_table().
               '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />');
  my $newbulform=(<<NBFORM);  
  <form action="/adm/coursedocs" method="post" name="newbul">      &untiehash();
  $uploadtag  }
  <input type="hidden" name="importdetail" value="" />  
  <span class="LC_nobreak">  sub mark_hash_old {
  <input name="newbulletin" type="button" value="$lt{'bull'}"      my $retie_hash=0;
  onClick="javascript:makebulboard();" />      if ($hashtied) {
  $help{'Bulletin Board'}   $retie_hash=1;
  </span>   &untiehash();
  </form>      }
 NBFORM      &tiehash('write');
       $hash{'old'}=1;
  my $newaboutmeform=(<<NAMFORM);      &untiehash();
  <form action="/adm/coursedocs" method="post" name="newaboutme">      if ($retie_hash) { &tiehash(); }
  $uploadtag  }
  <input type="hidden" name="importdetail"  
  value="$plainname=/adm/$udom/$uname/aboutme" />  sub is_hash_old {
  <span class="LC_nobreak">      my $untie_hash=0;
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      if (!$hashtied) {
  $help{'My Personal Info'}   $untie_hash=1;
  </span>   &tiehash();
  </form>      }
 NAMFORM      my $return=$hash{'old'};
       if ($untie_hash) { &untiehash(); }
  my $newaboutsomeoneform=(<<NASOFORM);      return $return;
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">  }
  $uploadtag  
  <input type="hidden" name="importdetail" value="" />  sub changewarning {
  <span class="LC_nobreak">      my ($r,$postexec,$message,$url)=@_;
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"      if (!&is_hash_old()) { return; }
  onClick="javascript:makeabout();" />      my $pathvar='folderpath';
  </span>      my $path=&escape($env{'form.folderpath'});
  </form>      if (!defined($url)) {
 NASOFORM   if (defined($env{'form.pagepath'})) {
       $pathvar='pagepath';
       $path=&escape($env{'form.pagepath'});
  my $newrosterform=(<<NROSTFORM);      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
  <form action="/adm/coursedocs" method="post" name="newroster">   }
  $uploadtag   $url='/adm/coursedocs?'.$pathvar.'='.$path;
  <input type="hidden" name="importdetail"      }
  value="$lt{'rost'}=/adm/viewclasslist" />      my $course_type = &Apache::loncommon::course_type();
  <span class="LC_nobreak">      if (!defined($message)) {
  <input name="newroster" type="submit" value="$lt{'rost'}" />   $message='Changes will become active for your current session after [_1], or the next time you log in.';
  $help{'Course Roster'}      }
  </span>      $r->print("\n\n".
  </form>  '<script type="text/javascript">'."\n".
 NROSTFORM  '// <![CDATA['."\n".
   'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
        $r->print(<<ENDFORM);  '// ]]>'."\n".
   '</script>'."\n".
 <ul class="LC_TabContent">  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 <li>$lt{'nd'}</li>  '<input type="hidden" name="orgurl" value="'.$url.
 <li>$lt{'pm'}</li>  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
 <li>$lt{'pubd'}</li>  &mt($message,' <input type="hidden" name="'.
 <li>$lt{'sd'}</li>      $env{'request.role'}.'" value="1" /><input type="button" value="'.
 <li>$lt{'mo'}</li>      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
 <li>$lt{'hao'}</li>  $help{'Caching'}.'</p></form>'."\n\n");
 </ul>  }
   
 <table class="LC_docs_adddocs">  
 <!-- <tr>  sub init_breadcrumbs {
 <th>$lt{'uplm'}</th>      my ($form,$text)=@_;
 <th>$lt{'impp'}</th>      &Apache::lonhtmlcommon::clear_breadcrumbs();
 <th>$lt{'spec'}</th>      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
 </tr> -->      text=>&Apache::loncommon::course_type().' Editor',
 <tr>      faq=>273,
 <td>      bug=>'Instructor Interface',
 $fileuploadform                                              help => 'Docs_Adding_Course_Doc'});
 </td>      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
 <td>      text=>$text,
 $simpleeditdefaultform      faq=>273,
 <hr />      bug=>'Instructor Interface'});
 $recoverform  }
 ENDFORM  
        unless ($env{'form.pagepath'}) {  # subroutine to list form elements
    $r->print(<<ENDFORM);  sub create_list_elements {
 <hr />     my @formarr = @_;
 $extresourcesform     my $list = '';
  <br />     foreach my $button (@formarr){
 $imspform          foreach my $picture (keys(%{$button})) {
 ENDFORM              $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
        }          }
        $r->print('</td><td>');     }
        unless ($env{'form.pagepath'}) {     return $list;
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');  }
   
   # subroutine to create ul from list elements
   sub create_form_ul {
  my $newpageform=(<<NPFORM);     my $list = shift;
  <form action="/adm/coursedocs" method="post" name="newpage">     my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
  <input type="hidden" name="folderpath" value="$path" />     return $ul;
  <input type="hidden" name="importdetail" value="" />  }
  <span class="LC_nobreak">  
  <input name="newpage" type="button"  #
  onClick="javascript:makenewpage(this.form,'$pageseq');"  # Start tabs
  value="$lt{'newp'}" />$help{'Adding_Pages'}  #
  </span>  
  </form>  sub startContentScreen {
 NPFORM      my ($mode) = @_;
       my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
  my $newfolderform=(<<NFFORM);      if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
  <form action="/adm/coursedocs" method="post" name="newfolder">          $output .= '<li'.(($mode eq 'navmaps')?' class="active"':'').'><a href="/adm/navmaps"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Overview').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
  <input type="hidden" name="folderpath" value="$path" />          $output .= '<li'.(($mode eq 'coursesearch')?' class="active"':'').'><a href="/adm/searchcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Search').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
  <input type="hidden" name="importdetail" value="" />          $output .= '<li'.(($mode eq 'courseindex')?' class="active"':'').'><a href="/adm/indexcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Index').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
  <span class="LC_nobreak">          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
  <input name="newfolder" type="button"      } else {
  onClick="javascript:makenewfolder(this.form,'$folderseq');"          $output .= '<li '.(($mode eq 'docs')?' class="active"':'').' id="tabbededitor"><a href="/adm/coursedocs?forcestandard=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Editor').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
  value="$lt{'newf'}" />$help{'Adding_Folders'}          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
  </span>          $output .= '<li '.(($mode eq 'tools')?' class="active"':'').'><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
  </form>                     '><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>';
 NFFORM      }
       $output .= "\n".'</ul>'."\n";
  my $newsylform=(<<NSYLFORM);      $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
  <form action="/adm/coursedocs" method="post" name="newsyl">                 '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
  $uploadtag                 '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
  <input type="hidden" name="importdetail"      return $output;
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />  }
  <span class="LC_nobreak">  
  <input name="newsyl" type="submit" value="$lt{'syll'}" />  #
  $help{'Syllabus'}  # End tabs
  </span>  #
  </form>  
 NSYLFORM  sub endContentScreen {
       return '</div></div></div>';
  my $newgroupfileform=(<<NGFFORM);  }
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">  
  $uploadtag  sub supplemental_base {
  <input type="hidden" name="importdetail"      return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />  }
  <span class="LC_nobreak">  
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />  sub handler {
  $help{'Group Files'}      my $r = shift;
  </span>      &Apache::loncommon::content_type($r,'text/html');
  </form>      $r->send_http_header;
 NGFFORM      return OK if $r->header_only;
   
   # get course data
            $r->print(<<ENDFORM);      my $crstype = &Apache::loncommon::course_type();
 <br />      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 $newfolderform      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 <br />  
 $newpageform  # graphics settings
 <br />      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
 $newsylform  
 <br />  #
 $newnavform  # --------------------------------------------- Initialize help topics for this
 <br />      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
 $newsmppageform                 'Adding_External_Resource','Navigate_Content',
 <br />                 'Adding_Folders','Docs_Overview', 'Load_Map',
 $newsmpproblemform                 'Supplemental','Score_Upload_Form','Adding_Pages',
 <br />                 'Importing_LON-CAPA_Resource','Importing_IMS_Course',
 $newdropboxform                         'Uploading_From_Harddrive',
 <br />                 'Check_Resource_Versions','Verify_Content') {
 $newexuploadform   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 <br />      }
 $newbulform      # Composite help files
 <br />      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 $newaboutmeform      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 <br />      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 $newaboutsomeoneform      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 <br />      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 $newgroupfileform      'Option_Response_Simple');
 <br />      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 $newrosterform      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 ENDFORM      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
        }    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
        if ($env{'form.pagepath'}) {      $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
            $r->print(<<ENDBLOCK);      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 $newsmpproblemform  
 <br />      
 $newexuploadform      my $allowed;
 ENDBLOCK  # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
        }      unless ($r->uri eq '/adm/supplemental') {
        $r->print('</td></tr>'."\n".          # does this user have privileges to modify content.  
 '</table>');          $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
        $r->print('</td></tr>');      }
     }  
 # ----------------------------------------------------- Supplemental documents      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
     if (!$forcestandard) {                                              'inhibitmenu']);
        $r->print('<tr><td class="LC_docs_document">');    if ($allowed && $env{'form.chooseserver'}) {
 # '<h2>'.&mt('Supplemental Course Documents').        &choose_dump_server($r);
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');        return OK;
        my $folder=$env{'form.folder'};    } elsif ($allowed && $env{'form.verify'}) {
        unless ($folder=~/^supplemental/) {        &init_breadcrumbs('verify','Verify Content');
    $folder='supplemental';        &verifycontent($r);
        }    } elsif ($allowed && $env{'form.listsymbs'}) {
        if ($folder =~ /^supplemental$/ &&        &init_breadcrumbs('listsymbs','List Content IDs');
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {        &list_symbs($r);
           $env{'form.folderpath'} = 'supplemental&'.    } elsif ($allowed && $env{'form.docslog'}) {
                                     &escape(&mt('Supplemental '.$type.' Documents'));        &init_breadcrumbs('docslog','Show Log');
        }        my $folder = $env{'form.folder'};
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);        if ($folder eq '') {
        if ($error) {            $folder='default';
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');        }
        }        &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
        if ($allowed) {    } elsif ($allowed && $env{'form.versions'}) {
    my $folderseq=        &init_breadcrumbs('versions','Check/Set Resource Versions');
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.        &checkversions($r);
        '.sequence';    } elsif ($allowed && $env{'form.dumpcourse'}) {
         &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');        &dumpcourse($r);
     } elsif ($allowed && $env{'form.exportcourse'}) {
  my $supupdocform=(<<SUPDOCFORM);        &init_breadcrumbs('exportcourse','IMS Export');
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">        &Apache::imsexport::exportcourse($r);
  $fileupload    } else {
  <br />  #
  <br />  # Done catching special calls
  <span class="LC_nobreak">  # The whole rest is for course and supplemental documents and utilities menu
  $checkbox  # Get the parameters that may be needed
  </span>  #
  <br /><br />      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  $lt{'comment'}:<br />                                              ['folderpath','pagepath',
  <textarea cols=50 rows=4 name='comment'>                                               'pagesymb','forcesupplement','forcestandard',
  </textarea>                                               'tools','symb','command']);
  <br />  
  <input type="hidden" name="folderpath" value="$path" />  # standard=1: this is a "new-style" course with an uploaded map as top level
  <input type="hidden" name="cmd" value="upload_supplemental" />  # standard=2: this is a "old-style" course, and there is nothing we can do
  <span class="LC_nobreak">  
  <input type="submit" value="$lt{'upld'}" />      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
  $help{'Uploading_From_Harddrive'}  
  </span>  # Decide whether this should display supplemental or main content or utilities
  </form>  # supplementalflag=1: show supplemental documents
 SUPDOCFORM  # supplementalflag=0: show standard documents
   # toolsflag=1: show utilities
  my $supnewfolderform=(<<SNFFORM);  
  <form action="/adm/coursedocs" method="post" name="supnewfolder">  
  <input type="hidden" name="folderpath" value="$path" />      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
  <input type="hidden" name="importdetail" value="" />      if (($env{'form.folderpath'}=~/^default/) || $env{'form.folderpath'} eq "" || ($env{'form.pagepath'})) {
  <span class="LC_nobreak">         $supplementalflag=0;
  <input name="newfolder" type="button"      }
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
  value="$lt{'newf'}" /> $help{'Adding_Folders'}      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
  </span>      unless ($allowed) { $supplementalflag=1; }
  </form>      unless ($standard) { $supplementalflag=1; }
 SNFFORM      my $toolsflag=0;
       if ($env{'form.tools'}) { $toolsflag=1; }
   
  my $supnewextform=(<<SNEFORM);      my $script='';
  <form action="/adm/coursedocs" method="post" name="supnewext">      my $showdoc=0;
  <input type="hidden" name="folderpath" value="$path" />      my $addentries = {};
  <input type="hidden" name="importdetail" value="" />      my $container;
  <span class="LC_nobreak">      my $containertag;
  <input name="newext" type="button"      my $uploadtag;
  onClick="javascript:makenewext('supnewext');"  
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}  # Do we directly jump somewhere?
  </span>  
  </form>     if ($env{'form.command'} eq 'direct') {
 SNEFORM         my ($mapurl,$id,$resurl);
          if ($env{'form.symb'} ne '') {
  my $supnewsylform=(<<SNSFORM);             ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
  <form action="/adm/coursedocs" method="post" name="supnewsyl">             if ($resurl=~/\.(sequence|page)$/) {
  <input type="hidden" name="folderpath" value="$path" />                 $mapurl=$resurl;
  <input type="hidden" name="importdetail"             } elsif ($resurl eq 'adm/navmaps') {
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />                 $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
  <span class="LC_nobreak">             }
  <input name="newsyl" type="submit" value="$lt{'syll'}" />             my $mapresobj;
  $help{'Syllabus'}             my $navmap = Apache::lonnavmaps::navmap->new();
  </span>             if (ref($navmap)) {
  </form>                 $mapresobj = $navmap->getResourceByUrl($mapurl);
 SNSFORM             }
              $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
  my $supnewaboutmeform=(<<SNAMFORM);             my $type=$2;
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">             my $path;
  <input type="hidden" name="folderpath" value="$path" />             if (ref($mapresobj)) {
  <input type="hidden" name="importdetail"                 my $pcslist = $mapresobj->map_hierarchy();
  value="$plainname=/adm/$udom/$uname/aboutme" />                 if ($pcslist ne '') {
  <span class="LC_nobreak">                     foreach my $pc (split(/,/,$pcslist)) {
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />                         next if ($pc <= 1);
  $help{'My Personal Info'}                         my $res = $navmap->getByMapPc($pc);
  </span>                         if (ref($res)) {
  </form>                             my $thisurl = $res->src();
 SNAMFORM                             $thisurl=~s{^.*/([^/]+)\.\w+$}{$1}; 
                              my $thistitle = $res->title();
    $r->print(<<ENDSUPFORM);                             $path .= '&'.
 <ul class="LC_TabContent">                                      &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
 <li>$lt{'nd'}</li>                                      &Apache::lonhtmlcommon::entity_encode($thistitle).
 <li>$lt{'sd'}</li>                                      ':'.$res->randompick().
 <li>$lt{'hao'}</li>                                      ':'.$res->randomout().
 </ul>                                      ':'.$res->encrypted().
 <table class="LC_docs_adddocs">                                      ':'.$res->randomorder();
 <tr><td>                         }
 $supupdocform                     }
 </td>                 }
 <td>                 $path .= '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
 $supnewfolderform                      &Apache::lonhtmlcommon::entity_encode($mapresobj->title()).
 <br />                      ':'.$mapresobj->randompick().
 $supnewextform                      ':'.$mapresobj->randomout().
 <br />                      ':'.$mapresobj->encrypted().
 $supnewsylform                      ':'.$mapresobj->randomorder();
 <br />             } else {
 $supnewaboutmeform                 my $maptitle = &Apache::lonnet::gettitle($mapurl);
 </td></tr>                 $path = '&default&...::::'.
 </table></td></tr>                     '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
 ENDSUPFORM                     &Apache::lonhtmlcommon::entity_encode($maptitle).'::::';
        }             }
     }             $path = 'default&'.
     $r->print('</table>');                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
     if ($allowed) {                     $path;
  $r->print('             if ($type eq 'sequence') {
 <form method="post" name="extimport" action="/adm/coursedocs">                 $env{'form.folderpath'}=$path;
   <input type="hidden" name="title" />                 $env{'form.pagepath'}='';
   <input type="hidden" name="url" />             } else {
   <input type="hidden" name="useform" />                 $env{'form.pagepath'}=$path;
   <input type="hidden" name="residx" />                 $env{'form.folderpath'}='';
 </form>');             }
     }         } elsif ($env{'form.supppath'} ne '') {
   } else {             $env{'form.folderpath'}=$env{'form.supppath'};
       unless ($upload_result eq 'phasetwo') {         }
 # -------------------------------------------------------- This is showdoc mode     } elsif ($env{'form.command'} eq 'editdocs') {
           $r->print("<h1>".&mt('Uploaded Document').' - '.          $env{'form.folderpath'} = 'default&'.
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.                                    &Apache::lonhtmlcommon::entity_encode('Main Course Content');
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".          $env{'form.pagepath'}='';
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');     } elsif ($env{'form.command'} eq 'editsupp') {
       }          $env{'form.folderpath'} = 'default&'.
   }                                    &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
  }          $env{'form.pagepath'}='';
  $r->print(&Apache::loncommon::end_page());     }
  return OK;  
 }  # Where do we store these for when we come back?
       my $stored_folderpath='docs_folderpath';
 sub generate_admin_options {      if ($supplementalflag) {
   my ($containertag,$uploadtag,$lt_ref,$help_ref,$env_ref) = @_;         $stored_folderpath='docs_sup_folderpath';
   my %lt = %{$lt_ref};      }
   my %help = %{$help_ref};  
   my %env = %{$env_ref};  # No folderpath, no pagepath, see if we have something stored
   my $dumpbut=&dumpbutton();      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
   my $exportbut=&exportbutton();          &Apache::loncommon::restore_course_settings($stored_folderpath,
   return (<<ENDOPTIONFORM);                                                {'folderpath' => 'scalar'});
  <form name="renameform" method="post" action="/adm/coursedocs">      }
    <input type="hidden" name="title" />     
    <input type="hidden" name="cmd" />  # If we are not allowed to make changes, all we can see are supplemental docs
    <input type="hidden" name="markcopy" />      if (!$allowed) {
    <input type="hidden" name="copyfolder" />          $env{'form.pagepath'}='';
    $containertag          unless ($env{'form.folderpath'} =~ /^supplemental/) {
  </form>              $env{'form.folderpath'} = &supplemental_base();
  <form name="simpleedit" method="post" action="/adm/coursedocs">          }
    <input type="hidden" name="importdetail" value="" />      }
    $uploadtag  # If we still not have a folderpath, see if we can resurrect at pagepath
  </form>      if (!$env{'form.folderpath'} && $allowed) {
  <form action="/adm/coursedocs" method="post" name="courseverify">          &Apache::loncommon::restore_course_settings($stored_folderpath,
    <ul style="list-style-type:none">                                                {'pagepath' => 'scalar'});
        <li>      }
            <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}  # Make the zeroth entry in supplemental docs page paths, so we can get to top level
        </li>      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
        <li>          $env{'form.folderpath'} = &supplemental_base()
            <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}                                    .'&'.
        </li>                                    $env{'form.folderpath'};
        <li>      }
            $dumpbut  # If after all of this, we still don't have any paths, make them
        </li>      unless (($env{'form.pagepath'}) || ($env{'form.folderpath'})) {
        <li>         if ($supplementalflag) {
            $exportbut            $env{'form.folderpath'}=&supplemental_base();
        </li>         } else {
        <li>            $env{'form.folderpath'}='default';
           <input type="submit" name="listsymbs" value="$lt{'ls'}" />         }
         </li>      }
         <li>  
           <input type="hidden" name="folder" value="$env{'form.folder'}" />  # Store this
           <input type="submit" name="docslog" value="$lt{'sl'}" />      unless ($toolsflag) {
         </li>          &Apache::loncommon::store_course_settings($stored_folderpath,
    </ul>                                                    {'pagepath' => 'scalar',
  </form>                                                     'folderpath' => 'scalar'});
  <div style="clear: both; height: 0px;">&nbsp;</div>          if ($env{'form.folderpath'}) {
 ENDOPTIONFORM      my (@folderpath)=split('&',$env{'form.folderpath'});
 }      $env{'form.foldername'}=&unescape(pop(@folderpath));
       $env{'form.folder'}=pop(@folderpath);
 sub generate_edit_table {              $container='sequence';
     my ($optionhash_ref,$namehash_ref,$orderhash_ref) = @_;          }
     my %optionhash = %{$optionhash_ref};         #id verlinkt mit inhalt          if ($env{'form.pagepath'}) {
     my %namehash = %{$namehash_ref};             #name verlinkt mit id              my (@pagepath)=split('&',$env{'form.pagepath'});
     my %orderhash = %{$orderhash_ref};           #name mit kürzel verlinkt mit name              $env{'form.pagename'}=&unescape(pop(@pagepath));
     my $form;              $env{'form.folder'}=pop(@pagepath);
     $form = '<div class="LC_ContentBoxSpecial"><h4 class="LC_hcell">'.&mt('Upload Course Documents').'<h4>';              $container='page';
     $form .= '<ul class="LC_TabContent">';              $containertag = '<input type="hidden" name="pagepath" value="" />'.
     foreach my $name (sort(keys(%orderhash))){                      '<input type="hidden" name="pagesymb" value="" />';
         if($name eq 'zz_hide'){              $uploadtag = 
             $form .= '<li><a onclick="hideAllSection();" href="#">'.&mt($orderhash{$name}).'</a></li>';                  '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
         }else{          '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />'.
             $form .= '<li><a onclick="popUpSection(\''.$namehash{$orderhash{$name}}.'\');" href="#">'.&mt($orderhash{$name}).'</a></li>';                  '<input type="hidden" name="folderpath" value="" />';
         }          } else {
     }              my $folderpath=$env{'form.folderpath'};
     foreach my $field (keys(%optionhash)){              if (!$folderpath) {
         $form .= '<div id="'.$field.'" class="LC_ContentBox LC_hideThis">'.$optionhash{$field}.'</div>';                  if ($env{'form.folder'} eq '' ||
     }                      $env{'form.folder'} eq 'supplemental') {
     $form .= '</div>';                      $folderpath='default&'.
     return $form;                          &escape(&mt('Main '.$crstype.' Documents'));
 }                  }
               }
 sub editing_js {              $containertag = '<input type="hidden" name="folderpath" value="" />';
     my ($udom,$uname) = @_;              $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
     my $now = time();          }
     my %lt = &Apache::lonlocal::texthash(          if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
                                           p_mnf => 'Name of New Folder',             $showdoc='/'.$1;
                                           t_mnf => 'New Folder',          }
                                           p_mnp => 'Name of New Page',          if ($showdoc) { # got called in sequence from course
                                           t_mnp => 'New Page',      $allowed=0; 
                                           p_mxu => 'Title for the Uploaded Score',          } else {
                                           p_msp => 'Title for the Page',              if ($allowed) {
                                           p_msb => 'Title for the Problem',                  &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                                           p_mdb => 'Title for the Drop Box',                  $script=&Apache::lonratedt::editscript('simple');
                                           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',  # get personal data
                                           p_chn => 'New Title',      my $uname=$env{'user.name'};
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',      my $udom=$env{'user.domain'};
                                           p_rmr2a => 'Remove[_99]',      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
                                           p_rmr2b => '?[_99]',  
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',      if ($allowed) {
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',          if ($toolsflag) {
                                           p_ctr2a => 'Cut[_98]',              $script .= &inject_data_js();
                                           p_ctr2b => '?[_98]'              my ($home,$other,%outhash)=&authorhosts();
                                         );              if (!$home && $other) {
                   my @hosts;
     return <<ENDNEWSCRIPT;                  foreach my $aurole (keys(%outhash)) {
 function makenewfolder(targetform,folderseq) {                      unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');                          push(@hosts,$outhash{$aurole});
     if (foldername) {                      }
        targetform.importdetail.value=escape(foldername)+"="+folderseq;                  }
         targetform.submit();                  $script .= &dump_switchserver_js(@hosts); 
     }              }
 }          } else {
               my @tabids;
 function makenewpage(targetform,folderseq) {              if ($supplementalflag) {
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');                  @tabids = ('002','ee2','ff2');
     if (pagename) {              } else {
         targetform.importdetail.value=escape(pagename)+"="+folderseq;                  @tabids = ('aa1','bb1','cc1','ff1');
         targetform.submit();                  unless ($env{'form.pagepath'}) {
     }                      unshift(@tabids,'001');
 }                      push(@tabids,('dd1','ee1'));
                   }
 function makenewext(targetname) {              }
     this.document.forms.extimport.useform.value=targetname;              my $tabidstr = join("','",@tabids);
     this.document.forms.extimport.title.value='';      $script .= &editing_js($udom,$uname,$supplementalflag).
     this.document.forms.extimport.url.value='';                         &history_tab_js().
     this.document.forms.extimport.residx.value='';                         &inject_data_js().
     window.open('/adm/rat/extpickframe.html');                         &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr);
 }              $addentries = {
                               onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
 function edittext(targetname,residx,title,url) {                            };
     this.document.forms.extimport.useform.value=targetname;          }
     this.document.forms.extimport.residx.value=residx;          if ($env{'docs.markedcopy_url'}) {
     this.document.forms.extimport.url.value=url;              $script .= &paste_popup_js(); 
     this.document.forms.extimport.title.value=title;          }
     window.open('/adm/rat/extpickframe.html');          my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
 }                               &mt('Switch server?');
           
 function makeexamupload() {  
    var title=prompt('$lt{"p_mxu"}');      }
    if (title) {  # -------------------------------------------------------------------- Body tag
     this.document.forms.newexamupload.importdetail.value=      $script = '<script type="text/javascript">'."\n"
  escape(title)+'=/res/lib/templates/examupload.problem';                .'// <![CDATA['."\n"
     this.document.forms.newexamupload.submit();                .$script."\n"
    }                .'// ]]>'."\n"
 }                .'</script>'."\n";
   
 function makesmppage() {      # Breadcrumbs
    var title=prompt('$lt{"p_msp"}');      &Apache::lonhtmlcommon::clear_breadcrumbs();
    if (title) {      unless ($showdoc) {
     this.document.forms.newsmppg.importdetail.value=          &Apache::lonhtmlcommon::add_breadcrumb({
  escape(title)+'=/adm/$udom/$uname/$now/smppg';              href=>"/adm/coursedocs",text=>"$crstype Contents"});
     this.document.forms.newsmppg.submit();  
    }          $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
 }                                                   {'force_register' => $showdoc,
                                                     'add_entries'    => $addentries,
 function makesmpproblem() {                                                   })
    var title=prompt('$lt{"p_msb"}');                   .&Apache::loncommon::help_open_menu('','',273,'RAT')
    if (title) {                   .&Apache::lonhtmlcommon::breadcrumbs(
     this.document.forms.newsmpproblem.importdetail.value=                       'Editing '.$crstype.' Contents',
  escape(title)+'=/res/lib/templates/simpleproblem.problem';                       'Docs_Adding_Course_Doc')
     this.document.forms.newsmpproblem.submit();          );
    }      } else {
 }          $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
                                                   {'force_register' => $showdoc,}));
 function makedropbox() {      }
    var title=prompt('$lt{"p_mdb"}');  
    if (title) {    my %allfiles = ();
     this.document.forms.newdropbox.importdetail.value=    my %codebase = ();
         escape(title)+'=/res/lib/templates/DropBox.problem';    my ($upload_result,$upload_output,$uploadphase);
     this.document.forms.newdropbox.submit();    if ($allowed) {
    }        if (($env{'form.uploaddoc.filename'}) &&
 }    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
             my $context = $1; 
 function makebulboard() {            # Process file upload - phase one - upload and parse primary file.
    var title=prompt('$lt{"p_mbb"}');    undef($hadchanges);
    if (title) {            $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
     this.document.forms.newbul.importdetail.value=                                                \%allfiles,\%codebase,$context);
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';    if ($hadchanges) {
     this.document.forms.newbul.submit();        &mark_hash_old();
    }    }
 }            $r->print($upload_output);
         } elsif ($env{'form.phase'} eq 'upload_embedded') {
 function makeabout() {            # Process file upload - phase two - upload embedded objects 
    var user=prompt("$lt{'p_mab'}");            $uploadphase = 'check_embedded';
    if (user) {            my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
        var comp=new Array();            my $state = &embedded_form_elems($uploadphase,$primaryurl,
        comp=user.split(':');                                             $env{'form.newidx'});
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {            my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
    if ((comp[0]) && (comp[1])) {            my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
        this.document.forms.newaboutsomeone.importdetail.value=            my ($destination,$dir_root) = &embedded_destination();
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';            my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
        this.document.forms.newaboutsomeone.submit();            my $actionurl = '/adm/coursedocs';
    } else {            my ($result,$flag) = 
                alert("$lt{'p_mab_alrt1'}");                &Apache::loncommon::upload_embedded('coursedoc',$destination,
            }                    $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
        } else {                    $actionurl);
            alert("$lt{'p_mab_alrt2'}");            $r->print($result.&return_to_editor());
        }        } elsif ($env{'form.phase'} eq 'check_embedded') {
    }            # Process file upload - phase three - modify references in HTML file
 }            $uploadphase = 'modified_orightml';
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 function makeims() {            my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
     var caller = document.forms.ims.folder.value;            my ($destination,$dir_root) = &embedded_destination();
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";            my $result = 
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");                &Apache::loncommon::modify_html_refs('coursedoc',$destination,
     newWindow.location.href = newlocation;                                                     $docuname,$docudom,undef,
 }                                                     $dir_root);
             $r->print($result.&return_to_editor());   
         } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
 function finishpick() {            $uploadphase = 'decompress_phase_one';
     var title=this.document.forms.extimport.title.value;            $r->print(&decompression_phase_one().
     var url=this.document.forms.extimport.url.value;                      &return_to_editor());
     var form=this.document.forms.extimport.useform.value;        } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
     var residx=this.document.forms.extimport.residx.value;            $uploadphase = 'decompress_phase_two';
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');            $r->print(&decompression_phase_two().
 }                      &return_to_editor());
         }
 function changename(folderpath,index,oldtitle,container,pagesymb) {    }
     var title=prompt('$lt{"p_chn"}',oldtitle);  
     if (title) {    if ($allowed && $toolsflag) {
  this.document.forms.renameform.markcopy.value=-1;        $r->print(&startContentScreen('tools'));
  this.document.forms.renameform.title.value=title;        $r->print(&generate_admin_menu($crstype));
  this.document.forms.renameform.cmd.value='rename_'+index;        $r->print(&endContentScreen());
         if (container == 'sequence') {    } elsif ((!$showdoc) && (!$uploadphase)) {
     this.document.forms.renameform.folderpath.value=folderpath;  # -----------------------------------------------------------------------------
         }         my %lt=&Apache::lonlocal::texthash(
         if (container == 'page') {                  'uplm' => 'Upload a new main '.lc($crstype).' document',
             this.document.forms.renameform.pagepath.value=folderpath;                  'upls' => 'Upload a new supplemental '.lc($crstype).' document',
             this.document.forms.renameform.pagesymb.value=pagesymb;                  'impp' => 'Import a document',
         }   'copm' => 'All documents out of a published map into this folder',
         this.document.forms.renameform.submit();                  'upfi' => 'Upload File',
     }                  'upld' => 'Import Content',
 }                  'srch' => 'Search',
                   'impo' => 'Import',
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {   'lnks' => 'Import from Stored Links',
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {                  'impm' => 'Import from Assembled Map',
  this.document.forms.renameform.markcopy.value=-1;                  'selm' => 'Select Map',
  this.document.forms.renameform.cmd.value='del_'+index;                  'load' => 'Load Map',
         if (container == 'sequence') {                  'reco' => 'Recover Deleted Documents',
             this.document.forms.renameform.folderpath.value=folderpath;                  'newf' => 'New Folder',
         }                  'newp' => 'New Composite Page',
         if (container == 'page') {                  'extr' => 'External Resource',
             this.document.forms.renameform.pagepath.value=folderpath;                  'syll' => 'Syllabus',
             this.document.forms.renameform.pagesymb.value=pagesymb;                  'navc' => 'Table of Contents',
         }                  'sipa' => 'Simple Course Page',
         this.document.forms.renameform.submit();                  'sipr' => 'Simple Problem',
     }                  'drbx' => 'Drop Box',
 }                  'scuf' => 'External Scores (handgrade, upload, clicker)',
                   'bull' => 'Discussion Board',
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {                  'mypi' => 'My Personal Information Page',
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {                  'grpo' => 'Group Portfolio',
  this.document.forms.renameform.cmd.value='cut_'+index;                  'rost' => 'Course Roster',
  this.document.forms.renameform.markcopy.value=index;   'abou' => 'Personal Information Page for a User',
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;                  'imsf' => 'IMS Import',
         if (container == 'sequence') {                  'imsl' => 'Import IMS package',
             this.document.forms.renameform.folderpath.value=folderpath;                  'cms'  => 'Origin of IMS package',
         }                  'se'   => 'Select',
         if (container == 'page') {                  'file' =>  'File',
             this.document.forms.renameform.pagepath.value=folderpath;                  'title' => 'Title',
             this.document.forms.renameform.pagesymb.value=pagesymb;                  'comment' => 'Comment',
         }                  'url'  => 'URL',
         this.document.forms.renameform.submit();                  'prev' => 'Preview',
     }                  'lnk'  => 'Add Link', 
 }                  'parse' => 'Upload embedded images/multimedia files if HTML file',
    'nd' => 'Upload Document',
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {   'pm' => 'Published Map',
     this.document.forms.renameform.markcopy.value=index;   'sd' => 'Special Document',
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;   'mo' => 'More Options',
     if (container == 'sequence') {    );
  this.document.forms.renameform.folderpath.value=folderpath;  # -----------------------------------------------------------------------------
     }   my $fileupload=(<<FIUP);
     if (container == 'page') {   $lt{'file'}:<br />
  this.document.forms.renameform.pagepath.value=folderpath;   <input type="file" name="uploaddoc" size="40" />
  this.document.forms.renameform.pagesymb.value=pagesymb;  FIUP
     }  
     this.document.forms.renameform.submit();   my $checkbox=(<<CHBO);
 }   <!-- <label>$lt{'parse'}?
    <input type="checkbox" name="parserflag" />
    </label> -->
 ENDNEWSCRIPT   <label>
 }   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
 1;   </label>
 __END__  CHBO
           my $imsfolder = $env{'form.folder'};
           if ($imsfolder eq '') {
 =head1 NAME              $imsfolder = 'default';  
           }
 Apache::londocs.pm          my $imspform=(<<IMSFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
 =head1 SYNOPSIS          $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
           <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
 This is part of the LearningOnline Network with CAPA project          <fieldset id="uploadimsform" style="display: none;" />
 described at http://www.lon-capa.org.          <legend>$lt{'imsf'}</legend>
           $fileupload
 =head1 SUBROUTINES          <br />
           <p>
 =over          $lt{'cms'}:&nbsp; 
           <select name="source">
 =item %help=()          <option value="-1" selected="selected">$lt{'se'}</option>
           <option value="bb5">Blackboard 5</option>
 Available help topics          <option value="bb6">Blackboard 6</option>
           <option value="angel5">ANGEL 5.5</option>
 =item mapread()          <option value="webctce4">WebCT 4 Campus Edition</option>
           </select>
 Mapread read maps into LONCAPA::map:: global arrays          <input type="hidden" name="folder" value="$imsfolder" />
 @order and @resources, determines status          </p>
 sets @order - pointer to resources in right order          <input type="hidden" name="phase" value="one" />
 sets @resources - array with the resources with correct idx          <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" />
           </fieldset>
 =item authorhosts()          </form>
   IMSFORM
 Return hash with valid author names  
    my $fileuploadform=(<<FUFORM);
 =item dumpbutton()          <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
 Generate "dump" button          <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
           <fieldset id="uploaddocform" style="display: none;" />
 =item clean()          <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="aa" />
 =item dumpcourse()   $fileupload
    <br />
     Actually dump course   $lt{'title'}:<br />
    <input type="text" size="60" name="comment" />
    $uploadtag
 =item exportbutton()   <input type="hidden" name="cmd" value="upload_default" />
    <br />
     Generate "export" button   <span class="LC_nobreak" style="float:left">
    $checkbox
 =item exportcourse()   </span>
           <br clear="all" />
 =item create_ims_store()          <input type="submit" value="$lt{'upld'}" />
           </fieldset>
 =item build_package()          </form>
   FUFORM
 =item get_dependencies()  
    my $importpubform=(<<SEDFFORM);
 =item process_content()          <a class="LC_menubuttons_link" href="javascript:toggleMap();">
           $lt{'impm'}</a>$help{'Load_Map'}
 =item replicate_content()   <form action="/adm/coursedocs" method="post" name="mapimportform">
           <fieldset id="importmapform" style="display: none;" />
 =item extract_media()          <legend>$lt{'impm'}</legend>
    <input type="hidden" name="active" value="bb" />
 =item store_template()          $lt{'copm'}<br />
           <span class="LC_nobreak">
 =item group_import()          <input type="text" name="importmap" size="40" value="" 
           onfocus="this.blur();openbrowser('mapimportform','importmap','sequence,page','');" />
     Imports the given (name, url) resources into the course          &nbsp;<a href="javascript:openbrowser('mapimportform','importmap','sequence,page','');">$lt{'selm'}</a><br />
     coursenum, coursedom, and folder must precede the list          <input type="submit" name="loadmap" value="$lt{'load'}" />
           </fieldset>
 =item breadcrumbs()          </form>
   
 =item log_docs()  SEDFFORM
    my @importpubforma = (
 =item docs_change_log()   { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => "$uploadtag<a class='LC_menubuttons_link' href='javascript:groupsearch()'>$lt{'srch'}</a>" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{impo}.'"  onclick="javascript:groupimport();"/>' => "<a class='LC_menubuttons_link' href='javascript:groupimport();'>$lt{'impo'}</a>$help{'Importing_LON-CAPA_Resource'}" },
 =item update_paste_buffer()   { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{lnks}.'" onclick="javascript:open_StoredLinks_Import();" />' => "<a class='LC_menubuttons_link' href='javascript:open_StoredLinks_Import();'>$lt{'lnks'}</a>" },
           { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/sequence.png" alt="'.$lt{impm}.'" onclick="javascript:toggleMap();" />' => $importpubform }
 =item print_paste_buffer()   );
    $importpubform = &create_form_ul(&create_list_elements(@importpubforma));
 =item do_paste_from_buffer()  
         my $extresourcesform=(<<ERFORM);
 =item update_parameter()        <a class="LC_menubuttons_link" href="javascript:toggleUpload('ext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
         <form action="/adm/coursedocs" method="post" name="newext">
 =item handle_edit_cmd()        <fieldset id="uploadextform" style="display: none;" />
         <legend>$lt{'extr'}</legend>
 =item editor()        <input type="hidden" name="active" value="aa" />
         $lt{'url'}:<br />
 =item process_file_upload()        <input type="text" size="60" name="exturl" id="exturl" value="http://" />
         <input type="button" name="view" value="$lt{'prev'}" onclick="javascript:extUrlPreview('exturl');" /><br />
 =item process_secondary_uploads()        $lt{'title'}:<br />
         <input type="text" size="60" name="exttitle" value="$lt{'extr'}" />
 =item is_supplemental_title()        $uploadtag
         <br />
 =item parse_supplemental_title()        <input type="hidden" name="importdetail" value="" />
         <input type="button" value="$lt{'lnk'}" onclick="javascript:setExternal(this.form,0)" />
 =item entryline()        </fieldset>
         </form>
 =item tiehash()  ERFORM
   
 =item untiehash()  
       if ($allowed) {
 =item checkonthis()          my $folder = $env{'form.folder'};
           if ($folder eq '') {
 check on this              $folder='default';
           }
 =item verifycontent()   &update_paste_buffer($coursenum,$coursedom,$folder);
    $r->print(<<HIDDENFORM);
 Verify Content   <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
 =item devalidateversioncache() & checkversions()     <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
 Check Versions     <input type="hidden" name="copyfolder" />
      $containertag
 =item mark_hash_old()   </form>
   
 =item is_hash_old()  HIDDENFORM
           $r->print(&makesimpleeditform($uploadtag)."\n".
 =item changewarning()                    &makedocslogform($uploadtag."\n".
                                      '<input type="hidden" name="folder" value="'.
 =item init_breadcrumbs()                                     $env{'form.folder'}.'" />'."\n"));
       }
 Breadcrumbs for special functions  
   # Generate the tabs
 =back      my $mode;
       if (($supplementalflag) && (!$allowed)) {
 =cut          &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
       } else {
           $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
       }
   
   #
   
       my $savefolderpath;
   
       if ($allowed) {
          my $folder=$env{'form.folder'};
          if ($folder eq '' || $supplementalflag) {
              $folder='default';
      $savefolderpath = $env{'form.folderpath'};
      $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
              $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">'."\n"
                       .'// <![CDATA['."\n"
                       .'this.window.name="loncapaclient";'."\n"
                       .'// ]]>'."\n"
                       .'</script>'."\n"
          );
          } else {
              #$postexec='self.close();';
          }
          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 $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$lt{'navc'}=/adm/navmaps" />
    <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
    $help{'Navigate_Content'}
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
    $help{'Simple Page'}
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
    $help{'Simple Problem'}
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
    $help{'Score_Upload_Form'}
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
    $help{'Bulletin Board'}
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
    </form>
   NASOFORM
   
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$lt{'rost'}=/adm/viewclasslist" />
    <a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
    $help{'Course Roster'}
    </form>
   NROSTFORM
   
   my $specialdocumentsform;
   my @specialdocumentsforma;
   my $gradingform;
   my @gradingforma;
   my $communityform;
   my @communityforma;
   my $newfolderform;
   my $newfolderb;
   
    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="" />
    <input type="hidden" name="active" value="cc" />
    <a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
    $help{'Adding_Pages'}
    </form>
   NPFORM
   
   
    $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="aa" />
    <a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
   
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
    $help{'Group Portfolio'}
    </form>
   NGFFORM
    @specialdocumentsforma=(
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
           );
           $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
   
   
           my @importdoc = (
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform},
           {'<img class="LC_noBorder_LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'doc\');" />'=>$fileuploadform,
           });
           $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc));
   
           @gradingforma=(
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
   
           );
           $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
   
           @communityforma=(
          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
           );
           $communityform = &create_form_ul(&create_list_elements(@communityforma));
   
   my %orderhash = (
                   'aa' => ['Import Content',$fileuploadform],
                   'bb' => ['Published Content',$importpubform],
                   'cc' => ['Grading Resources',$gradingform],
                   );
   unless ($env{'form.pagepath'}) {
       $orderhash{'00'} = ['Newfolder',$newfolderform];
       $orderhash{'dd'} = ['Collaboration',$communityform];
       $orderhash{'ee'} = ['Special Documents',$specialdocumentsform];
   }
   
    $hadchanges=0;
          unless (($supplementalflag || $toolsflag)) {
             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                 $supplementalflag,\%orderhash,$iconpath,$uploadtag);
             if ($error) {
                $r->print('<p><span class="LC_error">'.$error.'</span></p>');
             }
             if ($hadchanges) {
                &mark_hash_old();
             }
   
             &changewarning($r,'');
           }
       }
   
   # Supplemental documents start here
   
          my $folder=$env{'form.folder'};
          unless ($supplementalflag) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = &supplemental_base();
          } elsif ($allowed) {
     $env{'form.folderpath'} = $savefolderpath;
          }
          $env{'form.pagepath'} = '';
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
          '.sequence';
   
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $supupdocform=(<<SUPDOCFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppdoc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
    <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
           <fieldset id="uploadsuppdocform" style="display: none;" />
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="ee" />
    $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" />
           <input type='submit' value="$lt{'upld'}" />
           </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="active" value="ee" />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
    $help{'Adding_Folders'}
    </form>
   SNFFORM
   
           my $supextform=(<<ERFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
           <form action="/adm/coursedocs" method="post" name="newsuppext">
           <fieldset id="uploadsuppextform" style="display: none;" />
           <legend>$lt{'extr'}</legend>
           <input type="hidden" name="active" value="ee" />
           $lt{'url'}:<br />
           <input type="text" size="60" name="exturl" id="exturl" value="http://" />
           <input type="button" name="view" value="$lt{'prev'}" onclick="javascript:extUrlPreview('exturl');" /><br />
           $lt{'title'}:<br />
           <input type="text" size="60" name="exttitle" value="$lt{'extr'}" />
           $uploadtag
           <br />
           <input type="hidden" name="importdetail" value="" />
           <input type="button" value="$lt{'lnk'}" onclick="javascript:setExternal(this.form,0)" />
           </fieldset>
           </form>
   ERFORM
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="active" value="ff" />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" 
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="supnewaboutme">
    <input type="hidden" name="active" value="ff" />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   SNAMFORM
   
   
   my @specialdocs = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.supnewsyl.submit()" />'
               =>$supnewsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
               =>$supnewaboutmeform},
    );
   my @supimportdoc = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'suppext\')" />'
               =>$supextform},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
               =>$supupdocform},
                      );
   
   $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
   my %suporderhash = (
    '00' => ['Supnewfolder', $supnewfolderform],
                   'ee' => ['Import Content',$supupdocform],
                   'ff' => ['Special Documents',&create_form_ul(&create_list_elements(@specialdocs))]
                   );
           if ($supplementalflag) {
              my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                  $supplementalflag,\%suporderhash,$iconpath,$uploadtag);
              if ($error) {
                 $r->print('<p><span class="LC_error">'.$error.'</span></p>');
              }
           }
       } elsif ($supplementalflag) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,'',$iconpath,$uploadtag);
           if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
       }
   
       $r->print(&endContentScreen());
   
       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>');
       }
     } elsif ($showdoc) {
   # -------------------------------------------------------- This is showdoc mode
         $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p class="LC_warning">'.
   &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 embedded_form_elems {
       my ($phase,$primaryurl,$newidx) = @_;
       my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
       return <<STATE;
       <input type="hidden" name="folderpath" value="$folderpath" />
       <input type="hidden" name="cmd" value="upload_embedded" />
       <input type="hidden" name="newidx" value="$newidx" />
       <input type="hidden" name="phase" value="$phase" />
       <input type="hidden" name="primaryurl" value="$primaryurl" />
   STATE
   }
   
   sub embedded_destination {
       my $folder=$env{'form.folder'};
       my $destination = 'docs/';
       if ($folder =~ /^supplemental/) {
           $destination = 'supplemental/';
       }
       if (($folder eq 'default') || ($folder eq 'supplemental')) {
           $destination .= 'default/';
       } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
           $destination .=  $2.'/';
       }
       $destination .= $env{'form.newidx'};
       my $dir_root = '/userfiles';
       return ($destination,$dir_root);
   }
   
   sub return_to_editor {
       my $actionurl = '/adm/coursedocs';
       return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
              '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
              '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
              '</a></p>';
   }
   
   sub decompression_info {
       my ($destination,$dir_root) = &embedded_destination();
       my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
       my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
       my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $container='sequence';
       my ($pathitem,$hiddenelem);
       my @hiddens = ('newidx','comment','position');
       if ($env{'form.pagepath'}) {
           $container='page';
           $pathitem = 'pagepath';
       } else {
           $pathitem = 'folderpath';
       }
       unshift(@hiddens,$pathitem);
       foreach my $item (@hiddens) {
           if ($env{'form.'.$item}) {
               $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
                              $env{'form.'.$item}.'" />'."\n";
           }
       }
       return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
               $hiddenelem);
   }
   
   sub decompression_phase_one {
       my ($dir,$file,$warning,$error,$output);
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/\E(?:docs|supplemental)/(?:default|\d+).*/([^/]+)$}) {
           $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
       } else {
           my $file = $1;
           $output = 
               &Apache::loncommon::process_decompression($docudom,$docuname,$file,
                                                         $destination,$dir_root,
                                                         $hiddenelem);
           if ($env{'form.autoextract_camtasia'}) {
               $output .= &remove_archive($docudom,$docuname,$container);
           }
       }
       if ($error) {
           $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                      $error.'</p>'."\n";
       }
       if ($warning) {
           $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
       }
       return $output;
   }
   
   sub decompression_phase_two {
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       my $output;
       if ($env{'form.archivedelete'}) {
           $output = &remove_archive($docudom,$docuname,$container);
       }
       $output .= 
           &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
                                                       $destination,$dir_root,$hiddenelem);
       return $output;
   }
   
   sub remove_archive {
       my ($docudom,$docuname,$container) = @_;
       my $map = $env{'form.folder'}.'.'.$container;
       my ($output,$delwarning,$delresult,$url);
       my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
       if ($fatal) {
           if ($container eq 'page') {
               $delwarning = &mt('An error occurred retrieving the contents of the current page.');
           } else {
               $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
           }
           $delwarning .= &mt('As a result the archive file has not been removed.');
       } else {
           my $currcmd = $env{'form.cmd'};
           my $position = $env{'form.position'};
           if ($position > 0) { 
               $env{'form.cmd'} = 'del_'.$position;
               my ($title,$url,@rrest) = 
                   split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$position]]);
               if (&handle_edit_cmd($docuname,$docudom)) {
                   ($errtext,$fatal) = &storemap($docuname,$docudom,$map,1);
                   if ($fatal) {
                       if ($container eq 'page') {
                           $delwarning = &mt('An error occurred updating the contents of the current page.');
                       } else {
                           $delwarning = &mt('An error occurred updating the contents of the current folder.');
                       }
                   } else {
                       $delresult = &mt('Archive file removed.');
                   }
               }
           }
           $env{'form.cmd'} = $currcmd;
       }
       if ($delwarning) {
           $output = '<p class="LC_warning">'.
                      $delwarning.
                      '</p>';
       }
       if ($delresult) {
           $output .= '<p class="LC_info">'.
                      $delresult.
                      '</p>';
       }
       return $output;
   }
   
   sub generate_admin_menu {
       my ($crstype) = @_;
       my $lc_crstype = lc($crstype);
       my ($home,$other,%outhash)=&authorhosts();
       my %lt=&Apache::lonlocal::texthash (
                                            'vc'   => 'Verify Content',
                                            'cv'   => 'Check/Set Resource Versions',
                                            'ls'   => 'List Resource Identifiers',
                                            'imse' => 'Export contents to IMS Archive',
                                            'dcd'  => "Dump $crstype Content to Authoring Space",
                                          );
       my ($candump,$dumpurl);
       if ($home + $other > 0) {
           $candump = 'F';
           if ($home) {
               $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
           } else {
               my @hosts;
               foreach my $aurole (keys(%outhash)) {
                   unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                       push(@hosts,$outhash{$aurole});
                   }  
               }
               if (@hosts == 1) {
                   my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
                                  '&amp;role='.
                                  &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
                                  &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
                   $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
               } else {
                   $dumpurl = "javascript:choose_switchserver_window()";
               }
           }
       }
       my @menu=
           ({  categorytitle=>'Administration',
               items =>[
                   {   linktext   => $lt{'vc'},
                       url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
                       permission => 'F',
                       help       => 'Verify_Content',
                       icon       => 'verify.png',
                       linktitle  => 'Verify contents can be retrieved/rendered',
                   },
                   {   linktext => $lt{'cv'},
                       url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
                       permission => 'F',
                       help       => 'Check_Resource_Versions',
                       icon       => 'resversion.png',
                       linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
                   },
                   {   linktext   => $lt{'ls'},
                       url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
                       permission => 'F',
                       #help => '',
                       icon       => 'symbs.png',
                       linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
                   },
                   ]
           },
           {   categorytitle=>'Export',
               items =>[
                   {   linktext   => $lt{'imse'},
                       url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
                       permission => 'F',
                       help       => 'Docs_Export_Course_Docs',
                       icon       => 'imsexport.png',
                       linktitle  => $lt{'imse'},
                   },
                   {   linktext   => $lt{'dcd'},
                       url        => $dumpurl,
                       permission => $candump,
                       #help => '',
                       icon       => 'dump.png',
                       linktitle  => $lt{'dcd'},
                   },
                   ]
           });
       return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
              '<input type="hidden" id="dummy" />'."\n".
              &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
              '</form>';
   }
   
   sub generate_edit_table {
       my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile) = @_;
       return unless(ref($orderhash_ref) eq 'HASH');
       my %orderhash = %{$orderhash_ref};
       my $form;
       my $activetab;
       my $active;
       if($env{'form.active'} ne ''){
           $activetab = $env{'form.active'};
       }
       my $backicon = $iconpath.'clickhere.gif';
       my $backtext = &mt('To Overview');
       $form = '<div class="LC_Box" style="margin:0;">'.
               '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
               '<li class="goback">'.
               '<a href="javascript:toContents('."'$jumpto'".');">'.
               '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
               '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n".
               '<li>'.
               '<a href="javascript:groupopen('."'$readfile'".',1);">'.
               &mt('Undo Delete').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li class="active">';
       } else {
           $form .= '<li>';
       }
       $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
                &mt('History').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
                    &mt('Edit').'</a></li>'."\n";
       }
       foreach my $name (reverse(sort(keys(%orderhash)))) {
           if($name ne '00'){
               if($activetab eq '' || $activetab ne $name){
                  $active = '';
               }elsif($activetab eq $name){
                  $active = 'class="active"';
               }
               $form .= '<li style="float:right" '.$active
                   .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
           } else {
       $form .= '<li '.$active.' style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
   
    }
       }
       $form .= '</ul>'."\n";
       $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
   
       if ($to_show ne '') {
           $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'."\n";
       }
       foreach my $field (keys(%orderhash)){
    if($field ne '00'){
               if($activetab eq '' || $activetab ne $field){
                   $active = 'style="display: none;float:left"';
               }elsif($activetab eq $field){
                   $active = 'style="display:block;float:left"';
               }
               $form .= '<div id="'.$field.$tid.'"'
                       .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
                       .'</div>'."\n";
           }
       }
       unless ($env{'form.docslog'}) {
           $form .= '</div></div>'."\n";
       }
       return $form;
   }
   
   sub editing_js {
       my ($udom,$uname,$supplementalflag) = @_;
       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 External Score',
                                             p_msp => 'Name of Simple Course Page',
                                             p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Discussion Board',
                                             p_mab => "Enter user:domain for User's Personal Information Page",
                                             p_mab2 => 'Personal Information Page of ',
                                             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]',
                                             rpck    => 'Enter number to pick (e.g., 3)',
                                             imsfile => 'You must choose an IMS package for import',
                                             imscms  => 'You must select which Course Management System was the source of the IMS package',
                                             invurl  => 'Invalid URL',
                                             titbl   => 'Title is blank',
                                           );
   
       my $crstype = &Apache::loncommon::course_type();
       my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
       my $docs_pagepath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.pagepath'},'<>&"');
       my $main_container_page;
       if ($docs_folderpath eq '') {
           if ($docs_pagepath ne '') {
               $main_container_page = 1;
           }
       }
       my $toplevelmain = 'default&Main%20'.$crstype.'%20Documents';
       my $toplevelsupp = &supplemental_base();
   
       my $backtourl = '/adm/navmaps';
       if ($supplementalflag) {
           $backtourl = '/adm/supplemental';
       }
   
       my $fieldsets = "'ext','doc','ims'";
       if ($supplementalflag) {
           $fieldsets = "'suppext','suppdoc'";
       }
   
       my $urlregexp = <<'ENDREGEXP';
   /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i
   ENDREGEXP
   
       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 editext(residx) {
       if (document.getElementById('uploadext'+residx)) {
           var curr = document.getElementById('uploadext'+residx).style.display;
           if (curr == 'none') {
               disp = 'block';
           } else {
               disp = 'none';
           }
           document.getElementById('uploadext'+residx).style.display=disp;
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   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 toggleUpload(caller) {
       var blocks = Array($fieldsets);
       for (var i=0; i<blocks.length; i++) {
           var disp = 'none';
           if (caller == blocks[i]) {
               var curr = document.getElementById('upload'+caller+'form').style.display;
               if (curr == 'none') {
                   disp='block';
               }
           }
           document.getElementById('upload'+blocks[i]+'form').style.display=disp;
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   function toggleMap() {
       var disp = 'none';
       var curr = document.getElementById('importmapform').style.display;
       if (curr == 'none') {
           disp='block';
       }
       document.getElementById('importmapform').style.display=disp;
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   
   function extUrlPreview(caller) {
       if (document.getElementById(caller)) {
           var url = document.getElementById(caller).value;
           var regexp = $urlregexp;
           if (regexp.test(url)) {
               openMyModal(url,500,400,'yes');
           } else {
               alert("$lt{'invurl'}");
           }
       }
   }
   
   function makeims(imsform) {
       if ((imsform.uploaddoc.value == '')  || (!imsform.uploaddoc.value)) {
           alert("$lt{'imsfile'}");
           return;
       }
       if (imsform.source.selectedIndex == 0) {
           alert("$lt{'imscms'}");
           return;
       }
       newWindow = window.open('', 'IMSimport',"HEIGHT=700,WIDTH=750,scrollbars=yes");
       imsform.submit();
   }
   
   function setExternal(extform,residx) {
       var title=extform.exttitle.value;
       if (!String.trim) {
           String.prototype.trim = function() {return this.replace(\/^\\s+|\\s+$\/g, "");};    }
       var url=extform.exturl.value;
       var regexp = $urlregexp;
       if (title == null || title.trim()=="") {
           alert("$lt{'titbl'}");
           extform.exttitle.focus();
           return;
       }
       if (regexp.test(url)) {
           url = escape(url);
           if (residx > 0) {
               eval("extform.importdetail.value=title+'='+url+'='+residx;extform.submit();");
           } else {
               eval("extform.importdetail.value=title+'='+url;extform.submit();");
           }
       } else {
           alert("$lt{'invurl'}");
           extform.exturl.focus();
           return;
       }
   }
   
   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();
   }
   
   function updatePick(targetform,index,caller) {
       var pickitem = document.getElementById('rpick_'+index);
       var picknumitem = document.getElementById('rpicknum_'+index);
       if (pickitem.checked) {
           var picknum=prompt('$lt{"rpck"}',picknumitem.value);
           if (picknum == '' || picknum == null) {
               if (caller == 'check') {
                   pickitem.checked=false;
                   return;
               }
           } else {
               picknum.toString();
               var regexdigit=/^\\d+\$/;
               if (regexdigit.test(picknum)) {
                   picknumitem.value = picknum;
                   targetform.changeparms.value='randompick';
                   targetform.submit();
               } else {
                   if (caller == 'check') {
                       pickitem.checked=false;
                   }
                   return;
               }
           }
       } else {
           picknumitem.value = 0;
           targetform.changeparms.value='randompick';
           targetform.submit();
       }
   }
   
   function unselectInactive(nav) {
   currentNav = document.getElementById(nav);
   currentLis = currentNav.getElementsByTagName('LI');
   for (i = 0; i < currentLis.length; i++) {
           if (currentLis[i].className == 'goback') {
               currentLis[i].className = 'goback';
           } else {
       if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
    currentLis[i].className = 'right';
       } else {
    currentLis[i].className = 'i';
       }
           }
   }
   }
   
   function hideAll(current, nav, data) {
   unselectInactive(nav);
   if(current.className == 'right'){
    current.className = 'right active'
    }else{
    current.className = 'active';
   }
   currentData = document.getElementById(data);
   currentDivs = currentData.getElementsByTagName('DIV');
   for (i = 0; i < currentDivs.length; i++) {
    if(currentDivs[i].className == 'LC_ContentBox'){
    currentDivs[i].style.display = 'none';
    }
   }
   }
   
   function openTabs(pageId) {
    tabnav = document.getElementById(pageId).getElementsByTagName('UL');
    if(tabnav.length > 2 ){
    currentNav = document.getElementById(tabnav[1].id);
    currentLis = currentNav.getElementsByTagName('LI');
    for(i = 0; i< currentLis.length; i++){
    if(currentLis[i].className == 'active') {
    funcString = currentLis[i].onclick.toString();
    tab = funcString.split('"');
                                   if(tab.length < 2) {
                                      tab = funcString.split("'");
                                   }
    currentData = document.getElementById(tab[1]);
           currentData.style.display = 'block';
    }
    }
    }
   }
   
   function showPage(current, pageId, nav, data) {
    hideAll(current, nav, data);
    openTabs(pageId);
    unselectInactive(nav);
    current.className = 'active';
    currentData = document.getElementById(pageId);
    currentData.style.display = 'block';
           activeTab = pageId;
           toggleUpload();
           if (nav == 'mainnav') {
               var storedpath = "$docs_folderpath";
               if (storedpath == '') {
                   storedpath = "$docs_pagepath";
               }
               var storedpage = "$main_container_page";
               var reg = new RegExp("^supplemental");
               if (pageId == 'mainCourseDocuments') {
                   if (storedpage == 1) {
                       document.simpleedit.folderpath.value = '';
                       document.uploaddocument.folderpath.value = '';
                   } else {
                       if (reg.test(storedpath)) {
                           document.simpleedit.folderpath.value = '$toplevelmain';
                           document.uploaddocument.folderpath.value = '$toplevelmain';
                           document.newext.folderpath.value = '$toplevelmain';
                       } else {
                           document.simpleedit.folderpath.value = storedpath;
                           document.uploaddocument.folderpath.value = storedpath;
                           document.newext.folderpath.value = storedpath;
                       }
                   }
               } else {
                   if (reg.test(storedpath)) {
                       document.simpleedit.folderpath.value = storedpath;
                       document.supuploaddocument.folderpath.value = storedpath;
                       document.supnewext.folderpath.value = storedpath;
                   } else {
                       document.simpleedit.folderpath.value = '$toplevelsupp';
                       document.supuploaddocument.folderpath.value = '$toplevelsupp';
                       document.supnewext.folderpath.value = '$toplevelsupp';
                   }
               }
           }
           resize_scrollbox('contentscroll','1','0');
    return false;
   }
   
   function toContents(jumpto) {
       var newurl = '$backtourl';
       if (jumpto != '') {
           newurl = newurl+'?postdata='+jumpto;
   ;
       }
       location.href=newurl;
   }
   
   ENDNEWSCRIPT
   }
   
   sub history_tab_js {
       return <<"ENDHIST";
   function toggleHistoryDisp(choice) {
       document.docslogform.docslog.value = choice;
       document.docslogform.submit();
       return;
   }
   
   ENDHIST
   }
   
   sub inject_data_js {
       return <<ENDINJECT;
   
   function injectData(current, hiddenField, name, value) {
           currentElement = document.getElementById(hiddenField);
           currentElement.name = name;
           currentElement.value = value;
           current.submit();
   }
   
   ENDINJECT
   }
   
   sub dump_switchserver_js {
       my @hosts = @_;
       my %lt = &Apache::lonlocal::texthash(
           dump => 'Dumping to Authoring Space requires switching server.',
           swit => 'Switch server?',
           duco => 'Dump content to Authoring Space',
           yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
           chos => 'Choose server',
       );
       my $role = $env{'request.role'};
       my $js = <<"ENDSWJS";
   <script type="text/javascript">
   function write_switchserver() {
       var server;
       if (document.setserver.posshosts.length > 0) {
           for (var i=0; i<document.setserver.posshosts.length; i++) {
               if (document.setserver.posshosts[i].checked) {
                   server = document.setserver.posshosts[i].value;
               }
          }
          opener.document.location.href="/adm/switchserver?otherserver="+server+"&role=$role&origurl=/adm/coursedocs";
       }
       window.close();
   }
   </script>
   
   ENDSWJS
   
       my $startpage = &Apache::loncommon::start_page('Choose server',$js,
                                                      {'only_body' => 1,
                                                       'js_ready'  => 1,});
       my $endpage = &Apache::loncommon::end_page({'js_ready'  => 1});
   
       my $hostpicker;
       my $count = 0;
       foreach my $host (sort(@hosts)) {
           my $checked;
           if ($count == 0) {
               $checked = ' checked="checked"';
           }
           $hostpicker .= '<label><input type="radio" name="posshosts" value="'.
                          $host.'"'.$checked.' />'.$host.'</label>&nbsp;&nbsp;';
           $count++;
       }
       
       return <<"ENDSWITCHJS";
   
   function dump_needs_switchserver(url) {
       if (url!='' && url!= null) {
           if (confirm("$lt{'dump'}\\n$lt{'swit'}")) {
               go(url);
           }
       }
       return;
   }
   
   function choose_switchserver_window() {
       newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
       newWindow.document.open();
       newWindow.document.writeln('$startpage');
       newWindow.document.write('<h3>$lt{'duco'}<\\/h3>\\n'+
          '<p>$lt{'yone'}<\\/p>\\n'+
          '<div class="LC_left_float"><fieldset><legend>$lt{'chos'}<\\/legend>\\n'+
          '<form name="setserver" method="post" action="" \\/>\\n'+
          '$hostpicker\\n'+
          '<br \\/><br \\/>\\n'+
          '<input type="button" name="makeswitch" value="$lt{'swit'}" '+
          'onclick="write_switchserver();" \\/>\\n'+
          '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
       newWindow.document.writeln('$endpage');
       newWindow.document.close();
       newWindow.focus();
   }
   
   ENDSWITCHJS
   }
   
   sub makedocslogform {
       my ($formelems,$docslog) = @_;
       return <<"LOGSFORM";
    <form action="/adm/coursedocs" method="post" name="docslogform">
      <input type="hidden" name="docslog" value="$docslog" />
      $formelems
    </form>
   LOGSFORM
   }
   
   sub makesimpleeditform {
       my ($formelems) = @_;
       return <<"SIMPFORM";
    <form name="simpleedit" method="post" action="/adm/coursedocs">
      <input type="hidden" name="importdetail" value="" />
      $formelems
    </form>
   SIMPFORM
   }
   
   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 clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   =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 get_newmap_url()
   
   =item dbcopy()
   
   =item uniqueness_check()
   
   =item contained_map_check()
   
   =item reinit_role()
   
   =item url_paste_fixups()
   
   =item apply_fixups()
   
   =item copy_dependencies()
   
   =item update_parameter()
   
   =item handle_edit_cmd()
   
   =item editor()
   
   =item process_file_upload()
   
   =item process_secondary_uploads()
   
   =item is_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
   
   =item create_list_elements()
   
   =item create_form_ul()
   
   =item startContentScreen() 
   
   =item endContentScreen()
   
   =item supplemental_base()
   
   =item embedded_form_elems()
   
   =item embedded_destination()
   
   =item return_to_editor()
   
   =item decompression_info()
   
   =item decompression_phase_one()
   
   =item decompression_phase_two()
   
   =item remove_archive()
   
   =item generate_admin_menu()
   
   =item generate_edit_table()
   
   =item editing_js()
   
   =item history_tab_js()
   
   =item inject_data_js()
   
   =item dump_switchserver_js()
   
   =item resize_scrollbox_js()
   
   =item makedocslogform()
   
   =item makesimpleeditform()
   
   =back
   
   =cut

Removed from v.1.327  
changed lines
  Added in v.1.502


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