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

version 1.327, 2009/01/28 12:56:08 version 1.484.2.41, 2013/09/22 02:24:27
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::lonextresedit();
 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 $suppchanges;
   
   
 sub mapread {  my %help=();
     my ($coursenum,$coursedom,$map)=@_;  
     return  
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.  sub mapread {
      $map);      my ($coursenum,$coursedom,$map)=@_;
 }      return
         &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
 sub storemap {       $map);
     my ($coursenum,$coursedom,$map)=@_;  }
     my ($outtext,$errtext)=  
       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.  sub storemap {
       $map,1);      my ($coursenum,$coursedom,$map,$contentchg)=@_;
     if ($errtext) { return ($errtext,2); }      my $report;
          if (($contentchg) && ($map =~ /^default/)) {
     $hadchanges=1;         $report = 1;
     return ($errtext,0);      }
 }      my ($outtext,$errtext)=
         &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1,$report);
       if ($errtext) { return ($errtext,2); }
 sub authorhosts {  
     my %outhash=();      if ($map =~ /^default/) {
     my $home=0;          $hadchanges=1;
     my $other=0;      } else {
     foreach my $key (keys(%env)) {          $suppchanges=1;
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {      }
     my $role=$1;      return ($errtext,0);
     my $realm=$2;  }
     my ($start,$end)=split(/\./,$env{$key});  
     if (($start) && ($start>time)) { next; }  
     if (($end) && (time>$end)) { next; }  
     my ($ca,$cd);  sub authorhosts {
     if ($1 eq 'au') {      my %outhash=();
  $ca=$env{'user.name'};      my $home=0;
  $cd=$env{'user.domain'};      my $other=0;
     } else {      foreach my $key (keys(%env)) {
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     }      my $role=$1;
     my $allowed=0;      my $realm=$2;
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);      my ($start,$end)=split(/\./,$env{$key});
     my @ids=&Apache::lonnet::current_machine_ids();      if (($start) && ($start>time)) { next; }
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      if (($end) && (time>$end)) { next; }
     if ($allowed) {      my ($ca,$cd);
  $home++;      if ($1 eq 'au') {
  $outhash{'home_'.$ca.'@'.$cd}=1;   $ca=$env{'user.name'};
     } else {   $cd=$env{'user.domain'};
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      } else {
  $other++;   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
     }      }
  }      my $allowed=0;
     }      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
     return ($home,$other,%outhash);      my @ids=&Apache::lonnet::current_machine_ids();
 }      foreach my $id (@ids) {
                   if ($id eq $myhome) {
                       $allowed=1;
 sub dumpbutton {                      last;
     my ($home,$other,%outhash)=&authorhosts();                  }
     my $type = &Apache::loncommon::course_type();              }
     if ($home+$other==0) { return ''; }      if ($allowed) {
     if ($home) {   $home++;
  return '<input type="submit" name="dumpcourse" value="'.   $outhash{'home_'.$ca.':'.$cd}=1;
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      } else {
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
     } else {   $other++;
  return '<div>'.      }
      &mt('Dump '.$type.   }
  ' DOCS to Construction Space: available on other servers').      }
  '</div>';      return ($home,$other,%outhash);
     }  }
 }  
   
 sub clean {  sub clean {
     my ($title)=@_;      my ($title)=@_;
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
     return $title;      return $title;
 }  }
   
   
   
 sub dumpcourse {  sub dumpcourse {
     my ($r) = @_;      my ($r) = @_;
     my $type = &Apache::loncommon::course_type();      my $crstype = &Apache::loncommon::course_type();
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').      $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
       '<form name="dumpdoc" method="post">');                &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      $r->print(&startContentScreen('tools'));
     my ($home,$other,%outhash)=&authorhosts();      my ($home,$other,%outhash)=&authorhosts();
     unless ($home) { return ''; }      unless ($home) {
     my $origcrsid=$env{'request.course.id'};          $r->print(&endContentScreen());
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);          return '';
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {      }
 # Do the dumping      my $origcrsid=$env{'request.course.id'};
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  $r->print('<h3>'.&mt('Copying Files').'</h3>');  # Do the dumping
  my $title=$env{'form.authorfolder'};   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
  $title=&clean($title);              $r->print(&endContentScreen());
  my %replacehash=();              return '';
  foreach my $key (keys(%env)) {          }
     if ($key=~/^form\.namefor\_(.+)/) {   my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  $replacehash{$1}=$env{$key};   $r->print('<h3>'.&mt('Copying Files').'</h3>');
     }   my $title=$env{'form.authorfolder'};
  }   $title=&clean($title);
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   my %replacehash=();
  $crs=~s/\_/\//g;   foreach my $key (keys(%env)) {
  foreach my $item (keys(%replacehash)) {      if ($key=~/^form\.namefor\_(.+)/) {
     my $newfilename=$title.'/'.$replacehash{$item};   $replacehash{$1}=$env{$key};
     $newfilename=~s/\.(\w+)$//;      }
     my $ext=$1;   }
     $newfilename=&clean($newfilename);   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
     $newfilename.='.'.$ext;   $crs=~s/\_/\//g;
     my @dirs=split(/\//,$newfilename);   foreach my $item (keys(%replacehash)) {
     my $path='/home/'.$ca.'/public_html';      my $newfilename=$title.'/'.$replacehash{$item};
     my $makepath=$path;      $newfilename=~s/\.(\w+)$//;
     my $fail=0;      my $ext=$1;
     for (my $i=0;$i<$#dirs;$i++) {      $newfilename=&clean($newfilename);
  $makepath.='/'.$dirs[$i];      $newfilename.='.'.$ext;
  unless (-e $makepath) {      my @dirs=split(/\//,$newfilename);
     unless(mkdir($makepath,0777)) { $fail=1; }      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
  }      my $makepath=$path;
     }      my $fail=0;
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      for (my $i=0;$i<$#dirs;$i++) {
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {   $makepath.='/'.$dirs[$i];
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {   unless (-e $makepath) {
     print $fh &Apache::lonclonecourse::rewritefile(      unless(mkdir($makepath,0777)) { $fail=1; }
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),   }
      (%replacehash,$crs => '')      }
     );      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
  } else {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     print $fh   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);      print $fh &Apache::lonclonecourse::rewritefile(
        }           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  $fh->close();       (%replacehash,$crs => '')
     } else {      );
  $fail=1;   } else {
     }      print $fh
     if ($fail) {           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');         }
     } else {   $fh->close();
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      } else {
     }   $fail=1;
  }      }
     } else {      if ($fail) {
 # Input form   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  unless ($home==1) {      } else {
     $r->print(   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');      }
  }   }
  foreach my $key (sort(keys(%outhash))) {      } else {
     if ($key=~/^home_(.+)$/) {          $r->print(&mt('Searching ...').'<br />');
  if ($home==1) {          $r->rflush();
     $r->print(  # Input form
   '<input type="hidden" name="authorspace" value="'.$1.'" />');          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
  } else {   unless ($home==1) {
     $r->print('<option value="'.$1.'">'.$1.' - '.      $r->print('<div class="LC_left_float">'.
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');        '<fieldset><legend>'.
  }                        &mt('Select the Authoring Space').
     }                        '</legend><select name="authorspace">');
  }   }
  unless ($home==1) {   foreach my $key (sort(keys(%outhash))) {
     $r->print('</select>');      if ($key=~/^home_(.+)$/) {
  }   if ($home==1) {
  my $title=$origcrsdata{'description'};      $r->print(
  $title=~s/[\/\s]+/\_/gs;    '<input type="hidden" name="authorspace" value="'.$1.'" />');
  $title=&clean($title);   } else {
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'      $r->print('<option value="'.$1.'">'.$1.' - '.
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
  &tiehash();   }
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'      }
                  .&Apache::loncommon::start_data_table()   }
                  .&Apache::loncommon::start_data_table_header_row()   unless ($home==1) {
                  .'<th>'.&mt('Internal Filename').'</th>'      $r->print('</select></fieldset></div>'."\n");
                  .'<th>'.&mt('Title').'</th>'   }
                  .'<th>'.&mt('Save as ...').'</th>'   my $title=$origcrsdata{'description'};
                  .&Apache::loncommon::end_data_table_header_row());   $title=~s/[\/\s]+/\_/gs;
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {   $title=&clean($title);
     $r->print(&Apache::loncommon::start_data_table_row()   $r->print('<div class="LC_left_float">'.
                      .'<td>'.$file.'</td>');                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
     my ($ext)=($file=~/\.(\w+)$/);                    '<input type="text" size="50" name="authorfolder" value="'.
     my $title=$hash{'title_'.$hash{                    $title.'" />'.
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                    '</fieldset></div><br clear="all" />'."\n");
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');   &tiehash();
     if (!$title) {   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
  $title=$file;                   .&Apache::loncommon::start_data_table()
     } else {                   .&Apache::loncommon::start_data_table_header_row()
  $title=~s|/|_|g;                   .'<th>'.&mt('Internal Filename').'</th>'
     }                   .'<th>'.&mt('Title').'</th>'
     $title=~s/\.(\w+)$//;                   .'<th>'.&mt('Save as ...').'</th>'
     $title=&clean($title);                   .&Apache::loncommon::end_data_table_header_row());
     $title.='.'.$ext;   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"      $r->print(&Apache::loncommon::start_data_table_row()
                      .&Apache::loncommon::end_data_table_row());                       .'<td>'.$file.'</td>');
  }      my ($ext)=($file=~/\.(\w+)$/);
  $r->print(&Apache::loncommon::end_data_table());      my $title=$hash{'title_'.$hash{
  &untiehash();   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
  $r->print(      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      if (!$title) {
     }   $title=$file;
 }      } else {
    $title=~s|/|_|g;
       }
       $title=~s/\.(\w+)$//;
 sub exportbutton {      $title=&clean($title);
     my $type = &Apache::loncommon::course_type();      $title.='.'.$ext;
     return '<input type="submit" name="exportcourse" value="'.      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
             &mt('Export '.$type.' to IMS').'" />'.                       .&Apache::loncommon::end_data_table_row());
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');   }
 }   $r->print(&Apache::loncommon::end_data_table());
    &untiehash();
    $r->print(
     '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
 sub exportcourse {      }
     my $r=shift;      $r->print(&endContentScreen());
     my $type = &Apache::loncommon::course_type();  }
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',  
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});  sub group_import {
     my $numdisc = keys(%discussiontime);      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
     my $navmap = Apache::lonnavmaps::navmap->new();      my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
     if (!defined($navmap)) {          %removeparam,$importuploaded,$fixuperrors);
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').      $allmaps = {};
                   '<h2>IMS Export Failed</h2>'.      while (@files) {
                   '<div class="LC_error">'.   my ($name, $url, $residx) = @{ shift(@files) };
                   &mt('Unable to retrieve information about course contents').          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');       && ($caller eq 'londocs')
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});       && (!&Apache::lonnet::stat_file($url))) {
         return;  
     }              my $errtext = '';
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);              my $fatal = 0;
     my $curRes;              my $newmapstr = '<map>'."\n".
     my $outcome;                              '<resource id="1" src="" type="start"></resource>'."\n".
                               '<link from="1" to="2" index="1"></link>'."\n".
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                              '<resource id="2" src="" type="finish"></resource>'."\n".
                                             ['finishexport']);                              '</map>';
     if ($env{'form.finishexport'}) {              $env{'form.output'}=$newmapstr;
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
                                             ['archive','discussion']);                                                  'output',$1.$2);
               if ($result !~ m{^/uploaded/}) {
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');                  $fatal = 2;
         if (@exportitems == 0 && @discussions == 0) {              }
             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';              if ($fatal) {
         } else {                  return ($errtext,$fatal);
             my $now = time;              }
             my %symbs;          }
             my $manifestok = 0;   if ($url) {
             my $imsresources;              if (($caller eq 'londocs') &&
             my $tempexport;                  ($folder =~ /^default/)) {
             my $copyresult;                  if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);                      my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
             if ($manifestok) {                      my $cid = $coursedom.'_'.$coursenum;
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);                      $allmaps =
                 close($ims_manifest);                          &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
                                                                $chome,$cid);
 #Create zip file in prtspool                      $donechk = 1;
                 my $imszipfile = '/prtspool/'.                  }
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.                  if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
                    time.'_'.rand(1000000000).'.zip';                      &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
                 my $cwd = &Cwd::getcwd();                                           \%addedmaps,\%hierarchy,\%titles,$allmaps);
                 my $imszip = '/home/httpd/'.$imszipfile;                      $importuploaded = 1;
                 chdir $tempexport;                  } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");                      next if ($allmaps->{$url});
                 close(OUTPUT);                  }
                 chdir $cwd;              }
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      if (!$residx
                 if ($copyresult) {   || defined($LONCAPA::map::zombies[$residx])) {
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);   $residx = &LONCAPA::map::getresidx($url,$residx);
                 }   push(@LONCAPA::map::order, $residx);
             } else {      }
                 $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 $ext = 'false';
             }      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
         }      $name = &LONCAPA::map::qtunescape($name);
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));              if ($name eq '') {
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));                  $name = &LONCAPA::map::qtunescape(&mt('Web Page'));
         $r->print($outcome);              }
         $r->print(&Apache::loncommon::end_page());              if ($url =~ m{^/uploaded/$coursedom/$coursenum/((?:docs|supplemental)/(?:default|\d+))/new\.html$}) {
     } else {                  my $filepath = $1;
         my $display;                  my $fname = $name;
         $display = '<form name="exportdoc" method="post">'."\n";                  if ($fname =~ /^\W+$/) {
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');                      $fname = 'web';
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                  } else {
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.                      $fname =~ s/\W/_/g;
                     '<input type="button" value="check all" '.                  }
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.                  if (length($fname > 15)) {
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.                      $fname = substr($fname,0,14);
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.                  }
                     '<td>&nbsp;</td><td>&nbsp;</td>'.                  my $initialtext = &mt('Replace with your own content.');
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.                  my $newhtml = <<END;
                     '</b></legend><input type="button" value="check all"'.  <html>
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.  <head>
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.  <title>$name</title>
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.  </head>
                     '</tr></table>';  <body bgcolor="#ffffff">
         my $curRes;  $initialtext
         my $depth = 0;  </body>
         my $count = 0;  </html>
         my $boards = 0;  END
         my $startcount = 5;                  $env{'form.output'}=$newhtml;
         my %parent = ();                  my $result =
         my %children = ();                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
         my $lastcontainer = $startcount;                                                            'output',
         my @bgcolors = ('#F6F6F6','#FFFFFF');                                                            "$filepath/$residx/$fname.html");
         $display .= '<table cellspacing="0"><tr>'.                  if ($result =~ m{^/uploaded/}) {
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";                      $url = $result;
         if ($numdisc > 0) {                      if ($filepath =~ /^supplemental/) {
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";                          $name = time.'___&&&___'.$env{'user.name'}.'___&&&___'.
         }                                  $env{'user.domain'}.'___&&&___'.$name;
         $display.='&nbsp;</td></tr>';                      }
         while ($curRes = $it->next()) {                  } else {
             if (ref($curRes)) {                      return (&mt('Failed to save new web page.'),1);
                 $count ++;                  }
             }              }
             if ($curRes == $it->BEGIN_MAP()) {              $url  = &LONCAPA::map::qtunescape($url);
                 $depth++;      $LONCAPA::map::resources[$residx] =
                 $parent{$depth} = $lastcontainer;   join(':', ($name, $url, $ext, 'normal', 'res'));
             }   }
             if ($curRes == $it->END_MAP()) {      }
                 $depth--;      if ($importuploaded) {
                 $lastcontainer = $parent{$depth};          my %import_errors;
             }          my %updated = (
             if (ref($curRes)) {                            removefrommap => \%removefrommap,
                 my $symb = $curRes->symb();                            removeparam   => \%removeparam,
                 my $ressymb = $symb;                        );
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {          my ($result,$msgsarray,$lockerror) =
                     unless ($ressymb =~ m|adm/wrapper/adm|) {              &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';          if (keys(%import_errors) > 0) {
                     }              $fixuperrors =
                 }                  '<p span class="LC_warning">'."\n".
                 my $color = $count%2;                  &mt('The following files are either dependencies of a web page or references within a folder and/or composite page for which errors occurred during import:')."\n".
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".                  '<ul>'."\n";
                     '<input type="checkbox" name="archive" value="'.$count.'" ';              foreach my $key (sort(keys(%import_errors))) {
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {                  $fixuperrors .= '<li>'.$key.'</li>'."\n";
                     my $checkitem = $count + $boards + $startcount;              }
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';              $fixuperrors .= '</ul></p>'."\n";
                 }          }
                 $display .= ' />'."\n";          if (ref($msgsarray) eq 'ARRAY') {
                 for (my $i=0; $i<$depth; $i++) {              if (@{$msgsarray} > 0) {
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";                  $fixuperrors .= '<p class="LC_info">'.
                 }                                  join('<br />',@{$msgsarray}).
                 if ($curRes->is_sequence()) {                                  '</p>';
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";              }
                     $lastcontainer = $count + $startcount + $boards;          }
                 } elsif ($curRes->is_page()) {          if ($lockerror) {
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";              $fixuperrors .= '<p class="LC_error">'.
                     $lastcontainer = $count + $startcount + $boards;                              $lockerror.
                 }                              '</p>';
                 my $currelem = $count+$boards+$startcount;          }
                 $children{$parent{$depth}} .= $currelem.':';      }
                 $display .= '&nbsp;'.$curRes->title().'</td>';      my ($errtext,$fatal) =
                 if ($discussiontime{$ressymb} > 0) {          &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
                     $boards ++;      unless ($fatal) {
                     $currelem = $count+$boards+$startcount;          if ($folder =~ /^supplemental/) {
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";              &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
                 } else {              my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";                                              $folder.'.'.$container);
                 }          }
             }      }
         }      return ($errtext,$fatal,$fixuperrors);
         my $scripttag = qq|  }
 <script>  
   sub log_docs {
 function checkAll(field) {      return &Apache::lonnet::write_log('course','docslog',@_);
     if (field.length > 0) {  }
         for (i = 0; i < field.length; i++) {  
             field[i].checked = true ;  {
         }      my @oldresources=();
     } else {      my @oldorder=();
         field.checked = true      my $parmidx;
     }      my %parmaction=();
 }      my %parmvalue=();
                                                                                      my $changedflag;
 function uncheckAll(field) {  
     if (field.length > 0) {      sub snapshotbefore {
         for (i = 0; i < field.length; i++) {          @oldresources=@LONCAPA::map::resources;
             field[i].checked = false ;          @oldorder=@LONCAPA::map::order;
         }          $parmidx=undef;
     } else {          %parmaction=();
         field.checked = false ;          %parmvalue=();
     }          $changedflag=0;
 }      }
   
 function propagateCheck(item) {      sub remember_parms {
     if (document.exportdoc.elements[item].checked == true) {          my ($idx,$parameter,$action,$value)=@_;
         containerCheck(item)          $parmidx=$idx;
     }          $parmaction{$parameter}=$action;
 }          $parmvalue{$parameter}=$value;
           $changedflag=1;
 function containerCheck(item) {      }
     document.exportdoc.elements[item].checked = true  
     var numitems = $count + $boards + $startcount      sub log_differences {
     var parents = new Array(numitems)          my ($plain)=@_;
     for (var i=$startcount; i<numitems; i++) {          my %storehash=('folder' => $plain,
         parents[i] = new Array                         'currentfolder' => $env{'form.folder'});
     }          if ($parmidx) {
         |;             $storehash{'parameter_res'}=$oldresources[$parmidx];
              foreach my $parm (keys(%parmaction)) {
         foreach my $container (sort { $a <=> $b } (keys(%children))) {                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
             my @contents = split(/:/,$children{$container});                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
             for (my $i=0; $i<@contents; $i ++) {             }
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";          }
             }          my $maxidx=$#oldresources;
         }          if ($#LONCAPA::map::resources>$#oldresources) {
              $maxidx=$#LONCAPA::map::resources;
         $scripttag .= qq|          }
     if (parents[item].length > 0) {          for (my $idx=0; $idx<=$maxidx; $idx++) {
         for (var j=0; j<parents[item].length; j++) {             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
             containerCheck(parents[item][j])                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
         }                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
      }                  $changedflag=1;
 }             }
              if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
 </script>                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
         |;                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',                $changedflag=1;
  $scripttag));             }
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));          }
  $r->print($display.'</table>'.   $storehash{'maxidx'}=$maxidx;
                   '<p><input type="hidden" name="finishexport" value="1">'.          if ($changedflag) { &log_docs(\%storehash); }
                   '<input type="submit" name="exportcourse" value="'.      }
                   &mt('Export '.$type.' DOCS').'" /></p></form>');  }
     }  
 }  sub docs_change_log {
       my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
 sub create_ims_store {      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
     my ($now,$manifestok,$outcome,$tempexport) = @_;      my $js = '<script type="text/javascript">'."\n".
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';               '// <![CDATA['."\n".
     my $ims_manifest;               &Apache::loncommon::display_filter_js('docslog')."\n".
     if (!-e $$tempexport) {               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
         mkdir($$tempexport,0700);               &history_tab_js()."\n".
     }               &Apache::lonratedt::editscript('simple')."\n".
     $$tempexport .= '/'.$now;               '// ]]>'."\n".
     if (!-e $$tempexport) {               '</script>'."\n";
         mkdir($$tempexport,0700);      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
     }      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
     if (!-e $$tempexport) {      my %orderhash;
         mkdir($$tempexport,0700);      my $container='sequence';
     }      my $pathitem;
     if (!-e "$$tempexport/resources") {      if ($env{'form.folderpath'} =~ /\:1$/) {
         mkdir("$$tempexport/resources",0700);          $container='page';
     }      }
 # open manifest file      my $folderpath=$env{'form.folderpath'};
     my $manifest = '/imsmanifest.xml';      if ($folderpath eq '') {
     my $manifestfilename = $$tempexport.$manifest;          $folderpath = 'default&'.&escape(&mt('Main Content').':::::');
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      }
         $$manifestok=1;      $pathitem = '<input type="hidden" name="folderpath" value="'.
         print $ims_manifest                  &HTML::Entities::encode($folderpath,'<>&"').'" />';
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.      my $jumpto = $readfile;
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.      $jumpto =~ s{^/}{};
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.      my $tid = 1;
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.      if ($supplementalflag) {
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.          $tid = 2;
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      }
 '  <metadata>      my ($breadcrumbtrail) = 
     <schema></schema>          &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
     <imsmd:lom>      $r->print($breadcrumbtrail.
       <imsmd:general>                &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>                $readfile));
         <imsmd:title>      my %docslog=&Apache::lonnet::dump('nohist_docslog',
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
         </imsmd:title>                                        $env{'course.'.$env{'request.course.id'}.'.num'});
       </imsmd:general>  
     </imsmd:lom>      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
   </metadata>'."\n".  
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".      my %saveable_parameters = ('show' => 'scalar',);
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.      &Apache::loncommon::store_course_settings('docs_log',
 ' structure="hierarchical">'."\n".                                                \%saveable_parameters);
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'      &Apache::loncommon::restore_course_settings('docs_log',
     } else {                                                  \%saveable_parameters);
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'      if (!$env{'form.show'}) { $env{'form.show'}=10; }
 ;  # FIXME: internationalization seems wrong here
     }      my %lt=('hiddenresource' => 'Resources hidden',
     return $ims_manifest;      'encrypturl'     => 'URL hidden',
 }      'randompick'     => 'Randomly pick',
       'randomorder'    => 'Randomly ordered',
 sub build_package {      'set'            => 'set to',
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;      'del'            => 'deleted');
 # first iterator to look for dependencies      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                   $pathitem."\n".
     my $curRes;                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
     my $count = 0;                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
     my $depth = 0;      $r->print('<div class="LC_left_float">'.
     my $lastcontainer = 0;                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
     my %parent = ();                &makedocslogform($filter,1).
     my @dependencies = ();                '</fieldset></div><br clear="all" />');
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
     while ($curRes = $it->next()) {                &mt('After').'</th>'.
         if (ref($curRes)) {                &Apache::loncommon::end_data_table_header_row());
             $count ++;      my $shown=0;
         }      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
         if ($curRes == $it->BEGIN_MAP()) {   if ($env{'form.displayfilter'} eq 'currentfolder') {
             $depth++;      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
             $parent{$depth} = $lastcontainer;   }
         }          my @changes=keys(%{$docslog{$id}{'logentry'}});
         if ($curRes == $it->END_MAP()) {          if ($env{'form.displayfilter'} eq 'containing') {
             $depth--;      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
             $lastcontainer = $parent{$depth};   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
         }      foreach my $key (@changes) {
         if (ref($curRes)) {   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
             if ($curRes->is_sequence() || $curRes->is_page()) {      }
                 $lastcontainer = $count;      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
             }   }
             if (grep(/^$count$/,@$exportitems)) {          my $count = 0;
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);          my $time =
             }              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
         }          my $plainname =
     }              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
 # second iterator to build manifest and store resources                                            $docslog{$id}{'exe_udom'});
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);          my $about_me_link =
     $depth = 0;              &Apache::loncommon::aboutmewrapper($plainname,
     my $prevdepth;                                                 $docslog{$id}{'exe_uname'},
     $count = 0;                                                 $docslog{$id}{'exe_udom'});
     my $imsresources;          my $send_msg_link='';
     my $pkgdepth;          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
     while ($curRes = $it->next()) {               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
         if ($curRes == $it->BEGIN_MAP()) {              $send_msg_link ='<br />'.
             $prevdepth = $depth;                  &Apache::loncommon::messagewrapper(&mt('Send message'),
             $depth++;                                                     $docslog{$id}{'exe_uname'},
         }                                                     $docslog{$id}{'exe_udom'});
         if ($curRes == $it->END_MAP()) {          }
             $prevdepth = $depth;          $r->print(&Apache::loncommon::start_data_table_row());
             $depth--;          $r->print('<td>'.$time.'</td>
         }                         <td>'.$about_me_link.
                     '<br /><tt>'.$docslog{$id}{'exe_uname'}.
         if (ref($curRes)) {                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
             $count ++;                    $send_msg_link.'</td><td>'.
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
                 my $symb = $curRes->symb();          my $is_supp = 0; 
                 my $isvisible = 'true';          if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
                 my $resourceref;              $is_supp = 1;
                 if ($curRes->randomout()) {          }
                     $isvisible = 'false';  # Before
                 }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 unless ($curRes->is_sequence()) {      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
                 }      if ($oldname ne $newname) {
                 my $step = $prevdepth - $depth;                  my $shown = &LONCAPA::map::qtescape($oldname);
                 if (($step >= 0) && ($count > 1)) {                  if ($is_supp) {
                     while ($step >= 0) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                         print $ims_manifest "\n".'  </item>'."\n";                  }
                         $step --;                  $r->print($shown);
                     }      }
                 }   }
                 $prevdepth = $depth;   $r->print('<ul>');
    for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 my $itementry =              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.                  if ($is_supp) {
               '<title>'.$curRes->title().'</title>';                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                 print $ims_manifest "\n".$itementry;                  }
    $r->print('<li>'.$shown.'</li>');
                 unless ($curRes->is_sequence()) {      }
                     my $content_file;   }
                     my @hrefs = ();   $r->print('</ul>');
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);  # After
                     if ($content_file) {          $r->print('</td><td>');
                         $imsresources .= "\n".  
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                      '" type="webcontent" href="'.$content_file.'">'."\n".      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
                      '       <file href="'.$content_file.'" />'."\n";      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
                         foreach my $item (@hrefs) {      if ($oldname ne '' && $oldname ne $newname) {
                             $imsresources .=                  my $shown = &LONCAPA::map::qtescape($newname);
                      '        <file href="'.$item.'" />'."\n";                  if ($is_supp) {
                         }                      $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
                         if (grep(/^$count$/,@$discussions)) {                  }
                             my $ressymb = $symb;                  $r->print($shown);
                             my $mode;      }
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {   }
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {   $r->print('<ul>');
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                                 }              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
                                 $mode = 'board';                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
                             }                  if ($is_supp) {
                             my %extras = (                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                                           caller => 'imsexport',                  }
                                           tempexport => $tempexport.'/resources',                  $r->print('<li>'.$shown.'</li>');
                                           count => $count      }
                                          );   }
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);   $r->print('</ul>');
                         }   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                         $imsresources .= '    </resource>'."\n";      $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}) {
                 $pkgdepth = $depth;  # FIXME: internationalization seems wrong here
             }      $r->print('<li>'.
         }        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
     }    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
     while ($pkgdepth > 0) {        .'</li>');
         print $ims_manifest "    </item>\n";   }
         $pkgdepth --;      }
     }      $r->print('</ul>');
     my $resource_text = qq|   }
     </organization>  # End
   </organizations>          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
   <resources>          $shown++;
     $imsresources          if (!($env{'form.show'} eq &mt('all')
   </resources>                || $shown<=$env{'form.show'})) { last; }
 </manifest>      }
     |;      $r->print(&Apache::loncommon::end_data_table()."\n".
     print $ims_manifest $resource_text;                &makesimpleeditform($pathitem)."\n".
 }                '</div></div>');
       $r->print(&endContentScreen());
 sub get_dependencies {  }
     my ($exportitems,$parent,$depth,$dependencies) = @_;  
     if ($depth > 1) {  sub update_paste_buffer {
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {      my ($coursenum,$coursedom,$folder) = @_;
             push(@{$dependencies},$$parent{$depth});      my (@possibles,%removals,%cuts);
             if ($depth > 2) {      if ($env{'form.multiremove'}) {
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);          $env{'form.multiremove'} =~ s/,$//;
             }          map { $removals{$_} = 1; } split(/,/,$env{'form.multiremove'});
         }      }
     }      if (($env{'form.multicopy'}) || ($env{'form.multicut'})) {
 }          if ($env{'form.multicut'}) {
               $env{'form.multicut'} =~ s/,$//;
 sub process_content {              foreach my $item (split(/,/,$env{'form.multicut'})) {
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;                  unless ($removals{$item}) {
     my $content_type;                      $cuts{$item} = 1;
     my $message;                      push(@possibles,$item.':cut');
     my @uploads = ();                  }
     if ($curRes->is_sequence()) {              }
         $content_type = 'sequence';          }
     } elsif ($curRes->is_page()) {          if ($env{'form.multicopy'}) {
         $content_type = 'page'; # need to handle individual items in pages.              $env{'form.multicopy'} =~ s/,$//;
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {              foreach my $item (split(/,/,$env{'form.multicopy'})) {
         $content_type = 'syllabus';                  unless ($removals{$item} || $cuts{$item}) {
         my $contents = &Apache::imsexport::templatedpage($content_type);                      push(@possibles,$item.':copy'); 
         if ($contents) {                  }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              }
         }          }
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {      } elsif ($env{'form.markcopy'}) {
         $content_type = 'external';          @possibles = split(/,/,$env{'form.markcopy'});
         my $title = $curRes->title;      }
         my $contents =  &Apache::imsexport::external($symb,$title);  
         if ($contents) {      return if (@possibles == 0);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      return if (!defined($env{'form.copyfolder'}));
         }  
     } elsif ($symb =~ m-adm/navmaps$-) {      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
         $content_type =  'navmap';      $env{'form.copyfolder'});
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {      return if ($fatal);
         $content_type = 'simplepage';  
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);      my %curr_groups = &Apache::longroup::coursegroups();
         if ($contents) {  
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);  # Retrieve current paste buffer suffixes.
         }      my @currpaste = split(/,/,$env{'docs.markedcopies'});
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {      my (%pasteurls,@newpaste);
         $content_type = 'simpleproblem';  
         my $contents =  &Apache::imsexport::simpleproblem($symb);  # Construct identifiers for current contents of user's paste buffer
         if ($contents) {      if (@currpaste) {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          foreach my $suffix (@currpaste) {
         }               my $cid = $env{'docs.markedcopy_crs_'.$suffix};
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {               my $url = $env{'docs.markedcopy_url_'.$suffix};
         $content_type = 'examupload';               if (($cid =~ /^$match_domain(?:_)$match_courseid$/) &&
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {                   ($url ne '')) {
         $content_type = 'bulletinboard';                   $pasteurls{$cid.'_'.$url} = 1;
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);               }
         if ($contents) {          }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      }
         }  
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {  # Mark items for copying (skip any items already in user's paste buffer)
         $content_type = 'aboutme';      my %addtoenv;
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);                    
         if ($contents) {      foreach my $item (@possibles) {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          my ($orderidx,$cmd) = split(/:/,$item);
         }          next if ($orderidx =~ /\D/);
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {          next unless (($cmd eq 'cut') || ($cmd eq 'copy') || ($cmd eq 'remove'));
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');          my ($title,$url)=split(':',$LONCAPA::map::resources[$orderidx]);
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {          my %denied = &action_restrictions($coursenum,$coursedom,
         my $canedit = 0;                                            &LONCAPA::map::qtescape($url),
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {                                            $env{'form.folderpath'},\%curr_groups);
             $canedit= 1;          next if ($denied{'copy'});
         }          $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 # only include problem code where current user is author          next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$url}));
         if ($canedit) {          my ($suffix,$errortxt,$locknotfreed) =
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');              &new_timebased_suffix($env{'user.domain'},$env{'user.name'},'paste');
         } else {          push(@newpaste,$suffix);
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');          if ($locknotfreed) {
         }              return $locknotfreed;
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {              last;
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');          }
     }          if (&is_supplemental_title($title)) {
     if (@uploads > 0) {              &Apache::lonnet::appenv({'docs.markedcopy_supplemental_'.$suffix => $title});
         foreach my $item (@uploads) {      ($title) = &Apache::loncommon::parse_supplemental_title($title);
             my $uploadmsg = '';          }
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');  
             if ($uploadmsg) {          $addtoenv{'docs.markedcopy_title_'.$suffix} = $title,
                 $$copyresult .= $uploadmsg."\n";          $addtoenv{'docs.markedcopy_url_'.$suffix}   = $url,
             }          $addtoenv{'docs.markedcopy_cmd_'.$suffix}   = $cmd,
         }          $addtoenv{'docs.markedcopy_crs_'.$suffix}   = $env{'request.course.id'};
     }   
     if ($message) {          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
         $$copyresult .= $message."\n";              my $prefix = $1;
     }              my $subdir =$2;
 }              if ($subdir eq '') {
                   $subdir = $prefix;
 sub replicate_content {              }
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;              my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
     my ($map,$ind,$url);              &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
     if ($caller eq 'templateupload') {                                   \%hierarchy,\%titles,\%allmaps);
         $url = $symb;              if (ref($hierarchy{$url}) eq 'HASH') {
         $url =~ s#//#/#g;                  my ($nested,$nestednames);
     } else {                  &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);                  $nested =~ s/\&$//;
     }                  $nestednames =~ s/\Q___&&&___\E$//;
     my $content;                  if ($nested ne '') {
     my $filename;                      $addtoenv{'docs.markedcopy_nested_'.$suffix} = $nested;
     my $repstatus;                  }
     my $content_name;                  if ($nestednames ne '') {
     if ($url =~ m-/([^/]+)$-) {                      $addtoenv{'docs.markedcopy_nestednames_'.$suffix} = $nestednames;
         $filename = $1;                  }
         if (!-e $tempexport.'/resources') {              }
             mkdir($tempexport.'/resources',0700);          }
         }      }
         if (!-e $tempexport.'/resources/'.$count) {      if (@newpaste) {
             mkdir($tempexport.'/resources/'.$count,0700);          $addtoenv{'docs.markedcopies'} = join(',',(@currpaste,@newpaste));
         }      }
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;      &Apache::lonnet::appenv(\%addtoenv);
         my $copiedfile;      delete($env{'form.markcopy'});
         if ($copiedfile = Apache::File->new('>'.$destination)) {  }
             my $content;  
             if ($caller eq 'resource') {  sub recurse_uploaded_maps {
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';      my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);      if (ref($hierarchy->{$url}) eq 'HASH') {
                 $content = &Apache::lonnet::getfile($filepath);          my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
                 if ($content eq -1) {          my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
                     $$message = 'Could not copy file '.$filename;          my (@uploaded,@names,%shorter);
                 } else {          for (my $i=0; $i<@maps; $i++) {
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');              my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
                     $repstatus = 'ok';              if ($inner ne '') {
                 }                  push(@uploaded,$inner);
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {                  push(@names,&escape($titles[$i]));
                 my $rtncode;                  $shorter{$maps[$i]} = $inner;
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);              }
                 if ($repstatus eq 'ok') {          }
                     if ($url =~ /\.html?$/i) {          $$nestref .= "$dir:".join(',',@uploaded).'&';
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
                     }          foreach my $map (@maps) {
                 } else {              if ($shorter{$map} ne '') {
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
                 }              }
             } elsif ($caller eq 'noedit') {          }
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.      }
                 $repstatus = 'ok';      return;
                 $content = 'Not the owner of this resource';  }
             }  
             if ($repstatus eq 'ok') {  sub print_paste_buffer {
                 print $copiedfile $content;      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
             }      return if (!defined($env{'docs.markedcopies'}));
             close($copiedfile);  
         } else {      unless (($env{'form.pastemarked'}) || ($env{'form.clearmarked'})) {
             $$message = 'Could not open destination file for '.$filename."<br />\n";          return if ($env{'docs.markedcopies'} eq '');
         }      }
     } else {  
         $$message = 'Could not determine name of file for '.$symb."<br />\n";      my @currpaste = split(/,/,$env{'docs.markedcopies'});
     }      my ($pasteitems,@pasteable);
     if ($repstatus eq 'ok') {  
         $content_name = 'resources/'.$count.'/'.$filename;  # Construct identifiers for current contents of user's paste buffer
     }      foreach my $suffix (@currpaste) {
     return $content_name;          next if ($suffix =~ /\D/);
 }          my $cid = $env{'docs.markedcopy_crs_'.$suffix};
           my $url = $env{'docs.markedcopy_url_'.$suffix};
 sub extract_media {          if (($cid =~ /^$match_domain\_$match_courseid$/) &&
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;              ($url ne '')) {
     my ($dirpath,$container);              my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent,
     my %allfiles = ();                  $canpaste,$nopaste,$othercrs,$areachange);
     my %codebase = ();              my $extension = (split(/\./,$env{'docs.markedcopy_url_'.$suffix}))[-1];
     if ($url =~ m-(.*/)([^/]+)$-) {              if ($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
         $dirpath = $1;                  $is_external = 1;
         $container = $2;              }
     } else {              if ($folder =~ /^supplemental/) {
         $dirpath = $url;                  $canpaste = &supp_pasteable($env{'docs.markedcopy_url_'.$suffix});
         $container = '';                  unless ($canpaste) {
     }                      $nopaste = &mt('Paste into Supplemental Content unavailable.');
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);                  }
     foreach my $embed_file (keys(%allfiles)) {              } else {
         my $filename;                  $canpaste = 1;
         if ($embed_file =~ m#([^/]+)$#) {              }
             $filename = $1;              if ($canpaste) {
         } else {                  if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
             $filename = $embed_file;                      my $srcdom = $1;
         }                      my $srcnum = $2;
         my $newname = 'res/'.$filename;                      my $rem = $3;
         my ($rtncode,$embed_content,$repstatus);                      if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
         my $embed_url;                          $othercourse = 1;
         if ($embed_file =~ m-^/-) {                          if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
             $embed_url = $embed_file;           # points to absolute path                              if ($canpaste) {
         } else {                                  $othercrs = '<br />'.&mt('(from another course)');
             if ($embed_file =~ m-https?://-) {                              }
                 next;                           # points to url                          } else {
             } else {                              $canpaste = 0;
                 $embed_url = $dirpath.$embed_file;  # points to relative path                              $nopaste = &mt('Paste from another course unavailable.'); 
             }                          }
         }                      }
         if ($caller eq 'resource') {                      if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                            my $prefix = $1;
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);                          $parent = $2;
             $embed_content = &Apache::lonnet::getfile($embed_path);                          if ($folder !~ /^\Q$prefix\E/) {
             unless ($embed_content eq -1) {                              $areachange = 1;
                 $repstatus = 'ok';                          }
             }                          $is_uploaded_map = 1;
         } elsif ($caller eq 'uploaded') {                      }
                              }
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);              }
         }              if ($canpaste) {
         if ($repstatus eq 'ok') {                 push(@pasteable,$suffix);
             my $destination = $tempexport.'/resources/'.$count.'/res';              }
             if (!-e "$destination") {              my $buffer;
                 mkdir($destination,0755);              if ($is_external) {
             }                  $buffer = &mt('External Resource').': '.
             $destination .= '/'.$filename;                      &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
             my $copiedfile;                      &LONCAPA::map::qtescape($url).')';
             if ($copiedfile = Apache::File->new('>'.$destination)) {              } else {
                 print $copiedfile $embed_content;                  my $icon = &Apache::loncommon::icon($extension);
                 push(@{$href},'resources/'.$count.'/res/'.$filename);                  if ($extension eq 'sequence' &&
                 my $attrib_regexp = '';                      $url =~ m{/default_\d+\.sequence$}x) {
                 if (@{$allfiles{$embed_file}} > 1) {                      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});                      $icon .= '/navmap.folder.closed.gif';
                 } else {                  }
                     $attrib_regexp = $allfiles{$embed_file}[0];                  $buffer = '<img src="'.$icon.'" alt="" class="LC_icon" />'.
                 }                            ': '.
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;                            &Apache::loncommon::parse_supplemental_title(
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {                               &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}));
                     $$content =~ s#\Q$embed_file\E#$newname#gi;              }
                 }              $pasteitems .= '<div class="LC_left_float">';
             }              my ($options,$onclick);
         } else {              if (($canpaste) && (!$areachange) && (!$othercourse) &&
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";                  ($env{'docs.markedcopy_cmd_'.$suffix} eq 'cut')) {
         }                  if (($is_uploaded_map) ||
     }                      ($url =~ /(bulletinboard|smppg)$/) ||
     return;                      ($url =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
 }                      $options = &paste_options($suffix,$is_uploaded_map,$parent);
                       $onclick= 'onclick="showOptions(this,'."'$suffix'".');" ';
 sub store_template {                  }
     my ($contents,$tempexport,$count,$content_type) = @_;              }
     if ($contents) {              $pasteitems .= '<label><input type="checkbox" name="pasting" id="pasting_'.$suffix.'" value="'.$suffix.'" '.$onclick.'/>'.$buffer.'</label>';
         if ($tempexport) {              if ($nopaste) {
             if (!-e $tempexport.'/resources') {                   $pasteitems .= $nopaste;   
                 mkdir($tempexport.'/resources',0700);              } else {
             }                  if ($othercrs) {
             if (!-e $tempexport.'/resources/'.$count) {                      $pasteitems .= $othercrs;
                 mkdir($tempexport.'/resources/'.$count,0700);                  }
             }                  if ($options) {
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';                      $pasteitems .= $options;
             my $storetemplate;                  }
             if ($storetemplate = Apache::File->new('>'.$destination)) {              }
                 print $storetemplate $contents;              $pasteitems .= '</div>';
                 close($storetemplate);          }
             }      }
             if ($content_type eq 'external') {      if ($pasteitems eq '') {
                 return 'resources/'.$count.'/'.$content_type.'.html';          &Apache::lonnet::delenv('docs.markedcopies');
             } else {      }
                 return 'resources/'.$count.'/'.$content_type.'.xml';      my ($pasteform,$form_start,$buttons,$form_end);
             }      if ($pasteitems) {
         }          $pasteitems .= '<div style="padding:0;clear:both;margin:0;border:0"></div>';
     }          $form_start = '<form name="pasteform" action="/adm/coursedocs" method="post" onsubmit="return validateClipboard();">';
 }          if (@pasteable) {
               $buttons = '<input type="submit" name="pastemarked" value="'.&mt('Paste selected').'" />'.('&nbsp;'x2);
           }
 sub group_import {          $buttons .= '<input type="submit" name="clearmarked" value="'.&mt('Clear selected').'" />'.
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;                      '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
           $form_end = '</form>';
     while (@files) {      } else {
  my ($name, $url, $residx) = @{ shift(@files) };          $pasteitems = &mt('Clipboard is empty');
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})      }
      && ($caller eq 'londocs')      $r->print($form_start
      && (!&Apache::lonnet::stat_file($url))) {               .'<fieldset>'
                    .'<legend>'.&mt('Clipboard').('&nbsp;' x2).$buttons.'</legend>'
             my $errtext = '';               .$pasteitems
             my $fatal = 0;               .'</fieldset>'
             my $newmapstr = '<map>'."\n".               .$form_end);
                             '<resource id="1" src="" type="start"></resource>'."\n".  }
                             '<link from="1" to="2" index="1"></link>'."\n".  
                             '<resource id="2" src="" type="finish"></resource>'."\n".  sub paste_options {
                             '</map>';      my ($suffix,$is_uploaded_map,$parent) = @_;
             $env{'form.output'}=$newmapstr;      my ($copytext,$movetext);
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,      if ($is_uploaded_map) {
                                                 'output',$1.$2);          $copytext = &mt('Copy to new folder');
             if ($result != m|^/uploaded/|) {          $movetext = &mt('Move old');
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';      } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /bulletinboard$/) {
                 $fatal = 2;          $copytext = &mt('Copy to new board');
             }          $movetext = &mt('Move (not posts)');
             if ($fatal) {      } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /smppg$/) {
                 return ($errtext,$fatal);          $copytext = &mt('Copy to new page');
             }          $movetext = &mt('Move');
         }      } else {
  if ($url) {          $copytext = &mt('Copy to new file');
     if (!$residx          $movetext = &mt('Move');
  || defined($LONCAPA::map::zombies[$residx])) {      }
  $residx = &LONCAPA::map::getresidx($url,$residx);      my $output = '<br />'.
  push(@LONCAPA::map::order, $residx);                   '<span id="pasteoptionstext_'.$suffix.'" class="LC_fontsize_small LC_nobreak"></span>'.
     }                   '<div id="pasteoptions_'.$suffix.'" class="LC_dccid" style="display:none;"><span class="LC_nobreak">'.('&nbsp;'x 4).
     my $ext = 'false';                   '<label>'.
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }                   '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="new" checked="checked" />'.
     $url  = &LONCAPA::map::qtunescape($url);                   $copytext.'</label></span>'.('&nbsp;'x2).' '.
     $name = &LONCAPA::map::qtunescape($name);                   '<span class="LC_nobreak"><label>'.
     $LONCAPA::map::resources[$residx] =                   '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="move" />'.
  join(':', ($name, $url, $ext, 'normal', 'res'));                   $movetext.'</label></span>';
  }      if (($is_uploaded_map) && ($env{'docs.markedcopy_nested_'.$suffix})) {
     }          $output .= '<br /><fieldset><legend>'.&mt('Folder to paste contains sub-folders').
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);                     '</legend><table border="0">';
 }          my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
           my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames_'.$suffix});
 sub breadcrumbs {          my $lastdir = $parent;
     my ($where,$allowed,$type)=@_;          my %depths = (
     &Apache::lonhtmlcommon::clear_breadcrumbs();                         $lastdir => 0,
     my (@folders);                       );
     if ($env{'form.pagepath'}) {          my (%display,%deps);
         @folders = split('&',$env{'form.pagepath'});          for (my $i=0; $i<@pastemaps; $i++) {
     } else {              ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
         @folders=split('&',$env{'form.folderpath'});              my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
     }              my @subfolders = split(/,/,$subfolderstr);
     my $folderpath;              $deps{$lastdir} = \@subfolders;
     my $cpinfo='';              my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
     my $plain='';              my $depth = $depths{$lastdir} + 1;
     my $randompick=-1;              my $offset = int($depth * 4);
     my $isencrypted=0;              my $indent = ('&nbsp;' x $offset);
     my $ishidden=0;              for (my $j=0; $j<@subfolders; $j++) {
     my $is_random_order=0;                  $depths{$subfolders[$j]} = $depth;
     while (@folders) {                  $display{$subfolders[$j]} =
  my $folder=shift(@folders);                      '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
     my $foldername=shift(@folders);                      '<td><label>'.
  if ($folderpath) {$folderpath.='&';}                      '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
  $folderpath.=$folder.'&'.$foldername;                      '<label>'.
  my $url='/adm/coursedocs?folderpath='.                      '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="move" />'.
     &escape($folderpath);                      &mt('Move old').'</label>'.
     my $name=&unescape($foldername);                      '</td></tr>';
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername               }
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;          }
     if ($1 ne '') {          &recurse_print(\$output,$parent,\%deps,\%display);
                $randompick=$1;          $output .= '</table></fieldset>';
             } else {      }
                $randompick=-1;      $output .= '</div>';
             }      return $output;
             if ($2) { $ishidden=1; }  }
             if ($3) { $isencrypted=1; }  
     if ($4 ne '') { $is_random_order = 1; }  sub recurse_print {
             if ($folder eq 'supplemental') {      my ($outputref,$dir,$deps,$display) = @_;
                 if ($allowed) {      $$outputref .= $display->{$dir}."\n";
                     $name = &mt('Supplemental '.$type.' Documents');      if (ref($deps->{$dir}) eq 'ARRAY') {
                 } else {          foreach my $subdir (@{$deps->{$dir}}) {
                     $name = &mt($type.' Documents');              &recurse_print($outputref,$subdir,$deps,$display);
                 }          }
             }      }
     &Apache::lonhtmlcommon::add_breadcrumb(  }
       {'href'=>$url.$cpinfo,  
        'title'=>$name,  sub supp_pasteable {
        'text'=>'<font size="+1">'.      my ($url) = @_;
    $name.'</font>',      if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
        'no_mt'=>1,          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
        });          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
  $plain.=$name.' &gt; ';          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
     }          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
     $plain=~s/\&gt\;\s*$//;          return 1;
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',      }
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);      return;
 }  }
   
 sub log_docs {  sub paste_popup_js {
     return &Apache::lonnet::instructor_log('docslog',@_);      my %lt = &Apache::lonlocal::texthash(
 }                                            show => 'Show Options',
                                             hide => 'Hide Options',
 {                                            none => 'No items selected from clipboard.',
     my @oldresources=();                                          );
     my @oldorder=();      return <<"END";
     my $parmidx;  
     my %parmaction=();  function showPasteOptions(suffix) {
     my %parmvalue=();      document.getElementById('pasteoptions_'+suffix).style.display='block';
     my $changedflag;      document.getElementById('pasteoptionstext_'+suffix).innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:hidePasteOptions(\\''+suffix+'\\');" class="LC_menubuttons_link">$lt{'hide'}</a>';
       return;
     sub snapshotbefore {  }
         @oldresources=@LONCAPA::map::resources;  
         @oldorder=@LONCAPA::map::order;  function hidePasteOptions(suffix) {
         $parmidx=undef;      document.getElementById('pasteoptions_'+suffix).style.display='none';
         %parmaction=();      document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
         %parmvalue=();      return;
         $changedflag=0;  }
     }  
   function showOptions(caller,suffix) {
     sub remember_parms {      if (document.getElementById('pasteoptionstext_'+suffix)) {
         my ($idx,$parameter,$action,$value)=@_;          if (caller.checked) {
         $parmidx=$idx;              document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
         $parmaction{$parameter}=$action;          } else {
         $parmvalue{$parameter}=$value;              document.getElementById('pasteoptionstext_'+suffix).innerHTML ='';
         $changedflag=1;          }
     }          if (document.getElementById('pasteoptions_'+suffix)) {
               document.getElementById('pasteoptions_'+suffix).style.display='none';
     sub log_differences {          }
         my ($plain)=@_;      }
         my %storehash=('folder' => $plain,      return;
                        'currentfolder' => $env{'form.folder'});  }
         if ($parmidx) {  
            $storehash{'parameter_res'}=$oldresources[$parmidx];  function validateClipboard() {
            foreach my $parm (keys(%parmaction)) {      var numchk = 0;
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};      if (document.pasteform.pasting.length > 1) {
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};          for (var i=0; i<document.pasteform.pasting.length; i++) {
            }              if (document.pasteform.pasting[i].checked) {
         }                  numchk ++;
         my $maxidx=$#oldresources;              }
         if ($#LONCAPA::map::resources>$#oldresources) {          }
            $maxidx=$#LONCAPA::map::resources;      } else {
         }          if (document.pasteform.pasting.type == 'checkbox') {
         for (my $idx=0; $idx<=$maxidx; $idx++) {              if (document.pasteform.pasting.checked) {
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {                  numchk ++; 
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];              } 
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];          }
               $changedflag=1;      }
            }      if (numchk > 0) { 
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {          return true;
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];      } else {
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];          alert("$lt{'none'}");
               $changedflag=1;          return false;
            }      }
         }  }
  $storehash{'maxidx'}=$maxidx;  
         if ($changedflag) { &log_docs(\%storehash); }  END
     }  
 }  }
   
   sub do_paste_from_buffer {
       my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
   
   # Array of items in paste buffer
 sub docs_change_log {      my (@currpaste,%pastebuffer,%allerrors);
     my ($r)=@_;      @currpaste = split(/,/,$env{'docs.markedcopies'});
     my $folder=$env{'form.folder'};  
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));  # Early out if paste buffer is empty
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));      if (@currpaste == 0) {
     my %docslog=&Apache::lonnet::dump('nohist_docslog',          return ();
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},      } 
                                       $env{'course.'.$env{'request.course.id'}.'.num'});      map { $pastebuffer{$_} = 1; } @currpaste;
   
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }  # Array of items selected items to paste
       my @reqpaste = &Apache::loncommon::get_env_multiple('form.pasting');
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.  
               '<input type="hidden" name="docslog" value="1" />');  # Early out if nothing selected to paste
       if (@reqpaste == 0) {
     my %saveable_parameters = ('show' => 'scalar',);          return();
     &Apache::loncommon::store_course_settings('docs_log',      }
                                               \%saveable_parameters);      my @topaste;
     &Apache::loncommon::restore_course_settings('docs_log',      foreach my $suffix (@reqpaste) {
                                                 \%saveable_parameters);          next if ($suffix =~ /\D/);
     if (!$env{'form.show'}) { $env{'form.show'}=10; }          next unless (exists($pastebuffer{$suffix}));
     my %lt=('hiddenresource' => 'Resources hidden',          push(@topaste,$suffix);
     'encrypturl'     => 'URL hidden',      }
     'randompick'     => 'Randomly pick',  
     'randomorder'    => 'Randomly ordered',  # Early out if nothing available to paste
     'set'            => 'set to',      if (@topaste == 0) {
     'del'            => 'deleted');          return();
     $r->print(&Apache::loncommon::display_filter().      }
               '<input type="hidden" name="folder" value="'.$folder.'" />'.  
               '<input type="submit" value="'.&mt('Display').'" /></form>');      my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%duplicate,
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().          %prefixchg,%srcdom,%srcnum,%marktomove,$save_err,$lockerrors,$allresult);
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.  
               &mt('After').'</th>'.      foreach my $suffix (@topaste) {
               &Apache::loncommon::end_data_table_header_row());          my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
     my $shown=0;  # Supplemental content may only include certain types of content
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {  # Early out if pasted content is not supported in Supplemental area
  if ($env{'form.displayfilter'} eq 'currentfolder') {          if ($folder =~ /^supplemental/) {
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }              unless (&supp_pasteable($url)) {
  }                  $notinsupp{$suffix} = 1;
         my @changes=keys(%{$docslog{$id}{'logentry'}});                  next;
         if ($env{'form.displayfilter'} eq 'containing') {              }
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.          }
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});          if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/}) {
     foreach my $key (@changes) {              my $srcd = $1;
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};              my $srcn = $2;
     }  # When paste buffer was populated using an active role in a different course
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }          # check for mdc privilege in the course from which the resource was pasted
  }              if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
         my $count = 0;                  unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
         my $time =                      $notincrs{$suffix} = 1;
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});                      next;
         my $plainname =                  }
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},              }
                                           $docslog{$id}{'exe_udom'});              $srcdom{$suffix} = $srcd;
         my $about_me_link =              $srcnum{$suffix} = $srcn;
             &Apache::loncommon::aboutmewrapper($plainname,          }
                                                $docslog{$id}{'exe_uname'},  
                                                $docslog{$id}{'exe_udom'});          push(@dopaste,$suffix);
         my $send_msg_link='';          if ($url=~/\.(page|sequence)$/) {
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})              $is_map{$suffix} = 1; 
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {          }
             $send_msg_link ='<br />'.  
                 &Apache::loncommon::messagewrapper(&mt('Send message'),          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/([^/]+)}) {
                                                    $docslog{$id}{'exe_uname'},              my $oldprefix = $1;
                                                    $docslog{$id}{'exe_udom'});  # When pasting content from Main Content to Supplemental Content and vice versa 
         }  # URLs will contain different paths (which depend on whether pasted item is
         $r->print(&Apache::loncommon::start_data_table_row());  # a folder/page or a document.   
         $r->print('<td>'.$time.'</td>              if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
                        <td>'.$about_me_link.                  $prefixchg{$suffix} = 'docstosupp';
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.              } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.                  $prefixchg{$suffix} = 'supptodocs';
                   $send_msg_link.'</td><td>'.              }
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');  
 # Before  # If pasting an uploaded map, get list of contained uploaded maps.
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              if ($env{'docs.markedcopy_nested_'.$suffix}) {
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                  my @nested;
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];                  my ($type) = ($oldprefix =~ /^(default|supplemental)/);
     if ($oldname ne $newname) {                  my @items = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
  $r->print(&LONCAPA::map::qtescape($oldname));                  my @deps = map { /\d+:([\d,]+$)/ } @items;
     }                  foreach my $dep (@deps) {
  }                      if ($dep =~ /,/) {
  $r->print('<ul>');                          push(@nested,split(/,/,$dep));
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                      } else {
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {                          push(@nested,$dep);
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');                      }
     }                  }
  }                  foreach my $item (@nested) {
  $r->print('</ul>');                      if ($env{'form.docs.markedcopy_'.$suffix.'_'.$item} eq 'move') {
 # After                          push(@{$marktomove{$suffix}},$type.'_'.$item);
         $r->print('</td><td>');                      }
                   }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              }
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];          }
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];      }
     if ($oldname ne '' && $oldname ne $newname) {  
  $r->print(&LONCAPA::map::qtescape($newname));  # Early out if nothing available to paste
     }      if (@dopaste == 0) {
  }                  return ();
  $r->print('<ul>');      }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {  
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {  # Populate message hash and hashes used for main content <=> supplemental content
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');  # changes    
     }  
  }      %msgs = &Apache::lonlocal::texthash (
  $r->print('</ul>');                  notinsupp => 'Paste failed: content type is not supported within Supplemental Content',
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {                  notincrs  => 'Paste failed: Item is from a different course which you do not have rights to edit.',
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');                  duplicate => 'Paste failed: only one instance of a particular published sequence or page is allowed within each course.',
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {              );
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {  
     $r->print('<li>'.      %before = (
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',                   docstosupp => {
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})                                     map => 'default',
       .'</li>');                                     doc => 'docs',
  }                                 },
     }                   supptodocs => {
     $r->print('</ul>');                                     map => 'supplemental',
  }                                     doc => 'supplemental',
 # End                                 },
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());                );
         $shown++;  
         if (!($env{'form.show'} eq &mt('all')      %after = (
               || $shown<=$env{'form.show'})) { last; }                   docstosupp => {
     }                                     map => 'supplemental',
     $r->print(&Apache::loncommon::end_data_table());                                     doc => 'supplemental'
 }                                 },
                    supptodocs => {
 sub update_paste_buffer {                                     map => 'default',
     my ($coursenum,$coursedom) = @_;                                     doc => 'docs',
                                  },
     return if (!defined($env{'form.markcopy'}));               );
     return if (!defined($env{'form.copyfolder'}));  
     return if ($env{'form.markcopy'} < 0);  # Retrieve information about all course maps in main content area 
   
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,      my $allmaps = {};
     $env{'form.copyfolder'});      if ($folder =~ /^default/) {
              $allmaps =
     return if ($fatal);              &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
                                                    $env{"course.$env{'request.course.id'}.home"},
 # Mark for copying                                                   $env{'request.course.id'});
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);      }
     if (&is_supplemental_title($title)) {  
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});      my (@toclear,%mapurls,%lockerrs,%msgerrs,%results);
  ($title) = &parse_supplemental_title($title);  
     } elsif ($env{'docs.markedcopy_supplemental'}) {  # Loop over the items to paste
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');      foreach my $suffix (@dopaste) {
     }  # Maps need to be copied first
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};          my (%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
               %dbcopies,%zombies,%params,%docmoves,%mapmoves,%mapchanges,%newsubdir,
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,              %newurls,%tomove);
     'docs.markedcopy_url'   => $url});          if (ref($marktomove{$suffix}) eq 'ARRAY') {
     delete($env{'form.markcopy'});              map { $tomove{$_} = 1; } @{$marktomove{$suffix}};
 }          }
           my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
 sub print_paste_buffer {          my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
     my ($r,$container) = @_;          my $oldurl = $url;
     return if (!defined($env{'docs.markedcopy_url'}));          if ($is_map{$suffix}) {
   # If pasting a map, check if map contains other maps
     $r->print(<<ENDPASTE);              my (%hierarchy,%titles);
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>              &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
 ENDPASTE                                   \%addedmaps,\%hierarchy,\%titles,$allmaps);
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');              if ($url=~ m{^/uploaded/}) {
                   my $newurl;
     my $type;                  unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {                      ($newurl,my $error) = 
  $type = &mt('External Resource');                          &get_newmap_url($url,$folder,$prefixchg{$suffix},$coursedom,
  $r->print($type.': '.                                          $coursenum,$srcdom{$suffix},$srcnum{$suffix},
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.                                          \$title,$allmaps,\%newurls);
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');                      if ($error) {
     }  else {                          $allerrors{$suffix} = $error;
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];                          next;
  my $icon = &Apache::loncommon::icon($extension);                      }
  if ($extension eq 'sequence' &&                      if ($newurl ne '') {
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {                          if ($newurl ne $url) {
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));                              if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
     $icon .= '/folder_closed.gif';                                  $newsubdir{$url} = $1;
  }                              }
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';                              $mapchanges{$url} = 1;
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));                          }
     }                      }
     if ($container eq 'page') {                  }
  $r->print('                  if (($srcdom{$suffix} ne $coursedom) ||
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />                      ($srcnum{$suffix} ne $coursenum) ||
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />                      ($prefixchg{$suffix}) || (($newurl ne '') && ($newurl ne $url))) {
 ');                      unless (&url_paste_fixups($url,$folder,$prefixchg{$suffix},
     } else {                                                $coursedom,$coursenum,$srcdom{$suffix},
  $r->print('                                                $srcnum{$suffix},$allmaps,\%rewrites,
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />                                                \%retitles,\%copies,\%dbcopies,
 ');                                                \%zombies,\%params,\%mapmoves,
     }                                                \%mapchanges,\%tomove,\%newsubdir,
     $r->print('</p></form>');                                                \%newurls)) {
 }                          $mapmoves{$url} = 1;
                       }
 sub do_paste_from_buffer {                      $url = $newurl;
     my ($coursenum,$coursedom,$folder) = @_;                  } elsif ($env{'docs.markedcopy_nested_'.$suffix}) {
                       &url_paste_fixups($url,$folder,$prefixchg{$suffix},$coursedom,
     if (!$env{'form.pastemarked'}) {                                        $coursenum,$srcdom{$suffix},$srcnum{$suffix},
         return;                                        $allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
     }                                        \%zombies,\%params,\%mapmoves,\%mapchanges,
                                         \%tomove,\%newsubdir,\%newurls); 
 # paste resource to end of list                  }
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});              } elsif ($url=~m {^/res/}) {
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});  # published map can only exists once, so remove from paste buffer when done
 # Maps need to be copied first                  push(@toclear,$suffix);
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {  # if pasting published map (main content area only) check map not already in course
  $title=&mt('Copy of').' '.$title;                  if ($folder =~ /^default/) {
  my $newid=$$.int(rand(100)).time;                      if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);                          $duplicate{$suffix} = 1; 
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {                          next;
             my $path = $1;                      }
             my $prefix = $2;                  }
             my $ancestor = $3;              }
             if (length($ancestor) > 10) {          }
                 $ancestor = substr($ancestor,-10,10);          if ($url=~ m{/(bulletinboard|smppg)$}) {
             }              my $prefix = $1;
             $oldid = $path.$prefix.$ancestor;              #need to copy the db contents to a new one, unless this is a move.
         }              my %info = (
         my $counter = 0;                           src  => $url,
         my $newurl=$oldid.$newid.'.'.$ext;                           cdom => $coursedom,
         my $is_unique = &uniqueness_check($newurl);                           cnum => $coursenum,
         while (!$is_unique && $counter < 100) {              );
             $counter ++;              unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
             $newid ++;                  my (%lockerr,$msg); 
             $newurl = $oldid.$newid;                  my ($newurl,$result,$errtext) =
             $is_unique = &uniqueness_check($newurl);                      &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
         }                  if ($result eq 'ok') {
         if (!$is_unique) {                      $url = $newurl;
             if ($url=~/\.page$/) {                      $title=&mt('Copy of').' '.$title;
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');                  } else {
             } else {                      if ($prefix eq 'smppg') {
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');                          $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
             }                      } elsif ($prefix eq 'bulletinboard') {
         }                          $msg = &mt('Paste failed: An error occurred when copying the bulletin board.').' '.$errtext;
  my $storefn=$newurl;                      }
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};                      $results{$suffix} = $result;
  my $paste_map_result =                      $msgerrs{$suffix} = $msg;
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,                      $lockerrs{$suffix} = $lockerr{$prefix}; 
        &Apache::lonnet::getfile($url));                      next;
         if ($paste_map_result eq '/adm/notfound.html') {          }
             if ($url=~/\.page$/) {                  if ($lockerr{$prefix}) {
                 return &mt('Paste failed: an error occurred saving the composite page');                      $lockerrs{$suffix} = $lockerr{$prefix};
             } else {                  }
                 return &mt('Paste failed: an error occurred saving the folder');              }
             }          }
         }          $title = &LONCAPA::map::qtunescape($title);
  $url = $newurl;          my $ext='false';
     }          if ($url=~m{^http(|s)://}) { $ext='true'; }
 # published maps can only exists once, so remove it from paste buffer when done          if ($env{'docs.markedcopy_supplemental_'.$suffix}) {
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {              if ($folder !~ /^supplemental/) {
  &Apache::lonnet::delenv('docs\\.markedcopy');                  (undef,undef,$title) =
     }                      &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental_'.$suffix});
     if ($url=~ m{/smppg$}) {              }
  my $db_name = &Apache::lonsimplepage::get_db_name($url);          } else {
  if ($db_name =~ /^smppage_/) {              if ($folder=~/^supplemental/) {
     #simple pages, need to copy the db contents to a new one.                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);                         $env{'user.domain'}.'___&&&___'.$title;
     my $now = time();              }
     $db_name =~ s{_\d*$ }{_$now}x;          }
     my $result=&Apache::lonnet::put($db_name,\%contents,  
     $coursedom,$coursenum);  # For uploaded files (excluding pages/sequences) path in copied file is changed
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;  # if paste is from Main to Supplemental (or vice versa), or if pasting between
     $title=&mt('Copy of').' '.$title;  # courses.
  }  
     }          unless ($is_map{$suffix}) {
     $title = &LONCAPA::map::qtunescape($title);              my $newidx;
     my $ext='false';  # Now insert the URL at the bottom
     if ($url=~m{^http(|s)://}) { $ext='true'; }              $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
     $url       = &LONCAPA::map::qtunescape($url);              if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
 # Now insert the URL at the bottom                  my $relpath = $1;
     my $newidx = &LONCAPA::map::getresidx($url);                  if ($relpath ne '') {
     if ($env{'docs.markedcopy_supplemental'}) {                      my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
         if ($folder =~ /^supplemental/) {                      my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
             $title = $env{'docs.markedcopy_supplemental'};                      my $newprefix = $newloc;
         } else {                      if ($newloc eq 'default') {
             (undef,undef,$title) =                          $newprefix = 'docs';
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});                      }
         }                      if ($newdocsdir eq '') {
     } else {                          $newdocsdir = 'default';
         if ($folder=~/^supplemental/) {                      }
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                      if (($prefixchg{$suffix}) ||
                   $env{'user.domain'}.'___&&&___'.$title;                          ($srcdom{$suffix} ne $coursedom) || 
         }                          ($srcnum{$suffix} ne $coursenum) ||
     }                          ($env{'form.docs.markedcopy_options_'.$suffix} ne 'move')) {
                           my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';                          $url =
     push(@LONCAPA::map::order, $newidx);                              &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
     return 'ok';                                                                 &Apache::lonnet::getfile($oldurl));
 # Store the result                          if ($url eq '/adm/notfound.html') {
 }                              $msgs{$suffix} = &mt('Paste failed: an error occurred saving the file.');
                               next;
 sub uniqueness_check {                          } else {
     my ($newurl) = @_;                              my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
     my $unique = 1;                              $newsubpath =~ s{/+$}{/};
     foreach my $res (@LONCAPA::map::order) {                              $docmoves{$oldurl} = $newsubpath;
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                          }
         $url=&LONCAPA::map::qtescape($url);                      }
         if ($newurl eq $url) {                  }
             $unique = 0;              }
             last;                  $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
         }                                                ':'.$ext.':normal:res';
     }              push(@LONCAPA::map::order,$newidx);
     return $unique;  # Store the result
 }              my ($errtext,$fatal) =
                   &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 my %parameter_type = ( 'randompick'     => 'int_pos',              if ($fatal) {
        'hiddenresource' => 'string_yesno',                  $save_err .= $errtext;
        'encrypturl'     => 'string_yesno',                  $allresult = 'fail';
        'randomorder'    => 'string_yesno',);              }
 my $valid_parameters_re = join('|',keys(%parameter_type));          }
 # set parameters  
 sub update_parameter {  # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
           unless ($allresult eq 'fail') {
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);              my %updated = (
                               rewrites      => \%rewrites,
     my $which = $env{'form.changeparms'};                              zombies       => \%zombies,
     my $idx = $env{'form.setparms'};                              removefrommap => \%removefrommap,
     if ($env{'form.'.$which.'_'.$idx}) {                              removeparam   => \%removeparam,
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}                              dbcopies      => \%dbcopies,
                                      : 'yes';                              retitles      => \%retitles,
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,                            );
       $parameter_type{$which});              my %info = (
  &remember_parms($idx,$which,'set',$value);                             newsubdir => \%newsubdir,
     } else {                             params    => \%params,
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);                         );
               if ($prefixchg{$suffix}) {
  &remember_parms($idx,$which,'del');                  $info{'before'} = $before{$prefixchg{$suffix}};
     }                  $info{'after'} = $after{$prefixchg{$suffix}};
     return 1;              }
 }              my %moves = (
                              copies   => \%copies,
                              docmoves => \%docmoves,
 sub handle_edit_cmd {                             mapmoves => \%mapmoves,
     my ($coursenum,$coursedom) =@_;                          );
               (my $result,$msgs{$suffix},my $lockerror) =
     my ($cmd,$idx)=split('_',$env{'form.cmd'});                  &apply_fixups($folder,$is_map{$suffix},$coursedom,$coursenum,$errors,
                                 \%updated,\%info,\%moves,$prefixchg{$suffix},$oldurl,
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];                                $url,'paste');
     my ($title, $url, @rrest) = split(':', $ratstr);              $lockerrors .= $lockerror;
               if ($result eq 'ok') {
     if ($cmd eq 'del') {                  if ($is_map{$suffix}) {
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&                      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {                                                      $folder.'.'.$container);
     &Apache::lonnet::removeuploadedurl($url);                      if ($fatal) {
  } else {                          $allresult = 'failread';
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                      } else {
  }                          if ($#LONCAPA::map::order<1) {
  splice(@LONCAPA::map::order, $idx, 1);                              my $idx=&LONCAPA::map::getresidx();
                               if ($idx<=0) { $idx=1; }
     } elsif ($cmd eq 'cut') {                              $LONCAPA::map::order[0]=$idx;
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                              $LONCAPA::map::resources[$idx]='';
  splice(@LONCAPA::map::order, $idx, 1);                          }
                           my $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
     } elsif ($cmd eq 'up'                          $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {                                                            ':'.$ext.':normal:res';
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];                          push(@LONCAPA::map::order,$newidx);
   
     } elsif ($cmd eq 'down'  # Store the result
      && defined($LONCAPA::map::order[$idx+1])) {                          my ($errtext,$fatal) = 
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];                              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
                           if ($fatal) {
     } elsif ($cmd eq 'rename') {                              $save_err .= $errtext;
                               $allresult = 'failstore';
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});                          }
  if ($comment=~/\S/) {                      } 
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=                  }
  $comment.':'.join(':', $url, @rrest);                  if ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
  }                       push(@toclear,$suffix);
 # Devalidate title cache                  }
  my $renamed_url=&LONCAPA::map::qtescape($url);              }
  &Apache::lonnet::devalidate_title_cache($renamed_url);          }
     } else {      }
  return 0;      &clear_from_buffer(\@toclear,\@currpaste);
     }      my $msgsarray;
     return 1;      foreach my $suffix (keys(%msgs)) {
 }           if (ref($msgs{$suffix}) eq 'ARRAY') {
                $msgsarray .= join(',',@{$msgs{$suffix}});
 sub editor {           }
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;      }
       return ($allresult,$save_err,$msgsarray,$lockerrors);
     my $container= ($env{'form.pagepath'}) ? 'page'  }
                            : 'sequence';  
   sub do_buffer_empty {
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,      my @currpaste = split(/,/,$env{'docs.markedcopies'});
     $folder.'.'.$container);      if (@currpaste == 0) {
     return $errtext if ($fatal);          return &mt('Clipboard is already empty');
       }
     if ($#LONCAPA::map::order<1) {      my @toclear = &Apache::loncommon::get_env_multiple('form.pasting');
  my $idx=&LONCAPA::map::getresidx();      if (@toclear == 0) {
  if ($idx<=0) { $idx=1; }          return &mt('Nothing selected to clear from clipboard');
         $LONCAPA::map::order[0]=$idx;      }
         $LONCAPA::map::resources[$idx]='';      my $numdel = &clear_from_buffer(\@toclear,\@currpaste);
     }      if ($numdel) {
              return &mt('[quant,_1,item] cleared from clipboard',$numdel);
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=      } else {
  &breadcrumbs($folder,$allowed,$type);          return &mt('Clipboard unchanged');
     $r->print($breadcrumbtrail);      }
          return;
 # ------------------------------------------------------------ Process commands  }
   
 # ---------------- if they are for this folder and user allowed to make changes  sub clear_from_buffer {
     if (($allowed) && ($env{'form.folder'} eq $folder)) {      my ($toclear,$currpaste) = @_;
 # set parameters and change order      return unless ((ref($toclear) eq 'ARRAY') && (ref($currpaste) eq 'ARRAY'));
  &snapshotbefore();      my %pastebuffer;
       map { $pastebuffer{$_} = 1; } @{$currpaste};
  if (&update_parameter()) {      my $numdel = 0;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      foreach my $suffix (@{$toclear}) {
     return $errtext if ($fatal);          next if ($suffix =~ /\D/);
  }          next unless (exists($pastebuffer{$suffix}));
           my $regexp = 'docs.markedcopy_[a-z]+_'.$suffix;
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {          if (&Apache::lonnet::delenv($regexp,1) eq 'ok') {
 # change order              delete($pastebuffer{$suffix});
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);              $numdel ++;
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);          }
       }
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      my $newbuffer = join(',',sort(keys(%pastebuffer)));
     return $errtext if ($fatal);      &Apache::lonnet::appenv({'docs.markedcopies' => $newbuffer});
  }      return $numdel;
       }
  if ($env{'form.pastemarked'}) {  
             my $paste_res =  sub get_newmap_url {
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);      my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
             if ($paste_res eq 'ok') {          $titleref,$allmaps,$newurls) = @_;
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);      my $newurl;
                 return $errtext if ($fatal);      if ($url=~ m{^/uploaded/}) {
             } elsif ($paste_res ne '') {          $$titleref=&mt('Copy of').' '.$$titleref;
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');      }
             }      my $now = time;
  }      my $suffix=$$.int(rand(100)).$now;
       my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
  $r->print($upload_output);      if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
           my $path = $1;
  if (&handle_edit_cmd()) {          my $prefix = $2;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          my $ancestor = $3;
     return $errtext if ($fatal);          if (length($ancestor) > 10) {
  }              $ancestor = substr($ancestor,-10,10);
 # Group import/search          }
  if ($env{'form.importdetail'}) {          my $newid;
     my @imports;          if ($prefixchg) {
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {              if ($folder =~ /^supplemental/) {
  if (defined($item)) {                  $prefix =~ s/^default/supplemental/;
     my ($name,$url,$residx)=              } else {
  map {&unescape($_)} split(/\=/,$item);                  $prefix =~ s/^supplemental/default/;
     push(@imports, [$name, $url, $residx]);              }
  }          }
     }          if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,              $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     $container,'londocs',@imports);          } else {
     return $errtext if ($fatal);              $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
  }          }
 # Loading a complete map          my $counter = 0;
  if ($env{'form.loadmap'}) {          my $is_unique = &uniqueness_check($newurl);
     if ($env{'form.importmap'}=~/\w/) {          if ($folder =~ /^default/) {
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {              if ($allmaps->{$newurl}) {
     my ($title,$url,$ext,$type)=split(/\:/,$res);                  $is_unique = 0;
     my $idx=&LONCAPA::map::getresidx($url);              }
     $LONCAPA::map::resources[$idx]=$res;          }
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;          while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
  }              $counter ++;
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,              $suffix ++;
     $folder.'.'.$container);              if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
  return $errtext if ($fatal);                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     } else {              } else {
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
               }
     }              $is_unique = &uniqueness_check($newurl);
  }          }
  &log_differences($plain);          if ($is_unique) {
     }              $newurls->{$newurl} = 1;
 # ---------------------------------------------------------------- End commands          } else {
 # ---------------------------------------------------------------- Print screen              if ($url=~/\.page$/) {
     my $idx=0;                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
     my $shown=0;              } else {
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
  $r->print('<p>'.&mt('Parameters').':<ul>'.              }
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').          }
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').      }
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').      return ($newurl);
   '</ul></p>');  }
     }                                                                                                      
     if ($randompick>=0) {  sub dbcopy {
  $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>');      my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
     }      my ($url,$result,$errtext);
     if ($is_random_order) {      $url = $dbref->{'src'};
  $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 (ref($dbref) eq 'HASH') {
     }          if ($url =~ m{/(smppg|bulletinboard)$}) {
     $r->print('<table class="LC_docs_editor">');              my $prefix = $1;
     foreach my $res (@LONCAPA::map::order) {              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
  $name=&LONCAPA::map::qtescape($name);                  my $db_name;
  $url=&LONCAPA::map::qtescape($url);                  my $marker = (split(m{/},$url))[4];
  unless ($name) {  $name=(split(/\//,$url))[-1]; }                  $marker=~s/\D//g;
  unless ($name) { $idx++; next; }                  if ($dbref->{'src'} =~ m{/smppg$}) {
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,                      $db_name =
      $coursenum));                          &Apache::lonsimplepage::get_db_name($url,$marker,
  $idx++;                                                              $dbref->{'cdom'},
  $shown++;                                                              $dbref->{'cnum'});
     }                  } else {
     unless ($shown) {                      $db_name = 'bulletinpage_'.$marker;
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');                  }
     }                  my ($suffix,$freedlock,$error) =
     $r->print("\n</table>\n");                      &Apache::lonnet::get_timebased_id($prefix,'num','templated',
     if ($allowed) {                                                        $coursedom,$coursenum,
         &print_paste_buffer($r,$container);                                                        'concat');
     }                  if (!$suffix) {
     return;                      if ($prefix eq 'smppg') {
 }                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
                       } else {
 sub process_file_upload {                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a bulletin board [_1].',$url);
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;                      }
 # upload a file, if present                      if ($error) {
     my $parseaction;                          $errtext .= '<br />'.$error;
    if ($env{'form.parserflag'}) {                      }
         $parseaction = 'parse';                  } else {
     }                      #need to copy the db contents to a new one.
     my $phase_status;                      my %contents=&Apache::lonnet::dump($db_name,
     my $folder=$env{'form.folder'};                                                         $dbref->{'cdom'},
     if ($folder eq '') {                                                         $dbref->{'cnum'});
         $folder='default';                      if (exists($contents{'uploaded.photourl'})) {
     }                          my $photo = $contents{'uploaded.photourl'};
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {                          my ($subdir,$fname) =
         my $errtext='';                              ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
         my $fatal=0;                          my $newphoto;
         my $container='sequence';                          if ($fname ne '') {
         if ($env{'form.pagepath'}) {                              my $content = &Apache::lonnet::getfile($photo);
             $container='page';                              unless ($content eq '-1') {
         }                                  $env{'form.'.$suffix.'.photourl'} = $content;
         ($errtext,$fatal)=                                  $newphoto =
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
         if ($#LONCAPA::map::order<1) {                                  delete($env{'form.'.$suffix.'.photourl'});
             $LONCAPA::map::order[0]=1;                              }
             $LONCAPA::map::resources[1]='';                          }
         }                          if ($newphoto =~ m{^/uploaded/}) {
         if ($fatal) {                              $contents{'uploaded.photourl'} = $newphoto;
             return 'failed';                          }
         }                      }
         my $destination = 'docs/';                      $db_name =~ s{_\d*$ }{_$suffix}x;
         if ($folder =~ /^supplemental/) {                      $result=&Apache::lonnet::put($db_name,\%contents,
             $destination = 'supplemental/';                                                   $coursedom,$coursenum);
         }                      if ($result eq 'ok') {
         if (($folder eq 'default') || ($folder eq 'supplemental')) {                          $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
             $destination .= 'default/';                      }
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {                  }
             $destination .=  $2.'/';                  if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
         }                      $lockerrorsref->{$prefix} =
 # this is for a course, not a user, so set coursedoc flag                          '<div class="LC_error">'.
 # probably the only place in the system where this should be "1"                          &mt('There was a problem removing a lockfile.');
         my $newidx=&LONCAPA::map::getresidx();                      if ($prefix eq 'smppg') {
         $destination .= $newidx;                          $lockerrorsref->{$prefix} .=
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,                              ' '.&mt('This will prevent creation of additional simple pages in this course.');
  $parseaction,$allfiles,                      } else {
  $codebase);                          $lockerrorsref->{$prefix} .= ' '.&mt('This will prevent creation of additional bulletin boards in this course.');
         my $ext='false';                      }
         if ($url=~m{^http://}) { $ext='true'; }                      $lockerrorsref->{$prefix} .= ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
  $url     = &LONCAPA::map::qtunescape($url);                                                       '<a href="/adm/helpdesk" target="_helpdesk">','</a>').
         my $comment=$env{'form.comment'};                                                   '</div>';
  $comment = &LONCAPA::map::qtunescape($comment);                  }
         if ($folder=~/^supplemental/) {              }
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.          } elsif ($url =~ m{/syllabus$}) {
                   $env{'user.domain'}.'___&&&___'.$comment;              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
         }                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
                   if (($dbref->{'cdom'} ne $coursedom) ||
         $LONCAPA::map::resources[$newidx]=                      ($dbref->{'cnum'} ne $coursenum)) {
     $comment.':'.$url.':'.$ext.':normal:res';                      my %contents=&Apache::lonnet::dump('syllabus',
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;                                                         $dbref->{'cdom'},
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,                                                         $dbref->{'cnum'});
     $folder.'.'.$container);                      $result=&Apache::lonnet::put('syllabus',\%contents,
         if ($fatal) {                                                   $coursedom,$coursenum);
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';                  }
             return 'failed';              }
         } else {          }
             if ($parseaction eq 'parse') {      }
                 my $total_embedded = keys(%{$allfiles});      return ($url,$result,$errtext);
                 if ($total_embedded > 0) {  }
                     my $num = 0;  
     my $state = '  sub uniqueness_check {
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />      my ($newurl) = @_;
    <input type="hidden" name="cmd" value="upload_embedded" />      my $unique = 1;
    <input type="hidden" name="newidx" value="'.$newidx.'" />      foreach my $res (@LONCAPA::map::order) {
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';          $url=&LONCAPA::map::qtescape($url);
     $phase_status = 'phasetwo';          if ($newurl eq $url) {
               $unique = 0;
                     $$upload_output .=              last;
  '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);      return $unique;
                 } else {  }
                     $$upload_output .= 'No embedded items identified<br />';  
                 }  sub contained_map_check {
             }      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
         }          $allmaps) = @_;
     }      my $content = &Apache::lonnet::getfile($url);
     return $phase_status;      unless ($content eq '-1') {
 }          my $parser = HTML::TokeParser->new(\$content);
           $parser->attr_encoded(1);
 sub process_secondary_uploads {          while (my $token = $parser->get_token) {
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;              next if ($token->[0] ne 'S');
     my $folder=$env{'form.folder'};              if ($token->[1] eq 'resource') {
     my $destination = 'docs/';                  next if ($token->[2]->{'type'} eq 'zombie');
     if ($folder =~ /^supplemental/) {                  my $ressrc = $token->[2]->{'src'};
         $destination = 'supplemental/';                  if ($folder =~ /^supplemental/) {
     }                      unless (&supp_pasteable($ressrc)) {
     if (($folder eq 'default') || ($folder eq 'supplemental')) {                          $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
         $destination .= 'default/';                          next;
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {                      }
         $destination .=  $2.'/';                  }
     }                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
     $destination .= $newidx;                      if ($1 eq 'uploaded') {
     my ($url,$filename);                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);                          $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});                      } else {
     return $filename;                          if ($allmaps->{$ressrc}) {
 }                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
                           } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
 sub is_supplemental_title {                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     my ($title) = @_;                          } else {
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);                              $addedmaps->{$ressrc} = [$url];
 }                          }
                       }
 sub parse_supplemental_title {                      &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
     my ($title) = @_;                                           $addedmaps,$hierarchy,$titles,$allmaps);
                   }
     my ($foldertitle,$renametitle);              } elsif ($token->[1] eq 'param') {
     if ($title =~ /&amp;&amp;&amp;/) {                  if ($folder =~ /^supplemental/) {
  $title = &HTML::Entites::decode($title);                      if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
     }                          push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {                      } else {
  $renametitle=$4;                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
  my ($time,$uname,$udom) = ($1,$2,$3);                      }
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);                  }
  my $name =  &Apache::loncommon::plainname($uname,$udom);              }
  $name = &HTML::Entities::encode($name,'"<>&\'');          }
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.      }
     $name.': <br />'.$foldertitle;      return;
     }  }
     if (wantarray) {  
  return ($title,$foldertitle,$renametitle);  sub url_paste_fixups {
     }      my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
     return $title;          $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
 }          $mapchanges,$tomove,$newsubdir,$newurls) = @_;
       my $checktitle;
 # --------------------------------------------------------------- An entry line      if (($prefixchg) &&
           ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
 sub entryline {          $checktitle = 1;
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;      }
       my $skip;
     my ($foldertitle,$pagetitle,$renametitle);      if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
     if (&is_supplemental_title($title)) {          my $mapid = $1.$2;
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);          if ($tomove->{$mapid}) {
  $pagetitle = $foldertitle;              $skip = 1;
     } else {          }
  $title=&HTML::Entities::encode($title,'"<>&\'');      }
  $renametitle=$title;      my $file = &Apache::lonnet::getfile($oldurl);
  $foldertitle=$title;      return if ($file eq '-1');
  $pagetitle=$title;      my $parser = HTML::TokeParser->new(\$file);
     }      $parser->attr_encoded(1);
       my $changed = 0;
     my $orderidx=$LONCAPA::map::order[$index];      while (my $token = $parser->get_token) {
              next if ($token->[0] ne 'S');
           if ($token->[1] eq 'resource') {
     $renametitle=~s/\\/\\\\/g;              my $ressrc = $token->[2]->{'src'};
     $renametitle=~s/\&quot\;/\\\"/g;              next if ($ressrc eq '');
     $renametitle=~s/ /%20/g;              my $id = $token->[2]->{'id'};
     my $line='<tr>';              my $title = $token->[2]->{'title'};
     my ($form_start,$form_end);              if ($checktitle) {
 # Edit commands                  if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
     my ($container, $type, $esc_path, $path, $symb);                      $retitles->{$oldurl}{$id} = $ressrc;
     if ($env{'form.folderpath'}) {                  }
  $type = 'folder';              }
         $container = 'sequence';              next if ($token->[2]->{'type'} eq 'external');
  $esc_path=&escape($env{'form.folderpath'});              if ($token->[2]->{'type'} eq 'zombie') {
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                  next if ($skip);
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');                  $zombies->{$oldurl}{$id} = $ressrc;
     }                  $changed = 1;
     if ($env{'form.pagepath'}) {              } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
         $type = $container = 'page';                  my $srcdom = $1;
         $esc_path=&escape($path = $env{'form.pagepath'});                  my $srcnum = $2;
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');                  my $rem = $3;
         $symb=&escape($env{'form.pagesymb'});                  my $newurl;
     }                  my $mapname;
     my $cpinfo='';                  if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
     if ($allowed) {                      my $prefix = $1;
  my $incindex=$index+1;                      $mapname = $prefix.$2;
  my $selectbox='';                      if ($tomove->{$mapname}) {
  if (($folder!~/^supplemental/) &&                          &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
     ($#LONCAPA::map::order>0) &&                                            $srcdom,$srcnum,$allmaps,$rewrites,
     ((split(/\:/,                                            $retitles,$copies,$dbcopies,$zombies,
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]                                            $params,$mapmoves,$mapchanges,$tomove,
      ne '') &&                                            $newsubdir,$newurls);
     ((split(/\:/,                          next;
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]                      } else {
      ne '')) {                          ($newurl,my $error) =
     $selectbox=                              &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
  '<select name="newpos" onChange="this.form.submit()">';                          if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {                              $newsubdir->{$ressrc} = $1;
  if ($i==$incindex) {                          }
     $selectbox.='<option value="" selected="1">('.$i.')</option>';                          if ($error) {
  } else {                              next;
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';                          }
  }                      }
     }                  }
     $selectbox.='</select>';                  if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
  }                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
  my %lt=&Apache::lonlocal::texthash(                     
                 'up' => 'Move Up',                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
  'dw' => 'Move Down',                          $rewrites->{$oldurl}{$id} = $ressrc;
  'rm' => 'Remove',                          $mapchanges->{$ressrc} = 1;
                 'ct' => 'Cut',                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
  'rn' => 'Rename',                                                    $cnum,$srcdom,$srcnum,$allmaps,
  'cp' => 'Copy');                                                    $rewrites,$retitles,$copies,$dbcopies,
  my $nocopy=0;                                                    $zombies,$params,$mapmoves,$mapchanges,
         my $nocut=0;                                                    $tomove,$newsubdir,$newurls)) {
         if ($url=~/\.(page|sequence)$/) {                              $mapmoves->{$ressrc} = 1;
     if ($url =~ m{/res/}) {                          }
  # no copy for published maps                          $changed = 1;
  $nocopy = 1;                      } else {
     } else {                          $rewrites->{$oldurl}{$id} = $ressrc;
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {                          $copies->{$oldurl}{$ressrc} = $id;
     my ($title,$url,$ext,$type)=split(/\:/,$item);                          $changed = 1;
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {                      }
  $nocopy=1;                  }
  last;              } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
     }                  next if ($skip);
  }                  my $srcdom = $1;
     }                  my $srcnum = $2;
  }                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
         if ($url=~/^\/res\/lib\/templates\//) {                      $rewrites->{$oldurl}{$id} = $ressrc;
            $nocopy=1;                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
            $nocut=1;                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
         }                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
         my $copylink='&nbsp;';                      $changed = 1;
         my $cutlink='&nbsp;';                  }
               } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
  my $skip_confirm = 0;                  if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
  if ( $folder =~ /^supplemental/                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
      || ($url =~ m{( /smppg$                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
     |/syllabus$                      $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
     |/aboutme$                      $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
     |/navmaps$                      $changed = 1;
     |/bulletinboard$                  }
     |\.html$              } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
     |^/adm/wrapper/ext)}x)) {                  next if ($skip);
     $skip_confirm = 1;                  my $srcdom = $1;
  }                  my $srcnum = $2;
                   if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
  if (!$nocopy) {                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
     $copylink=(<<ENDCOPY);                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
 ENDCOPY                      $changed = 1;
         }                  }
  if (!$nocut) {              }
     $cutlink=(<<ENDCUT);          } elsif ($token->[1] eq 'param') {
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>              next if ($skip);
 ENDCUT              my $to = $token->[2]->{'to'}; 
         }              if ($to ne '') {
  $form_start = (<<END);                  if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
    <form  action="/adm/coursedocs" method="post">                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
    <input type="hidden" name="${type}path" value="$path" />                  } else {
    <input type="hidden" name="${type}symb" value="$symb" />                      @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
    <input type="hidden" name="setparms" value="$orderidx" />                  }
    <input type="hidden" name="changeparms" value="0" />              }
 END          }
         $form_end = '</form>';      }
  $line.=(<<END);      return $changed;
 <td>  }
    <table class="LC_docs_entry_move">  
       <tr>  sub apply_fixups {
          <td>      my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
             <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>          $oldurl,$url,$caller) = @_;
          </td>      my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
       </tr>          %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
       <tr>          %lockerrors,$lockmsg);
         <td>      if (ref($updated) eq 'HASH') {
            <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>          if (ref($updated->{'rewrites'}) eq 'HASH') {
         </td>              %rewrites = %{$updated->{'rewrites'}};
       </tr>          }
     </table>          if (ref($updated->{'zombies'}) eq 'HASH') {
 </td>              %zombies = %{$updated->{'zombies'}};
 <td>          }
    $form_start          if (ref($updated->{'removefrommap'}) eq 'HASH') {
    $selectbox              %removefrommap = %{$updated->{'removefrommap'}};
    $form_end          }
 </td>          if (ref($updated->{'removeparam'}) eq 'HASH') {
 <td class="LC_docs_entry_commands">              %removeparam = %{$updated->{'removeparam'}};
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>          }
 $cutlink          if (ref($updated->{'dbcopies'}) eq 'HASH') {
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>              %dbcopies = %{$updated->{'dbcopies'}};
 $copylink          }
 </td>          if (ref($updated->{'retitles'}) eq 'HASH') {
 END              %retitles = %{$updated->{'retitles'}};
           }
     }      }
 # Figure out what kind of a resource this is      if (ref($info) eq 'HASH') {
     my ($extension)=($url=~/\.(\w+)$/);          if (ref($info->{'newsubdir'}) eq 'HASH') {
     my $uploaded=($url=~/^\/*uploaded\//);              %newsubdir = %{$info->{'newsubdir'}};
     my $icon=&Apache::loncommon::icon($url);          }
     my $isfolder=0;          if (ref($info->{'params'}) eq 'HASH') {
     my $ispage=0;              %params = %{$info->{'params'}};
     my $folderarg;          }
     my $pagearg;          if (ref($info->{'before'}) eq 'HASH') {
     my $pagefile;              %before = %{$info->{'before'}};
     if ($uploaded) {          }
  if ($extension eq 'sequence') {          if (ref($info->{'after'}) eq 'HASH') {
     $icon=$iconpath.'/folder_closed.gif';              %after = %{$info->{'after'}};
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;          }
     $url='/adm/coursedocs?';      }
     $folderarg=$1;      if (ref($moves) eq 'HASH') {
     $isfolder=1;          if (ref($moves->{'copies'}) eq 'HASH') {
         } elsif ($extension eq 'page') {              %copies = %{$moves->{'copies'}};
             $icon=$iconpath.'/page.gif';          }
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;          if (ref($moves->{'docmoves'}) eq 'HASH') {
             $pagearg=$1;              %docmoves = %{$moves->{'docmoves'}};
             $url='/adm/coursedocs?';          }
             $ispage=1;          if (ref($moves->{'mapmoves'}) eq 'HASH') {
  } else {              %mapmoves = %{$moves->{'mapmoves'}};
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);          }
  }      }
     }      foreach my $key (keys(%copies),keys(%docmoves)) {
              my @allcopies;
     my $orig_url = $url;          if (exists($copies{$key})) {
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});              if (ref($copies{$key}) eq 'HASH') {
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {                  my %added;
  my $symb=&Apache::lonnet::symbclean(                  foreach my $innerkey (keys(%{$copies{$key}})) {
           &Apache::lonnet::declutter('uploaded/'.                      if (($innerkey ne '') && (!$added{$innerkey})) {
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.                          push(@allcopies,$innerkey);
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.                          $added{$innerkey} = 1;
            '.sequence').                      }
            '___'.$residx.'___'.                  }
    &Apache::lonnet::declutter($url));                  undef(%added);
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);              }
  $url=&Apache::lonnet::clutter($url);          }
  if ($url=~/^\/*uploaded\//) {          if ($key eq $oldurl) {
     $url=~/\.(\w+)$/;              if ((exists($docmoves{$key}))) {
     my $embstyle=&Apache::loncommon::fileembstyle($1);                  unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {                      push(@allcopies,$oldurl);
  $url='/adm/wrapper'.$url;                  }
     } elsif ($embstyle eq 'ssi') {              }
  #do nothing with these          }
     } elsif ($url!~/\.(sequence|page)$/) {          if (@allcopies > 0) {
  $url='/adm/coursedocs/showdoc'.$url;              foreach my $item (@allcopies) {
     }                  my ($relpath,$oldsubdir,$fname) = 
  } elsif ($url=~m|^/ext/|) {                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
     $url='/adm/wrapper'.$url;                  if ($fname ne '') {
     $external = 1;                      my $content = &Apache::lonnet::getfile($item);
  }                      unless ($content eq '-1') {
         if (&Apache::lonnet::symbverify($symb,$url)) {                          my $storefn;
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                          if (($key eq $oldurl) && (exists($docmoves{$key}))) {
         } else {                              $storefn = $docmoves{$key};
             $url='';                          } else {
         }                              $storefn = $relpath;
  if ($container eq 'page') {                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
     my $symb=$env{'form.pagesymb'};                              if ($prefixchg && $before{'doc'} && $after{'doc'}) {
                                           $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);                              }
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                              if ($newsubdir{$key}) {
  }                                  $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
     }                              }
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');                          }
     if ($isfolder || $extension eq 'sequence') {                          &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
  my $foldername=&escape($foldertitle);                          my $copyurl = 
  my $folderpath=$env{'form.folderpath'};                              &Apache::lonclonecourse::writefile($env{'request.course.id'},
  if ($folderpath) { $folderpath.='&' };                                                                 $storefn.$fname,$content);
 # Append randompick number, hidden, and encrypted with ":" to foldername,                          if ($copyurl eq '/adm/notfound.html') {
 # so it gets transferred between levels                              if (exists($docmoves{$oldurl})) {
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,                                  return &mt('Paste failed: an error occurred copying the file.');
                                               'parameter_randompick'))[0]                              } elsif (ref($errors) eq 'HASH') {
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                                  $errors->{$item} = 1;
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)                              }
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                          }
                                               'parameter_encrypturl'))[0]=~/^yes$/i)                      }
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                  }
                                               'parameter_randomorder'))[0]=~/^yes$/i);              }
  $url.='folderpath='.&escape($folderpath).$cpinfo;          }
  $parameterset='<label>'.&mt('Randomly Pick: ').      }
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.      foreach my $key (keys(%mapmoves)) {
     (&LONCAPA::map::getparameter($orderidx,          my $storefn=$key;
                                               'parameter_randompick'))[0].          $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                                               '" />'.          if ($prefixchg && $before{'map'} && $after{'map'}) {
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';              $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
     my $ro_set=          }
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');          if ($newsubdir{$key}) {
  $rand_order_text ='              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
 <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 $mapcontent = &Apache::lonnet::getfile($key);
     if ($ispage) {          if ($mapcontent eq '-1') {
         my $pagename=&escape($pagetitle);              if (ref($errors) eq 'HASH') {
         my $pagepath;                  $errors->{$key} = 1;
         my $folderpath=$env{'form.folderpath'};              }
         if ($folderpath) { $pagepath = $folderpath.'&' };          } else {
         $pagepath.=$pagearg.'&'.$pagename;              my $newmap =
  my $symb=$env{'form.pagesymb'};                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
  if (!$symb) {                                                     $mapcontent);
     my $path='uploaded/'.              if ($newmap eq '/adm/notfound.html') {
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.                  if (ref($errors) eq 'HASH') {
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';                      $errors->{$key} = 1;
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',                  }
        $residx,              }
        $path.$pagearg.'.page');          }
  }      }
  $url.='pagepath='.&escape($pagepath).      my %updates;
     '&amp;pagesymb='.&escape($symb).$cpinfo;      if ($is_map) {
     }          if (ref($updated) eq 'HASH') {
     if ($external) {              foreach my $type (keys(%{$updated})) {
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';                  if (ref($updated->{$type}) eq 'HASH') {
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';                      foreach my $key (keys(%{$updated->{$type}})) {
     } else {                          $updates{$key} = 1;
  undef($external);                      }
     }                  }
     $line.='              }
   <td class="LC_docs_entry_icon">          }
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'          foreach my $key (keys(%updates)) {
   </td>              my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
   <td class="LC_docs_entry_title">              if (ref($rewrites{$key}) eq 'HASH') {
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."                  %torewrite = %{$rewrites{$key}};
   </td>";              }
     if (($allowed) && ($folder!~/^supplemental/)) {              if (ref($retitles{$key}) eq 'HASH') {
   my %lt=&Apache::lonlocal::texthash(                  %toretitle = %{$retitles{$key}};
        'hd' => 'Hidden',              }
        'ec' => 'URL hidden');              if (ref($removefrommap{$key}) eq 'HASH') {
  my $enctext=                  %toremove = %{$removefrommap{$key}};
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');              }
  my $hidtext=              if (ref($removeparam{$key}) eq 'HASH') {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');                  %remparam = %{$removeparam{$key}};
  $line.=(<<ENDPARMS);              }
   <td class="LC_docs_entry_parameter">              if (ref($zombies{$key}) eq 'HASH') {
     $form_start                  %zombie = %{$zombies{$key}};
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>              }
     $form_end              if (ref($dbcopies{$key}) eq 'HASH') {
   </td>                  foreach my $idx (keys(%{$dbcopies{$key}})) {
   <td class="LC_docs_entry_parameter">                      if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
     $form_start                          my ($newurl,$result,$errtext) =
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>                              &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
     $form_end                          if ($result eq 'ok') {
   </td>                              $newdb{$idx} = $newurl;
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>                          } elsif (ref($errors) eq 'HASH') {
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>                              $errors->{$key} = 1;
 ENDPARMS                          }
     }                          push(@msgs,$errtext);
     $line.="</tr>";                      }
     return $line;                  }
 }              }
               if (ref($params{$key}) eq 'HASH') {
 =pod                  %currparam = %{$params{$key}};
               }
 =item tiehash()              my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
               if ($fatal) {
 tie the hash                  return ($errtext);
               }
 =cut              for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
                   if (defined($LONCAPA::map::zombies[$i])) {
 sub tiehash {                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
     my ($mode)=@_;                      if ($zombie{$i} eq $src) {
     $hashtied=0;                          undef($LONCAPA::map::zombies[$i]);
     if ($env{'request.course.fn'}) {                      }
  if ($mode eq 'write') {                  }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",              }
     &GDBM_WRCREAT(),0640)) {              for (my $i=0; $i<@LONCAPA::map::order; $i++) {
                 $hashtied=2;                  my $idx = $LONCAPA::map::order[$i];
     }                  if (defined($LONCAPA::map::resources[$idx])) {
  } else {                      my $changed;
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
     &GDBM_READER(),0640)) {                      if ((exists($toremove{$idx})) && 
                 $hashtied=1;                          ($toremove{$idx} eq &LONCAPA::map::qtescape($src))) {
     }                          splice(@LONCAPA::map::order,$i,1);
  }                          if (ref($currparam{$idx}) eq 'ARRAY') {
     }                                  foreach my $name (@{$currparam{$idx}}) {
 }                                  &LONCAPA::map::delparameter($idx,'parameter_'.$name);
                               }
 sub untiehash {                          }
     if ($hashtied) { untie %hash; }                          next;
     $hashtied=0;                      }
     return OK;                      my $origsrc = $src;
 }                      if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
                           if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
                               $changed = 1;
                           }
                       }
 sub checkonthis {                      if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
     my ($r,$url,$level,$title)=@_;                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
     $url=&unescape($url);                          if ($origsrc =~ m{^/uploaded/}) {
     $alreadyseen{$url}=1;                              if ($prefixchg && $before{'map'} && $after{'map'}) {
     $r->rflush();                                  if ($src =~ /\.(page|sequence)$/) {
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
        $r->print("\n<br />");                                  } else {
        if ($level==0) {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
            $r->print("<br />");                                  }
        }                              }
        for (my $i=0;$i<=$level*5;$i++) {                              if ($origsrc =~ /\.(page|sequence)$/) {
            $r->print('&nbsp;');                                  if ($newsubdir{$origsrc}) {
        }                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
        $r->print('<a href="'.$url.'" target="cat">'.                                  }
  ($title?$title:$url).'</a> ');                              } elsif ($newsubdir{$key}) {
        if ($url=~/^\/res\//) {                                  $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
   my $result=&Apache::lonnet::repcopy(                              }
                               &Apache::lonnet::filelocation('',$url));                          }
           if ($result eq 'ok') {                          $changed = 1;
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');                      } elsif ($newdb{$idx} ne '') {
              $r->rflush();                          $src = $newdb{$idx};
              &Apache::lonnet::countacc($url);                          $changed = 1;
              $url=~/\.(\w+)$/;                      }
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {                      if ($changed) {
  $r->print('<br />');                          $LONCAPA::map::resources[$idx] = join(':',($title,&LONCAPA::map::qtunescape($src),$ext,$type));
                  $r->rflush();                      }
                  for (my $i=0;$i<=$level*5;$i++) {                  }
                      $r->print('&nbsp;');              }
                  }              foreach my $idx (keys(%remparam)) {
                  $r->print('- '.&mt('Rendering:').' ');                  if (ref($remparam{$idx}) eq 'ARRAY') {
  my ($errorcount,$warningcount)=split(/:/,                      foreach my $name (@{$remparam{$idx}}) {   
        &Apache::lonnet::ssi_body($url,                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
        ('grade_target'=>'web',                      }
  'return_only_error_and_warning_counts' => 1)));                  }
                  if (($errorcount) ||              }
                      ($warningcount)) {              if (values(%lockerrors) > 0) {
      if ($errorcount) {                  $lockmsg = join('<br />',values(%lockerrors));
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.              }
                           &mt('[quant,_1,error]',$errorcount).'</span>');              my $storefn;
                      }              if ($key eq $oldurl) {
      if ($warningcount) {                  $storefn = $url;
                         $r->print('<span class="LC_warning">'.                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                           &mt('[quant,_1,warning]',$warningcount).'</span>');              } else {
                      }                  $storefn = $key;
                  } else {                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');                  if ($prefixchg && $before{'map'} && $after{'map'}) {
                  }                      $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
                  $r->rflush();                  }
              }                  if ($newsubdir{$key}) {
      my $dependencies=                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
                 &Apache::lonnet::metadata($url,'dependencies');                  }
              foreach my $dep (split(/\,/,$dependencies)) {              }
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {              my $report;
                     &checkonthis($r,$dep,$level+1);              if ($folder !~ /^supplemental/) {
                  }                  $report = 1;
              }              }
           } elsif ($result eq 'unavailable') {              (my $outtext,$errtext) =
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
           } elsif ($result eq 'not_found') {              if ($errtext) {
       unless ($url=~/\$/) {                  if ($caller eq 'paste') {
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');                      return (&mt('Paste failed: an error occurred saving the folder or page.'));
       } else {                  }
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');              }
       }          }
           } else {      }
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');      return ('ok',\@msgs,$lockmsg);
           }  }
        }  
     }  sub copy_dependencies {
 }      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
       my $content;
       if (ref($contentref)) {
           $content = $$contentref;
 =pod      } else {
           $content = &Apache::lonnet::getfile($item);
 =item list_symbs()      }
       unless ($content eq '-1') {
 List Symbs          my $mm = new File::MMagic;
           my $mimetype = $mm->checktype_contents($content);
 =cut          if ($mimetype eq 'text/html') {
               my (%allfiles,%codebase,$state);
 sub list_symbs {              my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
     my ($r) = @_;              if ($res eq 'ok') {
                   my ($numexisting,$numpathchanges,$existing);
     my $type = &Apache::loncommon::course_type();                  (undef,$numexisting,$numpathchanges,$existing) =
     $r->print(&Apache::loncommon::start_page('Symb List'));                      &Apache::loncommon::ask_for_embedded_content(
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));                          '/adm/coursedocs',$state,\%allfiles,\%codebase,
     my $navmap = Apache::lonnavmaps::navmap->new();                          {'error_on_invalid_names'   => 1,
     if (!defined($navmap)) {                           'ignore_remote_references' => 1,
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.                           'docs_url'                 => $item,
                   '<div class="LC_error">'.                           'context'                  => 'paste'});
                   &mt('Unable to retrieve information about course contents').                  if ($numexisting > 0) {
                   '</div>');                      if (ref($existing) eq 'HASH') {
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                          foreach my $dep (keys(%{$existing})) {
     } else {                              my $depfile = $dep;
         $r->print("<pre>\n");                              unless ($depfile =~ m{^\Q$relpath\E}) {
         foreach my $res ($navmap->retrieveResources()) {                                  $depfile = $relpath.$dep;
     $r->print($res->compTitle()."\t".$res->symb()."\n");                              }
         }                              my $depcontent = &Apache::lonnet::getfile($depfile);
         $r->print("\n</pre>\n");                              unless ($depcontent eq '-1') {
     }                                  my $storedep = $dep;
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');                                  $storedep =~ s{^\Q$relpath\E}{};
 }                                  my $dep_url =
                                       &Apache::lonclonecourse::writefile(
                                           $env{'request.course.id'},
 sub verifycontent {                                          $storefn.$storedep,$depcontent);
     my ($r) = @_;                                  if ($dep_url eq '/adm/notfound.html') {
     my $type = &Apache::loncommon::course_type();                                      if (ref($errors) eq 'HASH') {
    my $loaderror=&Apache::lonnet::overloaderror($r);                                          $errors->{$depfile} = 1;
    if ($loaderror) { return $loaderror; }                                      }
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));                                  } else {
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
    $hashtied=0;                                  }
    undef %alreadyseen;                              }
    %alreadyseen=();                          }
    &tiehash();                      }
    foreach my $key (keys(%hash)) {                  }
        if ($hash{$key}=~/\.(page|sequence)$/) {              }
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {          }
        $r->print('<hr /><span class="LC_error">'.      }
  &mt('The following sequence or page is included more than once in your '.$type.': ').      return;
  &unescape($hash{$key}).'</span><br />'.  }
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));  
    }  my %parameter_type = ( 'randompick'     => 'int_pos',
        }         'hiddenresource' => 'string_yesno',
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {         'encrypturl'     => 'string_yesno',
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});         'randomorder'    => 'string_yesno',);
        }  my $valid_parameters_re = join('|',keys(%parameter_type));
    }  # set parameters
    &untiehash();  sub update_parameter {
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.      if ($env{'form.changeparms'} eq 'all') {
      &mt('Return to DOCS').'</a>');          my (@allidx,@allmapidx,%allchecked,%currchecked);
 }          %allchecked = (
                            'hiddenresource' => {},
                            'encrypturl'     => {},
 sub devalidateversioncache {                           'randompick'     => {},
     my $src=shift;                           'randomorder'    => {},
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.                        );
   &Apache::lonnet::clutter($src));          foreach my $which (keys(%allchecked)) {
 }              $env{'form.all'.$which} =~ s/,$//;
               if ($which eq 'randompick') {
 sub checkversions {                  foreach my $item (split(/,/,$env{'form.all'.$which})) {
     my ($r) = @_;                      my ($res,$value) = split(/:/,$item);
     my $type = &Apache::loncommon::course_type();                      if ($value =~ /^\d+$/) {
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));                          $allchecked{$which}{$res} = $value;
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));                      }
     my $header='';                  }
     my $startsel='';              } else {
     my $monthsel='';                  if ($env{'form.all'.$which}) {
     my $weeksel='';                      map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.all'.$which});
     my $daysel='';                  }
     my $allsel='';              }
     my %changes=();          }
     my $starttime=0;          my $haschanges = 0;
     my $haschanged=0;          foreach my $res (@LONCAPA::map::order) {
     my %setversions=&Apache::lonnet::dump('resourceversions',              my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
   $env{'course.'.$env{'request.course.id'}.'.domain'},              $name=&LONCAPA::map::qtescape($name);
   $env{'course.'.$env{'request.course.id'}.'.num'});              $url=&LONCAPA::map::qtescape($url);
               next unless ($name && $url);
     $hashtied=0;              my $is_map;
     &tiehash();              if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
     my %newsetversions=();                  $is_map = 1;
     if ($env{'form.setmostrecent'}) {              }
  $haschanged=1;              foreach my $which (keys(%allchecked)) {
  foreach my $key (keys(%hash)) {                  if (($which eq 'randompick' || $which eq 'randomorder')) {
     if ($key=~/^ids\_(\/res\/.+)$/) {                      next if (!$is_map);
  $newsetversions{$1}='mostrecent';                  }
                 &devalidateversioncache($1);                  my $oldvalue = 0;
     }                  my $newvalue = 0;
  }                  if ($allchecked{$which}{$res}) {
     } elsif ($env{'form.setcurrent'}) {                      $newvalue = $allchecked{$which}{$res};
  $haschanged=1;                  }
  foreach my $key (keys(%hash)) {                  my $current = (&LONCAPA::map::getparameter($res,'parameter_'.$which))[0];
     if ($key=~/^ids\_(\/res\/.+)$/) {                  if ($which eq 'randompick') {
  my $getvers=&Apache::lonnet::getversion($1);                      if ($current =~ /^(\d+)$/) {
  if ($getvers>0) {                          $oldvalue = $1;
     $newsetversions{$1}=$getvers;                      }
     &devalidateversioncache($1);                  } else {
  }                      if ($current =~ /^yes$/i) {
     }                          $oldvalue = 1;
  }                      }
     } elsif ($env{'form.setversions'}) {                  }
  $haschanged=1;                  if ($oldvalue ne $newvalue) {
  foreach my $key (keys(%env)) {                      $haschanges = 1;
     if ($key=~/^form\.set_version_(.+)$/) {                      if ($newvalue) {
  my $src=$1;                          my $storeval = 'yes';
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {                          if ($which eq 'randompick') {
     $newsetversions{$src}=$env{$key};                              $storeval = $newvalue;
     &devalidateversioncache($src);                          }
  }                          &LONCAPA::map::storeparameter($res,'parameter_'.$which,
     }                                                        $storeval,
  }                                                        $parameter_type{$which});
     }                          &remember_parms($res,$which,'set',$storeval);
     if ($haschanged) {                      } elsif ($oldvalue) {
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,                          &LONCAPA::map::delparameter($res,'parameter_'.$which);
   $env{'course.'.$env{'request.course.id'}.'.domain'},                          &remember_parms($res,$which,'del');
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {                      }
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');                  }
  } else {              }
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');          }
  }          return $haschanges;
  &mark_hash_old();      } else {
     }          return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     &changewarning($r,'');  
     if ($env{'form.timerange'} eq 'all') {          my $which = $env{'form.changeparms'};
 # show all documents          my $idx = $env{'form.setparms'};
  $header=&mt('All Documents in '.$type);          if ($env{'form.'.$which.'_'.$idx}) {
  $allsel=1;      my $value = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
  foreach my $key (keys(%hash)) {                                           : 'yes';
     if ($key=~/^ids\_(\/res\/.+)$/) {      &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
  my $src=$1;            $parameter_type{$which});
  $changes{$src}=1;      &remember_parms($idx,$which,'set',$value);
     }          } else {
  }      &LONCAPA::map::delparameter($idx,'parameter_'.$which);
     } else {  
 # show documents which changed      &remember_parms($idx,$which,'del');
  %changes=&Apache::lonnet::dump          }
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},          return 1;
                      $env{'course.'.$env{'request.course.id'}.'.num'});      }
  my $firstkey=(keys(%changes))[0];  }
  unless ($firstkey=~/^error\:/) {  
     unless ($env{'form.timerange'}) {  
  $env{'form.timerange'}=604800;  sub handle_edit_cmd {
     }      my ($coursenum,$coursedom) =@_;
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '      if ($env{'form.cmd'} eq '') {
  .&mt('seconds');          return 0;
     if ($env{'form.timerange'}==-1) {      }
  $seltext='since start of course';      my ($cmd,$idx)=split('_',$env{'form.cmd'});
  $startsel='selected';  
  $env{'form.timerange'}=time;      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     }      my ($title, $url, @rrest) = split(':', $ratstr);
     $starttime=time-$env{'form.timerange'};  
     if ($env{'form.timerange'}==2592000) {      if ($cmd eq 'remove') {
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  $monthsel='selected';      ($url!~/$LONCAPA::assess_page_seq_re/)) {
     } elsif ($env{'form.timerange'}==604800) {      &Apache::lonnet::removeuploadedurl($url);
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   } else {
  $weeksel='selected';      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     } elsif ($env{'form.timerange'}==86400) {   }
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   splice(@LONCAPA::map::order, $idx, 1);
  $daysel='selected';  
     }      } elsif ($cmd eq 'cut') {
     $header=&mt('Content changed').' '.$seltext;   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  } else {   splice(@LONCAPA::map::order, $idx, 1);
     $header=&mt('No content modifications yet.');  
  }      } elsif ($cmd eq 'up'
     }       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     %setversions=&Apache::lonnet::dump('resourceversions',   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
   $env{'course.'.$env{'request.course.id'}.'.domain'},  
   $env{'course.'.$env{'request.course.id'}.'.num'});      } elsif ($cmd eq 'down'
     my %lt=&Apache::lonlocal::texthash       && defined($LONCAPA::map::order[$idx+1])) {
       ('st' => 'Version changes since start of '.$type,   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
        'lm' => 'Version changes since last Month',  
        'lw' => 'Version changes since last Week',      } elsif ($cmd eq 'rename') {
        'sy' => 'Version changes since Yesterday',   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
                'al' => 'All Resources (possibly large output)',   if ($comment=~/\S/) {
        'sd' => 'Display',      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
        'fi' => 'File',   $comment.':'.join(':', $url, @rrest);
        'md' => 'Modification Date',   }
                'mr' => 'Most recently published Version',  # Devalidate title cache
        've' => 'Version used in '.$type,   my $renamed_url=&LONCAPA::map::qtescape($url);
                'vu' => 'Set Version to be used in '.$type,   &Apache::lonnet::devalidate_title_cache($renamed_url);
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',  
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      } else {
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',   return 0;
        'di' => 'Differences');      }
     $r->print(<<ENDHEADERS);      return 1;
 <form action="/adm/coursedocs" method="post">  }
 <input type="hidden" name="versions" value="1" />  
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />  sub editor {
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 <select name="timerange">          $supplementalflag,$orderhash,$iconpath,$pathitem)=@_;
 <option value='all' $allsel>$lt{'al'}</option>      my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
 <option value="-1" $startsel>$lt{'st'}</option>      if ($allowed) {
 <option value="2592000" $monthsel>$lt{'lm'}</option>          (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
 <option value="604800" $weeksel>$lt{'lw'}</option>           $is_random_order,$container) =
 <option value="86400" $daysel>$lt{'sy'}</option>              &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 </select>          $r->print($breadcrumbtrail);
 <input type="submit" name="display" value="$lt{'sd'}" />      } elsif ($env{'form.folderpath'} =~ /\:1$/) {
 <h3>$header</h3>          $container = 'page'; 
 <input type="submit" name="setversions" value="$lt{'sv'}" />      } else {
 <table border="0">          $container = 'sequence';
 ENDHEADERS      }
     foreach my $key (sort(keys(%changes))) {  
  if ($changes{$key}>$starttime) {      my $jumpto;
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);  
     my $currentversion=&Apache::lonnet::getversion($key);      unless ($supplementalflag) {
     if ($currentversion<0) {          $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
  $currentversion=&mt('Could not be determined.');      }
     }  
     my $linkurl=&Apache::lonnet::clutter($key);      unless ($allowed) {
     $r->print(          $randompick = -1;
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.      }
       &Apache::lonnet::gettitle($linkurl).  
                       '</b></font></td></tr>'.      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      $folder.'.'.$container);
                       '<td colspan="4">'.      return $errtext if ($fatal);
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.  
       '</a></td></tr>'.      if ($#LONCAPA::map::order<1) {
                       '<tr><td></td>'.   my $idx=&LONCAPA::map::getresidx();
                       '<td title="'.$lt{'md'}.'">'.   if ($idx<=0) { $idx=1; }
       &Apache::lonlocal::locallocaltime(          $LONCAPA::map::order[0]=$idx;
                            &Apache::lonnet::metadata($root.'.'.$extension,          $LONCAPA::map::resources[$idx]='';
                                                      'lastrevisiondate')      }
                                                         ).  
                       '</td>'.  # ------------------------------------------------------------ Process commands
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.  
                       '<font size="+1">'.$currentversion.'</font>'.  # ---------------- if they are for this folder and user allowed to make changes
                       '</span></td>'.      if (($allowed) && ($env{'form.folder'} eq $folder)) {
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.  # set parameters and change order
                       '<font size="+1">');   &snapshotbefore();
 # Used in course  
     my $usedversion=$hash{'version_'.$linkurl};   if (&update_parameter()) {
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
  $r->print($usedversion);      return $errtext if ($fatal);
     } else {   }
  $r->print($currentversion);  
     }   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.  # change order
                       '<span class="LC_nobreak">Use: ');      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
 # Set version      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},  
       'set_version_'.$linkurl,      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
       ('select_form_order' =>      return $errtext if ($fatal);
        ['',1..$currentversion,'mostrecent'],   }
        '' => '',  
        'mostrecent' => 'most recent',   if ($env{'form.pastemarked'}) {
        map {$_,$_} (1..$currentversion))));              my %paste_errors;
     $r->print('</span></td></tr><tr><td></td>');              my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
     my $lastold=1;                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {                                        \%paste_errors);
  my $url=$root.'.'.$prevvers.'.'.$extension;              if (ref($pastemsgarray) eq 'ARRAY') {
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                  if (@{$pastemsgarray} > 0) {
     $starttime) {                      $r->print('<p class="LC_info">'.
     $lastold=$prevvers;                                join('<br />',@{$pastemsgarray}).
  }                                '</p>');
     }                  }
             #              }
             # Code to figure out how many version entries should go in              if ($lockerror) {
             # each of the four columns                  $r->print('<p class="LC_error">'.
             my $entries_per_col = 0;                            $lockerror.
             my $num_entries = ($currentversion-$lastold);                            '</p>');
             if ($num_entries % 4 == 0) {              }
                 $entries_per_col = $num_entries/4;              if ($save_error ne '') {
             } else {                  return $save_error; 
                 $entries_per_col = $num_entries/4 + 1;              }
             }              if ($paste_res) {
             my $entries_count = 0;                  my %errortext = &Apache::lonlocal::texthash (
             $r->print('<td valign="top"><font size="-2">');                                      fail      => 'Storage of folder contents failed',
             my $cols_output = 1;                                      failread  => 'Reading folder contents failed',
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {                                      failstore => 'Storage of folder contents failed',
  my $url=$root.'.'.$prevvers.'.'.$extension;                                  );
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).                  if ($errortext{$paste_res}) {
   '">'.&mt('Version').' '.$prevvers.'</a> ('.                      $r->print('<p class="LC_error">'.$errortext{$paste_res}.'</p>');
   &Apache::lonlocal::locallocaltime(                  }
                                 &Apache::lonnet::metadata($url,              }
                                                           'lastrevisiondate')              if (keys(%paste_errors) > 0) {
                                                             ).                  $r->print('<p 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".
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {                            '<ul>'."\n");
                     $r->print(' <a href="/adm/diff?filename='.                  foreach my $key (sort(keys(%paste_errors))) {
       &Apache::lonnet::clutter($root.'.'.$extension).                      $r->print('<li>'.$key.'</li>'."\n");
       '&versionone='.$prevvers.                  }
       '">'.&mt('Diffs').'</a>');                  $r->print('</ul></p>'."\n");
  }              }
  $r->print('</span><br />');   } elsif ($env{'form.clearmarked'}) {
                 if (++$entries_count % $entries_per_col == 0) {              my $output = &do_buffer_empty();
                     $r->print('</font></td>');              if ($output) {
                     if ($cols_output != 4) {                  $r->print('<p class="LC_info">'.$output.'</p>');
                         $r->print('<td valign="top"><font size="-2">');              }
                         $cols_output++;          }
                     }  
                 }   $r->print($upload_output);
     }  
             while($cols_output++ < 4) {  # Rename, cut, copy or remove a single resource
                 $r->print('</font></td><td><font>')   if (&handle_edit_cmd()) {
             }              my $contentchg;
     $r->print('</font></td></tr>'."\n");              if ($env{'form.cmd'} =~ m{^(del|cut)_}) {
  }                  $contentchg = 1;
     }              }
     $r->print('</table></form>');      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
     $r->print('<h1>'.&mt('Done').'.</h1>');      return $errtext if ($fatal);
    }
     &untiehash();  
 }  # Cut, copy and/or remove multiple resources
           if ($env{'form.multichange'}) {
 sub mark_hash_old {              my %allchecked = (
     my $retie_hash=0;                                 cut     => {},
     if ($hashtied) {                                 remove  => {},
  $retie_hash=1;                               );
  &untiehash();              my $needsupdate;
     }              foreach my $which (keys(%allchecked)) {
     &tiehash('write');                  $env{'form.multi'.$which} =~ s/,$//;
     $hash{'old'}=1;                  if ($env{'form.multi'.$which}) {
     &untiehash();                      map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.multi'.$which});
     if ($retie_hash) { &tiehash(); }                      if (ref($allchecked{$which}) eq 'HASH') {
 }                          $needsupdate += scalar(keys(%{$allchecked{$which}}));
                       }
 sub is_hash_old {                  }
     my $untie_hash=0;              }
     if (!$hashtied) {              if ($needsupdate) {
  $untie_hash=1;                  my $haschanges = 0;
  &tiehash();                  my %curr_groups = &Apache::longroup::coursegroups();
     }                  my $total = scalar(@LONCAPA::map::order) - 1; 
     my $return=$hash{'old'};                  for (my $i=$total; $i>=0; $i--) {
     if ($untie_hash) { &untiehash(); }                      my $res = $LONCAPA::map::order[$i];
     return $return;                      my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 }                      $name=&LONCAPA::map::qtescape($name);
                       $url=&LONCAPA::map::qtescape($url);
 sub changewarning {                      next unless ($name && $url);
     my ($r,$postexec,$message,$url)=@_;                      my %denied =
     if (!&is_hash_old()) { return; }                          &action_restrictions($coursenum,$coursedom,$url,
     my $pathvar='folderpath';                                               $env{'form.folderpath'},\%curr_groups);
     my $path=&escape($env{'form.folderpath'});                      foreach my $which (keys(%allchecked)) {
     if (!defined($url)) {                          next if ($denied{$which});
  if (defined($env{'form.pagepath'})) {                          next unless ($allchecked{$which}{$res});
     $pathvar='pagepath';                          if ($which eq 'remove') {
     $path=&escape($env{'form.pagepath'});                              if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                                  ($url!~/$LONCAPA::assess_page_seq_re/)) {
  }                                  &Apache::lonnet::removeuploadedurl($url);
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                              } else {
     }                                  &LONCAPA::map::makezombie($res);
     my $course_type = &Apache::loncommon::course_type();                              }
     if (!defined($message)) {                              splice(@LONCAPA::map::order,$i,1);
  $message='Changes will become active for your current session after [_1], or the next time you log in.';                              $haschanges ++;
     }                          } elsif ($which eq 'cut') {
     $r->print("\n\n".                              &LONCAPA::map::makezombie($res);
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".                              splice(@LONCAPA::map::order,$i,1);
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.                              $haschanges ++;
 '<input type="hidden" name="orgurl" value="'.$url.                          }
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.                      }
 &mt($message,' <input type="hidden" name="'.                  }
     $env{'request.role'}.'" value="1" /><input type="button" value="'.                  if ($haschanges) {
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').                      ($errtext,$fatal) = 
 $help{'Caching'}.'</span></h3></form>'."\n\n");                          &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 }                      return $errtext if ($fatal);
                   }
               }
 sub init_breadcrumbs {          }
     my ($form,$text)=@_;  
     &Apache::lonhtmlcommon::clear_breadcrumbs();  # Group import/search
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",   if ($env{'form.importdetail'}) {
     text=>"Edit ".&Apache::loncommon::course_type(),      my @imports;
     faq=>273,      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
     bug=>'Instructor Interface',   if (defined($item)) {
                                             help => 'Docs_Adding_Course_Doc'});      my ($name,$url,$residx)=
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',   map { &unescape($_); } split(/\=/,$item);
     text=>$text,                      if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
     faq=>273,                          my ($suffix,$errortxt,$locknotfreed) =
     bug=>'Instructor Interface'});                              &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
 }                          if ($locknotfreed) {
                               $r->print($locknotfreed);
                           }
                           if ($suffix) {
                               $url =~ s/_new\./_$suffix./; 
 sub handler {                          } else {
     my $r = shift;                              return $errortxt;
     &Apache::loncommon::content_type($r,'text/html');                          }
     $r->send_http_header;                      } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
     return OK if $r->header_only;                          my $type = $1;
     my $type = &Apache::loncommon::course_type();                          my ($suffix,$errortxt,$locknotfreed) =
                               &new_timebased_suffix($coursedom,$coursenum,$type);
                           if ($locknotfreed) {
 # --------------------------------------------- Initialize help topics for this                              $r->print($locknotfreed);
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',                          }
                'Adding_External_Resource','Navigate_Content',                          if ($suffix) {
                'Adding_Folders','Docs_Overview', 'Load_Map',                              $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
                'Supplemental','Score_Upload_Form','Adding_Pages',                          } else {
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',                              return $errortxt;
                'Check_Resource_Versions','Verify_Content') {                          }
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);                      } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
     }                          if ($supplementalflag) {
     # Composite help files                              next unless ($1 eq 'supplemental');
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(                              if ($folder eq 'supplemental') {
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');                                  next unless ($2 eq 'default');
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(                              } else {
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');                                  next unless ($folder eq 'supplemental_'.$2);
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(                              }
     'Option_Response_Simple');                          } else {
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(                              next unless ($1 eq 'docs');
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');                              if ($folder eq 'default') {
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(                                  next unless ($2 eq 'default');
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');                              } else {
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');                                  next unless ($folder eq 'default_'.$2);
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');                              }
                           }
 # does this user have privileges to modify docs                      }
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});      push(@imports, [$name, $url, $residx]);
   if ($allowed && $env{'form.verify'}) {   }
       &init_breadcrumbs('verify','Verify Content');      }
       &verifycontent($r);              ($errtext,$fatal,my $fixuperrors) =
   } elsif ($allowed && $env{'form.listsymbs'}) {                  &group_import($coursenum, $coursedom, $folder,$container,
       &init_breadcrumbs('listsymbs','List Symbs');                                'londocs',@imports);
       &list_symbs($r);      return $errtext if ($fatal);
   } elsif ($allowed && $env{'form.docslog'}) {              if ($fixuperrors) {
       &init_breadcrumbs('docslog','Show Log');                  $r->print($fixuperrors);
       &docs_change_log($r);              }
   } elsif ($allowed && $env{'form.versions'}) {   }
       &init_breadcrumbs('versions','Check/Set Resource Versions');  # Loading a complete map
       &checkversions($r);   if ($env{'form.loadmap'}) {
   } elsif ($allowed && $env{'form.dumpcourse'}) {      if ($env{'form.importmap'}=~/\w/) {
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
       &dumpcourse($r);      my ($title,$url,$ext,$type)=split(/\:/,$res);
   } elsif ($allowed && $env{'form.exportcourse'}) {      my $idx=&LONCAPA::map::getresidx($url);
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');      $LONCAPA::map::resources[$idx]=$res;
       &exportcourse($r);      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
   } else {   }
 # is this a standard course?   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
       $folder.'.'.$container,1);
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);   return $errtext if ($fatal);
     my $forcestandard = 0;      } else {
     my $forcesupplement;   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
     my $script='';  
     my $showdoc=0;      }
     my $containertag;   }
     my $uploadtag;   &log_differences($plain);
       }
   # ---------------------------------------------------------------- End commands
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  # ---------------------------------------------------------------- Print screen
     ['folderpath','pagepath',      my $idx=0;
      'pagesymb']);      my $shown=0;
 # No folderpath, no pagepath, see if we have something stored      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {   $r->print('<div class="LC_Box">'.
         &Apache::loncommon::restore_course_settings('docs_folderpath',            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
                                               {'folderpath' => 'scalar'});    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
     }    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
     if (!$env{'form.folderpath'}) {    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
         &Apache::loncommon::restore_course_settings('docs_folderpath',    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
                                               {'pagepath' => 'scalar'});    '</ol>');
     }          if ($randompick>=0) {
     if ($env{'form.pagepath'}) {              $r->print('<p class="LC_warning">'
        $env{'form.folderpath'}='';                   .&mt('Caution: this folder is set to randomly pick a subset'
     }                       .' of resources. Adding or removing resources from this'
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {                       .' folder will change the set of resources that the'
         $env{'form.folderpath'} = 'supplemental&'.                       .' students see, resulting in spurious or missing credit'
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.                       .' for completed problems, not limited to ones you'
                                   $env{'form.folderpath'};                       .' modify. Do not modify the contents of this folder if'
     }                       .' it is in active student use.')
     &Apache::loncommon::store_course_settings('docs_folderpath',                   .'</p>'
                                                 {'pagepath' => 'scalar',              );
                                                  'folderpath' => 'scalar'});          }
     if ($env{'form.folderpath'}) {          if ($is_random_order) {
  my (@folderpath)=split('&',$env{'form.folderpath'});              $r->print('<p class="LC_warning">'
  $env{'form.foldername'}=&unescape(pop(@folderpath));                   .&mt('Caution: this folder is set to randomly order its'
  $env{'form.folder'}=pop(@folderpath);                       .' contents. Adding or removing resources from this folder'
     }                       .' will change the order of resources shown.')
     if ($env{'form.pagepath'}) {                   .'</p>'
         my (@pagepath)=split('&',$env{'form.pagepath'});              );
         $env{'form.pagename'}=&unescape(pop(@pagepath));          }
         $env{'form.folder'}=pop(@pagepath);          $r->print('</div>');
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      }
     '<input type="hidden" name="pagesymb" value="" />';  
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.      my ($to_show,$output,@allidx,@allmapidx,%filters,%lists,%curr_groups);
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';      %filters =  (
     }                    canremove      => [],
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {                    cancut         => [],
        $showdoc='/'.$1;                    cancopy        => [],
     }                    hiddenresource => [],
     unless ($showdoc) { # got called from remote                    encrypturl     => [],
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||                    randomorder    => [],
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {                    randompick     => [],
            $forcestandard = 1;                  );
        }      %curr_groups = &Apache::longroup::coursegroups();
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);      &Apache::loncommon::start_data_table_count(); #setup a row counter 
       foreach my $res (@LONCAPA::map::order) {
        if ($allowed) {          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);          $name=&LONCAPA::map::qtescape($name);
          $script=&Apache::lonratedt::editscript('simple');          $url=&LONCAPA::map::qtescape($url);
        }          unless ($name) {  $name=(split(/\//,$url))[-1]; }
     } else { # got called in sequence from course          unless ($name) { $idx++; next; }
        $allowed=0;          push(@allidx,$res);
     }          if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
               push(@allmapidx,$res);
 # get course data          }
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};                                $coursenum,$coursedom,$crstype,
                                 $pathitem,$supplementalflag,$container,
 # get personal data                                \%filters,\%curr_groups);
     my $uname=$env{'user.name'};          $idx++;
     my $udom=$env{'user.domain'};          $shown++;
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));      }
       &Apache::loncommon::end_data_table_count();
 # graphics settings  
       my $need_save;
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");      if (($allowed) || ($supplementalflag && $folder eq 'supplemental')) {
           my $toolslink;
     if ($allowed) {          if ($allowed || &Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
  $script .= &editing_js($udom,$uname);              $toolslink = '<table><tr><td>'
     }                         .&Apache::loncommon::help_open_menu('Navigation Screen',
 # -------------------------------------------------------------------- Body tag                                                             'Navigation_Screen',undef,'RAT')
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';                         .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];                         .'<td align="left"><ul id="LC_toolbar">'
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,                         .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
     {'force_register' => $showdoc,                         .'id="LC_content_toolbar_edittoplevel" '
                                      'bread_crumbs' => $brcrum}).                         .'class="LC_toolbarItem" '
       &Apache::loncommon::help_open_menu('','',273,'RAT'));                         .'title="'.&mt('Supplemental Content Editor').'">'
                           .'</a></li></ul></td></tr></table><br />';
   my %allfiles = ();          }
   my %codebase = ();          if ($shown) {
   my ($upload_result,$upload_output);              if ($allowed) {
   if ($allowed) {                  $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
       if (($env{'form.uploaddoc.filename'}) &&                            .&Apache::loncommon::start_data_table(undef,'contentlist')
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {                            .&Apache::loncommon::start_data_table_header_row()
 # Process file upload - phase one - upload and parse primary file.                              .'<th colspan="2">'.&mt('Move').'</th>'
   undef($hadchanges);                            .'<th colspan="2">'.&mt('Actions').'</th>'
           $upload_result = &process_file_upload(\$upload_output,$coursenum,                            .'<th>'.&mt('Document').'</th>';
  $coursedom,\%allfiles,                  if ($folder !~ /^supplemental/) {
  \%codebase,$1);                      $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
   if ($hadchanges) {                  }
       &mark_hash_old();                  $to_show .= &Apache::loncommon::end_data_table_header_row();
   }                  if ($folder !~ /^supplemental/) {
           if ($upload_result eq 'phasetwo') {                      $lists{'canhide'} = join(',',@allidx);
               $r->print($upload_output);                      $lists{'canrandomlyorder'} = join(',',@allmapidx);
           }                      my @possfilters = ('canremove','cancut','cancopy','hiddenresource','encrypturl',
       } elsif ($env{'form.phasetwo'}) {                                         'randomorder','randompick');
           my %newname = ();                      foreach my $item (@possfilters) {
           my %origname = ();                          if (ref($filters{$item}) eq 'ARRAY') {
           my %attribs = ();                              if (@{$filters{$item}} > 0) {
           my $updateflag = 0;                                  $lists{$item} = join(',',@{$filters{$item}});
           my $residx = $env{'form.newidx'};                              }
           my $primary_url = &unescape($env{'form.primaryurl'});                          }
 # Process file upload - phase two - gather secondary files.                      }
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {                      if (@allidx > 0) {
               if ($env{'form.embedded_item_'.$i.'.filename'}) {                          my $path;
                   my $javacodebase;                          if ($env{'form.folderpath'}) {
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);                              $path =
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});                                  &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
                   if (exists($env{'form.embedded_codebase_'.$i})) {                          }
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});                            if (@allidx > 1) {
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;                              $to_show .=
                   }                                  &Apache::loncommon::continue_data_table_row().
                   my @attributes = ();                                  '<td colspan="2">&nbsp;</td>'.
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {                                  '<td>'.
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});                                  &multiple_check_form('actions',\%lists).
                   } else {                                  '</td>'.
                       @attributes = ($env{'form.embedded_attrib_'.$i});                                  '<td>&nbsp;</td>'.
                   }                                  '<td>&nbsp;</td>'.
                   foreach my $attr (@attributes) {                                  '<td colspan="4">'.
                       push(@{$attribs{$i}},&unescape($attr));                                  &multiple_check_form('settings',\%lists).
                   }                                  '</td>'.
                   if ($javacodebase) {                                  &Apache::loncommon::end_data_table_row();
                       $codebase{$i} = $javacodebase;                               $need_save = 1;
                       $codebase{$i} =~ s#/$##;                          }
                       $updateflag = 1;                      }
                   }                  }
               }                  $to_show .= $output.' '
               unless ($newname{$i} eq $origname{$i}) {                             .&Apache::loncommon::end_data_table()
                   $updateflag = 1;                             .'<br style="line-height:2px;" />'
               }                             .&Apache::loncommon::end_scrollbox();
           }              } else {
 # Process file upload - phase three - modify primary file                  $to_show .= $toolslink
           if ($updateflag) {                             .&Apache::loncommon::start_data_table('LC_tableOfContent')
               my ($content,$rtncode);                             .$output.' '
               my $updateflag = 0;                             .&Apache::loncommon::end_data_table();
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);              }
               if ($getstatus eq 'ok') {          } else {
                   foreach my $item (keys(%newname)) {              if (!$allowed) {
                       if ($newname{$item} ne $origname{$item}) {                  $to_show .= $toolslink;
                           my $attrib_regexp = '';              }
                           if (@{$attribs{$item}} > 1) {              $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
                               $attrib_regexp = join('|',@{$attribs{$item}});                         .'<div class="LC_info" id="contentlist">'
                           } else {                         .&mt('Currently empty')
                               $attrib_regexp = $attribs{$item}[0];                         .'</div>'
                           }                         .&Apache::loncommon::end_scrollbox();
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {          }
                           }      } else {
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;          if ($shown) {
                       }              $to_show = '<div>'
                       if (exists($codebase{$item})) {                        .&Apache::loncommon::start_data_table('LC_tableOfContent')
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs                        .$output
                       }                        .&Apache::loncommon::end_data_table()
                   }                        .'</div>';
 # Save edited file.          } else {
                   my $saveresult;              $to_show = '<div class="LC_info" id="contentlist">'
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};                        .&mt('Currently empty')
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};                        .'</div>'
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);          }
               } else {      }
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);      my $tid = 1;
               }      if ($supplementalflag) {
           }          $tid = 2;
       }      }
   }      if ($allowed) {
           my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
   unless ($showdoc ||  $upload_result eq 'phasetwo') {          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,
 # -----------------------------------------------------------------------------                                         $jumpto,$readfile,$need_save,"$folder.$container"));
        my %lt=&Apache::lonlocal::texthash(          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
                 'uplm' => 'Upload a new main '.lc($type).' document',      } else {
                 'upls' => 'Upload a new supplemental '.lc($type).' document',          $r->print($to_show);
                 'impp' => 'Import a document',      }
                 'pubd' => 'Published Documents',      return;
  'copm' => 'All documents out of a published map into this folder',  }
                 'upld' => 'Upload Document',  
                 'srch' => 'Search',  sub multiple_check_form {
                 'impo' => 'Import',      my ($caller,$listsref) = @_;
  'book' => 'Import Bookmarks',      return unless (ref($listsref) eq 'HASH');
                 'selm' => 'Select Map',      my $output =
                 'load' => 'Load Map',      '<form action="/adm/coursedocs" method="post" name="togglemult'.$caller.'">'.
                 'reco' => 'Recover Deleted Resources',      '<span class="LC_nobreak" style="font-size:x-small;font-weight:bold;">'.
                 'newf' => 'New Folder',      '<label><input type="radio" name="showmultpick" value="0" onclick="javascript:togglePick('."'$caller','0'".');" checked="checked" />'.&mt('one').'</label>'.('&nbsp;'x2).'<label><input type="radio" name="showmultpick" value="1" onclick="javascript:togglePick('."'$caller','1'".');" />'.&mt('multiple').'</label></span><span id="more'.$caller.'" class="LC_nobreak LC_docs_ext_edit"></span></form>'.
                 'newp' => 'New Composite Page',      '<div id="multi'.$caller.'" style="display:none;margin:0;padding:0;border:0">'.
                 'extr' => 'External Resource',      '<form action="/adm/coursedocs" method="post" name="cumulative'.$caller.'">'."\n".
                 'syll' => 'Syllabus',      '<fieldset id="allfields'.$caller.'" style="display:none"><legend style="font-size:x-small;">'.&mt('check/uncheck all').'</legend>'."\n";
                 'navc' => 'Navigate Contents',      if ($caller eq 'settings') {
                 'sipa' => 'Simple Page',          $output .= 
                 'sipr' => 'Simple Problem',              '<table><tr>'.
                 'drbx' => 'Drop Box',              '<td class="LC_docs_entry_parameter">'.
                 'scuf' => 'Score Upload Form',              '<span class="LC_nobreak"><label>'.
                 'bull' => 'Bulletin Board',              '<input type="checkbox" name="hiddenresourceall" id="hiddenresourceall" onclick="propagateState(this.form,'."'hiddenresource'".')" />'.&mt('Hidden').
                 'mypi' => 'My Personal Info',              '</label></span></td>'.
                 'grpo' => 'Group Files',              '<td class="LC_docs_entry_parameter">'.
                 'rost' => 'Course Roster',              '<span class="LC_nobreak"><label><input type="checkbox" name="randompickall" id="randompickall" onclick="updatePick(this.form,'."'all','check'".');propagateState(this.form,'."'randompick'".');propagateState(this.form,'."'rpicknum'".');" />'.&mt('Randomly Pick').'</label><span id="rpicktextall"></span><input type="hidden" name="rpicknumall" id="rpicknumall" value="" />'.
  'abou' => 'About User',              '</span></td>'.
                 'imsf' => 'Import IMS package',              '</tr>'."\n".
                 'file' =>  'File',              '<tr>'.
                 'title' => 'Title',              '<td class="LC_docs_entry_parameter">'.
                 'comment' => 'Comment',              '<span class="LC_nobreak"><label><input type="checkbox" name="encrypturlall" id="encrypturlall" onclick="propagateState(this.form,'."'encrypturl'".')" />'.&mt('URL hidden').'</label></span></td><td class="LC_docs_entry_parameter"><span class="LC_nobreak"><label><input type="checkbox" name="randomorderall" id="randomorderall" onclick="propagateState(this.form,'."'randomorder'".')" />'.&mt('Random Order').
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',              '</label></span>'.
  'nd' => 'New Document',              '</td></tr></table>'."\n";
  'pm' => 'Published Map',      } else {
  'sd' => 'Special Document',          $output .=
  'mo' => 'More Options',              '<table><tr>'.
  'hao' => 'Hide all Options'              '<td class="LC_docs_entry_parameter">'.
   );              '<span class="LC_nobreak LC_docs_remove">'.
 # -----------------------------------------------------------------------------              '<label><input type="checkbox" name="removeall" id="removeall" onclick="propagateState(this.form,'."'remove'".')" />'.&mt('Remove').
  my $fileupload=(<<FIUP);              '</label></span></td>'.
  $lt{'file'}:<br />              '<td class="LC_docs_entry_parameter">'.
  <input type="file" name="uploaddoc" size="40" />              '<span class="LC_nobreak LC_docs_cut">'.
 FIUP              '<label><input type="checkbox" name="cut" id="cutall" onclick="propagateState(this.form,'."'cut'".');" />'.&mt('Cut').
               '</label></span></td>'."\n".
  my $checkbox=(<<CHBO);              '<td class="LC_docs_entry_parameter">'.
  <!-- <label>$lt{'parse'}?              '<span class="LC_nobreak LC_docs_copy">'.
  <input type="checkbox" name="parserflag" />              '<label><input type="checkbox" name="copyall" id="copyall" onclick="propagateState(this.form,'."'copy'".')" />'.&mt('Copy').
  </label> -->              '</label></span></td>'.
  <label>              '</tr></table>'."\n";
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}      }
  </label>      $output .= 
 CHBO          '</fieldset>'.
           '<input type="hidden" name="allidx" value="'.$listsref->{'canhide'}.'" />';
  my $fileuploadform=(<<FUFORM);      if ($caller eq 'settings') {
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">          $output .= 
  $fileupload          '<input type="hidden" name="allmapidx" value="'.$listsref->{'canrandomlyorder'}.'" />'."\n".
  <br />          '<input type="hidden" name="currhiddenresource" value="'.$listsref->{'hiddenresource'}.'" />'."\n".
  $lt{'title'}:<br />          '<input type="hidden" name="currencrypturl" value="'.$listsref->{'encrypturl'}.'" />'."\n".
  <input type="text" size="50" name="comment" />          '<input type="hidden" name="currrandomorder" value="'.$listsref->{'randomorder'}.'" />'."\n".
  $uploadtag          '<input type="hidden" name="currrandompick" value="'.$listsref->{'randompick'}.'" />'."\n";
  <input type="hidden" name="cmd" value="upload_default" />      } elsif ($caller eq 'actions') {
  <br />          $output .=
  <span class="LC_nobreak">          '<input type="hidden" name="allremoveidx" id="allremoveidx" value="'.$listsref->{'canremove'}.'" />'.
  $checkbox          '<input type="hidden" name="allcutidx" id="allcutidx" value="'.$listsref->{'cancut'}.'" />'.
  </span>          '<input type="hidden" name="allcopyidx" id="allcopyidx" value="'.$listsref->{'cancopy'}.'" />';
  <br />      }
  <br />      $output .= 
  <span class="LC_nobreak">          '</form>'.
  <input type="submit" value="$lt{'upld'}" />          '</div>';
  $help{'Uploading_From_Harddrive'}      return $output;
  </span>  }
  </form>  
 FUFORM  sub process_file_upload {
       my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd,$crstype) = @_;
  my $simpleeditdefaultform=(<<SEDFFORM);  # upload a file, if present
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">      my $filesize = length($env{'form.uploaddoc'});
  $lt{'pubd'}<br />      if (!$filesize) {
  $uploadtag          $$upload_output = '<div class="LC_error">'.
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />                             &mt('Unable to upload [_1]. (size = [_2] bytes)',
  <br />                            '<span class="LC_filename">'.$env{'form.uploaddoc.filename'}.'</span>',
  <span class="LC_nobreak">                            $filesize).'<br />'.
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />                            &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
  $help{'Importing_LON-CAPA_Resource'}                            '</div>';
  </span>          return;
  <br />      }
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />      my $quotatype = 'unofficial';
  <hr />      if ($crstype eq 'Community') {
  <p>          $quotatype = 'community';
  $lt{'copm'}<br />      } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.instcode'}) {
  <input type="text" size="40" name="importmap" /><br />          $quotatype = 'official';
  <span class="LC_nobreak"><input type="button"      }
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      if (&Apache::loncommon::get_user_quota($coursenum,$coursedom,'course',$quotatype)) {
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />          $filesize = int($filesize/1000); #expressed in kb
  $help{'Load_Map'}</span>          $$upload_output = &Apache::loncommon::excess_filesize_warning($coursenum,$coursedom,'course',
  </p>                                                                        $env{'form.uploaddoc.filename'},$filesize,'upload');
  </form>          return if ($$upload_output);
 SEDFFORM      }
       my ($parseaction,$showupload,$nextphase,$mimetype);
  my $extresourcesform=(<<ERFORM);      if ($env{'form.parserflag'}) {
  <form action="/adm/coursedocs" method="post" name="newext">          $parseaction = 'parse';
  $uploadtag      }
  <input type="hidden" name="importdetail" value="" />      my $folder=$env{'form.folder'};
  <span class="LC_nobreak">      if ($folder eq '') {
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"          $folder='default';
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      }
  </span>      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  </form>          my $errtext='';
 ERFORM          my $fatal=0;
           my $container='sequence';
     if ($allowed) {          if ($env{'form.folderpath'} =~ /:1$/) {
  &update_paste_buffer($coursenum,$coursedom);              $container='page';
        my $dumpbut=&dumpbutton();          }
        my $exportbut=&exportbutton();          ($errtext,$fatal)=
        my %lt=&Apache::lonlocal::texthash(              &mapread($coursenum,$coursedom,$folder.'.'.$container);
  'vc' => 'Verify Content',          if ($#LONCAPA::map::order<1) {
  'cv' => 'Check/Set Resource Versions',              $LONCAPA::map::order[0]=1;
  'ls' => 'List Symbs',              $LONCAPA::map::resources[1]='';
                                          'sl' => 'Show Log'          }
   );          my $destination = 'docs/';
           if ($folder =~ /^supplemental/) {
        my $folderpath=$env{'form.folderpath'};              $destination = 'supplemental/';
        if (!$folderpath) {          }
    if ($env{'form.folder'} eq '' ||          if (($folder eq 'default') || ($folder eq 'supplemental')) {
        $env{'form.folder'} eq 'supplemental') {              $destination .= 'default/';
        $folderpath='default&'.          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
    &escape(&mt('Main '.$type.' Documents'));              $destination .=  $2.'/';
    }          }
        }          if ($fatal) {
        unless ($env{'form.pagepath'}) {              $$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>';
            $containertag = '<input type="hidden" name="folderpath" value="" />';              return;
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';          }
        }  # this is for a course, not a user, so set context to coursedoc.
        $r->print(&generate_admin_options($containertag,$uploadtag,\%lt,\%help,\%env));          my $newidx=&LONCAPA::map::getresidx();
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',          $destination .= $newidx;
      &mt('Editing the Table of Contents for your '.$type)));          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
     }   $parseaction,$allfiles,
 # --------------------------------------------------------- Standard documents   $codebase,undef,undef,undef,undef,
     $r->print('<table class="LC_docs_documents">');                                                  undef,undef,\$mimetype);
           if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
     if (($standard) && ($allowed) && (!$forcesupplement)) {              my $stored = $1;
  $r->print('<tr><td class="LC_docs_document">');              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 #  '<h2>'.&mt('Main Course Documents').                            $stored.'</span>').'</p>';
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');          } else {
        my $folder=$env{'form.folder'};              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
        if ($folder eq '' || $folder eq 'supplemental') {              
            $folder='default';              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));              return;
            $uploadtag = '<input type="hidden" name="folderpath" value="'.          }
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';          my $ext='false';
        }          if ($url=~m{^http://}) { $ext='true'; }
        my $postexec='';   $url     = &LONCAPA::map::qtunescape($url);
        if ($folder eq 'default') {          my $comment=$env{'form.comment'};
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');   $comment = &LONCAPA::map::qtunescape($comment);
        } else {          if ($folder=~/^supplemental/) {
            #$postexec='self.close();';                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
        }                    $env{'user.domain'}.'___&&&___'.$comment;
        $hadchanges=0;          }
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,  
    $upload_output,$type);          $LONCAPA::map::resources[$newidx]=
        if ($error) {      $comment.':'.$url.':'.$ext.':normal:res';
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
        }          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
        if ($hadchanges) {      $folder.'.'.$container,1);
    &mark_hash_old();          if ($fatal) {
        }              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
        &changewarning($r,$postexec);              return;
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.          } else {
                      '.sequence';              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.                  $$upload_output = $showupload;
                      '.page';                  my $total_embedded = scalar(keys(%{$allfiles}));
  my $container='sequence';                  if ($total_embedded > 0) {
  if ($env{'form.pagepath'}) {                      my $uploadphase = 'upload_embedded';
     $container='page';                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
  }      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;                      my ($embedded,$num) = 
                           &Apache::loncommon::ask_for_embedded_content(
                               '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
                       if ($embedded) {
  my $recoverform=(<<RFORM);                          if ($num) {
  <form action="/adm/groupsort" method="post" name="recover">                              $$upload_output .=
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
  </form>                              $nextphase = $uploadphase;
 RFORM                          } else {
                               $$upload_output .= $embedded;
  my $imspform=(<<IMSPFORM);                          }
  <form action="/adm/imsimportdocs" method="post" name="ims">                      } else {
  <input type="hidden" name="folder" value="$folder" />                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />                      }
  </form>                  } else {
 IMSPFORM                      $$upload_output .= &mt('No embedded items identified').'<br />';
                   }
  my $newnavform=(<<NNFORM);                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
  <form action="/adm/coursedocs" method="post" name="newnav">              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
  $uploadtag                  $nextphase = 'decompress_uploaded';
  <input type="hidden" name="importdetail"                  my $position = scalar(@LONCAPA::map::order)-1;
  value="$lt{'navc'}=/adm/navmaps" />                  my $noextract = &return_to_editor();
  <span class="LC_nobreak">                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
  <input name="newnav" type="submit" value="$lt{'navc'}" />                  my %archiveitems = (
  $help{'Navigate_Content'}                      folderpath => $env{'form.folderpath'},
  </span>                      cmd        => $nextphase,
  </form>                      newidx     => $newidx,
 NNFORM                      position   => $position,
  my $newsmppageform=(<<NSPFORM);                      phase      => $nextphase,
  <form action="/adm/coursedocs" method="post" name="newsmppg">                      comment    => $comment,
  $uploadtag                  );
  <input type="hidden" name="importdetail" value="" />                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
  <span class="LC_nobreak">                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
  <input name="newsmppg" type="button" value="$lt{'sipa'}"                  $$upload_output = $showupload.
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}                                    &Apache::loncommon::decompress_form($mimetype,
  </span>                                        $archiveurl,'/adm/coursedocs',$noextract,
  </form>                                        \%archiveitems,\@current);
 NSPFORM              }
           }
  my $newsmpproblemform=(<<NSPROBFORM);      }
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">      return $nextphase;
  $uploadtag  }
  <input type="hidden" name="importdetail" value="" />  
  <span class="LC_nobreak">  sub get_dir_list {
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"      my ($url,$coursenum,$coursedom,$newidx) = @_;
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}      my ($destination,$dir_root) = &embedded_destination();
  </span>      my ($dirlistref,$listerror) =  
  </form>          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
       my @dir_lines;
 NSPROBFORM      my $dirptr=16384;
       if (ref($dirlistref) eq 'ARRAY') {
  my $newdropboxform=(<<NDBFORM);          foreach my $dir_line (sort
  <form action="/adm/coursedocs" method="post" name="newdropbox">                            {
  $uploadtag                                      my ($afile)=split('&',$a,2);
  <input type="hidden" name="importdetail" value="" />                                my ($bfile)=split('&',$b,2);
  <span class="LC_nobreak">                                          return (lc($afile) cmp lc($bfile));
  <input name="newdropbox" type="button" value="$lt{'drbx'}"                            } (@{$dirlistref})) {
  onClick="javascript:makedropbox();" />              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
  </span>                      $filename =~ s/\s+$//;
  </form>              next if ($filename =~ /^\.\.?$/); 
 NDBFORM              my $isdir = 0;
               if ($dirptr&$testdir) {
  my $newexuploadform=(<<NEXUFORM);                  $isdir = 1;
  <form action="/adm/coursedocs" method="post" name="newexamupload">              }
  $uploadtag              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
  <input type="hidden" name="importdetail" value="" />          }
  <span class="LC_nobreak">      }
  <input name="newexamupload" type="button" value="$lt{'scuf'}"      return @dir_lines;
  onClick="javascript:makeexamupload();" />  }
  $help{'Score_Upload_Form'}  
  </span>  sub is_supplemental_title {
  </form>      my ($title) = @_;
 NEXUFORM      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
   }
  my $newbulform=(<<NBFORM);  
  <form action="/adm/coursedocs" method="post" name="newbul">  # --------------------------------------------------------------- An entry line
  $uploadtag  
  <input type="hidden" name="importdetail" value="" />  sub entryline {
  <span class="LC_nobreak">      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
  <input name="newbulletin" type="button" value="$lt{'bull'}"          $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups)=@_;
  onClick="javascript:makebulboard();" />      my ($foldertitle,$renametitle);
  $help{'Bulletin Board'}      if (&is_supplemental_title($title)) {
  </span>   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
  </form>      } else {
 NBFORM   $title=&HTML::Entities::encode($title,'"<>&\'');
    $renametitle=$title;
  my $newaboutmeform=(<<NAMFORM);   $foldertitle=$title;
  <form action="/adm/coursedocs" method="post" name="newaboutme">      }
  $uploadtag  
  <input type="hidden" name="importdetail"      my $orderidx=$LONCAPA::map::order[$index];
  value="$plainname=/adm/$udom/$uname/aboutme" />  
  <span class="LC_nobreak">      $renametitle=~s/\\/\\\\/g;
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      $renametitle=~s/\&quot\;/\\\"/g;
  $help{'My Personal Info'}      $renametitle=~s/ /%20/g;
  </span>      my $line=&Apache::loncommon::start_data_table_row();
  </form>      my ($form_start,$form_end,$form_common,$form_param);
 NAMFORM  # Edit commands
       my ($esc_path, $path, $symb);
  my $newaboutsomeoneform=(<<NASOFORM);      if ($env{'form.folderpath'}) {
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">   $esc_path=&escape($env{'form.folderpath'});
  $uploadtag   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  <input type="hidden" name="importdetail" value="" />   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
  <span class="LC_nobreak">      }
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"      my $isexternal;
  onClick="javascript:makeabout();" />      if ($residx) {
  </span>          my $currurl = $url;
  </form>          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
 NASOFORM          if ($currurl =~ m{^/adm/wrapper/ext/}) {
               $isexternal = 1;
           }
  my $newrosterform=(<<NROSTFORM);          if (!$supplementalflag) {
  <form action="/adm/coursedocs" method="post" name="newroster">              my $path = 'uploaded/'.
  $uploadtag                         $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
  <input type="hidden" name="importdetail"                         $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
  value="$lt{'rost'}=/adm/viewclasslist" />              $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
  <span class="LC_nobreak">                                                   $residx,
  <input name="newroster" type="submit" value="$lt{'rost'}" />                                                   &Apache::lonnet::declutter($currurl));
  $help{'Course Roster'}          }
  </span>      }
  </form>      my ($renamelink,%lt,$ishash);
 NROSTFORM      if (ref($filtersref) eq 'HASH') {
           $ishash = 1;
        $r->print(<<ENDFORM);      }
   
 <ul class="LC_TabContent">      if ($allowed) {
 <li>$lt{'nd'}</li>          $form_start = '
 <li>$lt{'pm'}</li>     <form action="/adm/coursedocs" method="post">
 <li>$lt{'pubd'}</li>  ';
 <li>$lt{'sd'}</li>          $form_common=(<<END);
 <li>$lt{'mo'}</li>     <input type="hidden" name="folderpath" value="$path" />
 <li>$lt{'hao'}</li>     <input type="hidden" name="symb" value="$symb" />
 </ul>  END
           $form_param=(<<END);
 <table class="LC_docs_adddocs">     <input type="hidden" name="setparms" value="$orderidx" />
 <!-- <tr>     <input type="hidden" name="changeparms" value="0" />
 <th>$lt{'uplm'}</th>  END
 <th>$lt{'impp'}</th>          $form_end = '</form>';
 <th>$lt{'spec'}</th>  
 </tr> -->   my $incindex=$index+1;
 <tr>   my $selectbox='';
 <td>   if (($#LONCAPA::map::order>0) &&
 $fileuploadform      ((split(/\:/,
 </td>       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
 <td>       ne '') &&
 $simpleeditdefaultform      ((split(/\:/,
 <hr />       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
 $recoverform       ne '')) {
 ENDFORM      $selectbox=
        unless ($env{'form.pagepath'}) {   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
    $r->print(<<ENDFORM);   '<select name="newpos" onchange="this.form.submit()">';
 <hr />      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
 $extresourcesform   if ($i==$incindex) {
  <br />      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
 $imspform   } else {
 ENDFORM      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
        }   }
        $r->print('</td><td>');      }
        unless ($env{'form.pagepath'}) {      $selectbox.='</select>';
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');   }
    %lt=&Apache::lonlocal::texthash(
                   'up' => 'Move Up',
    'dw' => 'Move Down',
  my $newpageform=(<<NPFORM);   'rm' => 'Remove',
  <form action="/adm/coursedocs" method="post" name="newpage">                  'ct' => 'Cut',
  <input type="hidden" name="folderpath" value="$path" />   'rn' => 'Rename',
  <input type="hidden" name="importdetail" value="" />   'cp' => 'Copy',
  <span class="LC_nobreak">                  'ex' => 'External Resource',
  <input name="newpage" type="button"                  'ed' => 'Edit',
  onClick="javascript:makenewpage(this.form,'$pageseq');"                  'pr' => 'Preview',
  value="$lt{'newp'}" />$help{'Adding_Pages'}                  'sv' => 'Save',
  </span>                  'ul' => 'URL',
  </form>                  'ti' => 'Title', 
 NPFORM                  );
    my %denied = &action_restrictions($coursenum,$coursedom,$url,
  my $newfolderform=(<<NFFORM);                                            $env{'form.folderpath'},
  <form action="/adm/coursedocs" method="post" name="newfolder">                                            $currgroups);
  <input type="hidden" name="folderpath" value="$path" />          my ($copylink,$cutlink,$removelink);
  <input type="hidden" name="importdetail" value="" />   my $skip_confirm = 0;
  <span class="LC_nobreak">   if ( $folder =~ /^supplemental/
  <input name="newfolder" type="button"       || ($url =~ m{( /smppg$
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      |/syllabus$
  value="$lt{'newf'}" />$help{'Adding_Folders'}      |/aboutme$
  </span>      |/navmaps$
  </form>      |/bulletinboard$
 NFFORM      |\.html$)}x)
                || $isexternal) {
  my $newsylform=(<<NSYLFORM);      $skip_confirm = 1;
  <form action="/adm/coursedocs" method="post" name="newsyl">   }
  $uploadtag  
  <input type="hidden" name="importdetail"   if ($denied{'copy'}) {
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />              $copylink=(<<ENDCOPY)
  <span class="LC_nobreak">  <span style="visibility: hidden;">$lt{'cp'}</span>
  <input name="newsyl" type="submit" value="$lt{'syll'}" />  ENDCOPY
  $help{'Syllabus'}          } else {
  </span>              my $formname = 'edit_copy_'.$orderidx;
  </form>              my $js = "javascript:checkForSubmit(document.forms.renameform,'copy','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 NSYLFORM      $copylink=(<<ENDCOPY);
   <form name="$formname" method="post" action="/adm/coursedocs">
  my $newgroupfileform=(<<NGFFORM);  $form_common
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">  <input type="checkbox" name="copy" id="copy_$orderidx" value="$orderidx" onclick="javascript:singleCheck(this,'$orderidx','copy');" class="LC_hidden" /><a href="$js" class="LC_docs_copy">$lt{'cp'}</a>
  $uploadtag  $form_end
  <input type="hidden" name="importdetail"  ENDCOPY
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />              if (($ishash) && (ref($filtersref->{'cancopy'}) eq 'ARRAY')) {
  <span class="LC_nobreak">                  push(@{$filtersref->{'cancopy'}},$orderidx);
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />              }
  $help{'Group Files'}          }
  </span>   if ($denied{'cut'}) {
  </form>              $cutlink=(<<ENDCUT);
 NGFFORM  <span style="visibility: hidden;">$lt{'ct'}</span>
   ENDCUT
           } else {
            $r->print(<<ENDFORM);              my $formname = 'edit_cut_'.$orderidx;
 <br />              my $js = "javascript:checkForSubmit(document.forms.renameform,'cut','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 $newfolderform      $cutlink=(<<ENDCUT);
 <br />  <form name="$formname" method="post" action="/adm/coursedocs">
 $newpageform  $form_common
 <br />  <input type="hidden" name="skip_$orderidx" id="skip_cut_$orderidx" value="$skip_confirm" />
 $newsylform  <input type="checkbox" name="cut" id="cut_$orderidx" value="$orderidx" onclick="javascript:singleCheck(this,'$orderidx','cut');" class="LC_hidden" /><a href="$js" class="LC_docs_cut">$lt{'ct'}</a>
 <br />  $form_end
 $newnavform  ENDCUT
 <br />              if (($ishash) && (ref($filtersref->{'cancut'}) eq 'ARRAY')) {
 $newsmppageform                  push(@{$filtersref->{'cancut'}},$orderidx);
 <br />              }
 $newsmpproblemform          }
 <br />          if ($denied{'remove'}) {
 $newdropboxform              $removelink=(<<ENDREM);
 <br />  <span style="visibility: hidden;">$lt{'rm'}</a>
 $newexuploadform  ENDREM
 <br />          } else {
 $newbulform              my $formname = 'edit_remove_'.$orderidx;
 <br />              my $js = "javascript:checkForSubmit(document.forms.renameform,'remove','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm);";
 $newaboutmeform              $removelink=(<<ENDREM);
 <br />  <form name="$formname" method="post" action="/adm/coursedocs">
 $newaboutsomeoneform  $form_common
 <br />  <input type="hidden" name="skip_$orderidx" id="skip_remove_$orderidx" value="$skip_confirm" />
 $newgroupfileform  <input type="checkbox" name="remove" id="remove_$orderidx" value="$orderidx" onclick="javascript:singleCheck(this,'$orderidx','remove');" class="LC_hidden" /><a href="$js" class="LC_docs_remove">$lt{'rm'}</a>
 <br />  $form_end
 $newrosterform  ENDREM
 ENDFORM              if (($ishash) && (ref($filtersref->{'canremove'}) eq 'ARRAY')) {
        }                  push(@{$filtersref->{'canremove'}},$orderidx);
        if ($env{'form.pagepath'}) {              }
            $r->print(<<ENDBLOCK);          }
 $newsmpproblemform          $renamelink=(<<ENDREN);
 <br />  <a href='javascript:changename("$esc_path","$index","$renametitle");' class="LC_docs_rename">$lt{'rn'}</a>
 $newexuploadform  ENDREN
 ENDBLOCK   $line.=(<<END);
        }  <td>
        $r->print('</td></tr>'."\n".  <div class="LC_docs_entry_move">
 '</table>');    <a href='/adm/coursedocs?cmd=up_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
        $r->print('</td></tr>');      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
     }    </a>
 # ----------------------------------------------------- Supplemental documents  </div>
     if (!$forcestandard) {  <div class="LC_docs_entry_move">
        $r->print('<tr><td class="LC_docs_document">');    <a href='/adm/coursedocs?cmd=down_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
 # '<h2>'.&mt('Supplemental Course Documents').      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');    </a>
        my $folder=$env{'form.folder'};  </div>
        unless ($folder=~/^supplemental/) {  </td>
    $folder='supplemental';  <td>
        }     $form_start
        if ($folder =~ /^supplemental$/ &&     $form_param
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {     $form_common
           $env{'form.folderpath'} = 'supplemental&'.     $selectbox
                                     &escape(&mt('Supplemental '.$type.' Documents'));     $form_end
        }  </td>
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);  <td class="LC_docs_entry_commands LC_nobreak">
        if ($error) {  $removelink
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');  $cutlink
        }  $copylink
        if ($allowed) {  </td>
    my $folderseq=  END
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.      }
        '.sequence';  # Figure out what kind of a resource this is
       my ($extension)=($url=~/\.(\w+)$/);
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      my $uploaded=($url=~/^\/*uploaded\//);
       my $icon=&Apache::loncommon::icon($url);
  my $supupdocform=(<<SUPDOCFORM);      my $isfolder;
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">      my $ispage;
  $fileupload      my $containerarg;
  <br />      if ($uploaded) {
  <br />          if (($extension eq 'sequence') || ($extension eq 'page')) {
  <span class="LC_nobreak">              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
  $checkbox              $containerarg = $1;
  </span>      if ($extension eq 'sequence') {
  <br /><br />          $icon=$iconpath.'navmap.folder.closed.gif';
  $lt{'comment'}:<br />                  $isfolder=1;
  <textarea cols=50 rows=4 name='comment'>              } else {
  </textarea>                  $icon=$iconpath.'page.gif';
  <br />                  $ispage=1;
  <input type="hidden" name="folderpath" value="$path" />              }
  <input type="hidden" name="cmd" value="upload_supplemental" />              if ($allowed) {
  <span class="LC_nobreak">                  $url='/adm/coursedocs?';
  <input type="submit" value="$lt{'upld'}" />              } else {
  $help{'Uploading_From_Harddrive'}                  $url='/adm/supplemental?';
  </span>              }
  </form>   } else {
 SUPDOCFORM      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
    }
  my $supnewfolderform=(<<SNFFORM);      }
  <form action="/adm/coursedocs" method="post" name="supnewfolder">  
  <input type="hidden" name="folderpath" value="$path" />      my ($editlink,$extresform);
  <input type="hidden" name="importdetail" value="" />      my $orig_url = $url;
  <span class="LC_nobreak">      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
  <input name="newfolder" type="button"      $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      if (!$supplementalflag && $residx && $symb) {
  value="$lt{'newf'}" /> $help{'Adding_Folders'}          if ((!$isfolder) && (!$ispage)) {
  </span>      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  </form>      $url=&Apache::lonnet::clutter($url);
 SNFFORM      if ($url=~/^\/*uploaded\//) {
           $url=~/\.(\w+)$/;
           my $embstyle=&Apache::loncommon::fileembstyle($1);
  my $supnewextform=(<<SNEFORM);          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
  <form action="/adm/coursedocs" method="post" name="supnewext">      $url='/adm/wrapper'.$url;
  <input type="hidden" name="folderpath" value="$path" />          } elsif ($embstyle eq 'ssi') {
  <input type="hidden" name="importdetail" value="" />      #do nothing with these
  <span class="LC_nobreak">          } elsif ($url!~/\.(sequence|page)$/) {
  <input name="newext" type="button"      $url='/adm/coursedocs/showdoc'.$url;
  onClick="javascript:makenewext('supnewext');"          }
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      } elsif ($url=~m|^/ext/|) {
  </span>          $url='/adm/wrapper'.$url;
  </form>      }
 SNEFORM              if (&Apache::lonnet::symbverify($symb,$url)) {
           $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  my $supnewsylform=(<<SNSFORM);              } else {
  <form action="/adm/coursedocs" method="post" name="supnewsyl">                  $url='';
  <input type="hidden" name="folderpath" value="$path" />              }
  <input type="hidden" name="importdetail"   }
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />      }
  <span class="LC_nobreak">      my ($rand_pick_text,$rand_order_text);
  <input name="newsyl" type="submit" value="$lt{'syll'}" />      if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
  $help{'Syllabus'}   my $foldername=&escape($foldertitle);
  </span>   my $folderpath=$env{'form.folderpath'};
  </form>   if ($folderpath) { $folderpath.='&' };
 SNSFORM          if (!$allowed && $supplementalflag) {
               $folderpath.=$containerarg.'&'.$foldername;
  my $supnewaboutmeform=(<<SNAMFORM);              $url.='folderpath='.&escape($folderpath);
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">          } else {
  <input type="hidden" name="folderpath" value="$path" />  # Append randompick number, hidden, and encrypted with ":" to foldername,
  <input type="hidden" name="importdetail"  # so it gets transferred between levels
  value="$plainname=/adm/$udom/$uname/aboutme" />      $folderpath.=$containerarg.'&'.$foldername.
  <span class="LC_nobreak">                                                ':'.(&LONCAPA::map::getparameter($orderidx,
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />                                                'parameter_randompick'))[0]
  $help{'My Personal Info'}                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  </span>                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
  </form>                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
 SNAMFORM                                                'parameter_encrypturl'))[0]=~/^yes$/i)
                                                  .':'.((&LONCAPA::map::getparameter($orderidx,
    $r->print(<<ENDSUPFORM);                                                'parameter_randomorder'))[0]=~/^yes$/i)
 <ul class="LC_TabContent">                                                 .':'.$ispage;
 <li>$lt{'nd'}</li>      $url.='folderpath='.&escape($folderpath);
 <li>$lt{'sd'}</li>              my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
 <li>$lt{'hao'}</li>                                                          'parameter_randompick'))[0];
 </ul>              my $rpckchk;
 <table class="LC_docs_adddocs">              if ($rpicknum) {
 <tr><td>                  $rpckchk = ' checked="checked"';
 $supupdocform                  if (($ishash) && (ref($filtersref->{'randompick'}) eq 'ARRAY')) {
 </td>                      push(@{$filtersref->{'randompick'}},$orderidx.':'.$rpicknum);
 <td>                  }
 $supnewfolderform              }
 <br />              my $formname = 'edit_randompick_'.$orderidx;
 $supnewextform      $rand_pick_text = 
 <br />  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
 $supnewsylform  $form_param."\n".
 <br />  $form_common."\n".
 $supnewaboutmeform  '<span class="LC_nobreak"><label><input type="checkbox" name="randompick_'.$orderidx.'" id="randompick_'.$orderidx.'" onclick="'."updatePick(this.form,'$orderidx','check');".'"'.$rpckchk.' /> '.&mt('Randomly Pick').'</label><input type="hidden" name="rpicknum_'.$orderidx.'" id="rpicknum_'.$orderidx.'" value="'.$rpicknum.'" /><span id="randompicknum_'.$orderidx.'">';
 </td></tr>              if ($rpicknum ne '') {
 </table></td></tr>                  $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
 ENDSUPFORM              }
        }              $rand_pick_text .= '</span></span>'.
     }                                 $form_end;
     $r->print('</table>');              my $ro_set;
     if ($allowed) {              if ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i) {
  $r->print('                  $ro_set = 'checked="checked"';
 <form method="post" name="extimport" action="/adm/coursedocs">                  if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
   <input type="hidden" name="title" />                      push(@{$filtersref->{'randomorder'}},$orderidx);
   <input type="hidden" name="url" />                  }
   <input type="hidden" name="useform" />              }
   <input type="hidden" name="residx" />              $formname = 'edit_rorder_'.$orderidx;
 </form>');      $rand_order_text = 
     }  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
   } else {  $form_param."\n".
       unless ($upload_result eq 'phasetwo') {  $form_common."\n".
 # -------------------------------------------------------- This is showdoc mode  '<span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" id="randomorder_'.$orderidx.'" onclick="checkForSubmit(this.form,'."'randomorder','settings'".');" '.$ro_set.' /> '.&mt('Random Order').' </label></span>'.
           $r->print("<h1>".&mt('Uploaded Document').' - '.  $form_end;
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.          }
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".      } elsif ($supplementalflag && !$allowed) {
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');          $url .= ($url =~ /\?/) ? '&amp;':'?';
       }          $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
   }          if ($title) {
  }              $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
  $r->print(&Apache::loncommon::end_page());          }
  return OK;          if ($isexternal && $orderidx) {
 }              $url .= '&amp;idx='.$orderidx;
           }
 sub generate_admin_options {      }
   my ($containertag,$uploadtag,$lt_ref,$help_ref,$env_ref) = @_;      my ($tdalign,$tdwidth);
   my %lt = %{$lt_ref};      if ($allowed) {
   my %help = %{$help_ref};          my $fileloc = 
   my %env = %{$env_ref};              &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
   my $dumpbut=&dumpbutton();          if ($isexternal) {
   my $exportbut=&exportbutton();              ($editlink,$extresform) = 
   return (<<ENDOPTIONFORM);                  &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
  <form name="renameform" method="post" action="/adm/coursedocs">          } elsif (!$isfolder && !$ispage) {
    <input type="hidden" name="title" />              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
    <input type="hidden" name="cmd" />                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
    <input type="hidden" name="markcopy" />              if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
    <input type="hidden" name="copyfolder" />                  my $jscall = 
    $containertag                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
  </form>                                                              $switchserver,
  <form name="simpleedit" method="post" action="/adm/coursedocs">                                                              $forceedit,
    <input type="hidden" name="importdetail" value="" />                                                              undef,$symb,
    $uploadtag                                                              &escape($env{'form.folderpath'}),
  </form>                                                              $renametitle,'','',1);
  <form action="/adm/coursedocs" method="post" name="courseverify">                  if ($jscall) {
    <ul style="list-style-type:none">                      $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
        <li>                                  $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
            <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}                  }
        </li>              }
        <li>          }
            <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}          $tdalign = ' align="right" valign="top"';
        </li>          $tdwidth = ' width="80%"';
        <li>      }
            $dumpbut      my $reinit;
        </li>      if ($crstype eq 'Community') {
        <li>          $reinit = &mt('(re-initialize community to access)');
            $exportbut      } else {
        </li>          $reinit = &mt('(re-initialize course to access)');
        <li>      }
           <input type="submit" name="listsymbs" value="$lt{'ls'}" />      $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
         </li>      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
         <li>         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
           <input type="hidden" name="folder" value="$env{'form.folder'}" />      } elsif ($url) {
           <input type="submit" name="docslog" value="$lt{'sl'}" />         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
         </li>                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
    </ul>      } else {
  </form>         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
  <div style="clear: both; height: 0px;">&nbsp;</div>      }
 ENDOPTIONFORM      $line.='</span></td><td'.$tdwidth.'>';
 }      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
          $line.='<a href="'.$url.'">'.$title.'</a>';
 sub generate_edit_table {      } elsif ($url) {
     my ($optionhash_ref,$namehash_ref,$orderhash_ref) = @_;         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
     my %optionhash = %{$optionhash_ref};         #id verlinkt mit inhalt                                               $title,600,500);
     my %namehash = %{$namehash_ref};             #name verlinkt mit id      } else {
     my %orderhash = %{$orderhash_ref};           #name mit kürzel verlinkt mit name         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
     my $form;      }
     $form = '<div class="LC_ContentBoxSpecial"><h4 class="LC_hcell">'.&mt('Upload Course Documents').'<h4>';      $line.="$extresform</td>";
     $form .= '<ul class="LC_TabContent">';      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
     foreach my $name (sort(keys(%orderhash))){      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
         if($name eq 'zz_hide'){      if (($allowed) && ($folder!~/^supplemental/)) {
             $form .= '<li><a onclick="hideAllSection();" href="#">'.&mt($orderhash{$name}).'</a></li>';    my %lt=&Apache::lonlocal::texthash(
         }else{         'hd' => 'Hidden',
             $form .= '<li><a onclick="popUpSection(\''.$namehash{$orderhash{$name}}.'\');" href="#">'.&mt($orderhash{$name}).'</a></li>';         'ec' => 'URL hidden');
         }          my ($enctext,$hidtext);
     }          if ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i) {
     foreach my $field (keys(%optionhash)){              $enctext = ' checked="checked"';
         $form .= '<div id="'.$field.'" class="LC_ContentBox LC_hideThis">'.$optionhash{$field}.'</div>';              if (($ishash) && (ref($filtersref->{'encrypturl'}) eq 'ARRAY')) {
     }                  push(@{$filtersref->{'encrypturl'}},$orderidx);
     $form .= '</div>';              }
     return $form;          }
 }          if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
               $hidtext = ' checked="checked"';
 sub editing_js {              if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
     my ($udom,$uname) = @_;                  push(@{$filtersref->{'hiddenresource'}},$orderidx);
     my $now = time();              }
     my %lt = &Apache::lonlocal::texthash(          }
                                           p_mnf => 'Name of New Folder',          my $formhidden = 'edit_hiddenresource_'.$orderidx;
                                           t_mnf => 'New Folder',          my $formurlhidden = 'edit_encrypturl_'.$orderidx;
                                           p_mnp => 'Name of New Page',   $line.=(<<ENDPARMS);
                                           t_mnp => 'New Page',    <td class="LC_docs_entry_parameter">
                                           p_mxu => 'Title for the Uploaded Score',      <form action="/adm/coursedocs" method="post" name="$formhidden">
                                           p_msp => 'Title for the Page',      $form_param
                                           p_msb => 'Title for the Problem',      $form_common
                                           p_mdb => 'Title for the Drop Box',      <label><input type="checkbox" name="hiddenresource_$orderidx" id="hiddenresource_$orderidx" onclick="checkForSubmit(this.form,'hiddenresource','settings');" $hidtext /> $lt{'hd'}</label>
                                           p_mbb => 'Title for the Bulletin Board',      $form_end
                                           p_mab => "Enter user:domain for User's 'About Me' Page",      <br />
                                           p_mab2 => "About [_99]",      <form action="/adm/coursedocs" method="post" name="$formurlhidden">
                                           p_mab_alrt1 => 'Not a valid user:domain',      $form_param
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',      $form_common
                                           p_chn => 'New Title',      <label><input type="checkbox" name="encrypturl_$orderidx" id="encrypturl_$orderidx" onclick="checkForSubmit(this.form,'encrypturl','settings');" $enctext /> $lt{'ec'}</label>
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',      $form_end
                                           p_rmr2a => 'Remove[_99]',    </td>
                                           p_rmr2b => '?[_99]',    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',                                        $rand_order_text</td>
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',  ENDPARMS
                                           p_ctr2a => 'Cut[_98]',      }
                                           p_ctr2b => '?[_98]'      $line.=&Apache::loncommon::end_data_table_row();
                                         );      return $line;
   }
     return <<ENDNEWSCRIPT;  
 function makenewfolder(targetform,folderseq) {  sub action_restrictions {
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');      my ($cnum,$cdom,$url,$folderpath,$currgroups) = @_;
     if (foldername) {      my %denied = (
        targetform.importdetail.value=escape(foldername)+"="+folderseq;                     cut    => 0,
         targetform.submit();                     copy   => 0,
     }                     remove => 0,
 }                   );
       if ($url=~ m{^/res/.+\.(page|sequence)$}) {
 function makenewpage(targetform,folderseq) {          # no copy for published maps
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');          $denied{'copy'} = 1;
     if (pagename) {      } elsif ($url=~m{^/res/lib/templates/}) {
         targetform.importdetail.value=escape(pagename)+"="+folderseq;         $denied{'copy'} = 1;
         targetform.submit();         $denied{'cut'} = 1;
     }      } elsif ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
 }          if ($folderpath =~ /^default&[^\&]+$/) {
               if ((ref($currgroups) eq 'HASH') && (keys(%{$currgroups}) > 0)) {
 function makenewext(targetname) {                  $denied{'remove'} = 1;
     this.document.forms.extimport.useform.value=targetname;              }
     this.document.forms.extimport.title.value='';              $denied{'cut'} = 1;
     this.document.forms.extimport.url.value='';              $denied{'copy'} = 1;
     this.document.forms.extimport.residx.value='';          }
     window.open('/adm/rat/extpickframe.html');      } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
 }          my $group = $1;
           if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
 function edittext(targetname,residx,title,url) {              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
     this.document.forms.extimport.useform.value=targetname;                  $denied{'remove'} = 1;
     this.document.forms.extimport.residx.value=residx;              }
     this.document.forms.extimport.url.value=url;          }
     this.document.forms.extimport.title.value=title;          $denied{'cut'} = 1;
     window.open('/adm/rat/extpickframe.html');          $denied{'copy'} = 1;
 }      } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
           my $group = $1;
 function makeexamupload() {          if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
    var title=prompt('$lt{"p_mxu"}');              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
    if (title) {                  my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
     this.document.forms.newexamupload.importdetail.value=                  if (keys(%groupsettings) > 0) {
  escape(title)+'=/res/lib/templates/examupload.problem';                      $denied{'remove'} = 1;
     this.document.forms.newexamupload.submit();                  }
    }                  $denied{'cut'} = 1;
 }                  $denied{'copy'} = 1;
               }
 function makesmppage() {          }
    var title=prompt('$lt{"p_msp"}');      } elsif ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
    if (title) {          my $group = $1;
     this.document.forms.newsmppg.importdetail.value=          if ($url =~ /group_boards_\Q$group\E/) {
  escape(title)+'=/adm/$udom/$uname/$now/smppg';              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
     this.document.forms.newsmppg.submit();                  my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
    }                  if (keys(%groupsettings) > 0) {
 }                      if (ref($groupsettings{'functions'}) eq 'HASH') {
                           if ($groupsettings{'functions'}{'discussion'} eq 'on') {
 function makesmpproblem() {                              $denied{'remove'} = 1;
    var title=prompt('$lt{"p_msb"}');                          }
    if (title) {                      }
     this.document.forms.newsmpproblem.importdetail.value=                  }
  escape(title)+'=/res/lib/templates/simpleproblem.problem';                  $denied{'cut'} = 1;
     this.document.forms.newsmpproblem.submit();                  $denied{'copy'} = 1;
    }              }
 }          }
       }
 function makedropbox() {      return %denied;
    var title=prompt('$lt{"p_mdb"}');  }
    if (title) {  
     this.document.forms.newdropbox.importdetail.value=  sub new_timebased_suffix {
         escape(title)+'=/res/lib/templates/DropBox.problem';      my ($dom,$num,$type,$area,$container) = @_;
     this.document.forms.newdropbox.submit();      my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
    }      if ($type eq 'paste') {
 }          $prefix = $type;
           $namespace = 'courseeditor';
 function makebulboard() {      } elsif ($type eq 'map') {
    var title=prompt('$lt{"p_mbb"}');          $prefix = 'docs';
    if (title) {          if ($area eq 'supplemental') {
     this.document.forms.newbul.importdetail.value=              $prefix = 'supp';
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';          }
     this.document.forms.newbul.submit();          $prefix .= $container;
    }          $namespace = 'uploadedmaps';
 }      } else {
           $prefix = $type;
 function makeabout() {          $namespace = 'templated';
    var user=prompt("$lt{'p_mab'}");      }
    if (user) {      $idtype = 'concat';
        var comp=new Array();      my ($suffix,$freedlock,$error) =
        comp=user.split(':');          &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,$dom,$num);
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {      if (!$suffix) {
    if ((comp[0]) && (comp[1])) {          if ($type eq 'paste') {
        this.document.forms.newaboutsomeone.importdetail.value=              $errtext = &mt('Failed to acquire a unique timestamp-based suffix when adding to the paste buffer.');
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';          } elsif ($type eq 'map') {
        this.document.forms.newaboutsomeone.submit();              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
    } else {          } elsif ($type eq 'smppg') {
                alert("$lt{'p_mab_alrt1'}");              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
            }          } else {
        } else {              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new bulletin board.');
            alert("$lt{'p_mab_alrt2'}");          }
        }          if ($error) {
    }              $errtext .= '<br />'.$error;
 }          }
       }
 function makeims() {      if ($freedlock ne 'ok') {
     var caller = document.forms.ims.folder.value;          $locknotfreed =
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";              '<div class="LC_error">'.
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");              &mt('There was a problem removing a lockfile.').' ';
     newWindow.location.href = newlocation;          if ($type eq 'paste') {
 }              &mt('This will prevent use of the paste buffer until th next log-in.');
           } elsif ($type eq 'map') {
               &mt('This will prevent creation of additional folders or composite pages in this course.');
 function finishpick() {          } elsif ($type eq 'smppg') {
     var title=this.document.forms.extimport.title.value;              $locknotfreed .=
     var url=this.document.forms.extimport.url.value;                  &mt('This will prevent creation of additional simple pages in this course.');
     var form=this.document.forms.extimport.useform.value;          } else {
     var residx=this.document.forms.extimport.residx.value;              $locknotfreed .=
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');                  &mt('This will prevent creation of additional bulletin boards in this course.');
 }          }
           unless ($type eq 'paste') {
 function changename(folderpath,index,oldtitle,container,pagesymb) {              $locknotfreed .=
     var title=prompt('$lt{"p_chn"}',oldtitle);                  ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
     if (title) {                          '<a href="/adm/helpdesk" target="_helpdesk">','</a>');
  this.document.forms.renameform.markcopy.value=-1;          }
  this.document.forms.renameform.title.value=title;          $locknotfreed .= '</div>';
  this.document.forms.renameform.cmd.value='rename_'+index;      }
         if (container == 'sequence') {      return ($suffix,$errtext,$locknotfreed);
     this.document.forms.renameform.folderpath.value=folderpath;  }
         }  
         if (container == 'page') {  =pod
             this.document.forms.renameform.pagepath.value=folderpath;  
             this.document.forms.renameform.pagesymb.value=pagesymb;  =item tiehash()
         }  
         this.document.forms.renameform.submit();  tie the hash
     }  
 }  =cut
   
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {  sub tiehash {
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {      my ($mode)=@_;
  this.document.forms.renameform.markcopy.value=-1;      $hashtied=0;
  this.document.forms.renameform.cmd.value='del_'+index;      if ($env{'request.course.fn'}) {
         if (container == 'sequence') {   if ($mode eq 'write') {
             this.document.forms.renameform.folderpath.value=folderpath;      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
         }      &GDBM_WRCREAT(),0640)) {
         if (container == 'page') {                  $hashtied=2;
             this.document.forms.renameform.pagepath.value=folderpath;      }
             this.document.forms.renameform.pagesymb.value=pagesymb;   } else {
         }      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
         this.document.forms.renameform.submit();      &GDBM_READER(),0640)) {
     }                  $hashtied=1;
 }      }
    }
 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;  sub untiehash {
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;      if ($hashtied) { untie %hash; }
         if (container == 'sequence') {      $hashtied=0;
             this.document.forms.renameform.folderpath.value=folderpath;      return OK;
         }  }
         if (container == 'page') {  
             this.document.forms.renameform.pagepath.value=folderpath;  
             this.document.forms.renameform.pagesymb.value=pagesymb;  
         }  
         this.document.forms.renameform.submit();  sub checkonthis {
     }      my ($r,$url,$level,$title)=@_;
 }      $url=&unescape($url);
       $alreadyseen{$url}=1;
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {      $r->rflush();
     this.document.forms.renameform.markcopy.value=index;      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;         $r->print("\n<br />");
     if (container == 'sequence') {         if ($level==0) {
  this.document.forms.renameform.folderpath.value=folderpath;             $r->print("<br />");
     }         }
     if (container == 'page') {         for (my $i=0;$i<=$level*5;$i++) {
  this.document.forms.renameform.pagepath.value=folderpath;             $r->print('&nbsp;');
  this.document.forms.renameform.pagesymb.value=pagesymb;         }
     }         $r->print('<a href="'.$url.'" target="cat">'.
     this.document.forms.renameform.submit();   ($title?$title:$url).'</a> ');
 }         if ($url=~/^\/res\//) {
     my $result=&Apache::lonnet::repcopy(
                                 &Apache::lonnet::filelocation('',$url));
 ENDNEWSCRIPT            if ($result eq 'ok') {
 }               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 1;               $r->rflush();
 __END__               &Apache::lonnet::countacc($url);
                $url=~/\.(\w+)$/;
                if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 =head1 NAME   $r->print('<br />');
                    $r->rflush();
 Apache::londocs.pm                   for (my $i=0;$i<=$level*5;$i++) {
                        $r->print('&nbsp;');
 =head1 SYNOPSIS                   }
                    $r->print('- '.&mt('Rendering:').' ');
 This is part of the LearningOnline Network with CAPA project   my ($errorcount,$warningcount)=split(/:/,
 described at http://www.lon-capa.org.         &Apache::lonnet::ssi_body($url,
          ('grade_target'=>'web',
 =head1 SUBROUTINES   'return_only_error_and_warning_counts' => 1)));
                    if (($errorcount) ||
 =over                       ($warningcount)) {
        if ($errorcount) {
 =item %help=()                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
                             &mt('[quant,_1,error]',$errorcount).'</span>');
 Available help topics                       }
        if ($warningcount) {
 =item mapread()                          $r->print('<span class="LC_warning">'.
                             &mt('[quant,_1,warning]',$warningcount).'</span>');
 Mapread read maps into LONCAPA::map:: global arrays                       }
 @order and @resources, determines status                   } else {
 sets @order - pointer to resources in right order                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 sets @resources - array with the resources with correct idx                   }
                    $r->rflush();
 =item authorhosts()               }
        my $dependencies=
 Return hash with valid author names                  &Apache::lonnet::metadata($url,'dependencies');
                foreach my $dep (split(/\,/,$dependencies)) {
 =item dumpbutton()   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
                       &checkonthis($r,$dep,$level+1);
 Generate "dump" button                   }
                }
 =item clean()            } elsif ($result eq 'unavailable') {
                $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 =item dumpcourse()            } elsif ($result eq 'not_found') {
         unless ($url=~/\$/) {
     Actually dump course    $r->print('<span class="LC_error">'.&mt('not found').'</span>');
         } else {
     $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
 =item exportbutton()        }
             } else {
     Generate "export" button               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
             }
 =item exportcourse()         }
       }
 =item create_ims_store()  }
   
 =item build_package()  
   
 =item get_dependencies()  =pod
   
 =item process_content()  =item list_symbs()
   
 =item replicate_content()  List Content Identifiers
   
 =item extract_media()  =cut
   
 =item store_template()  sub list_symbs {
       my ($r) = @_;
 =item group_import()  
       my $crstype = &Apache::loncommon::course_type();
     Imports the given (name, url) resources into the course      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
     coursenum, coursedom, and folder must precede the list      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
       $r->print(&startContentScreen('tools'));
 =item breadcrumbs()      my $navmap = Apache::lonnavmaps::navmap->new();
       if (!defined($navmap)) {
 =item log_docs()          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
                     '<div class="LC_error">'.
 =item docs_change_log()                    &mt('Unable to retrieve information about course contents').
                     '</div>');
 =item update_paste_buffer()          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
       } else {
 =item print_paste_buffer()          $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
                     &Apache::loncommon::start_data_table().
 =item do_paste_from_buffer()                    &Apache::loncommon::start_data_table_header_row().
                     '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
 =item update_parameter()                    &Apache::loncommon::end_data_table_header_row()."\n");
           my $count;
 =item handle_edit_cmd()          foreach my $res ($navmap->retrieveResources()) {
               $r->print(&Apache::loncommon::start_data_table_row().
 =item editor()                        '<td>'.$res->compTitle().'</td>'.
                         '<td>'.$res->symb().'</td>'.
 =item process_file_upload()                        &Apache::loncommon::end_data_table_row());
               $count ++;
 =item process_secondary_uploads()          }
           if (!$count) {
 =item is_supplemental_title()              $r->print(&Apache::loncommon::start_data_table_row().
                         '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
 =item parse_supplemental_title()                        &Apache::loncommon::end_data_table_row()); 
           }
 =item entryline()          $r->print(&Apache::loncommon::end_data_table());
       }
 =item tiehash()      $r->print(&endContentScreen());
   }
 =item untiehash()  
   
 =item checkonthis()  sub verifycontent {
       my ($r) = @_;
 check on this      my $crstype = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
 =item verifycontent()      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
       $r->print(&startContentScreen('tools'));
 Verify Content      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
      $hashtied=0;
 =item devalidateversioncache() & checkversions()     undef %alreadyseen;
      %alreadyseen=();
 Check Versions     &tiehash();
      
 =item mark_hash_old()     foreach my $key (keys(%hash)) {
          if ($hash{$key}=~/\.(page|sequence)$/) {
 =item is_hash_old()     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
          $r->print('<hr /><span class="LC_error">'.
 =item changewarning()   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
    &unescape($hash{$key}).'</span><br />'.
 =item init_breadcrumbs()   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
      }
 Breadcrumbs for special functions         }
          if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 =back             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
          }
 =cut     }
      &untiehash();
      $r->print('<p class="LC_success">'.&mt('Done').'</p>');
       $r->print(&endContentScreen());
   }
   
   
   sub devalidateversioncache {
       my $src=shift;
       &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
     &Apache::lonnet::clutter($src));
   }
   
   sub checkversions {
       my ($r) = @_;
       my $crstype = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
       $r->print(&startContentScreen('tools'));
   
       my $header='';
       my $startsel='';
       my $monthsel='';
       my $weeksel='';
       my $daysel='';
       my $allsel='';
       my %changes=();
       my $starttime=0;
       my $haschanged=0;
       my %setversions=&Apache::lonnet::dump('resourceversions',
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
   
       $hashtied=0;
       &tiehash();
       my %newsetversions=();
       if ($env{'form.setmostrecent'}) {
    $haschanged=1;
    foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
    $newsetversions{$1}='mostrecent';
                   &devalidateversioncache($1);
       }
    }
       } elsif ($env{'form.setcurrent'}) {
    $haschanged=1;
    foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
    my $getvers=&Apache::lonnet::getversion($1);
    if ($getvers>0) {
       $newsetversions{$1}=$getvers;
       &devalidateversioncache($1);
    }
       }
    }
       } elsif ($env{'form.setversions'}) {
    $haschanged=1;
    foreach my $key (keys(%env)) {
       if ($key=~/^form\.set_version_(.+)$/) {
    my $src=$1;
    if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
       $newsetversions{$src}=$env{$key};
       &devalidateversioncache($src);
    }
       }
    }
       }
       if ($haschanged) {
           if (&Apache::lonnet::put('resourceversions',\%newsetversions,
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
       $r->print(&Apache::loncommon::confirmwrapper(
                   &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
    } else {
       $r->print(&Apache::loncommon::confirmwrapper(
                   &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
    }
    &mark_hash_old();
       }
       &changewarning($r,'');
       if ($env{'form.timerange'} eq 'all') {
   # show all documents
    $header=&mt('All content in '.$crstype);
    $allsel=' selected="selected"';
    foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
    my $src=$1;
    $changes{$src}=1;
       }
    }
       } else {
   # show documents which changed
    %changes=&Apache::lonnet::dump
    ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
                        $env{'course.'.$env{'request.course.id'}.'.num'});
    my $firstkey=(keys(%changes))[0];
    unless ($firstkey=~/^error\:/) {
       unless ($env{'form.timerange'}) {
    $env{'form.timerange'}=604800;
       }
       my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
    .&mt('seconds');
       if ($env{'form.timerange'}==-1) {
    $seltext='since start of course';
    $startsel=' selected="selected"';
    $env{'form.timerange'}=time;
       }
       $starttime=time-$env{'form.timerange'};
       if ($env{'form.timerange'}==2592000) {
    $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $monthsel=' selected="selected"';
       } elsif ($env{'form.timerange'}==604800) {
    $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $weeksel=' selected="selected"';
       } elsif ($env{'form.timerange'}==86400) {
    $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $daysel=' selected="selected"';
       }
       $header=&mt('Content changed').' '.$seltext;
    } else {
       $header=&mt('No content modifications yet.');
    }
       }
       %setversions=&Apache::lonnet::dump('resourceversions',
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
       my %lt=&Apache::lonlocal::texthash
         ('st' => 'Version changes since start of '.$crstype,
          'lm' => 'Version changes since last Month',
          'lw' => 'Version changes since last Week',
          'sy' => 'Version changes since Yesterday',
                  'al' => 'All Resources (possibly large output)',
                  'cd' => 'Change display', 
          'sd' => 'Display',
          'fi' => 'File',
          'md' => 'Modification Date',
                  'mr' => 'Most recently published Version',
          've' => 'Version used in '.$crstype,
                  'vu' => 'Set Version to be used in '.$crstype,
   'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
   'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
   'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
          'di' => 'Differences',
          'save' => 'Save changes',
                  'vers' => 'Version choice(s) for specific resources', 
          'act' => 'Actions');
       $r->print(<<ENDHEADERS);
   <h4 class="LC_info">$header</h4>
   <form action="/adm/coursedocs" method="post">
   <input type="hidden" name="versions" value="1" />
   <div class="LC_left_float">
   <fieldset>
   <legend>$lt{'cd'}</legend>
   <select name="timerange">
   <option value='all'$allsel>$lt{'al'}</option>
   <option value="-1"$startsel>$lt{'st'}</option>
   <option value="2592000"$monthsel>$lt{'lm'}</option>
   <option value="604800"$weeksel>$lt{'lw'}</option>
   <option value="86400"$daysel>$lt{'sy'}</option>
   </select>
   <input type="submit" name="display" value="$lt{'sd'}" />
   </fieldset>
   </div>
   <div class="LC_left_float">
   <fieldset>
   <legend>$lt{'act'}</legend>
   $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
   $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
   </fieldset>
   </div>
   <br clear="all" />
   <hr />
   <h4>$lt{'vers'}</h4>
   <input type="submit" name="setversions" value="$lt{'save'}" />
   ENDHEADERS
       #number of columns for version history
       $r->print(
           &Apache::loncommon::start_data_table().
           &Apache::loncommon::start_data_table_header_row().
           '<th>'.&mt('Resources').'</th>'.
           "<th>$lt{'mr'}</th>".
           "<th>$lt{'ve'}</th>".
           "<th>$lt{'vu'}</th>".
           '<th>'.&mt('History').'</th>'.
           &Apache::loncommon::end_data_table_header_row()
       );
       foreach my $key (sort(keys(%changes))) {
           #excludes not versionable problems from resource version history:
           next unless ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/);
           my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
           my $currentversion=&Apache::lonnet::getversion($key);
           if ($currentversion<0) {
               $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
           }
           my $linkurl=&Apache::lonnet::clutter($key);
           $r->print(
               &Apache::loncommon::start_data_table_row().
               '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
               '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
               '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
               &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
               '<td align="right">'
           );
           # Used in course
           my $usedversion=$hash{'version_'.$linkurl};
           if (($usedversion) && ($usedversion ne 'mostrecent')) {
                   if ($usedversion != $currentversion) {
                       $r->print('<span class="LC_warning">'.$usedversion.'</span>');
                   } else {
                       $r->print($usedversion);
                   }
               } else {
                   $r->print($currentversion);
               }
           $r->print('</td><td title="'.$lt{'vu'}.'">');
           # Set version
           $r->print(&Apache::loncommon::select_form(
               $setversions{$linkurl},
               'set_version_'.$linkurl,
               {'select_form_order' => ['',1..$currentversion,'mostrecent'],
                '' => '',
                'mostrecent' => &mt('most recent'),
                map {$_,$_} (1..$currentversion)}));
           my $lastold=1;
           for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
               my $url=$root.'.'.$prevvers.'.'.$extension;
               if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
                   $lastold=$prevvers;
               }
           }
           $r->print('</td>');
           # List all available versions
           $r->print('<td valign="top"><span class="LC_fontsize_medium">');
           for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
               my $url=$root.'.'.$prevvers.'.'.$extension;
               $r->print(
                   '<span class="LC_nobreak">'
                  .'<a href="'.&Apache::lonnet::clutter($url).'">'
                  .&mt('Version [_1]',$prevvers).'</a>'
                  .' ('.&Apache::lonlocal::locallocaltime(
                            &Apache::lonnet::metadata($url,'lastrevisiondate'))
                  .')');
               if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
                   $r->print(
                       ' <a href="/adm/diff?filename='.
                       &Apache::lonnet::clutter($root.'.'.$extension).
                       &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
                       '" target="diffs">'.&mt('Diffs').'</a>');
               }
               $r->print('</span><br />');
           }
           $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
       }
       $r->print(
           &Apache::loncommon::end_data_table().
           '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
           '</form>'
       );
   
       &untiehash();
       $r->print(&endContentScreen());
   }
   
   sub mark_hash_old {
       my $retie_hash=0;
       if ($hashtied) {
    $retie_hash=1;
    &untiehash();
       }
       &tiehash('write');
       $hash{'old'}=1;
       &untiehash();
       if ($retie_hash) { &tiehash(); }
   }
   
   sub is_hash_old {
       my $untie_hash=0;
       if (!$hashtied) {
    $untie_hash=1;
    &tiehash();
       }
       my $return=$hash{'old'};
       if ($untie_hash) { &untiehash(); }
       return $return;
   }
   
   sub changewarning {
       my ($r,$postexec,$message,$url)=@_;
       if (!&is_hash_old()) { return; }
       my $pathvar='folderpath';
       my $path=&escape($env{'form.folderpath'});
       if (!defined($url)) {
    $url='/adm/coursedocs?'.$pathvar.'='.$path;
       }
       my $course_type = &Apache::loncommon::course_type();
       if (!defined($message)) {
    $message='Changes will become active for your current session after [_1], or the next time you log in.';
       }
       $r->print("\n\n".
   '<script type="text/javascript">'."\n".
   '// <![CDATA['."\n".
   'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
   '// ]]>'."\n".
   '</script>'."\n".
   '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
   '<input type="hidden" name="orgurl" value="'.$url.
   '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
   &mt($message,' <input type="hidden" name="'.
       $env{'request.role'}.'" value="1" /><input type="button" value="'.
       &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
   $help{'Caching'}.'</p></form>'."\n\n");
   }
   
   
   sub init_breadcrumbs {
       my ($form,$text)=@_;
       &Apache::lonhtmlcommon::clear_breadcrumbs();
       &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
       text=>&Apache::loncommon::course_type().' Editor',
       faq=>273,
       bug=>'Instructor Interface',
                                               help => 'Docs_Adding_Course_Doc'});
       &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
       text=>$text,
       faq=>273,
       bug=>'Instructor Interface'});
   }
   
   # subroutine to list form elements
   sub create_list_elements {
      my @formarr = @_;
      my $list = '';
      foreach my $button (@formarr){
           foreach my $picture (keys(%{$button})) {
               $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
           }
      }
      return $list;
   }
   
   # subroutine to create ul from list elements
   sub create_form_ul {
      my $list = shift;
      my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
      return $ul;
   }
   
   #
   # Start tabs
   #
   
   sub startContentScreen {
       my ($mode) = @_;
       my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
       if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
           $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";
           $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";
           $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
       } else {
           $output .= '<li '.(($mode eq 'docs')?' class="active"':'').' id="tabbededitor"><a href="/adm/coursedocs?forcestandard=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Main Content Editor').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
           $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
           $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";
                      '><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>';
       }
       $output .= "\n".'</ul>'."\n";
       $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
                  '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
                  '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
       return $output;
   }
   
   #
   # End tabs
   #
   
   sub endContentScreen {
       return '</div></div></div>';
   }
   
   sub supplemental_base {
       return 'supplemental&'.&escape(&mt('Supplemental Content'));
   }
   
   sub handler {
       my $r = shift;
       &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
       return OK if $r->header_only;
   
   # get course data
       my $crstype = &Apache::loncommon::course_type();
       my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
   
   # graphics settings
       $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
   
   #
   # --------------------------------------------- Initialize help topics for this
       foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
                  'Adding_External_Resource','Navigate_Content',
                  'Adding_Folders','Docs_Overview', 'Load_Map',
                  'Supplemental','Score_Upload_Form','Adding_Pages',
                  'Importing_LON-CAPA_Resource','Importing_IMS_Course',
                          'Uploading_From_Harddrive',
                  'Check_Resource_Versions','Verify_Content',
                          'Course_Roster','Web_Page','Dropbox') {
    $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
       }
       # Composite help files
       $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
       $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
       $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
       'Option_Response_Simple');
       $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
       $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
     'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
       $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
       $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
    
       my $allowed;
   # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
       unless ($r->uri eq '/adm/supplemental') {
           # does this user have privileges to modify content.  
           $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
       }
   
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
                                               'inhibitmenu']);
     if ($allowed && $env{'form.chooseserver'}) {
         &choose_dump_server($r);
         return OK;
     } elsif ($allowed && $env{'form.verify'}) {
         &init_breadcrumbs('verify','Verify Content');
         &verifycontent($r);
     } elsif ($allowed && $env{'form.listsymbs'}) {
         &init_breadcrumbs('listsymbs','List Content IDs');
         &list_symbs($r);
     } elsif ($allowed && $env{'form.docslog'}) {
         &init_breadcrumbs('docslog','Show Log');
         my $folder = $env{'form.folder'};
         if ($folder eq '') {
             $folder='default';
         }
         &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
     } elsif ($allowed && $env{'form.versions'}) {
         &init_breadcrumbs('versions','Check/Set Resource Versions');
         &checkversions($r);
     } elsif ($allowed && $env{'form.dumpcourse'}) {
         &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
         &dumpcourse($r);
     } elsif ($allowed && $env{'form.exportcourse'}) {
         &init_breadcrumbs('exportcourse','IMS Export');
         &Apache::imsexport::exportcourse($r);
     } else {
   #
   # Done catching special calls
   # The whole rest is for course and supplemental documents and utilities menu
   # Get the parameters that may be needed
   #
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                               ['folderpath',
                                                'forcesupplement','forcestandard',
                                                'tools','symb','command','supppath']);
   
   # standard=1: this is a "new-style" course with an uploaded map as top level
   # standard=2: this is a "old-style" course, and there is nothing we can do
   
       my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
   
   # Decide whether this should display supplemental or main content or utilities
   # supplementalflag=1: show supplemental documents
   # supplementalflag=0: show standard documents
   # toolsflag=1: show utilities
   
       my $unesc_folderpath = &unescape($env{'form.folderpath'});
       my $supplementalflag=($unesc_folderpath=~/^supplemental/);
       if (($unesc_folderpath=~/^default/) || ($unesc_folderpath eq "")) {
          $supplementalflag=0;
       }
       if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
       if ($env{'form.forcestandard'})   { $supplementalflag=0; }
       unless ($allowed) { $supplementalflag=1; }
       unless ($standard) { $supplementalflag=1; }
       my $toolsflag=0;
       if ($env{'form.tools'}) { $toolsflag=1; }
   
       my $script='';
       my $showdoc=0;
       my $addentries = {};
       my $container;
       my $containertag;
       my $pathitem;
   
   # Do we directly jump somewhere?
   
      if (($env{'form.command'} eq 'direct') || ($env{'form.command'} eq 'directnav')) {
          if ($env{'form.symb'} ne '') {
              $env{'form.folderpath'}=
                  &Apache::loncommon::symb_to_docspath($env{'form.symb'});
              &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
                  $env{'form.command'}.'_'.$env{'form.symb'}});
          } elsif ($env{'form.supppath'} ne '') {
              $env{'form.folderpath'}=$env{'form.supppath'};
              &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
                  $env{'form.command'}.'_'.$env{'form.supppath'}});
          }
      } elsif ($env{'form.command'} eq 'editdocs') {
          $env{'form.folderpath'} = 'default&'.
                                    &escape(&mt('Main Content').':::::');
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => $env{'form.command'}});
      } elsif ($env{'form.command'} eq 'editsupp') {
          $env{'form.folderpath'} = 'supplemental&'.
                                     &escape('Supplemental Content');
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/supplemental'});
      } elsif ($env{'form.command'} eq 'contents') {
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/navmaps'});
      } elsif ($env{'form.command'} eq 'home') {
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/menu'});
      }
   
   
   # Where do we store these for when we come back?
       my $stored_folderpath='docs_folderpath';
       if ($supplementalflag) {
          $stored_folderpath='docs_sup_folderpath';
       }
   
   # No folderpath, and in edit mode, see if we have something stored
       if ((!$env{'form.folderpath'}) && $allowed) {
           &Apache::loncommon::restore_course_settings($stored_folderpath,
                                             {'folderpath' => 'scalar'});
           unless (&unescape($env{'form.folderpath'}) =~ m{^(default|supplemental)&}) {
               undef($env{'form.folderpath'});
           }
       }
      
   # If we are not allowed to make changes, all we can see are supplemental docs
       if (!$allowed) {
           unless ($env{'form.folderpath'} =~ /^supplemental/) {
               $env{'form.folderpath'} = &supplemental_base();
           }
       }
   # Make the zeroth entry in supplemental docs page paths, so we can get to top level
       if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
           $env{'form.folderpath'} = &supplemental_base()
                                     .'&'.
                                     $env{'form.folderpath'};
       }
   # If after all of this, we still don't have any paths, make them
       unless ($env{'form.folderpath'}) {
          if ($supplementalflag) {
             $env{'form.folderpath'}=&supplemental_base();
          } else {
             $env{'form.folderpath'}='default&'.&escape(&mt('Main Content').
                                     ':::::');
          }
       }
   
   # Store this
       unless ($toolsflag) {
           if ($allowed) {
               &Apache::loncommon::store_course_settings($stored_folderpath,
                                                         {'folderpath' => 'scalar'});
           }
           my $folderpath;
           if ($env{'form.folderpath'}) {
               $folderpath = $env{'form.folderpath'};
       my (@folders)=split('&',$env{'form.folderpath'});
       $env{'form.foldername'}=&unescape(pop(@folders));
               if ($env{'form.foldername'} =~ /\:1$/) {
                   $container = 'page';
               } else {
                   $container = 'sequence';
               }
       $env{'form.folder'}=pop(@folders);
           } else {
               if ($env{'form.folder'} eq '' ||
                   $env{'form.folder'} eq 'supplemental') {
                   $folderpath='default&'.
                               &escape(&mt('Main Content').':::::');
               }
           }
           $containertag = '<input type="hidden" name="folderpath" value="" />';
           $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
           if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
              $showdoc='/'.$1;
           }
           if ($showdoc) { # got called in sequence from course
       $allowed=0; 
           } else {
               if ($allowed) {
                   &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                   $script=&Apache::lonratedt::editscript('simple');
               }
           }
       }
   
   # get personal data
       my $uname=$env{'user.name'};
       my $udom=$env{'user.domain'};
       my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
   
       if ($allowed) {
           if ($toolsflag) {
               $script .= &inject_data_js();
               my ($home,$other,%outhash)=&authorhosts();
               if (!$home && $other) {
                   my @hosts;
                   foreach my $aurole (keys(%outhash)) {
                       unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                           push(@hosts,$outhash{$aurole});
                       }
                   }
                   $script .= &dump_switchserver_js(@hosts); 
               }
           } else {
               my @tabids;
               if ($supplementalflag) {
                   @tabids = ('002','ee2','ff2');
               } else {
                   @tabids = ('aa1','bb1','cc1','ff1');
                   unless ($env{'form.folderpath'} =~ /\:1$/) {
                       unshift(@tabids,'001');
                       push(@tabids,('dd1','ee1'));
                   }
               }
               my $tabidstr = join("','",@tabids);
       $script .= &editing_js($udom,$uname,$supplementalflag).
                          &history_tab_js().
                          &inject_data_js().
                          &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr).
                          &Apache::lonextresedit::extedit_javascript();
               $addentries = {
                               onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
                             };
           }
           $script .= &paste_popup_js(); 
           my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
                                &mt('Switch server?');
           
   
       }
   # -------------------------------------------------------------------- Body tag
       $script = '<script type="text/javascript">'."\n"
                 .'// <![CDATA['."\n"
                 .$script."\n"
                 .'// ]]>'."\n"
                 .'</script>'."\n";
   
       # Breadcrumbs
       &Apache::lonhtmlcommon::clear_breadcrumbs();
   
       if ($showdoc) {
           $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
                                                   {'force_register' => $showdoc,}));
       } elsif ($r->uri eq '/adm/supplemental') {
           my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype);
           $r->print(&Apache::loncommon::start_page("Supplemental $crstype Content",undef,
                                                   {'bread_crumbs' => $brcrum,}));
       } else {
           &Apache::lonhtmlcommon::add_breadcrumb({
               href=>"/adm/coursedocs",text=>"$crstype Contents"});
           $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
                                                    {'add_entries'    => $addentries}
                                                   )
                    .&Apache::loncommon::help_open_menu('','',273,'RAT')
                    .&Apache::lonhtmlcommon::breadcrumbs(
                        'Editing '.$crstype.' Contents',
                        'Docs_Adding_Course_Doc')
           );
       }
   
     my %allfiles = ();
     my %codebase = ();
     my ($upload_result,$upload_output,$uploadphase);
     if ($allowed) {
         if (($env{'form.uploaddoc.filename'}) &&
     ($env{'form.cmd'}=~/^upload_(\w+)/)) {
             my $context = $1; 
             # Process file upload - phase one - upload and parse primary file.
     undef($hadchanges);
             $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
                                                 \%allfiles,\%codebase,$context,$crstype);
     if ($hadchanges) {
         &mark_hash_old();
     }
             $r->print($upload_output);
         } elsif ($env{'form.phase'} eq 'upload_embedded') {
             # Process file upload - phase two - upload embedded objects 
             $uploadphase = 'check_embedded';
             my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
             my $state = &embedded_form_elems($uploadphase,$primaryurl,
                                              $env{'form.newidx'});
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
             my $actionurl = '/adm/coursedocs';
             my ($result,$flag) = 
                 &Apache::loncommon::upload_embedded('coursedoc',$destination,
                     $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
                     $actionurl);
             $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'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $result = 
                 &Apache::loncommon::modify_html_refs('coursedoc',$destination,
                                                      $docuname,$docudom,undef,
                                                      $dir_root);
             $r->print($result.&return_to_editor());   
         } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
             $uploadphase = 'decompress_phase_one';
             $r->print(&decompression_phase_one().
                       &return_to_editor());
         } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
             $uploadphase = 'decompress_phase_two';
             $r->print(&decompression_phase_two().
                       &return_to_editor());
         }
     }
   
     if ($allowed && $toolsflag) {
         $r->print(&startContentScreen('tools'));
         $r->print(&generate_admin_menu($crstype));
         $r->print(&endContentScreen());
     } elsif ((!$showdoc) && (!$uploadphase)) {
   # -----------------------------------------------------------------------------
          my %lt=&Apache::lonlocal::texthash(
    'copm' => 'All documents out of a published map into this folder',
                   'upfi' => 'Upload File',
                   'upld' => 'Upload Content',
                   'srch' => 'Search',
                   'impo' => 'Import',
    'lnks' => 'Import from Stored Links',
                   'impm' => 'Import from Assembled Map',
                   'selm' => 'Select Map',
                   'load' => 'Load Map',
                   'newf' => 'New Folder',
                   'newp' => 'New Composite Page',
                   'syll' => 'Syllabus',
                   'navc' => 'Table of Contents',
                   'sipa' => 'Simple Course Page',
                   'sipr' => 'Simple Problem',
                   'webp' => 'Blank Web Page (editable)',
                   'drbx' => 'Drop Box',
                   'scuf' => 'External Scores (handgrade, upload, clicker)',
                   'bull' => 'Discussion Board',
                   'mypi' => 'My Personal Information Page',
                   'grpo' => 'Group Portfolio',
                   'rost' => 'Course Roster',
                   'abou' => 'Personal Information Page for a User',
                   'imsf' => 'IMS Upload',
                   'imsl' => 'Upload IMS package',
                   'cms'  => 'Origin of IMS package',
                   'se'   => 'Select',
                   'file' =>  'File',
                   'title' => 'Title',
                   'comment' => 'Comment',
                   'parse' => 'Upload embedded images/multimedia files if HTML file',
     );
   # -----------------------------------------------------------------------------
    my $fileupload=(<<FIUP);
    $lt{'file'}:<br />
    <input type="file" name="uploaddoc" size="40" />
   FIUP
   
    my $checkbox=(<<CHBO);
    <!-- <label>$lt{'parse'}?
    <input type="checkbox" name="parserflag" />
    </label> -->
    <label>
    <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
    </label>
   CHBO
           my $imsfolder = $env{'form.folder'};
           if ($imsfolder eq '') {
               $imsfolder = 'default';  
           }
           my $imspform=(<<IMSFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
           $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
           <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
           <fieldset id="uploadimsform" style="display: none;">
           <legend>$lt{'imsf'}</legend>
           $fileupload
           <br />
           <p>
           $lt{'cms'}:&nbsp; 
           <select name="source">
           <option value="-1" selected="selected">$lt{'se'}</option>
           <option value="bb5">Blackboard 5</option>
           <option value="bb6">Blackboard 6</option>
           <option value="angel5">ANGEL 5.5</option>
           <option value="webctce4">WebCT 4 Campus Edition</option>
           </select>
           <input type="hidden" name="folder" value="$imsfolder" />
           </p>
           <input type="hidden" name="phase" value="one" />
           <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" />
           </fieldset>
           </form>
   IMSFORM
   
    my $fileuploadform=(<<FUFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
           <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
           <fieldset id="uploaddocform" style="display: none;">
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="aa" />
    $fileupload
    <br />
    $lt{'title'}:<br />
    <input type="text" size="60" name="comment" />
    $pathitem
    <input type="hidden" name="cmd" value="upload_default" />
    <br />
    <span class="LC_nobreak" style="float:left">
    $checkbox
    </span>
           <br clear="all" />
           <input type="submit" value="$lt{'upld'}" />
           </fieldset>
           </form>
   FUFORM
   
    my $importpubform=(<<SEDFFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleMap('map');">
           $lt{'impm'}</a>$help{'Load_Map'}
    <form action="/adm/coursedocs" method="post" name="mapimportform">
           <fieldset id="importmapform" style="display: none;">
           <legend>$lt{'impm'}</legend>
    <input type="hidden" name="active" value="bb" />
           $lt{'copm'}<br />
           <span class="LC_nobreak">
           <input type="text" name="importmap" size="40" value="" 
           onfocus="this.blur();openbrowser('mapimportform','importmap','sequence,page','');" />
           &nbsp;<a href="javascript:openbrowser('mapimportform','importmap','sequence,page','');">$lt{'selm'}</a></span><br />
           <input type="submit" name="loadmap" value="$lt{'load'}" />
           </fieldset>
           </form>
   
   SEDFFORM
    my @importpubforma = (
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => $pathitem."<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'}" },
    { '<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(\'map\');" />' => $importpubform }
    );
    $importpubform = &create_form_ul(&create_list_elements(@importpubforma));
           my $extresourcesform =
               &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
       if ($allowed) {
           my $folder = $env{'form.folder'};
           if ($folder eq '') {
               $folder='default';
           }
    my $output = &update_paste_buffer($coursenum,$coursedom,$folder);
           if ($output) {
               $r->print($output);
           }
    $r->print(<<HIDDENFORM);
    <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
      <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
      <input type="hidden" name="copyfolder" />
      $containertag
    </form>
   
   HIDDENFORM
           $r->print(&makesimpleeditform($pathitem)."\n".
                     &makedocslogform($pathitem."\n".
                                      '<input type="hidden" name="folder" value="'.
                                      $env{'form.folder'}.'" />'."\n"));
       }
   
   # Generate the tabs
       my ($mode,$needs_end);
       if (($supplementalflag) && (!$allowed)) {
           my @folders = split('&',$env{'form.folderpath'});
           unless (@folders > 2) {
               &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
               $needs_end = 1;
           }
       } else {
           $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
           $needs_end = 1;
       }
   
   #
   
       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('Main Content'));
              $pathitem = '<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_new.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.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" />
    $pathitem
    <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" />
    $pathitem
    <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" />
    $pathitem
    <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" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
           $help{'Dropbox'}
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <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" />
    $pathitem
    <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" />
    $pathitem
    <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" />
    $pathitem
    <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" />
    $pathitem
    <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 $newwebpage;
           if ($folder =~ /^default_?(\d*)$/) {
               $newwebpage = "/uploaded/$coursedom/$coursenum/docs/";
               if ($1) {
                   $newwebpage .= $1;
               } else {
                   $newwebpage .= 'default';
               }
               $newwebpage .= '/new.html';
           }
           my $newwebpageform =(<<NWEBFORM);
           <form action="/adm/coursedocs" method="post" name="newwebpage">
           <input type="hidden" name="active" value="cc" />
           $pathitem
           <input type="hidden" name="importdetail" value="$newwebpage" />
           <a class="LC_menubuttons_link" href="javascript:makewebpage();">$lt{'webp'}</a>
           $help{'Web_Page'}
           </form>
   NWEBFORM
    
   
   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">
    $pathitem
    <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" />
    $pathitem
    <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" />
    $pathitem
    <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},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage();" />'=>$newwebpageform},
           );
           $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}
           );
           unless ($container eq 'page') {
               push(@importdoc,
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform}
               );
           }
           push(@importdoc,
               {'<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' => ['Upload',$fileuploadform],
                   'bb' => ['Import',$importpubform],
                   'cc' => ['Grading',$gradingform],
                   );
   unless ($container eq 'page') {
       $orderhash{'00'} = ['Newfolder',$newfolderform];
       $orderhash{'dd'} = ['Collaboration',$communityform];
       $orderhash{'ee'} = ['Other',$specialdocumentsform];
   }
   
    $hadchanges=0;
          unless (($supplementalflag || $toolsflag)) {
             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                 $supplementalflag,\%orderhash,$iconpath,$pathitem);
             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;
          }
          $pathitem = '<input type="hidden" name="folderpath" value="'.
                       &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_new.sequence';
   
    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 />
    $pathitem
    <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" />
           $pathitem
    <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 =
               &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="active" value="ff" />
           $pathitem
    <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" />
           $pathitem
    <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 $supwebpage;
           if ($folder =~ /^supplemental_?(\d*)$/) {
               $supwebpage = "/uploaded/$coursedom/$coursenum/supplemental/";
               if ($1) {
                   $supwebpage .= $1;
               } else {
                   $supwebpage .= 'default';
               }
               $supwebpage .= '/new.html';
           }
           my $supwebpageform =(<<SWEBFORM);
           <form action="/adm/coursedocs" method="post" name="supwebpage">
           <input type="hidden" name="active" value="cc" />
           $pathitem
           <input type="hidden" name="importdetail" value="$supwebpage" />
           <a class="LC_menubuttons_link" href="javascript:makewebpage('supp');">$lt{'webp'}</a>
           $help{'Web_Page'}
           </form>
   SWEBFORM
   
   
   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},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage('."'supp'".');" />'=>$supwebpageform},
   
    );
   my @supimportdoc = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript: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' => ['Upload',$supupdocform],
                   'ff' => ['Other',&create_form_ul(&create_list_elements(@specialdocs))]
                   );
           if ($supplementalflag) {
              my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                  $supplementalflag,\%suporderhash,$iconpath,$pathitem);
              if ($error) {
                 $r->print('<p><span class="LC_error">'.$error.'</span></p>');
              } else {
                  if ($suppchanges) {
                      my %servers = &Apache::lonnet::internet_dom_servers($coursedom);
                      my @ids=&Apache::lonnet::current_machine_ids();
                      foreach my $server (keys(%servers)) {
                          next if (grep(/^\Q$server\E$/,@ids));
                          my $hashid=$coursenum.':'.$coursedom;
                          &Apache::lonnet::remote_devalidate_cache($server,'suppcount',$hashid);
                      }
                      &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
                      undef($suppchanges);
                  }
              }
           }
       } elsif ($supplementalflag) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,'',$iconpath,$pathitem);
           if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
       }
   
       if ($needs_end) {
           $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','folderpath');
       if ($env{'form.folderpath'} =~ /\:1$/) {
           $container='page';
       }
       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'} = 'remove_'.$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,
           $need_save,$copyfolder) = @_;
       return unless(ref($orderhash_ref) eq 'HASH');
       my %orderhash = %{$orderhash_ref};
       my $form;
       my $activetab;
       my $active;
       if (($env{'form.active'} ne '') && ($env{'form.active'} ne 'aa')) {
           $activetab = $env{'form.active'};
       }
       my $backicon = $iconpath.'clickhere.gif';
       my $backtext = &mt('Exit Editor');
       $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 '') {
           my $saveform;
           if ($need_save) {
               my $button = &mt('Make changes');
               my $path;
               if ($env{'form.folderpath'}) {
                   $path =
                       &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
               }
               $saveform = <<"END";
   <div id="multisave" style="display:none; clear:both;" >
   <form name="saveactions" method="post" action="/adm/coursedocs" onsubmit="return checkSubmits();">
   <input type="hidden" name="folderpath" value="$path" />
   <input type="hidden" name="symb" value="$env{'form.symb'}" />
   <input type="hidden" name="allhiddenresource" value="" />
   <input type="hidden" name="allencrypturl" value="" />
   <input type="hidden" name="allrandompick" value="" />
   <input type="hidden" name="allrandomorder" value="" />
   <input type="hidden" name="changeparms" value="" />
   <input type="hidden" name="multiremove" value="" />
   <input type="hidden" name="multicut" value="" />
   <input type="hidden" name="multicopy" value="" />
   <input type="hidden" name="multichange" value="" />
   <input type="hidden" name="copyfolder" value="$copyfolder" />
   <input type="submit" name="savemultiples" value="$button" />
   </form>
   </div>
   END
           }
           $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'.$saveform."\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 %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_mwp => 'Title for Web Page',
                                             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_rmr3a => 'Remove those [_2]',
                                             p_rmr3b => 'items?[_2]',
                                             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]',
                                             p_ctr3a => 'Cut those[_2]',
                                             p_ctr3b => 'items?[_2]',
                                             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',
                                             more    => '(More ...)',
                                             less    => '(Less ...)',
                                             noor    => 'No actions selected or changes to settings specified.',
                                             noch    => 'No changes to settings specified.',
                                             noac    => 'No actions selected.',
                                           );
   
       my $crstype = &Apache::loncommon::course_type();
       my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
       my $main_container_page;
       if (&HTML::Entities::decode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'}) =~ /\:1$/) {
           $main_container_page = 1;
       }
       my $toplevelmain = 
           &escape(&mt('Main Content').':::::');
       my $toplevelsupp = &supplemental_base();
   
       my $backtourl;
       if ($env{'docs.exit.'.$env{'request.course.id'}} =~ /^direct_(.+)$/) {
           my $caller = $1;
           if ($caller =~ /^supplemental/) {
               $backtourl = '/adm/supplemental?folderpath='.&escape($caller);
           } else {
               my ($map,$id,$res)=&Apache::lonnet::decode_symb($caller);
               $res = &Apache::lonnet::clutter($res);
               if (&Apache::lonnet::is_on_map($res)) {
                   $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($res),'<>&"').'?symb='.
                                &HTML::Entities::encode($caller,'<>&"');
               } else {
                   $backtourl = '/adm/navmaps';
               }
           }
       } elsif ($env{'docs.exit.'.$env{'request.course.id'}} eq '/adm/menu') {
           $backtourl = '/adm/menu';
       } elsif ($supplementalflag) {
           $backtourl = '/adm/supplemental';
       } else {
           $backtourl = '/adm/navmaps';
       }
   
       my $fieldsets = "'ext','doc'";
       unless ($main_container_page) {
           $fieldsets .=",'ims'";
       }
       if ($supplementalflag) {
           $fieldsets = "'suppext','suppdoc'";
       }
   
       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 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/new/smppg';
       this.document.forms.newsmppg.submit();
      }
   }
   
   function makewebpage(type) {
      var title=prompt('$lt{"p_mwp"}');
      var formname;
      if (type == 'supp') {
          formname = this.document.forms.supwebpage;
      } else {
          formname = this.document.forms.newwebpage;
      }
      if (title) {
          var webpage = formname.importdetail.value;
          formname.importdetail.value = escape(title)+'='+webpage;
          formname.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/new/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(caller) {
       var disp = 'none';
       if (document.getElementById('importmapform')) {
           if (caller == 'map') {
               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 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 changename(folderpath,index,oldtitle) {
   var title=prompt('$lt{"p_chn"}',oldtitle);
   if (title) {
   this.document.forms.renameform.markcopy.value='';
   this.document.forms.renameform.title.value=title;
   this.document.forms.renameform.cmd.value='rename_'+index;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   }
   
   function updatePick(targetform,index,caller) {
       var pickitem;
       var picknumitem;
       var picknumtext;
       if (index == 'all') {
           pickitem = document.getElementById('randompickall');
           picknumitem = document.getElementById('rpicknumall');
           picknumtext = document.getElementById('rpicktextall');
       } else {
           pickitem = document.getElementById('randompick_'+index);
           picknumitem = document.getElementById('rpicknum_'+index);
           picknumtext = document.getElementById('randompicknum_'+index);
       }
       if (pickitem.checked) {
           var picknum=prompt('$lt{"rpck"}',picknumitem.value);
           if (picknum == '' || picknum == null) {
               if (caller == 'check') {
                   pickitem.checked=false;
                   if (index == 'all') {
                       picknumtext.innerHTML = '';
                       if (caller == 'link') {
                           propagateState(targetform,'rpicknum');
                       }
                   } else {
                       checkForSubmit(targetform,'randompick','settings');
                   }
               }
           } else {
               picknum.toString();
               var regexdigit=/^\\d+\$/;
               if (regexdigit.test(picknum)) {
                   picknumitem.value = picknum;
                   if (index == 'all') {
                       picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.cumulativesettings,\\'all\\',\\'link\\');">'+picknum+'</a>';
                       if (caller == 'link') {
                           propagateState(targetform,'rpicknum');
                       }
                   } else {
                       picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+index+',\\''+index+'\\',\\'link\\');">'+picknum+'</a>';
                       checkForSubmit(targetform,'randompick','settings');
                   }
               } else {
                   if (caller == 'check') {
                       if (index == 'all') {
                           picknumtext.innerHTML = '';
                           if (caller == 'link') {
                               propagateState(targetform,'rpicknum');
                           }
                       } else {
                           pickitem.checked=false;
                           checkForSubmit(targetform,'randompick','settings');
                       }
                   }
                   return;
               }
           }
       } else {
           picknumitem.value = '';
           picknumtext.innerHTML = '';
           if (index == 'all') {
               if (caller == 'link') {
                   propagateState(targetform,'rpicknum');
               }
           } else {
               checkForSubmit(targetform,'randompick','settings');
           }
       }
   }
   
   function propagateState(form,param) {
       if (document.getElementById(param+'all')) {
           var setcheck = 0;
           var rpick = 0;
           if (param == 'rpicknum') {
               if (document.getElementById('randompickall')) {
                   if (document.getElementById('randompickall').checked) {
                       if (document.getElementById('rpicknumall')) {
                           rpick = document.getElementById('rpicknumall').value;
                       }
                   }
               }
           } else {
               if (document.getElementById(param+'all').checked) {
                   setcheck = 1;
               }
           }
           var allidxlist;
           if ((param == 'remove') || (param == 'cut') || (param == 'copy')) {
               if (document.getElementById('all'+param+'idx')) {
                   allidxlist = document.getElementById('all'+param+'idx').value;
               }
               var actions = new Array ('remove','cut','copy');
               for (var i=0; i<actions.length; i++) {
                   if (actions[i] != param) {
                       if (document.getElementById(actions[i]+'all')) {
                           document.getElementById(actions[i]+'all').checked = false; 
                       }
                   }
               }
           }
           if ((param == 'encrypturl') || (param == 'hiddenresource')) {
               allidxlist = form.allidx.value;
           }
           if ((param == 'randompick') || (param == 'rpicknum') || (param == 'randomorder')) {
               allidxlist = form.allmapidx.value;
           }
           if ((allidxlist != '') && (allidxlist != null)) {
               var allidxs = allidxlist.split(',');
               if (allidxs.length > 1) {
                   for (var i=0; i<allidxs.length; i++) {
                       if (document.getElementById(param+'_'+allidxs[i])) {
                           if (param == 'rpicknum') {
                               if (document.getElementById('randompick_'+allidxs[i])) {
                                   if (document.getElementById('randompick_'+allidxs[i]).checked) {
                                       document.getElementById(param+'_'+allidxs[i]).value = rpick;
                                       if (rpick > 0) {
                                           document.getElementById('randompicknum_'+allidxs[i]).innerHTML = ':&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+allidxs[i]+',\\''+allidxs[i]+'\\',\\'link\\')">'+rpick+'</a>';
                                       } else {
                                           document.getElementById('randompicknum_'+allidxs[i]).innerHTML =  '';
                                       }
                                   }
                               }
                           } else {
                               if (setcheck == 1) {
                                   document.getElementById(param+'_'+allidxs[i]).checked = true;
                               } else {
                                   document.getElementById(param+'_'+allidxs[i]).checked = false;
                                   if (param == 'randompick') {
                                       document.getElementById('randompicknum_'+allidxs[i]).innerHTML =  '';
                                   }
                               }
                           }
                       }
                   }
                   if (setcheck == 1) {
                       if ((param == 'remove') || (param == 'cut') || (param == 'copy')) {
                           var actions = new Array('copy','cut','remove');
                           for (var i=0; i<actions.length; i++) {
                               var otheractions;
                               var otheridxs;
                               if (actions[i] === param) {
                                   continue;
                               } else {
                                   if (document.getElementById('all'+actions[i]+'idx')) {
                                       otheractions = document.getElementById('all'+actions[i]+'idx').value;
                                       otheridxs = otheractions.split(',');
                                       if (otheridxs.length > 1) {
                                           for (var j=0; j<otheridxs.length; j++) {
                                               if (document.getElementById(actions[i]+'_'+otheridxs[j])) {
                                                   document.getElementById(actions[i]+'_'+otheridxs[j]).checked = false;
                                               }
                                           }
                                       }
                                   }
                               }
                           } 
                       }
                   }
               }
           }
       }
       return;
   }
   
   function checkForSubmit(targetform,param,context,idx,folderpath,index,oldtitle,skip_confirm,container,folder) {
       var dosettings;
       var doaction;
       var control = document.togglemultsettings;
       if (context == 'actions') {
           control = document.togglemultactions;
           doaction = 1; 
       } else {
           dosettings = 1;
       }
       if (control) {
           if (control.showmultpick.length) {
               for (var i=0; i<control.showmultpick.length; i++) {
                   if (control.showmultpick[i].checked) {
                       if (control.showmultpick[i].value == 1) {
                           if (context == 'settings') {
                               dosettings = 0;
                           } else {
                               doaction = 0;
                           }
                       }
                   }
               }
           }
       }
       if (context == 'settings') {
           if (dosettings == 1) {
               targetform.changeparms.value=param;
               targetform.submit();
           }
       }
       if (context == 'actions') {
           if (doaction == 1) {
               targetform.cmd.value=param+'_'+index;
               targetform.folderpath.value=folderpath;
               targetform.markcopy.value=idx+':'+param;
               targetform.copyfolder.value=folder+'.'+container;
               if (param == 'remove') {
                   if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
                       targetform.markcopy.value='';
                       targetform.copyfolder.value='';
                       targetform.submit();
                   }
               }
               if (param == 'cut') {
                   if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
                       targetform.submit();
                       return;
                   }
               }
               if (param == 'copy') {
                   targetform.submit();
                   return;
               }
               targetform.markcopy.value='';
               targetform.copyfolder.value='';
               targetform.cmd.value='';
               targetform.folderpath.value='';
               return;
           } else {
               if (document.getElementById(param+'_'+idx)) {
                   item = document.getElementById(param+'_'+idx);
                   if (item.type == 'checkbox') {
                       if (item.checked) {
                           item.checked = false;
                       } else {
                           item.checked = true;
                           singleCheck(item,idx,param);
                       }
                   }
               }
           }
       }
       return;
   }
   
   function singleCheck(caller,idx,action) {
       actions = new Array('cut','copy','remove');
       if (caller.checked) {
           for (var i=0; i<actions.length; i++) {
               if (actions[i] != action) {
                   if (document.getElementById(actions[i]+'_'+idx)) {
                       if (document.getElementById(actions[i]+'_'+idx).checked) {
                           document.getElementById(actions[i]+'_'+idx).checked = false;
                       }
                   }
               }
           }
       }
       return;
   }
   
   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();
           toggleMap();
           if (nav == 'mainnav') {
               var storedpath = "$docs_folderpath";
               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 ((newurl == '/adm/navmaps') && (jumpto != '')) {
           newurl = newurl+'?postdata='+jumpto;
       }
       location.href=newurl;
   }
   
   function togglePick(caller,value) {
       var disp = 'none';
       if (document.getElementById('multi'+caller)) {
           var curr = document.getElementById('multi'+caller).style.display;
           if (value == 1) {
               disp='block';
           }
           if (curr == disp) {
               return; 
           }
           document.getElementById('multi'+caller).style.display=disp;
           if (value == 1) {
               document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$lt{'more'}</a>'; 
           } else {
               document.getElementById('more'+caller).innerHTML = '';
           }
           if (caller == 'actions') { 
               setClass(value);
               setBoxes(value);
           }
       }
       var showButton = multiSettings();
       if (showButton != 1) {
           showButton = multiActions();
       }
       if (document.getElementById('multisave')) {
           if (showButton == 1) {
               document.getElementById('multisave').style.display='block';
           } else {
               document.getElementById('multisave').style.display='none';
           }
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   function toggleCheckUncheck(caller,more) {
       if (more == 1) {
           document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',0);" style="text-decoration:none;">$lt{'less'}</a>';
           document.getElementById('allfields'+caller).style.display='block';
       } else {
           document.getElementById('more'+caller).innerHTML = '&nbsp;&nbsp;<a href="javascript:toggleCheckUncheck(\\''+caller+'\\',1);" style="text-decoration:none;">$lt{'more'}</a>';
           document.getElementById('allfields'+caller).style.display='none';
       }
       resize_scrollbox('contentscroll','1','1');
   }
   
   function multiSettings() {
       var inuse = 0;
       var settingsform = document.togglemultsettings;
       if (settingsform.showmultpick.length > 1) {
           for (var i=0; i<settingsform.showmultpick.length; i++) {
               if (settingsform.showmultpick[i].checked) {
                   if (settingsform.showmultpick[i].value == 1) {
                       inuse = 1;  
                   }
               }
           }
       }
       return inuse;
   }
   
   function multiActions() {
       var inuse = 0;
       var actionsform = document.togglemultactions;
       if (actionsform.showmultpick.length > 1) {
           for (var i=0; i<actionsform.showmultpick.length; i++) {
               if (actionsform.showmultpick[i].checked) {
                   if (actionsform.showmultpick[i].value == 1) {
                       inuse = 1;
                   }
               }
           }
       }
       return inuse;
   } 
   
   function checkSubmits() {
       var numchanges = 0;
       var form = document.saveactions;
       var doactions = multiActions();
       var cutwarnings = 0;
       var remwarnings = 0;
       if (doactions == 1) {
           var remidxlist = document.cumulativeactions.allremoveidx.value;
           if ((remidxlist != '') && (remidxlist != null)) {
               var remidxs = remidxlist.split(',');
               for (var i=0; i<remidxs.length; i++) {
                   if (document.getElementById('remove_'+remidxs[i])) {
                       if (document.getElementById('remove_'+remidxs[i]).checked) {
                           form.multiremove.value += remidxs[i]+',';
                           numchanges ++;
                           if (document.getElementById('skip_remove_'+remidxs[i])) {
                               if (document.getElementById('skip_remove_'+remidxs[i]).value == 0) {
                                   remwarnings ++;
                               }
                           }
                       }
                   }
               }
           }
           var cutidxlist = document.cumulativeactions.allcutidx.value;
           if ((cutidxlist != '') && (cutidxlist != null)) {
               var cutidxs = cutidxlist.split(',');
               for (var i=0; i<cutidxs.length; i++) {
                   if (document.getElementById('cut_'+cutidxs[i])) {
                       if (document.getElementById('cut_'+cutidxs[i]).checked == true) {
                           form.multicut.value += cutidxs[i]+',';
                           numchanges ++;
                           if (document.getElementById('skip_cut_'+cutidxs[i])) {
                               if (document.getElementById('skip_cut_'+cutidxs[i]).value == 0) {
                                   cutwarnings ++;
                               }
                           }
                       }
                   }
               }
           }
           var copyidxlist = document.cumulativeactions.allcopyidx.value;
           if ((copyidxlist != '') && (copyidxlist != null)) {
               var copyidxs = copyidxlist.split(',');
               for (var i=0; i<copyidxs.length; i++) {
                   if (document.getElementById('copy_'+copyidxs[i])) {
                       if (document.getElementById('copy_'+copyidxs[i]).checked) {
                           form.multicopy.value += copyidxs[i]+',';
                           numchanges ++;
                       }
                   }
               }
           }
           if (numchanges > 0) {
               form.multichange.value = numchanges;
           }
       }
       var dosettings = multiSettings();
       var haschanges = 0;
       if (dosettings == 1) {
           form.allencrypturl.value = '';
           form.allhiddenresource.value = '';
           form.changeparms.value = 'all';
           var patt=new RegExp(",\$");
           var allidxlist = document.cumulativesettings.allidx.value;
           if ((allidxlist != '') && (allidxlist != null)) {
               var allidxs = allidxlist.split(',');
               if (allidxs.length > 1) {
                   for (var i=0; i<allidxs.length; i++) {
                       if (document.getElementById('hiddenresource_'+allidxs[i])) {
                           if (document.getElementById('hiddenresource_'+allidxs[i]).checked) {
                               form.allhiddenresource.value += allidxs[i]+',';
                           }
                       }
                       if (document.getElementById('encrypturl_'+allidxs[i])) {
                           if (document.getElementById('encrypturl_'+allidxs[i]).checked) {
                               form.allencrypturl.value += allidxs[i]+',';
                           }
                       }
                   }
                   form.allhiddenresource.value = form.allhiddenresource.value.replace(patt,"");
                   form.allencrypturl.value = form.allencrypturl.value.replace(patt,"");
               }
           }
           form.allrandompick.value = '';
           form.allrandomorder.value = '';
           var allmapidxlist = document.cumulativesettings.allmapidx.value;
           if ((allmapidxlist != '') && (allmapidxlist != null)) {
               var allmapidxs = allmapidxlist.split(',');
               for (var i=0; i<allmapidxs.length; i++) {
                   var randompick = document.getElementById('randompick_'+allmapidxs[i]);
                   var rpicknum = document.getElementById('rpicknum_'+allmapidxs[i]);
                   var randorder = document.getElementById('randomorder_'+allmapidxs[i]);
                   if ((randompick.checked) && (rpicknum.value != '')) {
                       form.allrandompick.value += allmapidxs[i]+':'+rpicknum.value+',';
                   }
                   if (randorder.checked) {
                       form.allrandomorder.value += allmapidxs[i]+',';
                   }
               }
               form.allrandompick.value = form.allrandompick.value.replace(patt,"");
               form.allrandomorder.value = form.allrandomorder.value.replace(patt,"");
           }
           if (document.cumulativesettings.currhiddenresource.value != form.allhiddenresource.value) {
               haschanges = 1;
           }
           if (document.cumulativesettings.currencrypturl.value != form.allencrypturl.value) {
               haschanges = 1;
           }
           if (document.cumulativesettings.currrandomorder.value != form.allrandomorder.value) {
               haschanges = 1;
           }
           if (document.cumulativesettings.currrandompick.value != form.allrandompick.value) {
               haschanges = 1;
           }
       }
       if (doactions == 1) {
           if (numchanges > 0) {
               if ((cutwarnings > 0) || (remwarnings > 0)) {
                   if (remwarnings > 0) {
                       if (!confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr3a"} '+remwarnings+' $lt{"p_rmr3b"}')) {
                           return false;
                       }
                   }
                   if (cutwarnings > 0) {
                       if (!confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr3a"} '+cutwarnings+' $lt{"p_ctr3b"}')) {
                           return false;
                       }
                   }
               }
               form.submit();
               return true;
           }
       }
       if (dosettings == 1) {
           if (haschanges == 1) {
               form.submit();
               return true;
           }
       }
       if ((dosettings == 1) && (doactions == 1)) {
           alert("$lt{'noor'}");
       } else {
           if (dosettings == 1) {
               alert("$lt{'noch'}");
           } else {
               alert("$lt{'noac'}");
           }
       }
       return false;
   }
   
   function setClass(value) {
       var cutclass = 'LC_docs_cut';
       var copyclass = 'LC_docs_copy';
       var removeclass = 'LC_docs_remove';
       var cutreg = new RegExp("\\\\b"+cutclass+"\\\\b");
       var copyreg = new RegExp("\\\\b"+copyclass+"\\\\b");
       var removereg = new RegExp("\\\\"+removeclass+"\\\\b");
       var links = document.getElementsByTagName('a');
       for (var i=0; i<links.length; i++) {
           var classes = links[i].className;
           if (cutreg.test(classes)) {
               links[i].className = cutclass;
               if (value == 1) {
                   links[i].className += " LC_menubuttons_link";
               }
           } else {
               if (copyreg.test(classes)) {
                   links[i].className = copyclass;
                   if (value == 1) {
                       links[i].className += " LC_menubuttons_link";
                   } 
               } else {
                   if (removereg.test(classes)) {
                       links[i].className = removeclass;
                       if (value == 1) {
                           links[i].className += " LC_menubuttons_link";
                       }
                   }
               }
           }
       }
       return;
   }
   
   function setBoxes(value) {
       var remidxlist = document.cumulativeactions.allremoveidx.value;
       if ((remidxlist != '') && (remidxlist != null)) {
           var remidxs = remidxlist.split(',');
           for (var i=0; i<remidxs.length; i++) {
               if (document.getElementById('remove_'+remidxs[i])) {
                   var item = document.getElementById('remove_'+remidxs[i]);
                   if (value == 1) {
                       item.className = 'LC_docs_remove';
                   } else {
                       item.className = 'LC_hidden';
                   }
               }
           }
       }
       var cutidxlist = document.cumulativeactions.allcutidx.value;
       if ((cutidxlist != '') && (cutidxlist != null)) {
           var cutidxs = cutidxlist.split(',');
           for (var i=0; i<cutidxs.length; i++) {
               if (document.getElementById('cut_'+cutidxs[i])) {
                   var item = document.getElementById('cut_'+cutidxs[i]);
                   if (value == 1) {
                       item.className = 'LC_docs_cut';
                   } else {
                       item.className = 'LC_hidden';
                   }
               }
           }
       }
       var copyidxlist = document.cumulativeactions.allcopyidx.value;
       if ((copyidxlist != '') && (copyidxlist != null)) {
           var copyidxs = copyidxlist.split(',');
           for (var i=0; i<copyidxs.length; i++) {
               if (document.getElementById('copy_'+copyidxs[i])) {
                   var item = document.getElementById('copy_'+copyidxs[i]);
                   if (value == 1) {
                       item.className = 'LC_docs_copy';
                   } else {
                       item.className = 'LC_hidden';
                   }
               }
           }
       }
       return;
   }
   
   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 do_buffer_empty() 
   
   =item clear_from_buffer()
   
   =item get_newmap_url()
   
   =item dbcopy()
   
   =item uniqueness_check()
   
   =item contained_map_check()
   
   =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.484.2.41


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