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

version 1.326, 2009/01/28 11:51:22 version 1.546, 2013/05/19 15:33:54
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
   package Apache::londocs;
   
 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 %help=();
 sub mapread {  
     my ($coursenum,$coursedom,$map)=@_;  
     return  sub mapread {
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map)=@_;
      $map);      return
 }        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
        $map);
 sub storemap {  }
     my ($coursenum,$coursedom,$map)=@_;  
     my ($outtext,$errtext)=  sub storemap {
       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map,$contentchg)=@_;
       $map,1);      my $report;
     if ($errtext) { return ($errtext,2); }      if (($contentchg) && ($map =~ /^default/)) {
             $report = 1;
     $hadchanges=1;      }
     return ($errtext,0);      my ($outtext,$errtext)=
 }        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1,$report);
       if ($errtext) { return ($errtext,2); }
   
 sub authorhosts {      $hadchanges=1;
     my %outhash=();      return ($errtext,0);
     my $home=0;  }
     my $other=0;  
     foreach my $key (keys(%env)) {  
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {  
     my $role=$1;  sub authorhosts {
     my $realm=$2;      my %outhash=();
     my ($start,$end)=split(/\./,$env{$key});      my $home=0;
     if (($start) && ($start>time)) { next; }      my $other=0;
     if (($end) && (time>$end)) { next; }      foreach my $key (keys(%env)) {
     my ($ca,$cd);   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     if ($1 eq 'au') {      my $role=$1;
  $ca=$env{'user.name'};      my $realm=$2;
  $cd=$env{'user.domain'};      my ($start,$end)=split(/\./,$env{$key});
     } else {      if (($start) && ($start>time)) { next; }
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);      if (($end) && (time>$end)) { next; }
     }      my ($ca,$cd);
     my $allowed=0;      if ($1 eq 'au') {
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);   $ca=$env{'user.name'};
     my @ids=&Apache::lonnet::current_machine_ids();   $cd=$env{'user.domain'};
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      } else {
     if ($allowed) {   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  $home++;      }
  $outhash{'home_'.$ca.'@'.$cd}=1;      my $allowed=0;
     } else {      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      my @ids=&Apache::lonnet::current_machine_ids();
  $other++;      foreach my $id (@ids) {
     }                  if ($id eq $myhome) {
  }                      $allowed=1;
     }                      last;
     return ($home,$other,%outhash);                  }
 }              }
       if ($allowed) {
    $home++;
 sub dumpbutton {   $outhash{'home_'.$ca.':'.$cd}=1;
     my ($home,$other,%outhash)=&authorhosts();      } else {
     my $type = &Apache::loncommon::course_type();   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
     if ($home+$other==0) { return ''; }   $other++;
     if ($home) {      }
  return '<div>'.   }
     '<input type="submit" name="dumpcourse" value="'.      }
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      return ($home,$other,%outhash);
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs').  }
     '</div>';  
     } else {  
  return '<div>'.  sub clean {
      &mt('Dump '.$type.      my ($title)=@_;
  ' DOCS to Construction Space: available on other servers').      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
  '</div>';      return $title;
     }  }
 }  
   
 sub clean {  
     my ($title)=@_;  sub dumpcourse {
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;      my ($r) = @_;
     return $title;      my $crstype = &Apache::loncommon::course_type();
 }      $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
                 &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
       $r->print(&startContentScreen('tools'));
       my ($home,$other,%outhash)=&authorhosts();
 sub dumpcourse {      unless ($home) {
     my ($r) = @_;          $r->print(&endContentScreen());
     my $type = &Apache::loncommon::course_type();          return '';
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').      }
       '<form name="dumpdoc" method="post">');      my $origcrsid=$env{'request.course.id'};
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my ($home,$other,%outhash)=&authorhosts();      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     unless ($home) { return ''; }  # Do the dumping
     my $origcrsid=$env{'request.course.id'};   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);              $r->print(&endContentScreen());
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {              return '';
 # Do the dumping          }
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }   my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   my $title=$env{'form.authorfolder'};
  my $title=$env{'form.authorfolder'};   $title=&clean($title);
  $title=&clean($title);   my %replacehash=();
  my %replacehash=();   foreach my $key (keys(%env)) {
  foreach my $key (keys(%env)) {      if ($key=~/^form\.namefor\_(.+)/) {
     if ($key=~/^form\.namefor\_(.+)/) {   $replacehash{$1}=$env{$key};
  $replacehash{$1}=$env{$key};      }
     }   }
  }   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   $crs=~s/\_/\//g;
  $crs=~s/\_/\//g;   foreach my $item (keys(%replacehash)) {
  foreach my $item (keys(%replacehash)) {      my $newfilename=$title.'/'.$replacehash{$item};
     my $newfilename=$title.'/'.$replacehash{$item};      $newfilename=~s/\.(\w+)$//;
     $newfilename=~s/\.(\w+)$//;      my $ext=$1;
     my $ext=$1;      $newfilename=&clean($newfilename);
     $newfilename=&clean($newfilename);      $newfilename.='.'.$ext;
     $newfilename.='.'.$ext;      my @dirs=split(/\//,$newfilename);
     my @dirs=split(/\//,$newfilename);      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
     my $path='/home/'.$ca.'/public_html';      my $makepath=$path;
     my $makepath=$path;      my $fail=0;
     my $fail=0;      for (my $i=0;$i<$#dirs;$i++) {
     for (my $i=0;$i<$#dirs;$i++) {   $makepath.='/'.$dirs[$i];
  $makepath.='/'.$dirs[$i];   unless (-e $makepath) {
  unless (-e $makepath) {      unless(mkdir($makepath,0777)) { $fail=1; }
     unless(mkdir($makepath,0777)) { $fail=1; }   }
  }      }
     }      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {      print $fh &Apache::lonclonecourse::rewritefile(
     print $fh &Apache::lonclonecourse::rewritefile(           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),       (%replacehash,$crs => '')
      (%replacehash,$crs => '')      );
     );   } else {
  } else {      print $fh
     print $fh           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);         }
        }   $fh->close();
  $fh->close();      } else {
     } else {   $fail=1;
  $fail=1;      }
     }      if ($fail) {
     if ($fail) {   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');      } else {
     } else {   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      }
     }   }
  }      } else {
     } else {          $r->print(&mt('Searching ...').'<br />');
 # Input form          $r->rflush();
  unless ($home==1) {  # Input form
     $r->print(          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');   unless ($home==1) {
  }      $r->print('<div class="LC_left_float">'.
  foreach my $key (sort(keys(%outhash))) {        '<fieldset><legend>'.
     if ($key=~/^home_(.+)$/) {                        &mt('Select the Authoring Space').
  if ($home==1) {                        '</legend><select name="authorspace">');
     $r->print(   }
   '<input type="hidden" name="authorspace" value="'.$1.'" />');   foreach my $key (sort(keys(%outhash))) {
  } else {      if ($key=~/^home_(.+)$/) {
     $r->print('<option value="'.$1.'">'.$1.' - '.   if ($home==1) {
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');      $r->print(
  }    '<input type="hidden" name="authorspace" value="'.$1.'" />');
     }   } else {
  }      $r->print('<option value="'.$1.'">'.$1.' - '.
  unless ($home==1) {        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
     $r->print('</select>');   }
  }      }
  my $title=$origcrsdata{'description'};   }
  $title=~s/[\/\s]+/\_/gs;   unless ($home==1) {
  $title=&clean($title);      $r->print('</select></fieldset></div>'."\n");
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'   }
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');   my $title=$origcrsdata{'description'};
  &tiehash();   $title=~s/[\/\s]+/\_/gs;
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'   $title=&clean($title);
                  .&Apache::loncommon::start_data_table()   $r->print('<div class="LC_left_float">'.
                  .&Apache::loncommon::start_data_table_header_row()                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
                  .'<th>'.&mt('Internal Filename').'</th>'                    '<input type="text" size="50" name="authorfolder" value="'.
                  .'<th>'.&mt('Title').'</th>'                    $title.'" />'.
                  .'<th>'.&mt('Save as ...').'</th>'                    '</fieldset></div><br clear="all" />'."\n");
                  .&Apache::loncommon::end_data_table_header_row());   &tiehash();
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
     $r->print(&Apache::loncommon::start_data_table_row()                   .&Apache::loncommon::start_data_table()
                      .'<td>'.$file.'</td>');                   .&Apache::loncommon::start_data_table_header_row()
     my ($ext)=($file=~/\.(\w+)$/);                   .'<th>'.&mt('Internal Filename').'</th>'
     my $title=$hash{'title_'.$hash{                   .'<th>'.&mt('Title').'</th>'
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                   .'<th>'.&mt('Save as ...').'</th>'
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');                   .&Apache::loncommon::end_data_table_header_row());
     if (!$title) {   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  $title=$file;      $r->print(&Apache::loncommon::start_data_table_row()
     } else {                       .'<td>'.$file.'</td>');
  $title=~s|/|_|g;      my ($ext)=($file=~/\.(\w+)$/);
     }      my $title=$hash{'title_'.$hash{
     $title=~s/\.(\w+)$//;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     $title=&clean($title);      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
     $title.='.'.$ext;      if (!$title) {
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"   $title=$file;
                      .&Apache::loncommon::end_data_table_row());      } else {
  }   $title=~s|/|_|g;
  $r->print(&Apache::loncommon::end_data_table());      }
  &untiehash();      $title=~s/\.(\w+)$//;
  $r->print(      $title=&clean($title);
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      $title.='.'.$ext;
     }      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
 }                       .&Apache::loncommon::end_data_table_row());
    }
    $r->print(&Apache::loncommon::end_data_table());
    &untiehash();
 sub exportbutton {   $r->print(
     my $type = &Apache::loncommon::course_type();    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
     return '<div>'.      }
             '<input type="submit" name="exportcourse" value="'.      $r->print(&endContentScreen());
             &mt('Export '.$type.' to IMS').'" />'.  }
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs').'</div>';  
 }  sub group_import {
       my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
       my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
           %removeparam,$importuploaded,$fixuperrors);
 sub exportcourse {      $allmaps = {};
     my $r=shift;      while (@files) {
     my $type = &Apache::loncommon::course_type();   my ($name, $url, $residx) = @{ shift(@files) };
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});       && ($caller eq 'londocs')
     my $numdisc = keys(%discussiontime);       && (!&Apache::lonnet::stat_file($url))) {
     my $navmap = Apache::lonnavmaps::navmap->new();  
     if (!defined($navmap)) {              my $errtext = '';
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').              my $fatal = 0;
                   '<h2>IMS Export Failed</h2>'.              my $newmapstr = '<map>'."\n".
                   '<div class="LC_error">'.                              '<resource id="1" src="" type="start"></resource>'."\n".
                   &mt('Unable to retrieve information about course contents').                              '<link from="1" to="2" index="1"></link>'."\n".
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');                              '<resource id="2" src="" type="finish"></resource>'."\n".
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                              '</map>';
         return;              $env{'form.output'}=$newmapstr;
     }              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);                                                  'output',$1.$2);
     my $curRes;              if ($result !~ m{^/uploaded/}) {
     my $outcome;                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
                   $fatal = 2;
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              }
                                             ['finishexport']);              if ($fatal) {
     if ($env{'form.finishexport'}) {                  return ($errtext,$fatal);
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              }
                                             ['archive','discussion']);          }
    if ($url) {
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');              if (($caller eq 'londocs') &&
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');                  ($folder =~ /^default/)) {
         if (@exportitems == 0 && @discussions == 0) {                  if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';                      my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
         } else {                      my $cid = $coursedom.'_'.$coursenum;
             my $now = time;                      $allmaps =
             my %symbs;                          &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
             my $manifestok = 0;                                                               $chome,$cid);
             my $imsresources;                      $donechk = 1;
             my $tempexport;                  }
             my $copyresult;                  if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);                      &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
             if ($manifestok) {                                           \%addedmaps,\%hierarchy,\%titles,$allmaps);
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);                      $importuploaded = 1;
                 close($ims_manifest);                  } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                       next if ($allmaps->{$url});
 #Create zip file in prtspool                  }
                 my $imszipfile = '/prtspool/'.              }
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.      if (!$residx
                    time.'_'.rand(1000000000).'.zip';   || defined($LONCAPA::map::zombies[$residx])) {
                 my $cwd = &Cwd::getcwd();   $residx = &LONCAPA::map::getresidx($url,$residx);
                 my $imszip = '/home/httpd/'.$imszipfile;   push(@LONCAPA::map::order, $residx);
                 chdir $tempexport;      }
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");      my $ext = 'false';
                 close(OUTPUT);      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
                 chdir $cwd;      $name = &LONCAPA::map::qtunescape($name);
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);              if ($name eq '') {
                 if ($copyresult) {                  $name = &LONCAPA::map::qtunescape(&mt('Web Page'));
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);              }
                 }              if ($url =~ m{^/uploaded/$coursedom/$coursenum/((?:docs|supplemental)/(?:default|\d+))/new\.html$}) {
             } else {                  my $filepath = $1;
                 $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 $fname = $name;
             }                  if ($fname =~ /^\W+$/) {
         }                      $fname = 'web';
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));                  } else {
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));                      $fname =~ s/\W/_/g;
         $r->print($outcome);                  }
         $r->print(&Apache::loncommon::end_page());                  if (length($fname > 15)) {
     } else {                      $fname = substr($fname,0,14);
         my $display;                  }
         $display = '<form name="exportdoc" method="post">'."\n";                  my $initialtext = &mt('Replace with your own content.');
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');                  my $newhtml = <<END;
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.  <html>
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.  <head>
                     '<input type="button" value="check all" '.  <title>$name</title>
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.  </head>
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.  <body bgcolor="#ffffff">
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.  $initialtext
                     '<td>&nbsp;</td><td>&nbsp;</td>'.  </body>
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.  </html>
                     '</b></legend><input type="button" value="check all"'.  END
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.                  $env{'form.output'}=$newhtml;
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.                  my $result = 
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
                     '</tr></table>';                                                            'output',
         my $curRes;                                                            "$filepath/$residx/$fname.html");
         my $depth = 0;                  if ($result =~ m{^/uploaded/}) {
         my $count = 0;                      $url = $result;
         my $boards = 0;                      if ($filepath =~ /^supplemental/) {
         my $startcount = 5;                          $name = time.'___&&&___'.$env{'user.name'}.'___&&&___'.
         my %parent = ();                                  $env{'user.domain'}.'___&&&___'.$name;
         my %children = ();                      }
         my $lastcontainer = $startcount;                  } else {
         my @bgcolors = ('#F6F6F6','#FFFFFF');                      return (&mt('Failed to save new web page.'),1);
         $display .= '<table cellspacing="0"><tr>'.                  }
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";              }
         if ($numdisc > 0) {              $url  = &LONCAPA::map::qtunescape($url);
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";      $LONCAPA::map::resources[$residx] =
         }   join(':', ($name, $url, $ext, 'normal', 'res'));
         $display.='&nbsp;</td></tr>';   }
         while ($curRes = $it->next()) {      }
             if (ref($curRes)) {      if ($importuploaded) {
                 $count ++;          my %import_errors;
             }          my %updated = (
             if ($curRes == $it->BEGIN_MAP()) {                            removefrommap => \%removefrommap,
                 $depth++;                            removeparam   => \%removeparam,
                 $parent{$depth} = $lastcontainer;                        );
             }          my ($result,$msgsarray,$lockerror) = 
             if ($curRes == $it->END_MAP()) {              &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
                 $depth--;          if (keys(%import_errors) > 0) {
                 $lastcontainer = $parent{$depth};              $fixuperrors =
             }                  '<p span class="LC_warning">'."\n".
             if (ref($curRes)) {                  &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".
                 my $symb = $curRes->symb();                  '<ul>'."\n";
                 my $ressymb = $symb;              foreach my $key (sort(keys(%import_errors))) {
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {                  $fixuperrors .= '<li>'.$key.'</li>'."\n";
                     unless ($ressymb =~ m|adm/wrapper/adm|) {              }
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';              $fixuperrors .= '</ul></p>'."\n";
                     }          }
                 }          if (ref($msgsarray) eq 'ARRAY') {
                 my $color = $count%2;              if (@{$msgsarray} > 0) {
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".                  $fixuperrors .= '<p class="LC_info">'.
                     '<input type="checkbox" name="archive" value="'.$count.'" ';                                  join('<br />',@{$msgsarray}).
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {                                  '</p>';
                     my $checkitem = $count + $boards + $startcount;              }
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';          }
                 }          if ($lockerror) {
                 $display .= ' />'."\n";              $fixuperrors .= '<p class="LC_error">'.
                 for (my $i=0; $i<$depth; $i++) {                              $lockerror.
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";                              '</p>';
                 }          }
                 if ($curRes->is_sequence()) {      }
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";      my ($errtext,$fatal) =
                     $lastcontainer = $count + $startcount + $boards;          &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
                 } elsif ($curRes->is_page()) {      return ($errtext,$fatal,$fixuperrors);
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";  }
                     $lastcontainer = $count + $startcount + $boards;  
                 }  sub log_docs {
                 my $currelem = $count+$boards+$startcount;      return &Apache::lonnet::write_log('course','docslog',@_);
                 $children{$parent{$depth}} .= $currelem.':';  }
                 $display .= '&nbsp;'.$curRes->title().'</td>';  
                 if ($discussiontime{$ressymb} > 0) {  {
                     $boards ++;      my @oldresources=();
                     $currelem = $count+$boards+$startcount;      my @oldorder=();
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";      my $parmidx;
                 } else {      my %parmaction=();
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";      my %parmvalue=();
                 }      my $changedflag;
             }  
         }      sub snapshotbefore {
         my $scripttag = qq|          @oldresources=@LONCAPA::map::resources;
 <script>          @oldorder=@LONCAPA::map::order;
           $parmidx=undef;
 function checkAll(field) {          %parmaction=();
     if (field.length > 0) {          %parmvalue=();
         for (i = 0; i < field.length; i++) {          $changedflag=0;
             field[i].checked = true ;      }
         }  
     } else {      sub remember_parms {
         field.checked = true          my ($idx,$parameter,$action,$value)=@_;
     }          $parmidx=$idx;
 }          $parmaction{$parameter}=$action;
                                                                                          $parmvalue{$parameter}=$value;
 function uncheckAll(field) {          $changedflag=1;
     if (field.length > 0) {      }
         for (i = 0; i < field.length; i++) {  
             field[i].checked = false ;      sub log_differences {
         }          my ($plain)=@_;
     } else {          my %storehash=('folder' => $plain,
         field.checked = false ;                         'currentfolder' => $env{'form.folder'});
     }          if ($parmidx) {
 }             $storehash{'parameter_res'}=$oldresources[$parmidx];
              foreach my $parm (keys(%parmaction)) {
 function propagateCheck(item) {                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
     if (document.exportdoc.elements[item].checked == true) {                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
         containerCheck(item)             }
     }          }
 }          my $maxidx=$#oldresources;
           if ($#LONCAPA::map::resources>$#oldresources) {
 function containerCheck(item) {             $maxidx=$#LONCAPA::map::resources;
     document.exportdoc.elements[item].checked = true          }
     var numitems = $count + $boards + $startcount          for (my $idx=0; $idx<=$maxidx; $idx++) {
     var parents = new Array(numitems)             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
     for (var i=$startcount; i<numitems; i++) {                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
         parents[i] = new Array                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
     }                $changedflag=1;
         |;             }
              if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
         foreach my $container (sort { $a <=> $b } (keys(%children))) {                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
             my @contents = split(/:/,$children{$container});                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
             for (my $i=0; $i<@contents; $i ++) {                $changedflag=1;
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";             }
             }          }
         }   $storehash{'maxidx'}=$maxidx;
           if ($changedflag) { &log_docs(\%storehash); }
         $scripttag .= qq|      }
     if (parents[item].length > 0) {  }
         for (var j=0; j<parents[item].length; j++) {  
             containerCheck(parents[item][j])  sub docs_change_log {
         }      my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
      }        my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 }      my $js = '<script type="text/javascript">'."\n".
                '// <![CDATA['."\n".
 </script>               &Apache::loncommon::display_filter_js('docslog')."\n".
         |;               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',               &history_tab_js()."\n".
  $scripttag));               &Apache::lonratedt::editscript('simple')."\n".
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));               '// ]]>'."\n".
  $r->print($display.'</table>'.               '</script>'."\n";
                   '<p><input type="hidden" name="finishexport" value="1">'.      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
                   '<input type="submit" name="exportcourse" value="'.      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
                   &mt('Export '.$type.' DOCS').'" /></p></form>');      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
     }      my %orderhash;
 }      my $container='sequence';
       my $pathitem;
 sub create_ims_store {      if ($env{'form.folderpath'} =~ /\:1$/) {
     my ($now,$manifestok,$outcome,$tempexport) = @_;          $container='page';
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';      }
     my $ims_manifest;      my $folderpath=$env{'form.folderpath'};
     if (!-e $$tempexport) {      if ($folderpath eq '') {
         mkdir($$tempexport,0700);          $folderpath = 'default&'.&escape(&mt('Main '.$crstype.' Content').':::::');
     }      }
     $$tempexport .= '/'.$now;      $pathitem = '<input type="hidden" name="folderpath" value="'.
     if (!-e $$tempexport) {                  &HTML::Entities::encode($folderpath,'<>&"').'" />';
         mkdir($$tempexport,0700);      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
     }      my $jumpto = $readfile;
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};      $jumpto =~ s{^/}{};
     if (!-e $$tempexport) {      my $tid = 1;
         mkdir($$tempexport,0700);      if ($supplementalflag) {
     }          $tid = 2;
     if (!-e "$$tempexport/resources") {      }
         mkdir("$$tempexport/resources",0700);      my ($breadcrumbtrail) = 
     }          &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 # open manifest file      $r->print($breadcrumbtrail.
     my $manifest = '/imsmanifest.xml';                &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
     my $manifestfilename = $$tempexport.$manifest;                $readfile));
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      my %docslog=&Apache::lonnet::dump('nohist_docslog',
         $$manifestok=1;                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
         print $ims_manifest                                        $env{'course.'.$env{'request.course.id'}.'.num'});
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".  
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.  
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.      my %saveable_parameters = ('show' => 'scalar',);
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.      &Apache::loncommon::store_course_settings('docs_log',
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.                                                \%saveable_parameters);
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      &Apache::loncommon::restore_course_settings('docs_log',
 '  <metadata>                                                  \%saveable_parameters);
     <schema></schema>      if (!$env{'form.show'}) { $env{'form.show'}=10; }
     <imsmd:lom>  # FIXME: internationalization seems wrong here
       <imsmd:general>      my %lt=('hiddenresource' => 'Resources hidden',
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>      'encrypturl'     => 'URL hidden',
         <imsmd:title>      'randompick'     => 'Randomly pick',
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>      'randomorder'    => 'Randomly ordered',
         </imsmd:title>      'set'            => 'set to',
       </imsmd:general>      'del'            => 'deleted');
     </imsmd:lom>      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
   </metadata>'."\n".                   $pathitem."\n".
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
 ' structure="hierarchical">'."\n".      $r->print('<div class="LC_left_float">'.
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
     } else {                &makedocslogform($filter,1).
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'                '</fieldset></div><br clear="all" />');
 ;      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     }                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
     return $ims_manifest;                &mt('After').'</th>'.
 }                &Apache::loncommon::end_data_table_header_row());
       my $shown=0;
 sub build_package {      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;   if ($env{'form.displayfilter'} eq 'currentfolder') {
 # first iterator to look for dependencies      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);   }
     my $curRes;          my @changes=keys(%{$docslog{$id}{'logentry'}});
     my $count = 0;          if ($env{'form.displayfilter'} eq 'containing') {
     my $depth = 0;      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
     my $lastcontainer = 0;   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
     my %parent = ();      foreach my $key (@changes) {
     my @dependencies = ();   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};      }
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
     while ($curRes = $it->next()) {   }
         if (ref($curRes)) {          my $count = 0;
             $count ++;          my $time =
         }              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
         if ($curRes == $it->BEGIN_MAP()) {          my $plainname =
             $depth++;              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
             $parent{$depth} = $lastcontainer;                                            $docslog{$id}{'exe_udom'});
         }          my $about_me_link =
         if ($curRes == $it->END_MAP()) {              &Apache::loncommon::aboutmewrapper($plainname,
             $depth--;                                                 $docslog{$id}{'exe_uname'},
             $lastcontainer = $parent{$depth};                                                 $docslog{$id}{'exe_udom'});
         }          my $send_msg_link='';
         if (ref($curRes)) {          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
             if ($curRes->is_sequence() || $curRes->is_page()) {               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
                 $lastcontainer = $count;              $send_msg_link ='<br />'.
             }                  &Apache::loncommon::messagewrapper(&mt('Send message'),
             if (grep(/^$count$/,@$exportitems)) {                                                     $docslog{$id}{'exe_uname'},
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);                                                     $docslog{$id}{'exe_udom'});
             }          }
         }          $r->print(&Apache::loncommon::start_data_table_row());
     }          $r->print('<td>'.$time.'</td>
 # second iterator to build manifest and store resources                         <td>'.$about_me_link.
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
     $depth = 0;                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
     my $prevdepth;                    $send_msg_link.'</td><td>'.
     $count = 0;                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
     my $imsresources;          my $is_supp = 0; 
     my $pkgdepth;          if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
     while ($curRes = $it->next()) {              $is_supp = 1;
         if ($curRes == $it->BEGIN_MAP()) {          }
             $prevdepth = $depth;  # Before
             $depth++;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
         }      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
         if ($curRes == $it->END_MAP()) {      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
             $prevdepth = $depth;      if ($oldname ne $newname) {
             $depth--;                  my $shown = &LONCAPA::map::qtescape($oldname);
         }                  if ($is_supp) {
                       $shown = &Apache::loncommon::parse_supplemental_title($shown);
         if (ref($curRes)) {                  }
             $count ++;                  $r->print($shown);
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {      }
                 my $symb = $curRes->symb();   }
                 my $isvisible = 'true';   $r->print('<ul>');
                 my $resourceref;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 if ($curRes->randomout()) {              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
                     $isvisible = 'false';                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
                 }                  if ($is_supp) {
                 unless ($curRes->is_sequence()) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';                  }
                 }   $r->print('<li>'.$shown.'</li>');
                 my $step = $prevdepth - $depth;      }
                 if (($step >= 0) && ($count > 1)) {   }
                     while ($step >= 0) {   $r->print('</ul>');
                         print $ims_manifest "\n".'  </item>'."\n";  # After
                         $step --;          $r->print('</td><td>');
                     }  
                 }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 $prevdepth = $depth;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
       my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
                 my $itementry =      if ($oldname ne '' && $oldname ne $newname) {
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.                  my $shown = &LONCAPA::map::qtescape($newname);
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.                  if ($is_supp) {
               '<title>'.$curRes->title().'</title>';                      $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
                 print $ims_manifest "\n".$itementry;                  }
                   $r->print($shown);
                 unless ($curRes->is_sequence()) {      }
                     my $content_file;   }
                     my @hrefs = ();   $r->print('<ul>');
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                     if ($content_file) {              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
                         $imsresources .= "\n".                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.                  if ($is_supp) {
                      '" type="webcontent" href="'.$content_file.'">'."\n".                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                      '       <file href="'.$content_file.'" />'."\n";                  }
                         foreach my $item (@hrefs) {                  $r->print('<li>'.$shown.'</li>');
                             $imsresources .=      }
                      '        <file href="'.$item.'" />'."\n";   }
                         }   $r->print('</ul>');
                         if (grep(/^$count$/,@$discussions)) {   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                             my $ressymb = $symb;      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
                             my $mode;      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {  # FIXME: internationalization seems wrong here
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';      $r->print('<li>'.
                                 }        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
                                 $mode = 'board';    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
                             }        .'</li>');
                             my %extras = (   }
                                           caller => 'imsexport',      }
                                           tempexport => $tempexport.'/resources',      $r->print('</ul>');
                                           count => $count   }
                                          );  # End
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
                         }          $shown++;
                         $imsresources .= '    </resource>'."\n";          if (!($env{'form.show'} eq &mt('all')
                     }                || $shown<=$env{'form.show'})) { last; }
                 }      }
                 $pkgdepth = $depth;      $r->print(&Apache::loncommon::end_data_table()."\n".
             }                &makesimpleeditform($pathitem)."\n".
         }                '</div></div>');
     }      $r->print(&endContentScreen());
     while ($pkgdepth > 0) {  }
         print $ims_manifest "    </item>\n";  
         $pkgdepth --;  sub update_paste_buffer {
     }      my ($coursenum,$coursedom,$folder) = @_;
     my $resource_text = qq|      my (@possibles,%removals,%cuts);
     </organization>      if ($env{'form.multiremove'}) {
   </organizations>          $env{'form.multiremove'} =~ s/,$//;
   <resources>          map { $removals{$_} = 1; } split(/,/,$env{'form.multiremove'});
     $imsresources      }
   </resources>      if (($env{'form.multicopy'}) || ($env{'form.multicut'})) {
 </manifest>          if ($env{'form.multicut'}) {
     |;              $env{'form.multicut'} =~ s/,$//;
     print $ims_manifest $resource_text;              foreach my $item (split(/,/,$env{'form.multicut'})) {
 }                  unless ($removals{$item}) {
                       $cuts{$item} = 1;
 sub get_dependencies {                      push(@possibles,$item.':cut');
     my ($exportitems,$parent,$depth,$dependencies) = @_;                  }
     if ($depth > 1) {              }
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {          }
             push(@{$dependencies},$$parent{$depth});          if ($env{'form.multicopy'}) {
             if ($depth > 2) {              $env{'form.multicopy'} =~ s/,$//;
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);              foreach my $item (split(/,/,$env{'form.multicopy'})) {
             }                  unless ($removals{$item} || $cuts{$item}) {
         }                      push(@possibles,$item.':copy'); 
     }                  }
 }              }
           }
 sub process_content {      } elsif ($env{'form.markcopy'}) {
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;          @possibles = split(/,/,$env{'form.markcopy'});
     my $content_type;      }
     my $message;  
     my @uploads = ();      return if (@possibles == 0);
     if ($curRes->is_sequence()) {      return if (!defined($env{'form.copyfolder'}));
         $content_type = 'sequence';  
     } elsif ($curRes->is_page()) {      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
         $content_type = 'page'; # need to handle individual items in pages.      $env{'form.copyfolder'});
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {      return if ($fatal);
         $content_type = 'syllabus';  
         my $contents = &Apache::imsexport::templatedpage($content_type);      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-\.sequence___\d+___ext-) {      my (%pasteurls,@newpaste);
         $content_type = 'external';  
         my $title = $curRes->title;  # Construct identifiers for current contents of user's paste buffer
         my $contents =  &Apache::imsexport::external($symb,$title);      if (@currpaste) {
         if ($contents) {          foreach my $suffix (@currpaste) {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);               my $cid = $env{'docs.markedcopy_crs_'.$suffix};
         }               my $url = $env{'docs.markedcopy_url_'.$suffix};
     } elsif ($symb =~ m-adm/navmaps$-) {               if (($cid =~ /^$match_domain(?:_)$match_courseid$/) &&
         $content_type =  'navmap';                   ($url ne '')) {
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {                   $pasteurls{$cid.'_'.$url};
         $content_type = 'simplepage';               }
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);          }
         if ($contents) {      }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);  
         }  # Mark items for copying (skip any items already in user's paste buffer)
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {      my %addtoenv;
         $content_type = 'simpleproblem';                    
         my $contents =  &Apache::imsexport::simpleproblem($symb);      foreach my $item (@possibles) {
         if ($contents) {          my ($orderidx,$cmd) = split(/:/,$item);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          next if ($orderidx =~ /\D/);
         }          next unless (($cmd eq 'cut') || ($cmd eq 'copy') || ($cmd eq 'remove'));
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {          my ($title,$url)=split(':',$LONCAPA::map::resources[$orderidx]);
         $content_type = 'examupload';          my %denied = &action_restrictions($coursenum,$coursedom,
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {                                            &LONCAPA::map::qtescape($url),
         $content_type = 'bulletinboard';                                            $env{'form.folderpath'},\%curr_groups);
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);          next if ($denied{'copy'});
         if ($contents) {          $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$url}));
         }          my ($suffix,$errortxt,$locknotfreed) =
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {              &new_timebased_suffix($env{'user.domain'},$env{'user.name'},'paste');
         $content_type = 'aboutme';          push(@newpaste,$suffix);
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);          if ($locknotfreed) {
         if ($contents) {              return $locknotfreed;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              last;
         }          }
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {          if (&is_supplemental_title($title)) {
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');              &Apache::lonnet::appenv({'docs.markedcopy_supplemental_'.$suffix => $title});
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {      ($title) = &Apache::loncommon::parse_supplemental_title($title);
         my $canedit = 0;          }
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {  
             $canedit= 1;          $addtoenv{'docs.markedcopy_title_'.$suffix} = $title,
         }          $addtoenv{'docs.markedcopy_url_'.$suffix}   = $url,
 # only include problem code where current user is author          $addtoenv{'docs.markedcopy_cmd_'.$suffix}   = $cmd,
         if ($canedit) {          $addtoenv{'docs.markedcopy_crs_'.$suffix}   = $env{'request.course.id'};
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');   
         } else {          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');              my $prefix = $1;
         }              my $subdir =$2;
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {              if ($subdir eq '') {
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                  $subdir = $prefix;
     }              }
     if (@uploads > 0) {              my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
         foreach my $item (@uploads) {              &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
             my $uploadmsg = '';                                   \%hierarchy,\%titles,\%allmaps);
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');              if (ref($hierarchy{$url}) eq 'HASH') {
             if ($uploadmsg) {                  my ($nested,$nestednames);
                 $$copyresult .= $uploadmsg."\n";                  &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
             }                  $nested =~ s/\&$//;
         }                  $nestednames =~ s/\Q___&&&___\E$//;
     }                  if ($nested ne '') {
     if ($message) {                      $addtoenv{'docs.markedcopy_nested_'.$suffix} = $nested;
         $$copyresult .= $message."\n";                  }
     }                  if ($nestednames ne '') {
 }                      $addtoenv{'docs.markedcopy_nestednames_'.$suffix} = $nestednames;
                   }
 sub replicate_content {              }
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;          }
     my ($map,$ind,$url);      }
     if ($caller eq 'templateupload') {      if (@newpaste) {
         $url = $symb;          $addtoenv{'docs.markedcopies'} = join(',',(@currpaste,@newpaste));
         $url =~ s#//#/#g;      }
     } else {      &Apache::lonnet::appenv(\%addtoenv);
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);      delete($env{'form.markcopy'});
     }  }
     my $content;  
     my $filename;  sub recurse_uploaded_maps {
     my $repstatus;      my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
     my $content_name;      if (ref($hierarchy->{$url}) eq 'HASH') {
     if ($url =~ m-/([^/]+)$-) {          my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
         $filename = $1;          my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
         if (!-e $tempexport.'/resources') {          my (@uploaded,@names,%shorter);
             mkdir($tempexport.'/resources',0700);          for (my $i=0; $i<@maps; $i++) {
         }              my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
         if (!-e $tempexport.'/resources/'.$count) {              if ($inner ne '') {
             mkdir($tempexport.'/resources/'.$count,0700);                  push(@uploaded,$inner);
         }                  push(@names,&escape($titles[$i]));
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;                  $shorter{$maps[$i]} = $inner;
         my $copiedfile;              }
         if ($copiedfile = Apache::File->new('>'.$destination)) {          }
             my $content;          $$nestref .= "$dir:".join(',',@uploaded).'&';
             if ($caller eq 'resource') {          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';          foreach my $map (@maps) {
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);              if ($shorter{$map} ne '') {
                 $content = &Apache::lonnet::getfile($filepath);                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
                 if ($content eq -1) {              }
                     $$message = 'Could not copy file '.$filename;          }
                 } else {      }
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');      return;
                     $repstatus = 'ok';  }
                 }  
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {  sub print_paste_buffer {
                 my $rtncode;      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);      return if (!defined($env{'docs.markedcopies'}));
                 if ($repstatus eq 'ok') {  
                     if ($url =~ /\.html?$/i) {      unless (($env{'form.pastemarked'}) || ($env{'form.clearmarked'})) {
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');          return if ($env{'docs.markedcopies'} eq '');
                     }      }
                 } else {  
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";      my @currpaste = split(/,/,$env{'docs.markedcopies'});
                 }      my ($pasteitems,@pasteable);
             } 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.  # Construct identifiers for current contents of user's paste buffer
                 $repstatus = 'ok';      foreach my $suffix (@currpaste) {
                 $content = 'Not the owner of this resource';          next if ($suffix =~ /\D/);
             }          my $cid = $env{'docs.markedcopy_crs_'.$suffix};
             if ($repstatus eq 'ok') {          my $url = $env{'docs.markedcopy_url_'.$suffix};
                 print $copiedfile $content;          if (($cid =~ /^$match_domain\_$match_courseid$/) &&
             }              ($url ne '')) {
             close($copiedfile);              my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent,
         } else {                  $canpaste,$nopaste,$othercrs,$areachange);
             $$message = 'Could not open destination file for '.$filename."<br />\n";              my $extension = (split(/\./,$env{'docs.markedcopy_url_'.$suffix}))[-1];
         }              if ($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
     } else {                  $is_external = 1;
         $$message = 'Could not determine name of file for '.$symb."<br />\n";              }
     }              if ($folder =~ /^supplemental/) {
     if ($repstatus eq 'ok') {                  $canpaste = &supp_pasteable($env{'docs.markedcopy_url_'.$suffix});
         $content_name = 'resources/'.$count.'/'.$filename;                  unless ($canpaste) {
     }                      $nopaste = &mt('Paste into Supplemental Content unavailable.');
     return $content_name;                  }
 }              } else {
                   $canpaste = 1;
 sub extract_media {              }
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;              if ($canpaste) {
     my ($dirpath,$container);                  if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
     my %allfiles = ();                      my $srcdom = $1;
     my %codebase = ();                      my $srcnum = $2;
     if ($url =~ m-(.*/)([^/]+)$-) {                      my $rem = $3;
         $dirpath = $1;                      if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
         $container = $2;                          $othercourse = 1;
     } else {                          if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         $dirpath = $url;                              if ($canpaste) {
         $container = '';                                  $othercrs = '<br />'.&mt('(from another course)');
     }                              }
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);                          } else {
     foreach my $embed_file (keys(%allfiles)) {                              $canpaste = 0;
         my $filename;                              $nopaste = &mt('Paste from another course unavailable.'); 
         if ($embed_file =~ m#([^/]+)$#) {                          }
             $filename = $1;                      }
         } else {                      if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
             $filename = $embed_file;                          my $prefix = $1;
         }                          $parent = $2;
         my $newname = 'res/'.$filename;                          if ($folder !~ /^\Q$prefix\E/) {
         my ($rtncode,$embed_content,$repstatus);                              $areachange = 1;
         my $embed_url;                          }
         if ($embed_file =~ m-^/-) {                          $is_uploaded_map = 1;
             $embed_url = $embed_file;           # points to absolute path                      }
         } else {                  }
             if ($embed_file =~ m-https?://-) {              }
                 next;                           # points to url              if ($canpaste) {
             } else {                 push(@pasteable,$suffix);
                 $embed_url = $dirpath.$embed_file;  # points to relative path              }
             }              my $buffer;
         }              if ($is_external) {
         if ($caller eq 'resource') {                  $buffer = &mt('External Resource').': '.
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                        &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);                      &LONCAPA::map::qtescape($url).')';
             $embed_content = &Apache::lonnet::getfile($embed_path);              } else {
             unless ($embed_content eq -1) {                  my $icon = &Apache::loncommon::icon($extension);
                 $repstatus = 'ok';                  if ($extension eq 'sequence' &&
             }                      $url =~ m{/default_\d+\.sequence$}x) {
         } elsif ($caller eq 'uploaded') {                      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
                                  $icon .= '/navmap.folder.closed.gif';
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);                  }
         }                  $buffer = '<img src="'.$icon.'" alt="" class="LC_icon" />'.
         if ($repstatus eq 'ok') {                            ': '.
             my $destination = $tempexport.'/resources/'.$count.'/res';                            &Apache::loncommon::parse_supplemental_title(
             if (!-e "$destination") {                               &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}));
                 mkdir($destination,0755);              }
             }              $pasteitems .= '<div class="LC_left_float">';
             $destination .= '/'.$filename;              my ($options,$onclick);
             my $copiedfile;              if (($canpaste) && (!$areachange) && (!$othercourse) &&
             if ($copiedfile = Apache::File->new('>'.$destination)) {                  ($env{'docs.markedcopy_cmd_'.$suffix} eq 'cut')) {
                 print $copiedfile $embed_content;                  if (($is_uploaded_map) ||
                 push(@{$href},'resources/'.$count.'/res/'.$filename);                      ($url =~ /(bulletinboard|smppg)$/) ||
                 my $attrib_regexp = '';                      ($url =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
                 if (@{$allfiles{$embed_file}} > 1) {                      $options = &paste_options($suffix,$is_uploaded_map,$parent);
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});                      $onclick= 'onclick="showOptions(this,'."'$suffix'".');" ';
                 } else {                  }
                     $attrib_regexp = $allfiles{$embed_file}[0];              }
                 }              $pasteitems .= '<label><input type="checkbox" name="pasting" id="pasting_'.$suffix.'" value="'.$suffix.'" '.$onclick.'/>'.$buffer.'</label>';
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;              if ($nopaste) {
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {                   $pasteitems .= $nopaste;   
                     $$content =~ s#\Q$embed_file\E#$newname#gi;              } else {
                 }                  if ($othercrs) {
             }                      $pasteitems .= $othercrs;
         } else {                  }
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";                  if ($options) {
         }                      $pasteitems .= $options;
     }                  }
     return;              }
 }              $pasteitems .= '</div>';
           }
 sub store_template {      }
     my ($contents,$tempexport,$count,$content_type) = @_;      if ($pasteitems eq '') {
     if ($contents) {          &Apache::lonnet::delenv('docs.markedcopies');
         if ($tempexport) {      }
             if (!-e $tempexport.'/resources') {      my ($pasteform,$form_start,$buttons,$form_end);
                 mkdir($tempexport.'/resources',0700);      if ($pasteitems) {
             }          $pasteitems .= '<div style="padding:0;clear:both;margin:0;border:0"></div>';
             if (!-e $tempexport.'/resources/'.$count) {          $form_start = '<form name="pasteform" action="/adm/coursedocs" method="post" onsubmit="return validateClipboard();">';
                 mkdir($tempexport.'/resources/'.$count,0700);          if (@pasteable) {
             }              $buttons = '<input type="submit" name="pastemarked" value="'.&mt('Paste selected').'" />'.('&nbsp;'x2);
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';          }
             my $storetemplate;          $buttons .= '<input type="submit" name="clearmarked" value="'.&mt('Clear selected').'" />'.
             if ($storetemplate = Apache::File->new('>'.$destination)) {                      '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
                 print $storetemplate $contents;          $form_end = '</form>';
                 close($storetemplate);      } else {
             }          $pasteitems = &mt('Clipboard is empty');
             if ($content_type eq 'external') {      }
                 return 'resources/'.$count.'/'.$content_type.'.html';      $r->print($form_start
             } else {               .'<fieldset>'
                 return 'resources/'.$count.'/'.$content_type.'.xml';               .'<legend>'.&mt('Clipboard').('&nbsp;' x2).$buttons.'</legend>'
             }               .$pasteitems
         }               .'</fieldset>'
     }               .$form_end);
 }  }
   
   sub paste_options {
 sub group_import {      my ($suffix,$is_uploaded_map,$parent) = @_;
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;      my ($copytext,$movetext);
       if ($is_uploaded_map) {
     while (@files) {          $copytext = &mt('Copy to new folder');
  my ($name, $url, $residx) = @{ shift(@files) };          $movetext = &mt('Move old');
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})      } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /bulletinboard$/) {
      && ($caller eq 'londocs')          $copytext = &mt('Copy to new board');
      && (!&Apache::lonnet::stat_file($url))) {          $movetext = &mt('Move (not posts)');
           } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /smppg$/) {
             my $errtext = '';          $copytext = &mt('Copy to new page');
             my $fatal = 0;          $movetext = &mt('Move');
             my $newmapstr = '<map>'."\n".      } else {
                             '<resource id="1" src="" type="start"></resource>'."\n".          $copytext = &mt('Copy to new file');
                             '<link from="1" to="2" index="1"></link>'."\n".          $movetext = &mt('Move');
                             '<resource id="2" src="" type="finish"></resource>'."\n".      }
                             '</map>';      my $output = '<br />'.
             $env{'form.output'}=$newmapstr;                   '<span id="pasteoptionstext_'.$suffix.'" class="LC_fontsize_small LC_nobreak"></span>'.
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,                   '<div id="pasteoptions_'.$suffix.'" class="LC_dccid" style="display:none;"><span class="LC_nobreak">'.('&nbsp;'x 4).
                                                 'output',$1.$2);                   '<label>'.
             if ($result != m|^/uploaded/|) {                   '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="new" checked="checked" />'.
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';                   $copytext.'</label></span>'.('&nbsp;'x2).' '.
                 $fatal = 2;                   '<span class="LC_nobreak"><label>'.
             }                   '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="move" />'.
             if ($fatal) {                   $movetext.'</label></span>';
                 return ($errtext,$fatal);      if (($is_uploaded_map) && ($env{'docs.markedcopy_nested_'.$suffix})) {
             }          $output .= '<br /><fieldset><legend>'.&mt('Folder to paste contains sub-folders').
         }                     '</legend><table border="0">';
  if ($url) {          my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
     if (!$residx          my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames_'.$suffix});
  || defined($LONCAPA::map::zombies[$residx])) {          my $lastdir = $parent;
  $residx = &LONCAPA::map::getresidx($url,$residx);          my %depths = (
  push(@LONCAPA::map::order, $residx);                         $lastdir => 0,
     }                       );
     my $ext = 'false';          my (%display,%deps);
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }          for (my $i=0; $i<@pastemaps; $i++) {
     $url  = &LONCAPA::map::qtunescape($url);              ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
     $name = &LONCAPA::map::qtunescape($name);              my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
     $LONCAPA::map::resources[$residx] =              my @subfolders = split(/,/,$subfolderstr);
  join(':', ($name, $url, $ext, 'normal', 'res'));              $deps{$lastdir} = \@subfolders;
  }              my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
     }              my $depth = $depths{$lastdir} + 1;
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);              my $offset = int($depth * 4);
 }              my $indent = ('&nbsp;' x $offset);
               for (my $j=0; $j<@subfolders; $j++) {
 sub breadcrumbs {                  $depths{$subfolders[$j]} = $depth;
     my ($where,$allowed,$type)=@_;                  $display{$subfolders[$j]} =
     &Apache::lonhtmlcommon::clear_breadcrumbs();                      '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
     my (@folders);                      '<td><label>'.
     if ($env{'form.pagepath'}) {                      '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
         @folders = split('&',$env{'form.pagepath'});                      '<label>'.
     } else {                      '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="move" />'.
         @folders=split('&',$env{'form.folderpath'});                      &mt('Move old').'</label>'.
     }                      '</td></tr>';
     my $folderpath;               }
     my $cpinfo='';          }
     my $plain='';          &recurse_print(\$output,$parent,\%deps,\%display);
     my $randompick=-1;          $output .= '</table></fieldset>';
     my $isencrypted=0;      }
     my $ishidden=0;      $output .= '</div>';
     my $is_random_order=0;      return $output;
     while (@folders) {  }
  my $folder=shift(@folders);  
     my $foldername=shift(@folders);  sub recurse_print {
  if ($folderpath) {$folderpath.='&';}      my ($outputref,$dir,$deps,$display) = @_;
  $folderpath.=$folder.'&'.$foldername;      $$outputref .= $display->{$dir}."\n";
  my $url='/adm/coursedocs?folderpath='.      if (ref($deps->{$dir}) eq 'ARRAY') {
     &escape($folderpath);          foreach my $subdir (@{$deps->{$dir}}) {
     my $name=&unescape($foldername);              &recurse_print($outputref,$subdir,$deps,$display);
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername          }
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;      }
     if ($1 ne '') {  }
                $randompick=$1;  
             } else {  sub supp_pasteable {
                $randompick=-1;      my ($url) = @_;
             }      if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
             if ($2) { $ishidden=1; }          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
             if ($3) { $isencrypted=1; }          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
     if ($4 ne '') { $is_random_order = 1; }          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
             if ($folder eq 'supplemental') {          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
                 if ($allowed) {          return 1;
                     $name = &mt('Supplemental '.$type.' Documents');      }
                 } else {      return;
                     $name = &mt($type.' Documents');  }
                 }  
             }  sub paste_popup_js {
     &Apache::lonhtmlcommon::add_breadcrumb(      my %lt = &Apache::lonlocal::texthash(
       {'href'=>$url.$cpinfo,                                            show => 'Show Options',
        'title'=>$name,                                            hide => 'Hide Options',
        'text'=>'<font size="+1">'.                                            none => 'No items selected from clipboard.',
    $name.'</font>',                                          );
        'no_mt'=>1,      return <<"END";
        });  
  $plain.=$name.' &gt; ';  function showPasteOptions(suffix) {
     }      document.getElementById('pasteoptions_'+suffix).style.display='block';
     $plain=~s/\&gt\;\s*$//;      document.getElementById('pasteoptionstext_'+suffix).innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:hidePasteOptions(\\''+suffix+'\\');" class="LC_menubuttons_link">$lt{'hide'}</a>';
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',      return;
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);  }
 }  
   function hidePasteOptions(suffix) {
 sub log_docs {      document.getElementById('pasteoptions_'+suffix).style.display='none';
     return &Apache::lonnet::instructor_log('docslog',@_);      document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
 }      return;
   }
 {  
     my @oldresources=();  function showOptions(caller,suffix) {
     my @oldorder=();      if (document.getElementById('pasteoptionstext_'+suffix)) {
     my $parmidx;          if (caller.checked) {
     my %parmaction=();              document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
     my %parmvalue=();          } else {
     my $changedflag;              document.getElementById('pasteoptionstext_'+suffix).innerHTML ='';
           }
     sub snapshotbefore {          if (document.getElementById('pasteoptions_'+suffix)) {
         @oldresources=@LONCAPA::map::resources;              document.getElementById('pasteoptions_'+suffix).style.display='none';
         @oldorder=@LONCAPA::map::order;          }
         $parmidx=undef;      }
         %parmaction=();      return;
         %parmvalue=();  }
         $changedflag=0;  
     }  function validateClipboard() {
       var numchk = 0;
     sub remember_parms {      if (document.pasteform.pasting.length > 1) {
         my ($idx,$parameter,$action,$value)=@_;          for (var i=0; i<document.pasteform.pasting.length; i++) {
         $parmidx=$idx;              if (document.pasteform.pasting[i].checked) {
         $parmaction{$parameter}=$action;                  numchk ++;
         $parmvalue{$parameter}=$value;              }
         $changedflag=1;          }
     }      } else {
           if (document.pasteform.pasting.type == 'checkbox') {
     sub log_differences {              if (document.pasteform.pasting.checked) {
         my ($plain)=@_;                  numchk ++; 
         my %storehash=('folder' => $plain,              } 
                        'currentfolder' => $env{'form.folder'});          }
         if ($parmidx) {      }
            $storehash{'parameter_res'}=$oldresources[$parmidx];      if (numchk > 0) { 
            foreach my $parm (keys(%parmaction)) {          return true;
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};      } else {
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};          alert("$lt{'none'}");
            }          return false;
         }      }
         my $maxidx=$#oldresources;  }
         if ($#LONCAPA::map::resources>$#oldresources) {  
            $maxidx=$#LONCAPA::map::resources;  END
         }  
         for (my $idx=0; $idx<=$maxidx; $idx++) {  }
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {  
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];  sub do_paste_from_buffer {
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];      my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
               $changedflag=1;  
            }  # Array of items in paste buffer
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {      my (@currpaste,%pastebuffer,%allerrors);
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];      @currpaste = split(/,/,$env{'docs.markedcopies'});
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];  
               $changedflag=1;  # Early out if paste buffer is empty
            }      if (@currpaste == 0) {
         }          return ();
  $storehash{'maxidx'}=$maxidx;      } 
         if ($changedflag) { &log_docs(\%storehash); }      map { $pastebuffer{$_} = 1; } @currpaste;
     }  
 }  # Array of items selected items to paste
       my @reqpaste = &Apache::loncommon::get_env_multiple('form.pasting');
   
   # Early out if nothing selected to paste
       if (@reqpaste == 0) {
           return();
 sub docs_change_log {      }
     my ($r)=@_;      my @topaste;
     my $folder=$env{'form.folder'};      foreach my $suffix (@reqpaste) {
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));          next if ($suffix =~ /\D/);
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));          next unless (exists($pastebuffer{$suffix}));
     my %docslog=&Apache::lonnet::dump('nohist_docslog',          push(@topaste,$suffix);
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},      }
                                       $env{'course.'.$env{'request.course.id'}.'.num'});  
   # Early out if nothing available to paste
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }      if (@topaste == 0) {
           return();
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.      }
               '<input type="hidden" name="docslog" value="1" />');  
       my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%duplicate,
     my %saveable_parameters = ('show' => 'scalar',);          %prefixchg,%srcdom,%srcnum,%marktomove,$save_err,$lockerrors,$allresult,
     &Apache::loncommon::store_course_settings('docs_log',          %msgs);
                                               \%saveable_parameters);  
     &Apache::loncommon::restore_course_settings('docs_log',      foreach my $suffix (@topaste) {
                                                 \%saveable_parameters);          my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
     if (!$env{'form.show'}) { $env{'form.show'}=10; }  # Supplemental content may only include certain types of content
     my %lt=('hiddenresource' => 'Resources hidden',  # Early out if pasted content is not supported in Supplemental area
     'encrypturl'     => 'URL hidden',          if ($folder =~ /^supplemental/) {
     'randompick'     => 'Randomly pick',              unless (&supp_pasteable($url)) {
     'randomorder'    => 'Randomly ordered',                  $notinsupp{$suffix} = 1;
     'set'            => 'set to',                  next;
     'del'            => 'deleted');              }
     $r->print(&Apache::loncommon::display_filter().          }
               '<input type="hidden" name="folder" value="'.$folder.'" />'.          if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/}) {
               '<input type="submit" value="'.&mt('Display').'" /></form>');              my $srcd = $1;
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().              my $srcn = $2;
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.  # When paste buffer was populated using an active role in a different course
               &mt('After').'</th>'.  # check for mdc privilege in the course from which the resource was pasted
               &Apache::loncommon::end_data_table_header_row());              if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
     my $shown=0;                  unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {                      $notincrs{$suffix} = 1;
  if ($env{'form.displayfilter'} eq 'currentfolder') {                      next;
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }                  }
  }              }
         my @changes=keys(%{$docslog{$id}{'logentry'}});              $srcdom{$suffix} = $srcd;
         if ($env{'form.displayfilter'} eq 'containing') {              $srcnum{$suffix} = $srcn;
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.          }
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});  
     foreach my $key (@changes) {          push(@dopaste,$suffix);
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};          if ($url=~/\.(page|sequence)$/) {
     }              $is_map{$suffix} = 1; 
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }                  }
  }  
         my $count = 0;          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/([^/]+)}) {
         my $time =              my $oldprefix = $1;
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});  # When pasting content from Main Content to Supplemental Content and vice versa 
         my $plainname =  # URLs will contain different paths (which depend on whether pasted item is
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},  # a folder/page or a document.   
                                           $docslog{$id}{'exe_udom'});              if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
         my $about_me_link =                  $prefixchg{$suffix} = 'docstosupp';
             &Apache::loncommon::aboutmewrapper($plainname,              } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
                                                $docslog{$id}{'exe_uname'},                  $prefixchg{$suffix} = 'supptodocs';
                                                $docslog{$id}{'exe_udom'});              }
         my $send_msg_link='';  
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})  # If pasting an uploaded map, get list of contained uploaded maps.
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {              if ($env{'docs.markedcopy_nested_'.$suffix}) {
             $send_msg_link ='<br />'.                  my @nested;
                 &Apache::loncommon::messagewrapper(&mt('Send message'),                  my ($type) = ($oldprefix =~ /^(default|supplemental)/);
                                                    $docslog{$id}{'exe_uname'},                  my @items = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
                                                    $docslog{$id}{'exe_udom'});                  my @deps = map { /\d+:([\d,]+$)/ } @items;
         }                  foreach my $dep (@deps) {
         $r->print(&Apache::loncommon::start_data_table_row());                      if ($dep =~ /,/) {
         $r->print('<td>'.$time.'</td>                          push(@nested,split(/,/,$dep));
                        <td>'.$about_me_link.                      } else {
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.                          push(@nested,$dep);
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.                      }
                   $send_msg_link.'</td><td>'.                  }
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');                  foreach my $item (@nested) {
 # Before                      if ($env{'form.docs.markedcopy_'.$suffix.'_'.$item} eq 'move') {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                          push(@{$marktomove{$suffix}},$type.'_'.$item);
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                      }
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];                  }
     if ($oldname ne $newname) {              }
  $r->print(&LONCAPA::map::qtescape($oldname));          }
     }      }
  }  
  $r->print('<ul>');  # Early out if nothing available to paste
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {      if (@dopaste == 0) {
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {          return ();
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');      }
     }  
  }  # Populate message hash and hashes used for main content <=> supplemental content
  $r->print('</ul>');  # changes    
 # After  
         $r->print('</td><td>');      %msgs = &Apache::lonlocal::texthash (
                   notinsupp => 'Paste failed: content type is not supported within Supplemental Content',
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  notincrs  => 'Paste failed: Item is from a different course which you do not have rights to edit.',
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                  duplicate => 'Paste failed: only one instance of a particular published sequence or page is allowed within each course.',
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];              );
     if ($oldname ne '' && $oldname ne $newname) {  
  $r->print(&LONCAPA::map::qtescape($newname));      %before = (
     }                   docstosupp => {
  }                                             map => 'default',
  $r->print('<ul>');                                     doc => 'docs',
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                                 },
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {                   supptodocs => {
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');                                     map => 'supplemental',
     }                                     doc => 'supplemental',
  }                                 },
  $r->print('</ul>');                );
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {  
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');      %after = (
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {                   docstosupp => {
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {                                     map => 'supplemental',
     $r->print('<li>'.                                     doc => 'supplemental'
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',                                 },
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})                   supptodocs => {
       .'</li>');                                     map => 'default',
  }                                     doc => 'docs',
     }                                 },
     $r->print('</ul>');               );
  }  
 # End  # Retrieve information about all course maps in main content area 
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());  
         $shown++;      my $allmaps = {};
         if (!($env{'form.show'} eq &mt('all')      if ($folder =~ /^default/) {
               || $shown<=$env{'form.show'})) { last; }          $allmaps =
     }              &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
     $r->print(&Apache::loncommon::end_data_table());                                                   $env{"course.$env{'request.course.id'}.home"},
 }                                                   $env{'request.course.id'});
       }
 sub update_paste_buffer {  
     my ($coursenum,$coursedom) = @_;      my (@toclear,%mapurls,%lockerrs,%msgerrs,%results);
   
     return if (!defined($env{'form.markcopy'}));  # Loop over the items to paste
     return if (!defined($env{'form.copyfolder'}));      foreach my $suffix (@dopaste) {
     return if ($env{'form.markcopy'} < 0);  # Maps need to be copied first
           my (%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,              %dbcopies,%zombies,%params,%docmoves,%mapmoves,%mapchanges,%newsubdir,
     $env{'form.copyfolder'});              %newurls,%tomove);
              if (ref($marktomove{$suffix}) eq 'ARRAY') {
     return if ($fatal);              map { $tomove{$_} = 1; } @{$marktomove{$suffix}};
           }
 # Mark for copying          my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);          my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
     if (&is_supplemental_title($title)) {          my $oldurl = $url;
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});          if ($is_map{$suffix}) {
  ($title) = &parse_supplemental_title($title);  # If pasting a map, check if map contains other maps
     } elsif ($env{'docs.markedcopy_supplemental'}) {              my (%hierarchy,%titles);
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');              &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
     }                                   \%addedmaps,\%hierarchy,\%titles,$allmaps);
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};              if ($url=~ m{^/uploaded/}) {
                   my $newurl;
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,                  unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
     'docs.markedcopy_url'   => $url});                      ($newurl,my $error) = 
     delete($env{'form.markcopy'});                          &get_newmap_url($url,$folder,$prefixchg{$suffix},$coursedom,
 }                                          $coursenum,$srcdom{$suffix},$srcnum{$suffix},
                                           \$title,$allmaps,\%newurls);
 sub print_paste_buffer {                      if ($error) {
     my ($r,$container) = @_;                          $allerrors{$suffix} = $error;
     return if (!defined($env{'docs.markedcopy_url'}));                          next;
                       }
     $r->print(<<ENDPASTE);                      if ($newurl ne '') {
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>                          if ($newurl ne $url) {
 ENDPASTE                              if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');                                  $newsubdir{$url} = $1;
                               }
     my $type;                              $mapchanges{$url} = 1;
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {                          }
  $type = &mt('External Resource');                      }
  $r->print($type.': '.                  }
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.                  if (($srcdom{$suffix} ne $coursedom) ||
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');                      ($srcnum{$suffix} ne $coursenum) ||
     }  else {                      ($prefixchg{$suffix}) || (($newurl ne '') && ($newurl ne $url))) {
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];                      unless (&url_paste_fixups($url,$folder,$prefixchg{$suffix},
  my $icon = &Apache::loncommon::icon($extension);                                                $coursedom,$coursenum,$srcdom{$suffix},
  if ($extension eq 'sequence' &&                                                $srcnum{$suffix},$allmaps,\%rewrites,
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {                                                \%retitles,\%copies,\%dbcopies,
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));                                                \%zombies,\%params,\%mapmoves,
     $icon .= '/folder_closed.gif';                                                \%mapchanges,\%tomove,\%newsubdir,
  }                                                \%newurls)) {
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';                          $mapmoves{$url} = 1;
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));                      }
     }                      $url = $newurl;
     if ($container eq 'page') {                  } elsif ($env{'docs.markedcopy_nested_'.$suffix}) {
  $r->print('                      &url_paste_fixups($url,$folder,$prefixchg{$suffix},$coursedom,
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />                                        $coursenum,$srcdom{$suffix},$srcnum{$suffix},
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />                                        $allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
 ');                                        \%zombies,\%params,\%mapmoves,\%mapchanges,
     } else {                                        \%tomove,\%newsubdir,\%newurls); 
  $r->print('                  }
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />              } elsif ($url=~m {^/res/}) {
 ');  # published map can only exists once, so remove from paste buffer when done
     }                  push(@toclear,$suffix);
     $r->print('</p></form>');  # if pasting published map (main content area only) check map not already in course
 }                  if ($folder =~ /^default/) {
                       if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
 sub do_paste_from_buffer {                          $duplicate{$suffix} = 1; 
     my ($coursenum,$coursedom,$folder) = @_;                          next;
                       }
     if (!$env{'form.pastemarked'}) {                  }
         return;              }
     }          }
           if ($url=~ m{/(bulletinboard|smppg)$}) {
 # paste resource to end of list              my $prefix = $1;
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});              #need to copy the db contents to a new one, unless this is a move.
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});              my %info = (
 # Maps need to be copied first                           src  => $url,
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {                           cdom => $coursedom,
  $title=&mt('Copy of').' '.$title;                           cnum => $coursenum,
  my $newid=$$.int(rand(100)).time;              );
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);              unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {                  my (%lockerr,$msg); 
             my $path = $1;                  my ($newurl,$result,$errtext) =
             my $prefix = $2;                      &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
             my $ancestor = $3;                  if ($result eq 'ok') {
             if (length($ancestor) > 10) {                      $url = $newurl;
                 $ancestor = substr($ancestor,-10,10);                      $title=&mt('Copy of').' '.$title;
             }                  } else {
             $oldid = $path.$prefix.$ancestor;                      if ($prefix eq 'smppg') {
         }                          $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
         my $counter = 0;                      } elsif ($prefix eq 'bulletinboard') {
         my $newurl=$oldid.$newid.'.'.$ext;                          $msg = &mt('Paste failed: An error occurred when copying the bulletin board.').' '.$errtext;
         my $is_unique = &uniqueness_check($newurl);                      }
         while (!$is_unique && $counter < 100) {                      $results{$suffix} = $result;
             $counter ++;                      $msgerrs{$suffix} = $msg;
             $newid ++;                      $lockerrs{$suffix} = $lockerr{$prefix}; 
             $newurl = $oldid.$newid;                      next;
             $is_unique = &uniqueness_check($newurl);          }
         }                  if ($lockerr{$prefix}) {
         if (!$is_unique) {                      $lockerrs{$suffix} = $lockerr{$prefix};  
             if ($url=~/\.page$/) {                  }
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');              }
             } else {          }
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');          $title = &LONCAPA::map::qtunescape($title);
             }          my $ext='false';
         }          if ($url=~m{^http(|s)://}) { $ext='true'; }
  my $storefn=$newurl;          if ($env{'docs.markedcopy_supplemental_'.$suffix}) {
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};              if ($folder !~ /^supplemental/) {
  my $paste_map_result =                  (undef,undef,$title) =
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,                      &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental_'.$suffix});
        &Apache::lonnet::getfile($url));              }
         if ($paste_map_result eq '/adm/notfound.html') {          } else {
             if ($url=~/\.page$/) {              if ($folder=~/^supplemental/) {
                 return &mt('Paste failed: an error occurred saving the composite page');                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
             } else {                         $env{'user.domain'}.'___&&&___'.$title;
                 return &mt('Paste failed: an error occurred saving the folder');              }
             }          }
         }  
  $url = $newurl;  # For uploaded files (excluding pages/sequences) path in copied file is changed
     }  # if paste is from Main to Supplemental (or vice versa), or if pasting between
 # published maps can only exists once, so remove it from paste buffer when done  # courses.
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {  
  &Apache::lonnet::delenv('docs\\.markedcopy');          unless ($is_map{$suffix}) {
     }              my $newidx;
     if ($url=~ m{/smppg$}) {  # Now insert the URL at the bottom
  my $db_name = &Apache::lonsimplepage::get_db_name($url);              $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
  if ($db_name =~ /^smppage_/) {              if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
     #simple pages, need to copy the db contents to a new one.                  my $relpath = $1;
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);                  if ($relpath ne '') {
     my $now = time();                      my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
     $db_name =~ s{_\d*$ }{_$now}x;                      my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
     my $result=&Apache::lonnet::put($db_name,\%contents,                      my $newprefix = $newloc;
     $coursedom,$coursenum);                      if ($newloc eq 'default') {
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;                          $newprefix = 'docs';
     $title=&mt('Copy of').' '.$title;                      }
  }                      if ($newdocsdir eq '') {
     }                          $newdocsdir = 'default';
     $title = &LONCAPA::map::qtunescape($title);                      }
     my $ext='false';                      if (($prefixchg{$suffix}) || 
     if ($url=~m{^http(|s)://}) { $ext='true'; }                          ($srcdom{$suffix} ne $coursedom) || 
     $url       = &LONCAPA::map::qtunescape($url);                          ($srcnum{$suffix} ne $coursenum) ||
 # Now insert the URL at the bottom                          ($env{'form.docs.markedcopy_options_'.$suffix} ne 'move')) {
     my $newidx = &LONCAPA::map::getresidx($url);                          my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
     if ($env{'docs.markedcopy_supplemental'}) {                          $url =
         if ($folder =~ /^supplemental/) {                              &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
             $title = $env{'docs.markedcopy_supplemental'};                                                                 &Apache::lonnet::getfile($oldurl));
         } else {                          if ($url eq '/adm/notfound.html') {
             (undef,undef,$title) =                              $msgs{$suffix} = &mt('Paste failed: an error occurred saving the file.');
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});                              next;
         }                          } else {
     } else {                              my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
         if ($folder=~/^supplemental/) {                              $newsubpath =~ s{/+$}{/};
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                              $docmoves{$oldurl} = $newsubpath;
                   $env{'user.domain'}.'___&&&___'.$title;                          }
         }                      }
     }                  }
               }
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';              $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
     push(@LONCAPA::map::order, $newidx);                                                ':'.$ext.':normal:res';
     return 'ok';              push(@LONCAPA::map::order,$newidx);
 # Store the result  # Store the result
 }              my ($errtext,$fatal) =
                   &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 sub uniqueness_check {              if ($fatal) {
     my ($newurl) = @_;                  $save_err .= $errtext;
     my $unique = 1;                  $allresult = 'fail';
     foreach my $res (@LONCAPA::map::order) {              }
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);          }
         $url=&LONCAPA::map::qtescape($url);  
         if ($newurl eq $url) {  # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
             $unique = 0;          unless ($allresult eq 'fail') {
             last;                  my %updated = (
         }                              rewrites      => \%rewrites,
     }                              zombies       => \%zombies,
     return $unique;                              removefrommap => \%removefrommap,
 }                              removeparam   => \%removeparam,
                               dbcopies      => \%dbcopies,
 my %parameter_type = ( 'randompick'     => 'int_pos',                              retitles      => \%retitles,
        'hiddenresource' => 'string_yesno',                            );
        'encrypturl'     => 'string_yesno',              my %info = (
        'randomorder'    => 'string_yesno',);                             newsubdir => \%newsubdir,
 my $valid_parameters_re = join('|',keys(%parameter_type));                             params    => \%params,
 # set parameters                         );
 sub update_parameter {              if ($prefixchg{$suffix}) {
                   $info{'before'} = $before{$prefixchg{$suffix}};
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);                  $info{'after'} = $after{$prefixchg{$suffix}};
               }
     my $which = $env{'form.changeparms'};              my %moves = (
     my $idx = $env{'form.setparms'};                             copies   => \%copies,
     if ($env{'form.'.$which.'_'.$idx}) {                             docmoves => \%docmoves,
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}                             mapmoves => \%mapmoves,
                                      : 'yes';                          );
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,              (my $result,$msgs{$suffix},my $lockerror) =
       $parameter_type{$which});                  &apply_fixups($folder,$is_map{$suffix},$coursedom,$coursenum,$errors,
  &remember_parms($idx,$which,'set',$value);                                \%updated,\%info,\%moves,$prefixchg{$suffix},$oldurl,
     } else {                                $url,'paste');
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);              $lockerrors .= $lockerror;
               if ($result eq 'ok') {
  &remember_parms($idx,$which,'del');                  if ($is_map{$suffix}) {
     }                      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
     return 1;                                                      $folder.'.'.$container);
 }                      if ($fatal) {
                           $allresult = 'failread';
                       } else {
 sub handle_edit_cmd {                          if ($#LONCAPA::map::order<1) {
     my ($coursenum,$coursedom) =@_;                              my $idx=&LONCAPA::map::getresidx();
                               if ($idx<=0) { $idx=1; }
     my ($cmd,$idx)=split('_',$env{'form.cmd'});                              $LONCAPA::map::order[0]=$idx;
                               $LONCAPA::map::resources[$idx]='';
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];                          }
     my ($title, $url, @rrest) = split(':', $ratstr);                          my $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
                           $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
     if ($cmd eq 'del') {                                                            ':'.$ext.':normal:res';
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&                          push(@LONCAPA::map::order,$newidx);
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {  
     &Apache::lonnet::removeuploadedurl($url);  # Store the result
  } else {                          my ($errtext,$fatal) = 
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
  }                          if ($fatal) {
  splice(@LONCAPA::map::order, $idx, 1);                              $save_err .= $errtext;
                               $allresult = 'failstore';
     } elsif ($cmd eq 'cut') {                          }
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                      } 
  splice(@LONCAPA::map::order, $idx, 1);                  }
                   if ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
     } elsif ($cmd eq 'up'                       push(@toclear,$suffix);
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {                  }
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];              }
           }
     } elsif ($cmd eq 'down'      }
      && defined($LONCAPA::map::order[$idx+1])) {      &clear_from_buffer(\@toclear,\@currpaste);
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];      my $msgsarray;
       foreach my $suffix (keys(%msgs)) {
     } elsif ($cmd eq 'rename') {           if (ref($msgs{$suffix}) eq 'ARRAY') {
                $msgsarray .= join(',',@{$msgs{$suffix}});
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});           }
  if ($comment=~/\S/) {      }
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=      return ($allresult,$save_err,$msgsarray,$lockerrors);
  $comment.':'.join(':', $url, @rrest);  }
  }  
 # Devalidate title cache  sub do_buffer_empty {
  my $renamed_url=&LONCAPA::map::qtescape($url);      my @currpaste = split(/,/,$env{'docs.markedcopies'});
  &Apache::lonnet::devalidate_title_cache($renamed_url);      if (@currpaste == 0) {
     } else {          return &mt('Clipboard is already empty');
  return 0;      }
     }      my @toclear = &Apache::loncommon::get_env_multiple('form.pasting');
     return 1;      if (@toclear == 0) {
 }          return &mt('Nothing selected to clear from clipboard');
       }
 sub editor {      my $numdel = &clear_from_buffer(\@toclear,\@currpaste);
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;      if ($numdel) {
           return &mt('[quant,_1,item] cleared from clipboard',$numdel);
     my $container= ($env{'form.pagepath'}) ? 'page'      } else {
                            : 'sequence';          return &mt('Clipboard unchanged');
       }
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,      return;
     $folder.'.'.$container);  }
     return $errtext if ($fatal);  
   sub clear_from_buffer {
     if ($#LONCAPA::map::order<1) {      my ($toclear,$currpaste) = @_;
  my $idx=&LONCAPA::map::getresidx();      return unless ((ref($toclear) eq 'ARRAY') && (ref($currpaste) eq 'ARRAY'));
  if ($idx<=0) { $idx=1; }      my %pastebuffer;
         $LONCAPA::map::order[0]=$idx;      map { $pastebuffer{$_} = 1; } @{$currpaste};
         $LONCAPA::map::resources[$idx]='';      my $numdel = 0;
     }      foreach my $suffix (@{$toclear}) {
              next if ($suffix =~ /\D/);
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=          next unless (exists($pastebuffer{$suffix}));
  &breadcrumbs($folder,$allowed,$type);          my $regexp = 'docs.markedcopy_[a-z]+_'.$suffix;
     $r->print($breadcrumbtrail);          if (&Apache::lonnet::delenv($regexp,1) eq 'ok') {
                  delete($pastebuffer{$suffix});
 # ------------------------------------------------------------ Process commands              $numdel ++;
           }
 # ---------------- if they are for this folder and user allowed to make changes      }
     if (($allowed) && ($env{'form.folder'} eq $folder)) {      my $newbuffer = join(',',sort(keys(%pastebuffer)));
 # set parameters and change order      &Apache::lonnet::appenv({'docs.markedcopies' => $newbuffer});
  &snapshotbefore();      return $numdel;
   }
  if (&update_parameter()) {  
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);  sub get_newmap_url {
     return $errtext if ($fatal);      my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
  }          $titleref,$allmaps,$newurls) = @_;
       my $newurl;
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {      if ($url=~ m{^/uploaded/}) {
 # change order          $$titleref=&mt('Copy of').' '.$$titleref;
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);      }
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);      my $now = time;
       my $suffix=$$.int(rand(100)).$now;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
     return $errtext if ($fatal);      if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
  }          my $path = $1;
               my $prefix = $2;
  if ($env{'form.pastemarked'}) {          my $ancestor = $3;
             my $paste_res =          if (length($ancestor) > 10) {
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);              $ancestor = substr($ancestor,-10,10);
             if ($paste_res eq 'ok') {          }
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);          my $newid;
                 return $errtext if ($fatal);          if ($prefixchg) {
             } elsif ($paste_res ne '') {              if ($folder =~ /^supplemental/) {
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');                  $prefix =~ s/^default/supplemental/;
             }              } else {
  }                  $prefix =~ s/^supplemental/default/;
               }
  $r->print($upload_output);          }
           if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
  if (&handle_edit_cmd()) {              $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          } else {
     return $errtext if ($fatal);              $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
  }          }
 # Group import/search          my $counter = 0;
  if ($env{'form.importdetail'}) {          my $is_unique = &uniqueness_check($newurl);
     my @imports;          if ($folder =~ /^default/) {
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {              if ($allmaps->{$newurl}) {
  if (defined($item)) {                  $is_unique = 0;
     my ($name,$url,$residx)=              }
  map {&unescape($_)} split(/\=/,$item);          }
     push(@imports, [$name, $url, $residx]);          while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
  }              $counter ++;
     }              $suffix ++;
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,              if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
     $container,'londocs',@imports);                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     return $errtext if ($fatal);              } else {
  }                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
 # Loading a complete map              }
  if ($env{'form.loadmap'}) {              $is_unique = &uniqueness_check($newurl);
     if ($env{'form.importmap'}=~/\w/) {          }
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {          if ($is_unique) {
     my ($title,$url,$ext,$type)=split(/\:/,$res);              $newurls->{$newurl} = 1;
     my $idx=&LONCAPA::map::getresidx($url);          } else {
     $LONCAPA::map::resources[$idx]=$res;              if ($url=~/\.page$/) {
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
  }              } else {
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
     $folder.'.'.$container);              }
  return $errtext if ($fatal);          }
     } else {      }
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');      return ($newurl);
   }
     }  
  }  sub dbcopy {
  &log_differences($plain);      my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
     }      my ($url,$result,$errtext);
 # ---------------------------------------------------------------- End commands      my $url = $dbref->{'src'};
 # ---------------------------------------------------------------- Print screen      if (ref($dbref) eq 'HASH') {
     my $idx=0;          if ($url =~ m{/(smppg|bulletinboard)$}) {
     my $shown=0;              my $prefix = $1;
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {              if (($dbref->{'cdom'} =~ /^$match_domain$/) && 
  $r->print('<p>'.&mt('Parameters').':<ul>'.                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').                  my $db_name;
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').                  my $marker = (split(m{/},$url))[4];
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').                  $marker=~s/\D//g;
   '</ul></p>');                  if ($dbref->{'src'} =~ m{/smppg$}) {
     }                                                                                                                          $db_name =
     if ($randompick>=0) {                          &Apache::lonsimplepage::get_db_name($url,$marker,
  $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>');                                                              $dbref->{'cdom'},
     }                                                              $dbref->{'cnum'});
     if ($is_random_order) {                  } else {
  $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>');                      $db_name = 'bulletinpage_'.$marker;
     }                  }
     $r->print('<table class="LC_docs_editor">');                  my ($suffix,$freedlock,$error) =
     foreach my $res (@LONCAPA::map::order) {                      &Apache::lonnet::get_timebased_id($prefix,'num','templated',
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                                                        $coursedom,$coursenum,
  $name=&LONCAPA::map::qtescape($name);                                                        'concat');
  $url=&LONCAPA::map::qtescape($url);                  if (!$suffix) {
  unless ($name) {  $name=(split(/\//,$url))[-1]; }                      if ($prefix eq 'smppg') {
  unless ($name) { $idx++; next; }                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,                      } else {
      $coursenum));                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a bulletin board [_1].',$url);
  $idx++;                      }
  $shown++;                      if ($error) {
     }                          $errtext .= '<br />'.$error;
     unless ($shown) {                      }
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');                  } else {
     }                      #need to copy the db contents to a new one.
     $r->print("\n</table>\n");                      my %contents=&Apache::lonnet::dump($db_name,
     if ($allowed) {                                                         $dbref->{'cdom'},
         &print_paste_buffer($r,$container);                                                         $dbref->{'cnum'});
     }                      if (exists($contents{'uploaded.photourl'})) {
     return;                          my $photo = $contents{'uploaded.photourl'};
 }                          my ($subdir,$fname) =
                               ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
 sub process_file_upload {                          my $newphoto; 
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;                          if ($fname ne '') {
 # upload a file, if present                              my $content = &Apache::lonnet::getfile($photo);
     my $parseaction;                              unless ($content eq '-1') {
    if ($env{'form.parserflag'}) {                                  $env{'form.'.$suffix.'.photourl'} = $content;
         $parseaction = 'parse';                                  $newphoto = 
     }                                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
     my $phase_status;                                  delete($env{'form.'.$suffix.'.photourl'});
     my $folder=$env{'form.folder'};                              }
     if ($folder eq '') {                          }
         $folder='default';                          if ($newphoto =~ m{^/uploaded/}) {
     }                              $contents{'uploaded.photourl'} = $newphoto;
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {                          }
         my $errtext='';                      }
         my $fatal=0;                      $db_name =~ s{_\d*$ }{_$suffix}x;
         my $container='sequence';                      $result=&Apache::lonnet::put($db_name,\%contents,
         if ($env{'form.pagepath'}) {                                                   $coursedom,$coursenum);
             $container='page';                      if ($result eq 'ok') {
         }                          $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
         ($errtext,$fatal)=                      }
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                  }
         if ($#LONCAPA::map::order<1) {                  if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
             $LONCAPA::map::order[0]=1;                      $lockerrorsref->{$prefix} = 
             $LONCAPA::map::resources[1]='';                          '<div class="LC_error">'.
         }                          &mt('There was a problem removing a lockfile.');
         if ($fatal) {                      if ($prefix eq 'smppg') {
             return 'failed';                          $lockerrorsref->{$prefix} .= 
         }                              &mt('This will prevent creation of additional simple pages in this course.');
         my $destination = 'docs/';                      } else {
         if ($folder =~ /^supplemental/) {                          $lockerrorsref->{$prefix} .= &mt('This will prevent creation of additional bulletin boards in this course.');
             $destination = 'supplemental/';                      }
         }                      $lockerrorsref->{$prefix} .= &mt('Please contact the domain coordinator for your LON-CAPA domain.').'</div>';
         if (($folder eq 'default') || ($folder eq 'supplemental')) {                  }
             $destination .= 'default/';              }
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {          } elsif ($url =~ m{/syllabus$}) {
             $destination .=  $2.'/';              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
         }                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
 # this is for a course, not a user, so set coursedoc flag                  if (($dbref->{'cdom'} ne $coursedom) ||
 # probably the only place in the system where this should be "1"                      ($dbref->{'cnum'} ne $coursenum)) {
         my $newidx=&LONCAPA::map::getresidx();                      my %contents=&Apache::lonnet::dump('syllabus',
         $destination .= $newidx;                                                         $dbref->{'cdom'},
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,                                                         $dbref->{'cnum'});
  $parseaction,$allfiles,                      $result=&Apache::lonnet::put('syllabus',\%contents,
  $codebase);                                                   $coursedom,$coursenum);
         my $ext='false';                  }
         if ($url=~m{^http://}) { $ext='true'; }              }
  $url     = &LONCAPA::map::qtunescape($url);          }
         my $comment=$env{'form.comment'};      }
  $comment = &LONCAPA::map::qtunescape($comment);      return ($url,$result,$errtext);
         if ($folder=~/^supplemental/) {  }
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.  
                   $env{'user.domain'}.'___&&&___'.$comment;  sub uniqueness_check {
         }      my ($newurl) = @_;
       my $unique = 1;
         $LONCAPA::map::resources[$newidx]=      foreach my $res (@LONCAPA::map::order) {
     $comment.':'.$url.':'.$ext.':normal:res';          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;          $url=&LONCAPA::map::qtescape($url);
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,          if ($newurl eq $url) {
     $folder.'.'.$container);              $unique = 0;
         if ($fatal) {              last;
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';          }
             return 'failed';      }
         } else {      return $unique;
             if ($parseaction eq 'parse') {  }
                 my $total_embedded = keys(%{$allfiles});  
                 if ($total_embedded > 0) {  sub contained_map_check {
                     my $num = 0;      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
     my $state = '          $allmaps) = @_;
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />      my $content = &Apache::lonnet::getfile($url);
    <input type="hidden" name="cmd" value="upload_embedded" />      unless ($content eq '-1') {
    <input type="hidden" name="newidx" value="'.$newidx.'" />          my $parser = HTML::TokeParser->new(\$content);
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />          $parser->attr_encoded(1);
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';          while (my $token = $parser->get_token) {
     $phase_status = 'phasetwo';              next if ($token->[0] ne 'S');
               if ($token->[1] eq 'resource') {
                     $$upload_output .=                  next if ($token->[2]->{'type'} eq 'zombie');
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.                  my $ressrc = $token->[2]->{'src'};
  &Apache::loncommon::ask_for_embedded_content(                  if ($folder =~ /^supplemental/) {
                             '/adm/coursedocs',$state,$allfiles,$codebase);                      unless (&supp_pasteable($ressrc)) {
                 } else {                          $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
                     $$upload_output .= 'No embedded items identified<br />';                          next;
                 }                      }
             }                  }
         }                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
     }                      if ($1 eq 'uploaded') {
     return $phase_status;                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
 }                          $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
                       } else {
 sub process_secondary_uploads {                          if ($allmaps->{$ressrc}) {
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     my $folder=$env{'form.folder'};                          } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
     my $destination = 'docs/';                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     if ($folder =~ /^supplemental/) {                          } else {
         $destination = 'supplemental/';                              $addedmaps->{$ressrc} = [$url];
     }                          }
     if (($folder eq 'default') || ($folder eq 'supplemental')) {                      }
         $destination .= 'default/';                      &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {                                           $addedmaps,$hierarchy,$titles,$allmaps);
         $destination .=  $2.'/';                  }
     }              } elsif ($token->[1] eq 'param') {
     $destination .= $newidx;                  if ($folder =~ /^supplemental/) {
     my ($url,$filename);                      if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);                          push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});                      } else {
     return $filename;                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
 }                      }
                   }
 sub is_supplemental_title {              }
     my ($title) = @_;          }
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);      }
 }      return;
   }
 sub parse_supplemental_title {  
     my ($title) = @_;  sub url_paste_fixups {
       my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
     my ($foldertitle,$renametitle);          $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
     if ($title =~ /&amp;&amp;&amp;/) {          $mapchanges,$tomove,$newsubdir,$newurls) = @_;
  $title = &HTML::Entites::decode($title);      my $checktitle;
     }      if (($prefixchg) &&
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {          ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
  $renametitle=$4;          $checktitle = 1;
  my ($time,$uname,$udom) = ($1,$2,$3);      }
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);      my $skip;
  my $name =  &Apache::loncommon::plainname($uname,$udom);      if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
  $name = &HTML::Entities::encode($name,'"<>&\'');          my $mapid = $1.$2;
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.          if ($tomove->{$mapid}) {
     $name.': <br />'.$foldertitle;              $skip = 1;
     }          }
     if (wantarray) {      }
  return ($title,$foldertitle,$renametitle);      my $file = &Apache::lonnet::getfile($oldurl);
     }      return if ($file eq '-1');
     return $title;      my $parser = HTML::TokeParser->new(\$file);
 }      $parser->attr_encoded(1);
       my $changed = 0;
 # --------------------------------------------------------------- An entry line      while (my $token = $parser->get_token) {
           next if ($token->[0] ne 'S');
 sub entryline {          if ($token->[1] eq 'resource') {
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;              my $ressrc = $token->[2]->{'src'};
               next if ($ressrc eq '');
     my ($foldertitle,$pagetitle,$renametitle);              my $id = $token->[2]->{'id'};
     if (&is_supplemental_title($title)) {              my $title = $token->[2]->{'title'};
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);              if ($checktitle) {
  $pagetitle = $foldertitle;                  if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
     } else {                      $retitles->{$oldurl}{$id} = $ressrc;
  $title=&HTML::Entities::encode($title,'"<>&\'');                  }
  $renametitle=$title;              }
  $foldertitle=$title;              next if ($token->[2]->{'type'} eq 'external');
  $pagetitle=$title;              if ($token->[2]->{'type'} eq 'zombie') {
     }                  next if ($skip);  
                   $zombies->{$oldurl}{$id} = $ressrc;
     my $orderidx=$LONCAPA::map::order[$index];                  $changed = 1;
                  } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
                   my $srcdom = $1;
     $renametitle=~s/\\/\\\\/g;                  my $srcnum = $2;
     $renametitle=~s/\&quot\;/\\\"/g;                  my $rem = $3;
     $renametitle=~s/ /%20/g;                  my $newurl;
     my $line='<tr>';                  my $mapname;
     my ($form_start,$form_end);                  if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
 # Edit commands                      my $prefix = $1;
     my ($container, $type, $esc_path, $path, $symb);                      $mapname = $prefix.$2;
     if ($env{'form.folderpath'}) {                      if ($tomove->{$mapname}) {
  $type = 'folder';                          &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
         $container = 'sequence';                                            $srcdom,$srcnum,$allmaps,$rewrites,
  $esc_path=&escape($env{'form.folderpath'});                                            $retitles,$copies,$dbcopies,$zombies,
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                                            $params,$mapmoves,$mapchanges,$tomove,
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');                                            $newsubdir,$newurls);
     }                          next;
     if ($env{'form.pagepath'}) {                      } else {
         $type = $container = 'page';                          ($newurl,my $error) =
         $esc_path=&escape($path = $env{'form.pagepath'});                              &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
         $symb=&escape($env{'form.pagesymb'});                          if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
     }                              $newsubdir->{$ressrc} = $1;
     my $cpinfo='';                          }
     if ($allowed) {                          if ($error) {
  my $incindex=$index+1;                              next;
  my $selectbox='';                          }
  if (($folder!~/^supplemental/) &&                      }
     ($#LONCAPA::map::order>0) &&                  }
     ((split(/\:/,                  if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
      ne '') &&                     
     ((split(/\:/,                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]                          $rewrites->{$oldurl}{$id} = $ressrc;
      ne '')) {                          $mapchanges->{$ressrc} = 1;
     $selectbox=                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.                                                    $cnum,$srcdom,$srcnum,$allmaps,
  '<select name="newpos" onChange="this.form.submit()">';                                                    $rewrites,$retitles,$copies,$dbcopies,
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {                                                    $zombies,$params,$mapmoves,$mapchanges,
  if ($i==$incindex) {                                                    $tomove,$newsubdir,$newurls)) {
     $selectbox.='<option value="" selected="1">('.$i.')</option>';                              $mapmoves->{$ressrc} = 1;
  } else {                          }
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';                          $changed = 1;
  }                      } else {
     }                          $rewrites->{$oldurl}{$id} = $ressrc;
     $selectbox.='</select>';                          $copies->{$oldurl}{$ressrc} = $id;
  }                          $changed = 1;
  my %lt=&Apache::lonlocal::texthash(                      }
                 'up' => 'Move Up',                  }
  'dw' => 'Move Down',              } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
  'rm' => 'Remove',                  next if ($skip);
                 'ct' => 'Cut',                  my $srcdom = $1;
  'rn' => 'Rename',                  my $srcnum = $2;
  'cp' => 'Copy');                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
  my $nocopy=0;                      $rewrites->{$oldurl}{$id} = $ressrc;
         my $nocut=0;                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
         if ($url=~/\.(page|sequence)$/) {                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
     if ($url =~ m{/res/}) {                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
  # no copy for published maps                      $changed = 1;
  $nocopy = 1;                  }
     } else {              } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {                  if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
     my ($title,$url,$ext,$type)=split(/\:/,$item);                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
  $nocopy=1;                      $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
  last;                      $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
     }                      $changed = 1;
  }                  }
     }              } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
  }                  next if ($skip);
         if ($url=~/^\/res\/lib\/templates\//) {                  my $srcdom = $1;
            $nocopy=1;                  my $srcnum = $2;
            $nocut=1;                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
         }                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
         my $copylink='&nbsp;';                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
         my $cutlink='&nbsp;';                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
                       $changed = 1;
  my $skip_confirm = 0;                  }
  if ( $folder =~ /^supplemental/              }
      || ($url =~ m{( /smppg$          } elsif ($token->[1] eq 'param') {
     |/syllabus$              next if ($skip);
     |/aboutme$              my $to = $token->[2]->{'to'}; 
     |/navmaps$              if ($to ne '') {
     |/bulletinboard$                  if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
     |\.html$                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
     |^/adm/wrapper/ext)}x)) {                  } else {
     $skip_confirm = 1;                      @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
  }                  }
               }
  if (!$nocopy) {          }
     $copylink=(<<ENDCOPY);      }
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>      return $changed;
 ENDCOPY  }
         }  
  if (!$nocut) {  sub apply_fixups {
     $cutlink=(<<ENDCUT);      my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>          $oldurl,$url,$caller) = @_;
 ENDCUT      my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
         }          %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
  $form_start = (<<END);          %lockerrors,$lockmsg);
    <form  action="/adm/coursedocs" method="post">      if (ref($updated) eq 'HASH') {
    <input type="hidden" name="${type}path" value="$path" />          if (ref($updated->{'rewrites'}) eq 'HASH') {
    <input type="hidden" name="${type}symb" value="$symb" />              %rewrites = %{$updated->{'rewrites'}};
    <input type="hidden" name="setparms" value="$orderidx" />          }
    <input type="hidden" name="changeparms" value="0" />          if (ref($updated->{'zombies'}) eq 'HASH') {
 END              %zombies = %{$updated->{'zombies'}};
         $form_end = '</form>';          }
  $line.=(<<END);          if (ref($updated->{'removefrommap'}) eq 'HASH') {
 <td>              %removefrommap = %{$updated->{'removefrommap'}};
    <table class="LC_docs_entry_move">          }
       <tr>          if (ref($updated->{'removeparam'}) eq 'HASH') {
          <td>              %removeparam = %{$updated->{'removeparam'}};
             <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>          }
          </td>          if (ref($updated->{'dbcopies'}) eq 'HASH') {
       </tr>              %dbcopies = %{$updated->{'dbcopies'}};
       <tr>          }
         <td>          if (ref($updated->{'retitles'}) 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>              %retitles = %{$updated->{'retitles'}};
         </td>          }
       </tr>      }
     </table>      if (ref($info) eq 'HASH') {
 </td>          if (ref($info->{'newsubdir'}) eq 'HASH') {
 <td>              %newsubdir = %{$info->{'newsubdir'}};
    $form_start          }
    $selectbox          if (ref($info->{'params'}) eq 'HASH') {
    $form_end              %params = %{$info->{'params'}};
 </td>          }
 <td class="LC_docs_entry_commands">          if (ref($info->{'before'}) eq 'HASH') {
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>              %before = %{$info->{'before'}};
 $cutlink          }
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>          if (ref($info->{'after'}) eq 'HASH') {
 $copylink              %after = %{$info->{'after'}};
 </td>          }
 END      }
       if (ref($moves) eq 'HASH') {
     }          if (ref($moves->{'copies'}) eq 'HASH') {
 # Figure out what kind of a resource this is              %copies = %{$moves->{'copies'}};
     my ($extension)=($url=~/\.(\w+)$/);          }
     my $uploaded=($url=~/^\/*uploaded\//);          if (ref($moves->{'docmoves'}) eq 'HASH') {
     my $icon=&Apache::loncommon::icon($url);              %docmoves = %{$moves->{'docmoves'}};
     my $isfolder=0;          }
     my $ispage=0;          if (ref($moves->{'mapmoves'}) eq 'HASH') {
     my $folderarg;              %mapmoves = %{$moves->{'mapmoves'}};
     my $pagearg;          }
     my $pagefile;      }
     if ($uploaded) {      foreach my $key (keys(%copies),keys(%docmoves)) {
  if ($extension eq 'sequence') {          my @allcopies;
     $icon=$iconpath.'/folder_closed.gif';          if (exists($copies{$key})) {
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;              if (ref($copies{$key}) eq 'HASH') {
     $url='/adm/coursedocs?';                  my %added;
     $folderarg=$1;                  foreach my $innerkey (keys(%{$copies{$key}})) {
     $isfolder=1;                      if (($innerkey ne '') && (!$added{$innerkey})) {
         } elsif ($extension eq 'page') {                          push(@allcopies,$innerkey);
             $icon=$iconpath.'/page.gif';                          $added{$innerkey} = 1;
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;                      }
             $pagearg=$1;                  }
             $url='/adm/coursedocs?';                  undef(%added);
             $ispage=1;              }
  } else {          }
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);          if ($key eq $oldurl) {
  }              if ((exists($docmoves{$key}))) {
     }                  unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
                          push(@allcopies,$oldurl);
     my $orig_url = $url;                  }
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});              }
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {          }
  my $symb=&Apache::lonnet::symbclean(          if (@allcopies > 0) {
           &Apache::lonnet::declutter('uploaded/'.              foreach my $item (@allcopies) {
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.                  my ($relpath,$oldsubdir,$fname) = 
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
            '.sequence').                  if ($fname ne '') {
            '___'.$residx.'___'.                      my $content = &Apache::lonnet::getfile($item);
    &Apache::lonnet::declutter($url));                      unless ($content eq '-1') {
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);                          my $storefn;
  $url=&Apache::lonnet::clutter($url);                          if (($key eq $oldurl) && (exists($docmoves{$key}))) {
  if ($url=~/^\/*uploaded\//) {                              $storefn = $docmoves{$key};
     $url=~/\.(\w+)$/;                          } else {
     my $embstyle=&Apache::loncommon::fileembstyle($1);                              $storefn = $relpath;
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
  $url='/adm/wrapper'.$url;                              if ($prefixchg && $before{'doc'} && $after{'doc'}) {
     } elsif ($embstyle eq 'ssi') {                                  $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
  #do nothing with these                              }
     } elsif ($url!~/\.(sequence|page)$/) {                              if ($newsubdir{$key}) {
  $url='/adm/coursedocs/showdoc'.$url;                                  $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
     }                              }
  } elsif ($url=~m|^/ext/|) {                          }
     $url='/adm/wrapper'.$url;                          &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
     $external = 1;                          my $copyurl = 
  }                              &Apache::lonclonecourse::writefile($env{'request.course.id'},
         if (&Apache::lonnet::symbverify($symb,$url)) {                                                                 $storefn.$fname,$content);
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                          if ($copyurl eq '/adm/notfound.html') {
         } else {                              if (exists($docmoves{$oldurl})) {
             $url='';                                  return &mt('Paste failed: an error occurred copying the file.');
         }                              } elsif (ref($errors) eq 'HASH') {
  if ($container eq 'page') {                                  $errors->{$item} = 1;
     my $symb=$env{'form.pagesymb'};                              }
                                   }
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);                      }
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                  }
  }              }
     }          }
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');      }
     if ($isfolder || $extension eq 'sequence') {      foreach my $key (keys(%mapmoves)) {
  my $foldername=&escape($foldertitle);          my $storefn=$key;
  my $folderpath=$env{'form.folderpath'};          $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
  if ($folderpath) { $folderpath.='&' };          if ($prefixchg && $before{'map'} && $after{'map'}) {
 # Append randompick number, hidden, and encrypted with ":" to foldername,              $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
 # so it gets transferred between levels          }
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,          if ($newsubdir{$key}) {
                                               'parameter_randompick'))[0]              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
                                                .':'.((&LONCAPA::map::getparameter($orderidx,          }
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)          my $mapcontent = &Apache::lonnet::getfile($key);
                                                .':'.((&LONCAPA::map::getparameter($orderidx,          if ($mapcontent eq '-1') {
                                               'parameter_encrypturl'))[0]=~/^yes$/i)              if (ref($errors) eq 'HASH') {
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                  $errors->{$key} = 1;
                                               'parameter_randomorder'))[0]=~/^yes$/i);              }
  $url.='folderpath='.&escape($folderpath).$cpinfo;          } else {
  $parameterset='<label>'.&mt('Randomly Pick: ').              my $newmap =
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
     (&LONCAPA::map::getparameter($orderidx,                                                     $mapcontent);
                                               'parameter_randompick'))[0].              if ($newmap eq '/adm/notfound.html') {
                                               '" />'.                  if (ref($errors) eq 'HASH') {
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';                      $errors->{$key} = 1;
     my $ro_set=                  }
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');              }
  $rand_order_text ='          }
 <span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" onClick="this.form.changeparms.value=\'randomorder\';this.form.submit()" '.$ro_set.' /> '.&mt('Random Order').' </label></span>';        }
     }      my %updates;
     if ($ispage) {      if ($is_map) {
         my $pagename=&escape($pagetitle);          if (ref($updated) eq 'HASH') {
         my $pagepath;              foreach my $type (keys(%{$updated})) {
         my $folderpath=$env{'form.folderpath'};                  if (ref($updated->{$type}) eq 'HASH') {
         if ($folderpath) { $pagepath = $folderpath.'&' };                      foreach my $key (keys(%{$updated->{$type}})) {
         $pagepath.=$pagearg.'&'.$pagename;                          $updates{$key} = 1;
  my $symb=$env{'form.pagesymb'};                      }
  if (!$symb) {                  }
     my $path='uploaded/'.              }
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.          }
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';          foreach my $key (keys(%updates)) {
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',              my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
        $residx,              if (ref($rewrites{$key}) eq 'HASH') {
        $path.$pagearg.'.page');                  %torewrite = %{$rewrites{$key}};
  }              }
  $url.='pagepath='.&escape($pagepath).              if (ref($retitles{$key}) eq 'HASH') {
     '&amp;pagesymb='.&escape($symb).$cpinfo;                  %toretitle = %{$retitles{$key}};
     }              }
     if ($external) {              if (ref($removefrommap{$key}) eq 'HASH') {
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';                  %toremove = %{$removefrommap{$key}};
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';              }
     } else {              if (ref($removeparam{$key}) eq 'HASH') {
  undef($external);                  %remparam = %{$removeparam{$key}};
     }              }
     $line.='              if (ref($zombies{$key}) eq 'HASH') {
   <td class="LC_docs_entry_icon">                  %zombie = %{$zombies{$key}};
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'              }
   </td>              if (ref($dbcopies{$key}) eq 'HASH') {
   <td class="LC_docs_entry_title">                  foreach my $idx (keys(%{$dbcopies{$key}})) {
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."                      if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
   </td>";                          my ($newurl,$result,$errtext) =
     if (($allowed) && ($folder!~/^supplemental/)) {                              &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
   my %lt=&Apache::lonlocal::texthash(                          if ($result eq 'ok') {
        'hd' => 'Hidden',                              $newdb{$idx} = $newurl;
        'ec' => 'URL hidden');                          } elsif (ref($errors) eq 'HASH') {
  my $enctext=                              $errors->{$key} = 1;
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');                          }
  my $hidtext=                          push(@msgs,$errtext);
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');                      }
  $line.=(<<ENDPARMS);                  }
   <td class="LC_docs_entry_parameter">              }
     $form_start              if (ref($params{$key}) eq 'HASH') {
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>                  %currparam = %{$params{$key}};
     $form_end              }
   </td>              my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
   <td class="LC_docs_entry_parameter">              if ($fatal) {
     $form_start                  return ($errtext);
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>              }
     $form_end              for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
   </td>                  if (defined($LONCAPA::map::zombies[$i])) {
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>                      if ($zombie{$i} eq $src) {
 ENDPARMS                          undef($LONCAPA::map::zombies[$i]);
     }                      }
     $line.="</tr>";                  }
     return $line;              }
 }              for (my $i=0; $i<@LONCAPA::map::order; $i++) {
                   my $idx = $LONCAPA::map::order[$i];
 =pod                  if (defined($LONCAPA::map::resources[$idx])) {
                       my $changed;
 =item tiehash()                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
                       if ((exists($toremove{$idx})) && 
 tie the hash                          ($toremove{$idx} eq &LONCAPA::map::qtescape($src))) {
                           splice(@LONCAPA::map::order,$i,1);
 =cut                          if (ref($currparam{$idx}) eq 'ARRAY') {
                               foreach my $name (@{$currparam{$idx}}) {
 sub tiehash {                                  &LONCAPA::map::delparameter($idx,'parameter_'.$name);
     my ($mode)=@_;                              }
     $hashtied=0;                          }
     if ($env{'request.course.fn'}) {                          next;
  if ($mode eq 'write') {                      }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                      my $origsrc = $src;
     &GDBM_WRCREAT(),0640)) {                      if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
                 $hashtied=2;                          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;
  } else {                          }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                      }
     &GDBM_READER(),0640)) {                      if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
                 $hashtied=1;                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
     }                          if ($origsrc =~ m{^/uploaded/}) {
  }                              if ($prefixchg && $before{'map'} && $after{'map'}) {
     }                                      if ($src =~ /\.(page|sequence)$/) {
 }                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
                                   } else {
 sub untiehash {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
     if ($hashtied) { untie %hash; }                                  }
     $hashtied=0;                              }
     return OK;                              if ($origsrc =~ /\.(page|sequence)$/) {
 }                                  if ($newsubdir{$origsrc}) {
                                       $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
                                   }
                               } elsif ($newsubdir{$key}) {
                                   $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
 sub checkonthis {                              }
     my ($r,$url,$level,$title)=@_;                          }
     $url=&unescape($url);                          $changed = 1;
     $alreadyseen{$url}=1;                      } elsif ($newdb{$idx} ne '') {
     $r->rflush();                          $src = $newdb{$idx};
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {                          $changed = 1;
        $r->print("\n<br />");                      }
        if ($level==0) {                      if ($changed) {
            $r->print("<br />");                          $LONCAPA::map::resources[$idx] = join(':',($title,&LONCAPA::map::qtunescape($src),$ext,$type));
        }                      }
        for (my $i=0;$i<=$level*5;$i++) {                  }
            $r->print('&nbsp;');              }
        }              foreach my $idx (keys(%remparam)) {
        $r->print('<a href="'.$url.'" target="cat">'.                  if (ref($remparam{$idx}) eq 'ARRAY') {
  ($title?$title:$url).'</a> ');                      foreach my $name (@{$remparam{$idx}}) {   
        if ($url=~/^\/res\//) {                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
   my $result=&Apache::lonnet::repcopy(                      }
                               &Apache::lonnet::filelocation('',$url));                  }
           if ($result eq 'ok') {              }
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');              if (values(%lockerrors) > 0) {
              $r->rflush();                  $lockmsg = join('<br />',values(%lockerrors));
              &Apache::lonnet::countacc($url);              }
              $url=~/\.(\w+)$/;              my $storefn;
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {              if ($key eq $oldurl) {
  $r->print('<br />');                  $storefn = $url;
                  $r->rflush();                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                  for (my $i=0;$i<=$level*5;$i++) {              } else {
                      $r->print('&nbsp;');                  $storefn = $key;
                  }                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                  $r->print('- '.&mt('Rendering:').' ');                  if ($prefixchg && $before{'map'} && $after{'map'}) {
  my ($errorcount,$warningcount)=split(/:/,                      $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
        &Apache::lonnet::ssi_body($url,                  }
        ('grade_target'=>'web',                  if ($newsubdir{$key}) {
  'return_only_error_and_warning_counts' => 1)));                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
                  if (($errorcount) ||                  }
                      ($warningcount)) {              }
      if ($errorcount) {              my $report;
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.              if ($folder !~ /^supplemental/) {
                           &mt('[quant,_1,error]',$errorcount).'</span>');                  $report = 1;
                      }              }
      if ($warningcount) {              (my $outtext,$errtext) =
                         $r->print('<span class="LC_warning">'.                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
                           &mt('[quant,_1,warning]',$warningcount).'</span>');              if ($errtext) {
                      }                  if ($caller eq 'paste') {
                  } else {                      return (&mt('Paste failed: an error occurred saving the folder or page.'));
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');                  }
                  }              }
                  $r->rflush();          }
              }      }
      my $dependencies=      return ('ok',\@msgs,$lockmsg);
                 &Apache::lonnet::metadata($url,'dependencies');  }
              foreach my $dep (split(/\,/,$dependencies)) {  
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {  sub copy_dependencies {
                     &checkonthis($r,$dep,$level+1);      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
                  }      my $content;
              }      if (ref($contentref)) {
           } elsif ($result eq 'unavailable') {          $content = $$contentref;
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');      } else {
           } elsif ($result eq 'not_found') {          $content = &Apache::lonnet::getfile($item);
       unless ($url=~/\$/) {      }
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');      unless ($content eq '-1') {
       } else {          my $mm = new File::MMagic;
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');          my $mimetype = $mm->checktype_contents($content);
       }          if ($mimetype eq 'text/html') {
           } else {              my (%allfiles,%codebase,$state);
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');              my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
           }              if ($res eq 'ok') {
        }                  my ($numexisting,$numpathchanges,$existing);
     }                  (undef,$numexisting,$numpathchanges,$existing) =
 }                      &Apache::loncommon::ask_for_embedded_content(
                           '/adm/coursedocs',$state,\%allfiles,\%codebase,
                           {'error_on_invalid_names'   => 1,
                            'ignore_remote_references' => 1,
 =pod                           'docs_url'                 => $item,
                            'context'                  => 'paste'});
 =item list_symbs()                  if ($numexisting > 0) {
                       if (ref($existing) eq 'HASH') {
 List Symbs                          foreach my $dep (keys(%{$existing})) {
                               my $depfile = $dep;
 =cut                              unless ($depfile =~ m{^\Q$relpath\E}) {
                                   $depfile = $relpath.$dep;
 sub list_symbs {                              }
     my ($r) = @_;                              my $depcontent = &Apache::lonnet::getfile($depfile);
                               unless ($depcontent eq '-1') {
     my $type = &Apache::loncommon::course_type();                                  my $storedep = $dep;
     $r->print(&Apache::loncommon::start_page('Symb List'));                                  $storedep =~ s{^\Q$relpath\E}{};
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));                                  my $dep_url =
     my $navmap = Apache::lonnavmaps::navmap->new();                                      &Apache::lonclonecourse::writefile(
     if (!defined($navmap)) {                                          $env{'request.course.id'},
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.                                          $storefn.$storedep,$depcontent);
                   '<div class="LC_error">'.                                  if ($dep_url eq '/adm/notfound.html') {
                   &mt('Unable to retrieve information about course contents').                                      if (ref($errors) eq 'HASH') {
                   '</div>');                                          $errors->{$depfile} = 1;
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                                      }
     } else {                                  } else {
         $r->print("<pre>\n");                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
         foreach my $res ($navmap->retrieveResources()) {                                  }
     $r->print($res->compTitle()."\t".$res->symb()."\n");                              }
         }                          }
         $r->print("\n</pre>\n");                      }
     }                  }
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');              }
 }          }
       }
       return;
 sub verifycontent {  }
     my ($r) = @_;  
     my $type = &Apache::loncommon::course_type();  my %parameter_type = ( 'randompick'     => 'int_pos',
    my $loaderror=&Apache::lonnet::overloaderror($r);         'hiddenresource' => 'string_yesno',
    if ($loaderror) { return $loaderror; }         'encrypturl'     => 'string_yesno',
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));         'randomorder'    => 'string_yesno',);
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));  my $valid_parameters_re = join('|',keys(%parameter_type));
    $hashtied=0;  # set parameters
    undef %alreadyseen;  sub update_parameter {
    %alreadyseen=();      if ($env{'form.changeparms'} eq 'all') {
    &tiehash();          my (@allidx,@allmapidx,%allchecked,%currchecked);
    foreach my $key (keys(%hash)) {          %allchecked = (
        if ($hash{$key}=~/\.(page|sequence)$/) {                           'hiddenresource' => {},
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {                           'encrypturl'     => {},
        $r->print('<hr /><span class="LC_error">'.                           'randompick'     => {},
  &mt('The following sequence or page is included more than once in your '.$type.': ').                           'randomorder'    => {},
  &unescape($hash{$key}).'</span><br />'.                        );
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));          foreach my $which (keys(%allchecked)) {
    }              $env{'form.all'.$which} =~ s/,$//;   
        }              if ($which eq 'randompick') {
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {                  foreach my $item (split(/,/,$env{'form.all'.$which})) {
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});                      my ($res,$value) = split(/:/,$item);
        }                      if ($value =~ /^\d+$/) {
    }                          $allchecked{$which}{$res} = $value;
    &untiehash();                      }
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.                  }
      &mt('Return to DOCS').'</a>');              } else {
 }                  if ($env{'form.all'.$which}) {
                       map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.all'.$which});
                   }
 sub devalidateversioncache {              }
     my $src=shift;          }
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.          my $haschanges = 0;
   &Apache::lonnet::clutter($src));          foreach my $res (@LONCAPA::map::order) {
 }              my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
               $name=&LONCAPA::map::qtescape($name);
 sub checkversions {              $url=&LONCAPA::map::qtescape($url);
     my ($r) = @_;              next unless ($name && $url);
     my $type = &Apache::loncommon::course_type();              my $is_map;
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));              if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));                  $is_map = 1;
     my $header='';              }
     my $startsel='';              foreach my $which (keys(%allchecked)) {
     my $monthsel='';                  if (($which eq 'randompick' || $which eq 'randomorder')) {
     my $weeksel='';                      next if (!$is_map);
     my $daysel='';                  } 
     my $allsel='';                  my $oldvalue = 0;
     my %changes=();                  my $newvalue = 0;
     my $starttime=0;                  if ($allchecked{$which}{$res}) {
     my $haschanged=0;                      $newvalue = $allchecked{$which}{$res};
     my %setversions=&Apache::lonnet::dump('resourceversions',                  }
   $env{'course.'.$env{'request.course.id'}.'.domain'},                  my $current = (&LONCAPA::map::getparameter($res,'parameter_'.$which))[0];
   $env{'course.'.$env{'request.course.id'}.'.num'});                  if ($which eq 'randompick') {
                       if ($current =~ /^(\d+)$/) {
     $hashtied=0;                          $oldvalue = $1;
     &tiehash();                      }
     my %newsetversions=();                  } else {
     if ($env{'form.setmostrecent'}) {                      if ($current =~ /^yes$/i) {
  $haschanged=1;                          $oldvalue = 1;
  foreach my $key (keys(%hash)) {                      }
     if ($key=~/^ids\_(\/res\/.+)$/) {                  }
  $newsetversions{$1}='mostrecent';                  if ($oldvalue ne $newvalue) {
                 &devalidateversioncache($1);                      $haschanges = 1;
     }                      if ($newvalue) {
  }                          my $storeval = 'yes';
     } elsif ($env{'form.setcurrent'}) {                          if ($which eq 'randompick') {
  $haschanged=1;                              $storeval = $newvalue;
  foreach my $key (keys(%hash)) {                          }
     if ($key=~/^ids\_(\/res\/.+)$/) {                          &LONCAPA::map::storeparameter($res,'parameter_'.$which,
  my $getvers=&Apache::lonnet::getversion($1);                                                        $storeval,
  if ($getvers>0) {                                                        $parameter_type{$which});
     $newsetversions{$1}=$getvers;                          &remember_parms($res,$which,'set',$storeval);
     &devalidateversioncache($1);                      } elsif ($oldvalue) {
  }                          &LONCAPA::map::delparameter($res,'parameter_'.$which);
     }                          &remember_parms($res,$which,'del');
  }                      }
     } elsif ($env{'form.setversions'}) {                  }
  $haschanged=1;              }
  foreach my $key (keys(%env)) {          }
     if ($key=~/^form\.set_version_(.+)$/) {          return $haschanges;
  my $src=$1;      } else {
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {          return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     $newsetversions{$src}=$env{$key};  
     &devalidateversioncache($src);          my $which = $env{'form.changeparms'};
  }          my $idx = $env{'form.setparms'};
     }          if ($env{'form.'.$which.'_'.$idx}) {
  }      my $value = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
     }                                           : 'yes';
     if ($haschanged) {      &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,            $parameter_type{$which});
   $env{'course.'.$env{'request.course.id'}.'.domain'},      &remember_parms($idx,$which,'set',$value);
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {          } else {
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');      &LONCAPA::map::delparameter($idx,'parameter_'.$which);
  } else {  
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');      &remember_parms($idx,$which,'del');
  }          }
  &mark_hash_old();          return 1;
     }      }
     &changewarning($r,'');  }
     if ($env{'form.timerange'} eq 'all') {  
 # show all documents  
  $header=&mt('All Documents in '.$type);  sub handle_edit_cmd {
  $allsel=1;      my ($coursenum,$coursedom) =@_;
  foreach my $key (keys(%hash)) {      if ($env{'form.cmd'} eq '') {
     if ($key=~/^ids\_(\/res\/.+)$/) {          return 0;
  my $src=$1;      }
  $changes{$src}=1;      my ($cmd,$idx)=split('_',$env{'form.cmd'});
     }  
  }      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     } else {      my ($title, $url, @rrest) = split(':', $ratstr);
 # show documents which changed  
  %changes=&Apache::lonnet::dump      if ($cmd eq 'remove') {
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
                      $env{'course.'.$env{'request.course.id'}.'.num'});      ($url!~/$LONCAPA::assess_page_seq_re/)) {
  my $firstkey=(keys(%changes))[0];      &Apache::lonnet::removeuploadedurl($url);
  unless ($firstkey=~/^error\:/) {   } else {
     unless ($env{'form.timerange'}) {      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  $env{'form.timerange'}=604800;   }
     }   splice(@LONCAPA::map::order, $idx, 1);
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '  
  .&mt('seconds');      } elsif ($cmd eq 'cut') {
     if ($env{'form.timerange'}==-1) {   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  $seltext='since start of course';   splice(@LONCAPA::map::order, $idx, 1);
  $startsel='selected';  
  $env{'form.timerange'}=time;      } elsif ($cmd eq 'up'
     }       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     $starttime=time-$env{'form.timerange'};   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
     if ($env{'form.timerange'}==2592000) {  
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      } elsif ($cmd eq 'down'
  $monthsel='selected';       && defined($LONCAPA::map::order[$idx+1])) {
     } elsif ($env{'form.timerange'}==604800) {   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  
  $weeksel='selected';      } elsif ($cmd eq 'rename') {
     } elsif ($env{'form.timerange'}==86400) {   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   if ($comment=~/\S/) {
  $daysel='selected';      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
     }   $comment.':'.join(':', $url, @rrest);
     $header=&mt('Content changed').' '.$seltext;   }
  } else {  # Devalidate title cache
     $header=&mt('No content modifications yet.');   my $renamed_url=&LONCAPA::map::qtescape($url);
  }   &Apache::lonnet::devalidate_title_cache($renamed_url);
     }  
     %setversions=&Apache::lonnet::dump('resourceversions',      } else {
   $env{'course.'.$env{'request.course.id'}.'.domain'},   return 0;
   $env{'course.'.$env{'request.course.id'}.'.num'});      }
     my %lt=&Apache::lonlocal::texthash      return 1;
       ('st' => 'Version changes since start of '.$type,  }
        'lm' => 'Version changes since last Month',  
        'lw' => 'Version changes since last Week',  sub editor {
        'sy' => 'Version changes since Yesterday',      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
                'al' => 'All Resources (possibly large output)',          $supplementalflag,$orderhash,$iconpath,$pathitem)=@_;
        'sd' => 'Display',      my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
        'fi' => 'File',      if ($allowed) {
        'md' => 'Modification Date',          (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
                'mr' => 'Most recently published Version',           $is_random_order,$container) =
        've' => 'Version used in '.$type,              &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
                'vu' => 'Set Version to be used in '.$type,          $r->print($breadcrumbtrail);
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      } elsif ($env{'form.folderpath'} =~ /\:1$/) {
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',          $container = 'page'; 
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      } else {
        'di' => 'Differences');          $container = 'sequence';
     $r->print(<<ENDHEADERS);      }
 <form action="/adm/coursedocs" method="post">  
 <input type="hidden" name="versions" value="1" />      my $jumpto;
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />  
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />      unless ($supplementalflag) {
 <select name="timerange">          $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
 <option value='all' $allsel>$lt{'al'}</option>      }
 <option value="-1" $startsel>$lt{'st'}</option>  
 <option value="2592000" $monthsel>$lt{'lm'}</option>      unless ($allowed) {
 <option value="604800" $weeksel>$lt{'lw'}</option>          $randompick = -1;
 <option value="86400" $daysel>$lt{'sy'}</option>      }
 </select>  
 <input type="submit" name="display" value="$lt{'sd'}" />      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 <h3>$header</h3>      $folder.'.'.$container);
 <input type="submit" name="setversions" value="$lt{'sv'}" />      return $errtext if ($fatal);
 <table border="0">  
 ENDHEADERS      if ($#LONCAPA::map::order<1) {
     foreach my $key (sort(keys(%changes))) {   my $idx=&LONCAPA::map::getresidx();
  if ($changes{$key}>$starttime) {   if ($idx<=0) { $idx=1; }
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);          $LONCAPA::map::order[0]=$idx;
     my $currentversion=&Apache::lonnet::getversion($key);          $LONCAPA::map::resources[$idx]='';
     if ($currentversion<0) {      }
  $currentversion=&mt('Could not be determined.');  
     }  # ------------------------------------------------------------ Process commands
     my $linkurl=&Apache::lonnet::clutter($key);  
     $r->print(  # ---------------- if they are for this folder and user allowed to make changes
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.      if (($allowed) && ($env{'form.folder'} eq $folder)) {
       &Apache::lonnet::gettitle($linkurl).  # set parameters and change order
                       '</b></font></td></tr>'.   &snapshotbefore();
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.  
                       '<td colspan="4">'.   if (&update_parameter()) {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
       '</a></td></tr>'.      return $errtext if ($fatal);
                       '<tr><td></td>'.   }
                       '<td title="'.$lt{'md'}.'">'.  
       &Apache::lonlocal::locallocaltime(   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
                            &Apache::lonnet::metadata($root.'.'.$extension,  # change order
                                                      'lastrevisiondate')      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
                                                         ).      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
                       '</td>'.  
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                       '<font size="+1">'.$currentversion.'</font>'.      return $errtext if ($fatal);
                       '</span></td>'.   }
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.  
                       '<font size="+1">');   if ($env{'form.pastemarked'}) {
 # Used in course              my %paste_errors;
     my $usedversion=$hash{'version_'.$linkurl};              my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
     if (($usedversion) && ($usedversion ne 'mostrecent')) {                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
  $r->print($usedversion);                                        \%paste_errors);
     } else {              if (ref($pastemsgarray) eq 'ARRAY') {
  $r->print($currentversion);                  if (@{$pastemsgarray} > 0) {
     }                      $r->print('<p class="LC_info">'.
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.                                join('<br />',@{$pastemsgarray}).
                       '<span class="LC_nobreak">Use: ');                                '</p>');
 # Set version                  }
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},              }
       'set_version_'.$linkurl,              if ($lockerror) {
       ('select_form_order' =>                  $r->print('<p class="LC_error">'.
        ['',1..$currentversion,'mostrecent'],                            $lockerror.
        '' => '',                            '</p>');
        'mostrecent' => 'most recent',              }
        map {$_,$_} (1..$currentversion))));              if ($save_error ne '') {
     $r->print('</span></td></tr><tr><td></td>');                  return $save_error; 
     my $lastold=1;              }
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {              if ($paste_res) {
  my $url=$root.'.'.$prevvers.'.'.$extension;                  my %errortext = &Apache::lonlocal::texthash (
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                                      fail      => 'Storage of folder contents failed',
     $starttime) {                                      failread  => 'Reading folder contents failed',
     $lastold=$prevvers;                                      failstore => 'Storage of folder contents failed',
  }                                  );
     }                  if ($errortext{$paste_res}) {
             #                      $r->print('<p class="LC_error">'.$errortext{$paste_res}.'</p>');
             # Code to figure out how many version entries should go in                  }
             # each of the four columns              }
             my $entries_per_col = 0;              if (keys(%paste_errors) > 0) {
             my $num_entries = ($currentversion-$lastold);                  $r->print('<p class="LC_warning">'."\n".
             if ($num_entries % 4 == 0) {                            &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".
                 $entries_per_col = $num_entries/4;                            '<ul>'."\n");
             } else {                  foreach my $key (sort(keys(%paste_errors))) {
                 $entries_per_col = $num_entries/4 + 1;                      $r->print('<li>'.$key.'</li>'."\n");
             }                  }
             my $entries_count = 0;                  $r->print('</ul></p>'."\n");
             $r->print('<td valign="top"><font size="-2">');              }
             my $cols_output = 1;   } elsif ($env{'form.clearmarked'}) {
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {              my $output = &do_buffer_empty();
  my $url=$root.'.'.$prevvers.'.'.$extension;              if ($output) {
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).                  $r->print('<p class="LC_info">'.$output.'</p>');
   '">'.&mt('Version').' '.$prevvers.'</a> ('.              }
   &Apache::lonlocal::locallocaltime(          }
                                 &Apache::lonnet::metadata($url,  
                                                           'lastrevisiondate')   $r->print($upload_output);
                                                             ).  
   ')');  # Rename, cut, copy or remove a single resource
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {   if (&handle_edit_cmd()) {
                     $r->print(' <a href="/adm/diff?filename='.              my $contentchg;
       &Apache::lonnet::clutter($root.'.'.$extension).              if ($env{'form.cmd'} =~ m{^(del|cut)_}) {
       '&versionone='.$prevvers.                  $contentchg = 1;
       '">'.&mt('Diffs').'</a>');              }
  }      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
  $r->print('</span><br />');      return $errtext if ($fatal);
                 if (++$entries_count % $entries_per_col == 0) {   }
                     $r->print('</font></td>');  
                     if ($cols_output != 4) {  # Cut, copy and/or remove multiple resources
                         $r->print('<td valign="top"><font size="-2">');          if ($env{'form.multichange'}) {
                         $cols_output++;              my %allchecked = (
                     }                                 cut     => {},
                 }                                 remove  => {},
     }                               );
             while($cols_output++ < 4) {              my $needsupdate;
                 $r->print('</font></td><td><font>')              foreach my $which (keys(%allchecked)) {
             }                  $env{'form.multi'.$which} =~ s/,$//;
     $r->print('</font></td></tr>'."\n");                  if ($env{'form.multi'.$which}) {
  }                      map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.multi'.$which});
     }                      if (ref($allchecked{$which}) eq 'HASH') {
     $r->print('</table></form>');                          $needsupdate += scalar(keys(%{$allchecked{$which}}));
     $r->print('<h1>'.&mt('Done').'.</h1>');                      }
                   }
     &untiehash();              }
 }              if ($needsupdate) {
                   my $haschanges = 0;
 sub mark_hash_old {                  my %curr_groups = &Apache::longroup::coursegroups();
     my $retie_hash=0;                  my $total = scalar(@LONCAPA::map::order) - 1; 
     if ($hashtied) {                  for (my $i=$total; $i>=0; $i--) {
  $retie_hash=1;                      my $res = $LONCAPA::map::order[$i];
  &untiehash();                      my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     }                      $name=&LONCAPA::map::qtescape($name);
     &tiehash('write');                      $url=&LONCAPA::map::qtescape($url);
     $hash{'old'}=1;                      next unless ($name && $url);
     &untiehash();                      my %denied =
     if ($retie_hash) { &tiehash(); }                          &action_restrictions($coursenum,$coursedom,$url,
 }                                               $env{'form.folderpath'},\%curr_groups);
                       foreach my $which (keys(%allchecked)) {
 sub is_hash_old {                          next if ($denied{$which});
     my $untie_hash=0;                          next unless ($allchecked{$which}{$res});
     if (!$hashtied) {                          if ($which eq 'remove') {
  $untie_hash=1;                              if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  &tiehash();                                  ($url!~/$LONCAPA::assess_page_seq_re/)) {
     }                                  &Apache::lonnet::removeuploadedurl($url);
     my $return=$hash{'old'};                              } else {
     if ($untie_hash) { &untiehash(); }                                  &LONCAPA::map::makezombie($res);
     return $return;                              }
 }                              splice(@LONCAPA::map::order,$i,1);
                               $haschanges ++;
 sub changewarning {                          } elsif ($which eq 'cut') {
     my ($r,$postexec,$message,$url)=@_;                              &LONCAPA::map::makezombie($res);
     if (!&is_hash_old()) { return; }                              splice(@LONCAPA::map::order,$i,1);
     my $pathvar='folderpath';                              $haschanges ++;
     my $path=&escape($env{'form.folderpath'});                          }
     if (!defined($url)) {                      }
  if (defined($env{'form.pagepath'})) {                  }
     $pathvar='pagepath';                  if ($haschanges) {
     $path=&escape($env{'form.pagepath'});                      ($errtext,$fatal) = 
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                          &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
  }                      return $errtext if ($fatal);
  $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.';  # Group import/search
     }   if ($env{'form.importdetail'}) {
     $r->print("\n\n".      my @imports;
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.   if (defined($item)) {
 '<input type="hidden" name="orgurl" value="'.$url.      my ($name,$url,$residx)=
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.   map { &unescape($_); } split(/\=/,$item);
 &mt($message,' <input type="hidden" name="'.                      if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
     $env{'request.role'}.'" value="1" /><input type="button" value="'.                          my ($suffix,$errortxt,$locknotfreed) =
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').                              &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
 $help{'Caching'}.'</span></h3></form>'."\n\n");                          if ($locknotfreed) {
 }                              $r->print($locknotfreed);
                           }
                           if ($suffix) {
 sub init_breadcrumbs {                              $url =~ s/_new\./_$suffix./; 
     my ($form,$text)=@_;                          } else {
     &Apache::lonhtmlcommon::clear_breadcrumbs();                              return $errortxt;
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",                          }
     text=>"Edit ".&Apache::loncommon::course_type(),                      } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
     faq=>273,                          my $type = $1;
     bug=>'Instructor Interface',                          my ($suffix,$errortxt,$locknotfreed) =
                                             help => 'Docs_Adding_Course_Doc'});                              &new_timebased_suffix($coursedom,$coursenum,$type);
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',                          if ($locknotfreed) {
     text=>$text,                              $r->print($locknotfreed);
     faq=>273,                          }
     bug=>'Instructor Interface'});                          if ($suffix) {
 }                              $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
                           } else {
                               return $errortxt;
                           }
                       } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
 sub handler {                          if ($supplementalflag) {
     my $r = shift;                              next unless ($1 eq 'supplemental');
     &Apache::loncommon::content_type($r,'text/html');                              if ($folder eq 'supplemental') {
     $r->send_http_header;                                  next unless ($2 eq 'default');
     return OK if $r->header_only;                              } else {
     my $type = &Apache::loncommon::course_type();                                  next unless ($folder eq 'supplemental_'.$2);
                               }
                           } else {
 # --------------------------------------------- Initialize help topics for this                              next unless ($1 eq 'docs');
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',                              if ($folder eq 'default') {
                'Adding_External_Resource','Navigate_Content',                                  next unless ($2 eq 'default');
                'Adding_Folders','Docs_Overview', 'Load_Map',                              } else {
                'Supplemental','Score_Upload_Form','Adding_Pages',                                  next unless ($folder eq 'default_'.$2);
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',                              }
                'Check_Resource_Versions','Verify_Content') {                          }
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);                      }
     }      push(@imports, [$name, $url, $residx]);
     # Composite help files   }
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(      }
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');              ($errtext,$fatal,my $fixuperrors) =
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(                  &group_import($coursenum, $coursedom, $folder,$container,
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');                                'londocs',@imports);
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(      return $errtext if ($fatal);
     'Option_Response_Simple');              if ($fixuperrors) {
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(                  $r->print($fixuperrors);
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');              }
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(   }
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');  # Loading a complete map
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');   if ($env{'form.loadmap'}) {
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');      if ($env{'form.importmap'}=~/\w/) {
    foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
 # does this user have privileges to modify docs      my ($title,$url,$ext,$type)=split(/\:/,$res);
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});      my $idx=&LONCAPA::map::getresidx($url);
   if ($allowed && $env{'form.verify'}) {      $LONCAPA::map::resources[$idx]=$res;
       &init_breadcrumbs('verify','Verify Content');      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
       &verifycontent($r);   }
   } elsif ($allowed && $env{'form.listsymbs'}) {   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
       &init_breadcrumbs('listsymbs','List Symbs');      $folder.'.'.$container,1);
       &list_symbs($r);   return $errtext if ($fatal);
   } elsif ($allowed && $env{'form.docslog'}) {      } else {
       &init_breadcrumbs('docslog','Show Log');   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
       &docs_change_log($r);  
   } elsif ($allowed && $env{'form.versions'}) {      }
       &init_breadcrumbs('versions','Check/Set Resource Versions');   }
       &checkversions($r);   &log_differences($plain);
   } elsif ($allowed && $env{'form.dumpcourse'}) {      }
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');  # ---------------------------------------------------------------- End commands
       &dumpcourse($r);  # ---------------------------------------------------------------- Print screen
   } elsif ($allowed && $env{'form.exportcourse'}) {      my $idx=0;
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');      my $shown=0;
       &exportcourse($r);      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
   } else {   $r->print('<div class="LC_Box">'.
 # is this a standard course?            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
     ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
     my $forcestandard = 0;    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
     my $forcesupplement;    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
     my $script='';    '</ol>');
     my $showdoc=0;          if ($randompick>=0) {
     my $containertag;              $r->print('<p class="LC_warning">'
     my $uploadtag;                   .&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'
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                       .' students see, resulting in spurious or missing credit'
     ['folderpath','pagepath',                       .' for completed problems, not limited to ones you'
      'pagesymb']);                       .' modify. Do not modify the contents of this folder if'
 # No folderpath, no pagepath, see if we have something stored                       .' it is in active student use.')
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {                   .'</p>'
         &Apache::loncommon::restore_course_settings('docs_folderpath',              );
                                               {'folderpath' => 'scalar'});          }
     }          if ($is_random_order) {
     if (!$env{'form.folderpath'}) {              $r->print('<p class="LC_warning">'
         &Apache::loncommon::restore_course_settings('docs_folderpath',                   .&mt('Caution: this folder is set to randomly order its'
                                               {'pagepath' => 'scalar'});                       .' contents. Adding or removing resources from this folder'
     }                       .' will change the order of resources shown.')
     if ($env{'form.pagepath'}) {                   .'</p>'
        $env{'form.folderpath'}='';              );
     }          }
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {          $r->print('</div>');
         $env{'form.folderpath'} = 'supplemental&'.      }
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.  
                                   $env{'form.folderpath'};      my ($to_show,$output,@allidx,@allmapidx,%filters,%lists,%curr_groups);
     }      %filters =  (
     &Apache::loncommon::store_course_settings('docs_folderpath',                    canremove      => [],
                                                 {'pagepath' => 'scalar',                    cancut         => [],
                                                  'folderpath' => 'scalar'});                    cancopy        => [],
     if ($env{'form.folderpath'}) {                    hiddenresource => [],
  my (@folderpath)=split('&',$env{'form.folderpath'});                    encrypturl     => [],
  $env{'form.foldername'}=&unescape(pop(@folderpath));                    randomorder    => [],
  $env{'form.folder'}=pop(@folderpath);                    randompick     => [],
     }                  );
     if ($env{'form.pagepath'}) {      %curr_groups = &Apache::longroup::coursegroups();
         my (@pagepath)=split('&',$env{'form.pagepath'});      &Apache::loncommon::start_data_table_count(); #setup a row counter 
         $env{'form.pagename'}=&unescape(pop(@pagepath));      foreach my $res (@LONCAPA::map::order) {
         $env{'form.folder'}=pop(@pagepath);          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
         $containertag = '<input type="hidden" name="pagepath" value="" />'.          $name=&LONCAPA::map::qtescape($name);
     '<input type="hidden" name="pagesymb" value="" />';          $url=&LONCAPA::map::qtescape($url);
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.          unless ($name) {  $name=(split(/\//,$url))[-1]; }
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';          unless ($name) { $idx++; next; }
     }          push(@allidx,$res);
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {          if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
        $showdoc='/'.$1;              push(@allmapidx,$res);
     }          }
     unless ($showdoc) { # got called from remote          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||                                $coursenum,$coursedom,$crstype,
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {                                $pathitem,$supplementalflag,$container,
            $forcestandard = 1;                                \%filters,\%curr_groups);
        }          $idx++;
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);          $shown++;
       }
        if ($allowed) {      &Apache::loncommon::end_data_table_count();
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);  
          $script=&Apache::lonratedt::editscript('simple');      my $need_save;
        }      if (($allowed) || ($supplementalflag && $folder eq 'supplemental')) {
     } else { # got called in sequence from course          my $toolslink;
        $allowed=0;          if ($allowed || &Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
     }              $toolslink = '<table><tr><td>'
                          .&Apache::loncommon::help_open_menu('Navigation Screen',
 # get course data                                                             'Navigation_Screen',undef,'RAT')
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};                         .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};                         .'<td align="left"><ul id="LC_toolbar">'
                          .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
 # get personal data                         .'id="LC_content_toolbar_edittoplevel" '
     my $uname=$env{'user.name'};                         .'class="LC_toolbarItem" '
     my $udom=$env{'user.domain'};                         .'title="'.&mt('Supplemental Content Editor').'">'
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));                         .'</a></li></ul></td></tr></table><br />';
           }
 # graphics settings          if ($shown) {
               if ($allowed) {
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");                  $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
                             .&Apache::loncommon::start_data_table(undef,'contentlist')
     if ($allowed) {                            .&Apache::loncommon::start_data_table_header_row()
  $script .= &editing_js($udom,$uname);                            .'<th colspan="2">'.&mt('Move').'</th>'
     }                            .'<th colspan="2">'.&mt('Actions').'</th>'
 # -------------------------------------------------------------------- Body tag                            .'<th>'.&mt('Document').'</th>';
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';                  if ($folder !~ /^supplemental/) {
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];                      $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,                  }
     {'force_register' => $showdoc,                  $to_show .= &Apache::loncommon::end_data_table_header_row();
                                      'bread_crumbs' => $brcrum}).                  if ($folder !~ /^supplemental/) {
       &Apache::loncommon::help_open_menu('','',273,'RAT'));                      $lists{'canhide'} = join(',',@allidx);
                        $lists{'canrandomlyorder'} = join(',',@allmapidx);
   my %allfiles = ();                      my @possfilters = ('canremove','cancut','cancopy','hiddenresource','encrypturl',
   my %codebase = ();                                         'randomorder','randompick');
   my ($upload_result,$upload_output);                      foreach my $item (@possfilters) {
   if ($allowed) {                          if (ref($filters{$item}) eq 'ARRAY') {
       if (($env{'form.uploaddoc.filename'}) &&                              if (@{$filters{$item}} > 0) {
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {                                  $lists{$item} = join(',',@{$filters{$item}});
 # Process file upload - phase one - upload and parse primary file.                                }
   undef($hadchanges);                          }
           $upload_result = &process_file_upload(\$upload_output,$coursenum,                      }
  $coursedom,\%allfiles,                      if (@allidx > 0) {
  \%codebase,$1);                          my $path;
   if ($hadchanges) {                          if ($env{'form.folderpath'}) {
       &mark_hash_old();                              $path = 
   }                                  &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
           if ($upload_result eq 'phasetwo') {                          }
               $r->print($upload_output);                          if (@allidx > 1) {
           }                              $to_show .= 
       } elsif ($env{'form.phasetwo'}) {                                  &Apache::loncommon::continue_data_table_row().
           my %newname = ();                                  '<td colspan="2">&nbsp;</td>'.
           my %origname = ();                                  '<td>'.
           my %attribs = ();                                  &multiple_check_form('actions',\%lists).
           my $updateflag = 0;                                  '</td>'.
           my $residx = $env{'form.newidx'};                                  '<td>&nbsp;</td>'.
           my $primary_url = &unescape($env{'form.primaryurl'});                                  '<td>&nbsp;</td>'.
 # Process file upload - phase two - gather secondary files.                                  '<td colspan="4">'.
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {                                  &multiple_check_form('settings',\%lists).
               if ($env{'form.embedded_item_'.$i.'.filename'}) {                                  '</td>'.
                   my $javacodebase;                                  &Apache::loncommon::end_data_table_row();
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);                               $need_save = 1;
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});                          }
                   if (exists($env{'form.embedded_codebase_'.$i})) {                      }
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});                    }
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;                  $to_show .= $output.' '
                   }                             .&Apache::loncommon::end_data_table()
                   my @attributes = ();                             .'<br style="line-height:2px;" />'
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {                             .&Apache::loncommon::end_scrollbox();
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});              } else {
                   } else {                  $to_show .= $toolslink
                       @attributes = ($env{'form.embedded_attrib_'.$i});                             .&Apache::loncommon::start_data_table('LC_tableOfContent')
                   }                             .$output.' '
                   foreach my $attr (@attributes) {                             .&Apache::loncommon::end_data_table();
                       push(@{$attribs{$i}},&unescape($attr));              }
                   }          } else {
                   if ($javacodebase) {              if (!$allowed) {
                       $codebase{$i} = $javacodebase;                  $to_show .= $toolslink;
                       $codebase{$i} =~ s#/$##;              }
                       $updateflag = 1;              $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
                   }                         .'<div class="LC_info" id="contentlist">'
               }                         .&mt('Currently no documents.')
               unless ($newname{$i} eq $origname{$i}) {                         .'</div>'
                   $updateflag = 1;                         .&Apache::loncommon::end_scrollbox();
               }          }
           }      } else {
 # Process file upload - phase three - modify primary file          if ($shown) {
           if ($updateflag) {              $to_show = '<div>'
               my ($content,$rtncode);                        .&Apache::loncommon::start_data_table('LC_tableOfContent')
               my $updateflag = 0;                        .$output
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);                        .&Apache::loncommon::end_data_table()
               if ($getstatus eq 'ok') {                        .'</div>';
                   foreach my $item (keys(%newname)) {          } else {
                       if ($newname{$item} ne $origname{$item}) {              $to_show = '<div class="LC_info" id="contentlist">'
                           my $attrib_regexp = '';                        .&mt('Currently no documents.')
                           if (@{$attribs{$item}} > 1) {                        .'</div>'
                               $attrib_regexp = join('|',@{$attribs{$item}});          }
                           } else {      }
                               $attrib_regexp = $attribs{$item}[0];      my $tid = 1;
                           }      if ($supplementalflag) {
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {          $tid = 2;
                           }      }
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;      if ($allowed) {
                       }          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
                       if (exists($codebase{$item})) {          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs                                         $jumpto,$readfile,$need_save,"$folder.$container"));
                       }          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
                   }      } else {
 # Save edited file.          $r->print($to_show);
                   my $saveresult;      }
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};      return;
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};  }
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);  
               } else {  sub multiple_check_form {
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);      my ($caller,$listsref) = @_;
               }      return unless (ref($listsref) eq 'HASH');
           }      my $output =
       }      '<form action="/adm/coursedocs" method="post" name="togglemult'.$caller.'">'.
   }      '<span class="LC_nobreak" style="font-size:x-small;font-weight:bold;">'.
       '<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>'.
   unless ($showdoc ||  $upload_result eq 'phasetwo') {      '<div id="multi'.$caller.'" style="display:none;margin:0;padding:0;border:0">'.
 # -----------------------------------------------------------------------------      '<form action="/adm/coursedocs" method="post" name="cumulative'.$caller.'">'."\n".
        my %lt=&Apache::lonlocal::texthash(      '<fieldset id="allfields'.$caller.'" style="display:none"><legend style="font-size:x-small;">'.&mt('check/uncheck all').'</legend>'."\n";
                 'uplm' => 'Upload a new main '.lc($type).' document',      if ($caller eq 'settings') {
                 'upls' => 'Upload a new supplemental '.lc($type).' document',          $output .= 
                 'impp' => 'Import a document',              '<table><tr>'.
                 'pubd' => 'Published Documents',              '<td class="LC_docs_entry_parameter">'.
  'copm' => 'All documents out of a published map into this folder',              '<span class="LC_nobreak"><label>'.
                 'upld' => 'Upload Document',              '<input type="checkbox" name="hiddenresourceall" id="hiddenresourceall" onclick="propagateState(this.form,'."'hiddenresource'".')" />'.&mt('Hidden').
                 'srch' => 'Search',              '</label></span></td>'.
                 'impo' => 'Import',              '<td class="LC_docs_entry_parameter">'.
  'book' => 'Import Bookmarks',              '<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="" />'.
                 'selm' => 'Select Map',              '</span></td>'.
                 'load' => 'Load Map',              '</tr>'."\n".
                 'reco' => 'Recover Deleted Resources',              '<tr>'.
                 'newf' => 'New Folder',              '<td class="LC_docs_entry_parameter">'.
                 'newp' => 'New Composite Page',              '<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').
                 'extr' => 'External Resource',              '</label></span>'.
                 'syll' => 'Syllabus',              '</td></tr></table>'."\n";
                 'navc' => 'Navigate Contents',      } else {
                 '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 LC_docs_remove">'.
                 'bull' => 'Bulletin Board',              '<label><input type="checkbox" name="removeall" id="removeall" onclick="propagateState(this.form,'."'remove'".')" />'.&mt('Remove').
                 'mypi' => 'My Personal Info',              '</label></span></td>'.
                 'grpo' => 'Group Files',              '<td class="LC_docs_entry_parameter">'.
                 'rost' => 'Course Roster',              '<span class="LC_nobreak LC_docs_cut">'.
  'abou' => 'About User',              '<label><input type="checkbox" name="cut" id="cutall" onclick="propagateState(this.form,'."'cut'".');" />'.&mt('Cut').
                 'imsf' => 'Import IMS package',              '</label></span></td>'."\n".
                 'file' =>  'File',              '<td class="LC_docs_entry_parameter">'.
                 'title' => 'Title',              '<span class="LC_nobreak LC_docs_copy">'.
                 'comment' => 'Comment',              '<label><input type="checkbox" name="copyall" id="copyall" onclick="propagateState(this.form,'."'copy'".')" />'.&mt('Copy').
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',              '</label></span></td>'.
  'nd' => 'New Document',              '</tr></table>'."\n";
  'pm' => 'Published Map',      }
  'sd' => 'Special Document',      $output .= 
  'mo' => 'More Options',          '</fieldset>'.
  'hao' => 'Hide all Options'          '<input type="hidden" name="allidx" value="'.$listsref->{'canhide'}.'" />';
   );      if ($caller eq 'settings') {
 # -----------------------------------------------------------------------------          $output .= 
  my $fileupload=(<<FIUP);          '<input type="hidden" name="allmapidx" value="'.$listsref->{'canrandomlyorder'}.'" />'."\n".
  $lt{'file'}:<br />          '<input type="hidden" name="currhiddenresource" value="'.$listsref->{'hiddenresource'}.'" />'."\n".
  <input type="file" name="uploaddoc" size="40" />          '<input type="hidden" name="currencrypturl" value="'.$listsref->{'encrypturl'}.'" />'."\n".
 FIUP          '<input type="hidden" name="currrandomorder" value="'.$listsref->{'randomorder'}.'" />'."\n".
           '<input type="hidden" name="currrandompick" value="'.$listsref->{'randompick'}.'" />'."\n";
  my $checkbox=(<<CHBO);      } elsif ($caller eq 'actions') {
  <!-- <label>$lt{'parse'}?          $output .=
  <input type="checkbox" name="parserflag" />          '<input type="hidden" name="allremoveidx" id="allremoveidx" value="'.$listsref->{'canremove'}.'" />'.
  </label> -->          '<input type="hidden" name="allcutidx" id="allcutidx" value="'.$listsref->{'cancut'}.'" />'.
  <label>          '<input type="hidden" name="allcopyidx" id="allcopyidx" value="'.$listsref->{'cancopy'}.'" />';
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}      }
  </label>      $output .= 
 CHBO          '</form>'.
           '</div>';
  my $fileuploadform=(<<FUFORM);      return $output;
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">  }
  $fileupload  
  <br />  sub process_file_upload {
  $lt{'title'}:<br />      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
  <input type="text" size="50" name="comment" />  # upload a file, if present
  $uploadtag      my ($parseaction,$showupload,$nextphase,$mimetype);
  <input type="hidden" name="cmd" value="upload_default" />      if ($env{'form.parserflag'}) {
  <br />          $parseaction = 'parse';
  <span class="LC_nobreak">      }
  $checkbox      my $folder=$env{'form.folder'};
  </span>      if ($folder eq '') {
  <br />          $folder='default';
  <br />      }
  <span class="LC_nobreak">      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  <input type="submit" value="$lt{'upld'}" />          my $errtext='';
  $help{'Uploading_From_Harddrive'}          my $fatal=0;
  </span>          my $container='sequence';
  </form>          if ($env{'form.folderpath'} =~ /:1$/) {
 FUFORM              $container='page';
           }
  my $simpleeditdefaultform=(<<SEDFFORM);          ($errtext,$fatal)=
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">              &mapread($coursenum,$coursedom,$folder.'.'.$container);
  $lt{'pubd'}<br />          if ($#LONCAPA::map::order<1) {
  $uploadtag              $LONCAPA::map::order[0]=1;
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />              $LONCAPA::map::resources[1]='';
  <br />          }
  <span class="LC_nobreak">          my $destination = 'docs/';
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />          if ($folder =~ /^supplemental/) {
  $help{'Importing_LON-CAPA_Resource'}              $destination = 'supplemental/';
  </span>          }
  <br />          if (($folder eq 'default') || ($folder eq 'supplemental')) {
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />              $destination .= 'default/';
  <hr />          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
  <p>              $destination .=  $2.'/';
  $lt{'copm'}<br />          }
  <input type="text" size="40" name="importmap" /><br />          if ($fatal) {
  <span class="LC_nobreak"><input type="button"              $$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>';
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"              return;
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />          }
  $help{'Load_Map'}</span>  # this is for a course, not a user, so set context to coursedoc.
  </p>          my $newidx=&LONCAPA::map::getresidx();
  </form>          $destination .= $newidx;
 SEDFFORM          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
    $parseaction,$allfiles,
  my $extresourcesform=(<<ERFORM);   $codebase,undef,undef,undef,undef,
  <form action="/adm/coursedocs" method="post" name="newext">                                                  undef,undef,\$mimetype);
  $uploadtag          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
  <input type="hidden" name="importdetail" value="" />              my $stored = $1;
  <span class="LC_nobreak">              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"                            $stored.'</span>').'</p>';
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}          } else {
  </span>              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
  </form>              
 ERFORM              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
               return;
     if ($allowed) {          }
  &update_paste_buffer($coursenum,$coursedom);          my $ext='false';
        my $dumpbut=&dumpbutton();          if ($url=~m{^http://}) { $ext='true'; }
        my $exportbut=&exportbutton();   $url     = &LONCAPA::map::qtunescape($url);
        my %lt=&Apache::lonlocal::texthash(          my $comment=$env{'form.comment'};
  'vc' => 'Verify Content',   $comment = &LONCAPA::map::qtunescape($comment);
  'cv' => 'Check/Set Resource Versions',          if ($folder=~/^supplemental/) {
  'ls' => 'List Symbs',                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
                                          'sl' => 'Show Log'                    $env{'user.domain'}.'___&&&___'.$comment;
   );          }
   
        my $folderpath=$env{'form.folderpath'};          $LONCAPA::map::resources[$newidx]=
        if (!$folderpath) {      $comment.':'.$url.':'.$ext.':normal:res';
    if ($env{'form.folder'} eq '' ||          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
        $env{'form.folder'} eq 'supplemental') {          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
        $folderpath='default&'.      $folder.'.'.$container,1);
    &escape(&mt('Main '.$type.' Documents'));          if ($fatal) {
    }              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
        }              return;
        unless ($env{'form.pagepath'}) {          } else {
            $containertag = '<input type="hidden" name="folderpath" value="" />';              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';                  $$upload_output = $showupload;
        }                  my $total_embedded = scalar(keys(%{$allfiles}));
                   if ($total_embedded > 0) {
        $r->print(<<ENDCOURSEVERIFY);                      my $uploadphase = 'upload_embedded';
 <form name="renameform" method="post" action="/adm/coursedocs">                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
   <input type="hidden" name="title" />      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
   <input type="hidden" name="cmd" />                      my ($embedded,$num) = 
   <input type="hidden" name="markcopy" />                          &Apache::loncommon::ask_for_embedded_content(
   <input type="hidden" name="copyfolder" />                              '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
   $containertag                      if ($embedded) {
 </form>                          if ($num) {
 <form name="simpleedit" method="post" action="/adm/coursedocs">                              $$upload_output .=
   <input type="hidden" name="importdetail" value="" />           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
   $uploadtag                              $nextphase = $uploadphase;
 </form>                          } else {
 <form action="/adm/coursedocs" method="post" name="courseverify">                              $$upload_output .= $embedded;
   <div class="LC_docs_course_commands">                          }
                       } else {
       <div>                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
         <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}                      }
       </div>                  } else {
       <div>                      $$upload_output .= &mt('No embedded items identified').'<br />';
         <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}                  }
       </div>                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
         $dumpbut              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
         $exportbut                  $nextphase = 'decompress_uploaded';
       <div>                  my $position = scalar(@LONCAPA::map::order)-1;
         <input type="submit" name="listsymbs" value="$lt{'ls'}" />                  my $noextract = &return_to_editor();
       </div>                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
       <div>                  my %archiveitems = (
         <input type="hidden" name="folder" value="$env{'form.folder'}" />                      folderpath => $env{'form.folderpath'},
         <input type="submit" name="docslog" value="$lt{'sl'}" />                      cmd        => $nextphase,
       </div>                      newidx     => $newidx,
   </div>                      position   => $position,
 </form>                      phase      => $nextphase,
 <div style="clear: both; height: 0px;">&nbsp;</div>                      comment    => $comment,
 ENDCOURSEVERIFY                  );
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
      &mt('Editing the Table of Contents for your '.$type)));                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
     }                  $$upload_output = $showupload.
 # --------------------------------------------------------- Standard documents                                    &Apache::loncommon::decompress_form($mimetype,
     $r->print('<table class="LC_docs_documents">');                                        $archiveurl,'/adm/coursedocs',$noextract,
                                         \%archiveitems,\@current);
     if (($standard) && ($allowed) && (!$forcesupplement)) {              }
  $r->print('<tr><td class="LC_docs_document">');          }
 #  '<h2>'.&mt('Main Course Documents').      }
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');      return $nextphase;
        my $folder=$env{'form.folder'};  }
        if ($folder eq '' || $folder eq 'supplemental') {  
            $folder='default';  sub get_dir_list {
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));      my ($url,$coursenum,$coursedom,$newidx) = @_;
            $uploadtag = '<input type="hidden" name="folderpath" value="'.      my ($destination,$dir_root) = &embedded_destination();
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';      my ($dirlistref,$listerror) =  
        }          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
        my $postexec='';      my @dir_lines;
        if ($folder eq 'default') {      my $dirptr=16384;
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');      if (ref($dirlistref) eq 'ARRAY') {
        } else {          foreach my $dir_line (sort
            #$postexec='self.close();';                            {
        }                                my ($afile)=split('&',$a,2);
        $hadchanges=0;                                my ($bfile)=split('&',$b,2);
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,                                return (lc($afile) cmp lc($bfile));
    $upload_output,$type);                            } (@{$dirlistref})) {
        if ($error) {              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');              $filename =~ s/\s+$//;
        }              next if ($filename =~ /^\.\.?$/); 
        if ($hadchanges) {              my $isdir = 0;
    &mark_hash_old();              if ($dirptr&$testdir) {
        }                  $isdir = 1;
        &changewarning($r,$postexec);              }
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
                      '.sequence';          }
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      }
                      '.page';      return @dir_lines;
  my $container='sequence';  }
  if ($env{'form.pagepath'}) {  
     $container='page';  sub is_supplemental_title {
  }      my ($title) = @_;
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
   }
   
   # --------------------------------------------------------------- An entry line
  my $recoverform=(<<RFORM);  
  <form action="/adm/groupsort" method="post" name="recover">  sub entryline {
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
  </form>          $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups)=@_;
 RFORM      my ($foldertitle,$renametitle);
       if (&is_supplemental_title($title)) {
  my $imspform=(<<IMSPFORM);   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
  <form action="/adm/imsimportdocs" method="post" name="ims">      } else {
  <input type="hidden" name="folder" value="$folder" />   $title=&HTML::Entities::encode($title,'"<>&\'');
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />   $renametitle=$title;
  </form>   $foldertitle=$title;
 IMSPFORM      }
   
  my $newnavform=(<<NNFORM);      my $orderidx=$LONCAPA::map::order[$index];
  <form action="/adm/coursedocs" method="post" name="newnav">  
  $uploadtag      $renametitle=~s/\\/\\\\/g;
  <input type="hidden" name="importdetail"      $renametitle=~s/\&quot\;/\\\"/g;
  value="$lt{'navc'}=/adm/navmaps" />      $renametitle=~s/ /%20/g;
  <span class="LC_nobreak">      my $line=&Apache::loncommon::start_data_table_row();
  <input name="newnav" type="submit" value="$lt{'navc'}" />      my ($form_start,$form_end,$form_common,$form_param);
  $help{'Navigate_Content'}  # Edit commands
  </span>      my ($esc_path, $path, $symb);
  </form>      if ($env{'form.folderpath'}) {
 NNFORM   $esc_path=&escape($env{'form.folderpath'});
  my $newsmppageform=(<<NSPFORM);   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  <form action="/adm/coursedocs" method="post" name="newsmppg">   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
  $uploadtag      }
  <input type="hidden" name="importdetail" value="" />      my $isexternal;
  <span class="LC_nobreak">      if ($residx) {
  <input name="newsmppg" type="button" value="$lt{'sipa'}"          my $currurl = $url;
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
  </span>          if ($currurl =~ m{^/adm/wrapper/ext/}) {
  </form>              $isexternal = 1;
 NSPFORM          }
           if (!$supplementalflag) {
  my $newsmpproblemform=(<<NSPROBFORM);              my $path = 'uploaded/'.
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">                         $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
  $uploadtag                         $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
  <input type="hidden" name="importdetail" value="" />              $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
  <span class="LC_nobreak">                                                   $residx,
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"                                                   &Apache::lonnet::declutter($currurl));
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}          }
  </span>      }
  </form>      my ($renamelink,%lt,$ishash);
       if (ref($filtersref) eq 'HASH') {
 NSPROBFORM          $ishash = 1;
       }
  my $newdropboxform=(<<NDBFORM);  
  <form action="/adm/coursedocs" method="post" name="newdropbox">      if ($allowed) {
  $uploadtag                $form_start = '
  <input type="hidden" name="importdetail" value="" />     <form action="/adm/coursedocs" method="post">
  <span class="LC_nobreak">            ';
  <input name="newdropbox" type="button" value="$lt{'drbx'}"          $form_common=(<<END);
  onClick="javascript:makedropbox();" />     <input type="hidden" name="folderpath" value="$path" />
  </span>             <input type="hidden" name="symb" value="$symb" />
  </form>  END
 NDBFORM          $form_param=(<<END);
      <input type="hidden" name="setparms" value="$orderidx" />
  my $newexuploadform=(<<NEXUFORM);     <input type="hidden" name="changeparms" value="0" />
  <form action="/adm/coursedocs" method="post" name="newexamupload">  END
  $uploadtag          $form_end = '</form>';
  <input type="hidden" name="importdetail" value="" />  
  <span class="LC_nobreak">   my $incindex=$index+1;
  <input name="newexamupload" type="button" value="$lt{'scuf'}"   my $selectbox='';
  onClick="javascript:makeexamupload();" />   if (($#LONCAPA::map::order>0) &&
  $help{'Score_Upload_Form'}      ((split(/\:/,
  </span>       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
  </form>       ne '') &&
 NEXUFORM      ((split(/\:/,
        $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
  my $newbulform=(<<NBFORM);       ne '')) {
  <form action="/adm/coursedocs" method="post" name="newbul">      $selectbox=
  $uploadtag   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
  <input type="hidden" name="importdetail" value="" />   '<select name="newpos" onchange="this.form.submit()">';
  <span class="LC_nobreak">      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
  <input name="newbulletin" type="button" value="$lt{'bull'}"   if ($i==$incindex) {
  onClick="javascript:makebulboard();" />      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
  $help{'Bulletin Board'}   } else {
  </span>      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
  </form>   }
 NBFORM      }
       $selectbox.='</select>';
  my $newaboutmeform=(<<NAMFORM);   }
  <form action="/adm/coursedocs" method="post" name="newaboutme">   %lt=&Apache::lonlocal::texthash(
  $uploadtag                  'up' => 'Move Up',
  <input type="hidden" name="importdetail"   'dw' => 'Move Down',
  value="$plainname=/adm/$udom/$uname/aboutme" />   'rm' => 'Remove',
  <span class="LC_nobreak">                  'ct' => 'Cut',
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />   'rn' => 'Rename',
  $help{'My Personal Info'}   'cp' => 'Copy',
  </span>                  'ex' => 'External Resource',
  </form>                  'ed' => 'Edit',
 NAMFORM                  'pr' => 'Preview',
                   'sv' => 'Save',
  my $newaboutsomeoneform=(<<NASOFORM);                  'ul' => 'URL',
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">                  'ti' => 'Title', 
  $uploadtag                  );
  <input type="hidden" name="importdetail" value="" />   my %denied = &action_restrictions($coursenum,$coursedom,$url,
  <span class="LC_nobreak">                                            $env{'form.folderpath'},
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"                                            $currgroups);
  onClick="javascript:makeabout();" />          my ($copylink,$cutlink,$removelink);
  </span>   my $skip_confirm = 0;
  </form>   if ( $folder =~ /^supplemental/
 NASOFORM       || ($url =~ m{( /smppg$
       |/syllabus$
       |/aboutme$
  my $newrosterform=(<<NROSTFORM);      |/navmaps$
  <form action="/adm/coursedocs" method="post" name="newroster">      |/bulletinboard$
  $uploadtag      |\.html$)}x)
  <input type="hidden" name="importdetail"               || $isexternal) {
  value="$lt{'rost'}=/adm/viewclasslist" />      $skip_confirm = 1;
  <span class="LC_nobreak">   }
  <input name="newroster" type="submit" value="$lt{'rost'}" />  
  $help{'Course Roster'}   if ($denied{'copy'}) {
  </span>              $copylink=(<<ENDCOPY)
  </form>  <span style="visibility: hidden;">$lt{'cp'}</span>
 NROSTFORM  ENDCOPY
           } else {
        $r->print(<<ENDFORM);              my $formname = 'edit_copy_'.$orderidx;
               my $js = "javascript:checkForSubmit(document.forms.renameform,'copy','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 <ul class="LC_TabContent">      $copylink=(<<ENDCOPY);
 <li>$lt{'nd'}</li>  <form name="$formname" method="post" action="/adm/coursedocs">
 <li>$lt{'pm'}</li>  $form_common
 <li>$lt{'pubd'}</li>  <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>
 <li>$lt{'sd'}</li>  $form_end
 <li>$lt{'mo'}</li>  ENDCOPY
 <li>$lt{'hao'}</li>              if (($ishash) && (ref($filtersref->{'cancopy'}) eq 'ARRAY')) {
 </ul>                  push(@{$filtersref->{'cancopy'}},$orderidx);
               }
 <table class="LC_docs_adddocs">          }
 <!-- <tr>   if ($denied{'cut'}) {
 <th>$lt{'uplm'}</th>              $cutlink=(<<ENDCUT);
 <th>$lt{'impp'}</th>  <span style="visibility: hidden;">$lt{'ct'}</span>
 <th>$lt{'spec'}</th>  ENDCUT
 </tr> -->          } else {
 <tr>              my $formname = 'edit_cut_'.$orderidx;
 <td>              my $js = "javascript:checkForSubmit(document.forms.renameform,'cut','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 $fileuploadform      $cutlink=(<<ENDCUT);
 </td>  <form name="$formname" method="post" action="/adm/coursedocs">
 <td>  $form_common
 $simpleeditdefaultform  <input type="hidden" name="skip_$orderidx" id="skip_cut_$orderidx" value="$skip_confirm" />
 <hr />  <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>
 $recoverform  $form_end
 ENDFORM  ENDCUT
        unless ($env{'form.pagepath'}) {              if (($ishash) && (ref($filtersref->{'cancut'}) eq 'ARRAY')) {
    $r->print(<<ENDFORM);                  push(@{$filtersref->{'cancut'}},$orderidx);
 <hr />              }
 $extresourcesform          }
  <br />          if ($denied{'remove'}) {
 $imspform              $removelink=(<<ENDREM);
 ENDFORM  <span style="visibility: hidden;">$lt{'rm'}</a>
        }  ENDREM
        $r->print('</td><td>');          } else {
        unless ($env{'form.pagepath'}) {              my $formname = 'edit_remove_'.$orderidx;
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');              my $js = "javascript:checkForSubmit(document.forms.renameform,'remove','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm);";
               $removelink=(<<ENDREM);
   <form name="$formname" method="post" action="/adm/coursedocs">
   $form_common
  my $newpageform=(<<NPFORM);  <input type="hidden" name="skip_$orderidx" id="skip_remove_$orderidx" value="$skip_confirm" />
  <form action="/adm/coursedocs" method="post" name="newpage">  <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>
  <input type="hidden" name="folderpath" value="$path" />  $form_end
  <input type="hidden" name="importdetail" value="" />  ENDREM
  <span class="LC_nobreak">              if (($ishash) && (ref($filtersref->{'canremove'}) eq 'ARRAY')) {
  <input name="newpage" type="button"                  push(@{$filtersref->{'canremove'}},$orderidx);
  onClick="javascript:makenewpage(this.form,'$pageseq');"              }
  value="$lt{'newp'}" />$help{'Adding_Pages'}          }
  </span>          unless ($isexternal) {
  </form>              $renamelink=(<<ENDREN);
 NPFORM  <a href='javascript:changename("$esc_path","$index","$renametitle");' class="LC_docs_rename">$lt{'rn'}</a>
   ENDREN
  my $newfolderform=(<<NFFORM);          }
  <form action="/adm/coursedocs" method="post" name="newfolder">   $line.=(<<END);
  <input type="hidden" name="folderpath" value="$path" />  <td>
  <input type="hidden" name="importdetail" value="" />  <div class="LC_docs_entry_move">
  <span class="LC_nobreak">    <a href='/adm/coursedocs?cmd=up_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
  <input name="newfolder" type="button"      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
  onClick="javascript:makenewfolder(this.form,'$folderseq');"    </a>
  value="$lt{'newf'}" />$help{'Adding_Folders'}  </div>
  </span>  <div class="LC_docs_entry_move">
  </form>    <a href='/adm/coursedocs?cmd=down_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
 NFFORM      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
     </a>
  my $newsylform=(<<NSYLFORM);  </div>
  <form action="/adm/coursedocs" method="post" name="newsyl">  </td>
  $uploadtag  <td>
  <input type="hidden" name="importdetail"     $form_start
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />     $form_param
  <span class="LC_nobreak">     $form_common
  <input name="newsyl" type="submit" value="$lt{'syll'}" />     $selectbox
  $help{'Syllabus'}     $form_end
  </span>  </td>
  </form>  <td class="LC_docs_entry_commands LC_nobreak">
 NSYLFORM  $removelink
   $cutlink
  my $newgroupfileform=(<<NGFFORM);  $copylink
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">  </td>
  $uploadtag  END
  <input type="hidden" name="importdetail"      }
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />  # Figure out what kind of a resource this is
  <span class="LC_nobreak">      my ($extension)=($url=~/\.(\w+)$/);
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />      my $uploaded=($url=~/^\/*uploaded\//);
  $help{'Group Files'}      my $icon=&Apache::loncommon::icon($url);
  </span>      my $isfolder;
  </form>      my $ispage;
 NGFFORM      my $containerarg;
       if ($uploaded) {
           if (($extension eq 'sequence') || ($extension eq 'page')) {
            $r->print(<<ENDFORM);              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
 <br />              $containerarg = $1;
 $newfolderform      if ($extension eq 'sequence') {
 <br />          $icon=$iconpath.'navmap.folder.closed.gif';
 $newpageform                  $isfolder=1;
 <br />              } else {
 $newsylform                  $icon=$iconpath.'page.gif';
 <br />                  $ispage=1;
 $newnavform              }
 <br />              if ($allowed) {
 $newsmppageform                  $url='/adm/coursedocs?';
 <br />              } else {
 $newsmpproblemform                  $url='/adm/supplemental?';
 <br />              }
 $newdropboxform   } else {
 <br />      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 $newexuploadform   }
 <br />      }
 $newbulform  
 <br />      my ($editlink,$extresform);
 $newaboutmeform      my $orig_url = $url;
 <br />      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 $newaboutsomeoneform      $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
 <br />      if (!$supplementalflag && $residx && $symb) {
 $newgroupfileform          if ((!$isfolder) && (!$ispage)) {
 <br />      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 $newrosterform      $url=&Apache::lonnet::clutter($url);
 ENDFORM      if ($url=~/^\/*uploaded\//) {
        }          $url=~/\.(\w+)$/;
        if ($env{'form.pagepath'}) {          my $embstyle=&Apache::loncommon::fileembstyle($1);
            $r->print(<<ENDBLOCK);          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
 $newsmpproblemform      $url='/adm/wrapper'.$url;
 <br />          } elsif ($embstyle eq 'ssi') {
 $newexuploadform      #do nothing with these
 ENDBLOCK          } elsif ($url!~/\.(sequence|page)$/) {
        }      $url='/adm/coursedocs/showdoc'.$url;
        $r->print('</td></tr>'."\n".          }
 '</table>');      } elsif ($url=~m|^/ext/|) {
        $r->print('</td></tr>');          $url='/adm/wrapper'.$url;
     }      }
 # ----------------------------------------------------- Supplemental documents              if (&Apache::lonnet::symbverify($symb,$url)) {
     if (!$forcestandard) {          $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
        $r->print('<tr><td class="LC_docs_document">');              } else {
 # '<h2>'.&mt('Supplemental Course Documents').                  $url='';
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');              }
        my $folder=$env{'form.folder'};   }
        unless ($folder=~/^supplemental/) {      }
    $folder='supplemental';      my ($rand_pick_text,$rand_order_text);
        }      if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
        if ($folder =~ /^supplemental$/ &&   my $foldername=&escape($foldertitle);
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {   my $folderpath=$env{'form.folderpath'};
           $env{'form.folderpath'} = 'supplemental&'.   if ($folderpath) { $folderpath.='&' };
                                     &escape(&mt('Supplemental '.$type.' Documents'));          if (!$allowed && $supplementalflag) {
        }              $folderpath.=$containerarg.'&'.$foldername;
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);              $url.='folderpath='.&escape($folderpath);
        if ($error) {          } else {
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');  # Append randompick number, hidden, and encrypted with ":" to foldername,
        }  # so it gets transferred between levels
        if ($allowed) {      $folderpath.=$containerarg.'&'.$foldername.
    my $folderseq=                                                ':'.(&LONCAPA::map::getparameter($orderidx,
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.                                                'parameter_randompick'))[0]
        '.sequence';                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                                                 'parameter_hiddenresource'))[0]=~/^yes$/i)
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                                                 'parameter_encrypturl'))[0]=~/^yes$/i)
  my $supupdocform=(<<SUPDOCFORM);                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">                                                'parameter_randomorder'))[0]=~/^yes$/i)
  $fileupload                                                 .':'.$ispage;
  <br />      $url.='folderpath='.&escape($folderpath);
  <br />              my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
  <span class="LC_nobreak">                                                          'parameter_randompick'))[0];
  $checkbox              my $rpckchk;
  </span>              if ($rpicknum) {
  <br /><br />                  $rpckchk = ' checked="checked"';
  $lt{'comment'}:<br />                  if (($ishash) && (ref($filtersref->{'randompick'}) eq 'ARRAY')) {
  <textarea cols=50 rows=4 name='comment'>                      push(@{$filtersref->{'randompick'}},$orderidx.':'.$rpicknum);
  </textarea>                  }
  <br />              }
  <input type="hidden" name="folderpath" value="$path" />              my $formname = 'edit_randompick_'.$orderidx;
  <input type="hidden" name="cmd" value="upload_supplemental" />      $rand_pick_text = 
  <span class="LC_nobreak">  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
  <input type="submit" value="$lt{'upld'}" />  $form_param."\n".
  $help{'Uploading_From_Harddrive'}  $form_common."\n".
  </span>  '<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.'">';
  </form>              if ($rpicknum ne '') {
 SUPDOCFORM                  $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
               }
  my $supnewfolderform=(<<SNFFORM);              $rand_pick_text .= '</span></span>'.
  <form action="/adm/coursedocs" method="post" name="supnewfolder">                                 $form_end;
  <input type="hidden" name="folderpath" value="$path" />              my $ro_set;
  <input type="hidden" name="importdetail" value="" />              if ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i) {
  <span class="LC_nobreak">                  $ro_set = 'checked="checked"';
  <input name="newfolder" type="button"                  if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
  onClick="javascript:makenewfolder(this.form,'$folderseq');"                      push(@{$filtersref->{'randomorder'}},$orderidx);
  value="$lt{'newf'}" /> $help{'Adding_Folders'}                  }
  </span>              }
  </form>              my $formname = 'edit_rorder_'.$orderidx;
 SNFFORM      $rand_order_text = 
   '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
   $form_param."\n".
  my $supnewextform=(<<SNEFORM);  $form_common."\n".
  <form action="/adm/coursedocs" method="post" name="supnewext">  '<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>'.
  <input type="hidden" name="folderpath" value="$path" />  $form_end; 
  <input type="hidden" name="importdetail" value="" />          }
  <span class="LC_nobreak">      } elsif ($supplementalflag && !$allowed) {
  <input name="newext" type="button"          $url .= ($url =~ /\?/) ? '&amp;':'?';
  onClick="javascript:makenewext('supnewext');"          $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}          if ($title) {
  </span>              $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
  </form>          }
 SNEFORM          if ($isexternal && $orderidx) {
               $url .= '&amp;idx='.$orderidx;
  my $supnewsylform=(<<SNSFORM);          }
  <form action="/adm/coursedocs" method="post" name="supnewsyl">      }
  <input type="hidden" name="folderpath" value="$path" />      my ($tdalign,$tdwidth);
  <input type="hidden" name="importdetail"      if ($allowed) {
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />          my $fileloc = 
  <span class="LC_nobreak">              &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
  <input name="newsyl" type="submit" value="$lt{'syll'}" />          if ($isexternal) {
  $help{'Syllabus'}              ($editlink,$extresform) = 
  </span>                  &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
  </form>          } elsif (!$isfolder && !$ispage) {
 SNSFORM              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
                   &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
  my $supnewaboutmeform=(<<SNAMFORM);              if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">                  my $jscall = 
  <input type="hidden" name="folderpath" value="$path" />                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
  <input type="hidden" name="importdetail"                                                              $switchserver,
  value="$plainname=/adm/$udom/$uname/aboutme" />                                                              $forceedit,
  <span class="LC_nobreak">                                                              undef,$symb,
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />                                                              &escape($env{'form.folderpath'}),
  $help{'My Personal Info'}                                                              $renametitle,'','',1);
  </span>                  if ($jscall) {
  </form>                      $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
 SNAMFORM                                  $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
                   }
    $r->print(<<ENDSUPFORM);              }
 <ul class="LC_TabContent">          }
 <li>$lt{'nd'}</li>          $tdalign = ' align="right" valign="top"';
 <li>$lt{'sd'}</li>          $tdwidth = ' width="80%"';
 <li>$lt{'hao'}</li>      }
 </ul>      my $reinit;
 <table class="LC_docs_adddocs">      if ($crstype eq 'Community') {
 <tr><td>          $reinit = &mt('(re-initialize community to access)');
 $supupdocform      } else {
 </td>          $reinit = &mt('(re-initialize course to access)');
 <td>      }
 $supnewfolderform      $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
 <br />      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 $supnewextform         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
 <br />      } elsif ($url) {
 $supnewsylform         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
 <br />                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
 $supnewaboutmeform      } else {
 </td></tr>         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
 </table></td></tr>      }
 ENDSUPFORM      $line.='</span></td><td'.$tdwidth.'>';
        }      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
     }         $line.='<a href="'.$url.'">'.$title.'</a>';
     $r->print('</table>');      } elsif ($url) {
     if ($allowed) {         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
  $r->print('                                               $title,600,500);
 <form method="post" name="extimport" action="/adm/coursedocs">      } else {
   <input type="hidden" name="title" />         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
   <input type="hidden" name="url" />      }
   <input type="hidden" name="useform" />      $line.="$extresform</td>";
   <input type="hidden" name="residx" />      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
 </form>');      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
     }      if (($allowed) && ($folder!~/^supplemental/)) {
   } else {    my %lt=&Apache::lonlocal::texthash(
       unless ($upload_result eq 'phasetwo') {         'hd' => 'Hidden',
 # -------------------------------------------------------- This is showdoc mode         'ec' => 'URL hidden');
           $r->print("<h1>".&mt('Uploaded Document').' - '.          my ($enctext,$hidtext);
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.          if ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i) {
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".              $enctext = ' checked="checked"';
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');              if (($ishash) && (ref($filtersref->{'encrypturl'}) eq 'ARRAY')) {
       }                  push(@{$filtersref->{'encrypturl'}},$orderidx);
   }              }
  }          }
  $r->print(&Apache::loncommon::end_page());          if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
  return OK;              $hidtext = ' checked="checked"';
 }              if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
                   push(@{$filtersref->{'hiddenresource'}},$orderidx);
               }
 sub editing_js {          }
     my ($udom,$uname) = @_;          my $formhidden = 'edit_hiddenresource_'.$orderidx;
     my $now = time();          my $formurlhidden = 'edit_encrypturl_'.$orderidx;
     my %lt = &Apache::lonlocal::texthash(   $line.=(<<ENDPARMS);
                                           p_mnf => 'Name of New Folder',    <td class="LC_docs_entry_parameter">
                                           t_mnf => 'New Folder',      <form action="/adm/coursedocs" method="post" name="$formhidden">
                                           p_mnp => 'Name of New Page',      $form_param
                                           t_mnp => 'New Page',      $form_common
                                           p_mxu => 'Title for the Uploaded Score',      <label><input type="checkbox" name="hiddenresource_$orderidx" id="hiddenresource_$orderidx" onclick="checkForSubmit(this.form,'hiddenresource','settings');" $hidtext /> $lt{'hd'}</label>
                                           p_msp => 'Title for the Page',      $form_end
                                           p_msb => 'Title for the Problem',      <br />
                                           p_mdb => 'Title for the Drop Box',      <form action="/adm/coursedocs" method="post" name="$formurlhidden">
                                           p_mbb => 'Title for the Bulletin Board',      $form_param
                                           p_mab => "Enter user:domain for User's 'About Me' Page",      $form_common
                                           p_mab2 => "About [_99]",      <label><input type="checkbox" name="encrypturl_$orderidx" id="encrypturl_$orderidx" onclick="checkForSubmit(this.form,'encrypturl','settings');" $enctext /> $lt{'ec'}</label>
                                           p_mab_alrt1 => 'Not a valid user:domain',      $form_end
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',    </td>
                                           p_chn => 'New Title',    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',                                        $rand_order_text</td>
                                           p_rmr2a => 'Remove[_99]',  ENDPARMS
                                           p_rmr2b => '?[_99]',      }
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',      $line.=&Apache::loncommon::end_data_table_row();
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',      return $line;
                                           p_ctr2a => 'Cut[_98]',  }
                                           p_ctr2b => '?[_98]'  
                                         );  sub action_restrictions {
       my ($cnum,$cdom,$url,$folderpath,$currgroups) = @_;
     return <<ENDNEWSCRIPT;      my %denied = (
 function makenewfolder(targetform,folderseq) {                     cut    => 0,
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');                     copy   => 0,
     if (foldername) {                     remove => 0,
        targetform.importdetail.value=escape(foldername)+"="+folderseq;                   );
         targetform.submit();      if ($url=~ m{^/res/.+\.(page|sequence)$}) {
     }          # no copy for published maps
 }          $denied{'copy'} = 1;
       } elsif ($url=~m{^/res/lib/templates/}) {
 function makenewpage(targetform,folderseq) {         $denied{'copy'} = 1;
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');         $denied{'cut'} = 1;
     if (pagename) {      } elsif ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
         targetform.importdetail.value=escape(pagename)+"="+folderseq;          if ($folderpath =~ /^default&[^\&]+$/) {
         targetform.submit();              if ((ref($currgroups) eq 'HASH') && (keys(%{$currgroups}) > 0)) {
     }                  $denied{'remove'} = 1;
 }              }
               $denied{'cut'} = 1;
 function makenewext(targetname) {              $denied{'copy'} = 1;
     this.document.forms.extimport.useform.value=targetname;          }
     this.document.forms.extimport.title.value='';      } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
     this.document.forms.extimport.url.value='';          my $group = $1;
     this.document.forms.extimport.residx.value='';          if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
     window.open('/adm/rat/extpickframe.html');              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
 }                  $denied{'remove'} = 1;
               }
 function edittext(targetname,residx,title,url) {          }
     this.document.forms.extimport.useform.value=targetname;          $denied{'cut'} = 1;
     this.document.forms.extimport.residx.value=residx;          $denied{'copy'} = 1;
     this.document.forms.extimport.url.value=url;      } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
     this.document.forms.extimport.title.value=title;          my $group = $1;
     window.open('/adm/rat/extpickframe.html');          if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
 }              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
                   my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
 function makeexamupload() {                  if (keys(%groupsettings) > 0) {
    var title=prompt('$lt{"p_mxu"}');                      $denied{'remove'} = 1;
    if (title) {                  }
     this.document.forms.newexamupload.importdetail.value=                  $denied{'cut'} = 1;
  escape(title)+'=/res/lib/templates/examupload.problem';                  $denied{'copy'} = 1;
     this.document.forms.newexamupload.submit();              }
    }          }
 }      } elsif ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
           my $group = $1;
 function makesmppage() {          if ($url =~ /group_boards_\Q$group\E/) {
    var title=prompt('$lt{"p_msp"}');              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
    if (title) {                  my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
     this.document.forms.newsmppg.importdetail.value=                  if (keys(%groupsettings) > 0) {
  escape(title)+'=/adm/$udom/$uname/$now/smppg';                      if (ref($groupsettings{'functions'}) eq 'HASH') {
     this.document.forms.newsmppg.submit();                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
    }                              $denied{'remove'} = 1;
 }                          }
                       }
 function makesmpproblem() {                  }
    var title=prompt('$lt{"p_msb"}');                  $denied{'cut'} = 1;
    if (title) {                  $denied{'copy'} = 1;
     this.document.forms.newsmpproblem.importdetail.value=              }
  escape(title)+'=/res/lib/templates/simpleproblem.problem';          }
     this.document.forms.newsmpproblem.submit();      }
    }      return %denied;
 }  }
   
 function makedropbox() {  sub new_timebased_suffix {
    var title=prompt('$lt{"p_mdb"}');      my ($dom,$num,$type,$area,$container) = @_;
    if (title) {      my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
     this.document.forms.newdropbox.importdetail.value=      if ($type eq 'paste') {
         escape(title)+'=/res/lib/templates/DropBox.problem';          $prefix = $type;
     this.document.forms.newdropbox.submit();          $namespace = 'courseeditor';
    }      } elsif ($type eq 'map') {
 }          $prefix = 'docs';
           if ($area eq 'supplemental') {
 function makebulboard() {              $prefix = 'supp';
    var title=prompt('$lt{"p_mbb"}');          }
    if (title) {          $prefix .= $container;
     this.document.forms.newbul.importdetail.value=          $namespace = 'uploadedmaps';
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';      } else {
     this.document.forms.newbul.submit();          $prefix = $type;
    }          $namespace = 'templated';
 }      }
       $idtype = 'concat';
 function makeabout() {      my ($suffix,$freedlock,$error) =
    var user=prompt("$lt{'p_mab'}");          &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,$dom,$num);
    if (user) {      if (!$suffix) {
        var comp=new Array();          if ($type eq 'paste') {
        comp=user.split(':');              $errtext = &mt('Failed to acquire a unique timestamp-based suffix when adding to the paste buffer.');
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {          } elsif ($type eq 'map') {
    if ((comp[0]) && (comp[1])) {              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
        this.document.forms.newaboutsomeone.importdetail.value=          } elsif ($type eq 'smppg') {
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
        this.document.forms.newaboutsomeone.submit();          } else {
    } else {              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new bulletin board.');
                alert("$lt{'p_mab_alrt1'}");          }
            }          if ($error) {
        } else {              $errtext .= '<br />'.$error;
            alert("$lt{'p_mab_alrt2'}");          }
        }      }
    }      if ($freedlock ne 'ok') {
 }          $locknotfreed = 
               '<div class="LC_error">'.
 function makeims() {              &mt('There was a problem removing a lockfile.').' ';
     var caller = document.forms.ims.folder.value;          if ($type eq 'paste') {
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";              &mt('This will prevent use of the paste buffer until th next log-in.');
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");          } elsif ($type eq 'map') {
     newWindow.location.href = newlocation;              &mt('This will prevent creation of additional folders or composite pages in this course.');
 }          } elsif ($type eq 'smppg') {
               $locknotfreed .=
                   &mt('This will prevent creation of additional simple pages in this course.');
 function finishpick() {          } else {
     var title=this.document.forms.extimport.title.value;              $locknotfreed .=
     var url=this.document.forms.extimport.url.value;                  &mt('This will prevent creation of additional bulletin boards in this course.');
     var form=this.document.forms.extimport.useform.value;          }
     var residx=this.document.forms.extimport.residx.value;          unless ($type eq 'paste') {
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');              $locknotfreed .=
 }                  ' '.&mt('Please contact the domain coordinator for your LON-CAPA domain.');
           }
 function changename(folderpath,index,oldtitle,container,pagesymb) {          $locknotfreed .= '</div>';
     var title=prompt('$lt{"p_chn"}',oldtitle);      }
     if (title) {      return ($suffix,$errtext,$locknotfreed);
  this.document.forms.renameform.markcopy.value=-1;  }
  this.document.forms.renameform.title.value=title;  
  this.document.forms.renameform.cmd.value='rename_'+index;  =pod
         if (container == 'sequence') {  
     this.document.forms.renameform.folderpath.value=folderpath;  =item tiehash()
         }  
         if (container == 'page') {  tie the hash
             this.document.forms.renameform.pagepath.value=folderpath;  
             this.document.forms.renameform.pagesymb.value=pagesymb;  =cut
         }  
         this.document.forms.renameform.submit();  sub tiehash {
     }      my ($mode)=@_;
 }      $hashtied=0;
       if ($env{'request.course.fn'}) {
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {   if ($mode eq 'write') {
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  this.document.forms.renameform.markcopy.value=-1;      &GDBM_WRCREAT(),0640)) {
  this.document.forms.renameform.cmd.value='del_'+index;                  $hashtied=2;
         if (container == 'sequence') {      }
             this.document.forms.renameform.folderpath.value=folderpath;   } else {
         }      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
         if (container == 'page') {      &GDBM_READER(),0640)) {
             this.document.forms.renameform.pagepath.value=folderpath;                  $hashtied=1;
             this.document.forms.renameform.pagesymb.value=pagesymb;      }
         }   }
         this.document.forms.renameform.submit();      }
     }  }
 }  
   sub untiehash {
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {      if ($hashtied) { untie %hash; }
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {      $hashtied=0;
  this.document.forms.renameform.cmd.value='cut_'+index;      return OK;
  this.document.forms.renameform.markcopy.value=index;  }
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;  
         if (container == 'sequence') {  
             this.document.forms.renameform.folderpath.value=folderpath;  
         }  
         if (container == 'page') {  sub checkonthis {
             this.document.forms.renameform.pagepath.value=folderpath;      my ($r,$url,$level,$title)=@_;
             this.document.forms.renameform.pagesymb.value=pagesymb;      $url=&unescape($url);
         }      $alreadyseen{$url}=1;
         this.document.forms.renameform.submit();      $r->rflush();
     }      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 }         $r->print("\n<br />");
          if ($level==0) {
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {             $r->print("<br />");
     this.document.forms.renameform.markcopy.value=index;         }
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;         for (my $i=0;$i<=$level*5;$i++) {
     if (container == 'sequence') {             $r->print('&nbsp;');
  this.document.forms.renameform.folderpath.value=folderpath;         }
     }         $r->print('<a href="'.$url.'" target="cat">'.
     if (container == 'page') {   ($title?$title:$url).'</a> ');
  this.document.forms.renameform.pagepath.value=folderpath;         if ($url=~/^\/res\//) {
  this.document.forms.renameform.pagesymb.value=pagesymb;    my $result=&Apache::lonnet::repcopy(
     }                                &Apache::lonnet::filelocation('',$url));
     this.document.forms.renameform.submit();            if ($result eq 'ok') {
 }               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                $r->rflush();
                &Apache::lonnet::countacc($url);
 ENDNEWSCRIPT               $url=~/\.(\w+)$/;
 }               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 1;   $r->print('<br />');
 __END__                   $r->rflush();
                    for (my $i=0;$i<=$level*5;$i++) {
                        $r->print('&nbsp;');
 =head1 NAME                   }
                    $r->print('- '.&mt('Rendering:').' ');
 Apache::londocs.pm   my ($errorcount,$warningcount)=split(/:/,
          &Apache::lonnet::ssi_body($url,
 =head1 SYNOPSIS         ('grade_target'=>'web',
    'return_only_error_and_warning_counts' => 1)));
 This is part of the LearningOnline Network with CAPA project                   if (($errorcount) ||
 described at http://www.lon-capa.org.                       ($warningcount)) {
        if ($errorcount) {
 =head1 SUBROUTINES                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
                             &mt('[quant,_1,error]',$errorcount).'</span>');
 =over                       }
        if ($warningcount) {
 =item %help=()                          $r->print('<span class="LC_warning">'.
                             &mt('[quant,_1,warning]',$warningcount).'</span>');
 Available help topics                       }
                    } else {
 =item mapread()                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                    }
 Mapread read maps into LONCAPA::map:: global arrays                   $r->rflush();
 @order and @resources, determines status               }
 sets @order - pointer to resources in right order       my $dependencies=
 sets @resources - array with the resources with correct idx                  &Apache::lonnet::metadata($url,'dependencies');
                foreach my $dep (split(/\,/,$dependencies)) {
 =item authorhosts()   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
                       &checkonthis($r,$dep,$level+1);
 Return hash with valid author names                   }
                }
 =item dumpbutton()            } elsif ($result eq 'unavailable') {
                $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 Generate "dump" button            } elsif ($result eq 'not_found') {
         unless ($url=~/\$/) {
 =item clean()    $r->print('<span class="LC_error">'.&mt('not found').'</span>');
         } else {
 =item dumpcourse()    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
         }
     Actually dump course            } else {
                $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
             }
 =item exportbutton()         }
       }
     Generate "export" button  }
   
 =item exportcourse()  
   
 =item create_ims_store()  =pod
   
 =item build_package()  =item list_symbs()
   
 =item get_dependencies()  List Content Identifiers
   
 =item process_content()  =cut
   
 =item replicate_content()  sub list_symbs {
       my ($r) = @_;
 =item extract_media()  
       my $crstype = &Apache::loncommon::course_type();
 =item store_template()      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
 =item group_import()      $r->print(&startContentScreen('tools'));
       my $navmap = Apache::lonnavmaps::navmap->new();
     Imports the given (name, url) resources into the course      if (!defined($navmap)) {
     coursenum, coursedom, and folder must precede the list          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
                     '<div class="LC_error">'.
 =item breadcrumbs()                    &mt('Unable to retrieve information about course contents').
                     '</div>');
 =item log_docs()          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
       } else {
 =item docs_change_log()          $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
                     &Apache::loncommon::start_data_table().
 =item update_paste_buffer()                    &Apache::loncommon::start_data_table_header_row().
                     '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
 =item print_paste_buffer()                    &Apache::loncommon::end_data_table_header_row()."\n");
           my $count;
 =item do_paste_from_buffer()          foreach my $res ($navmap->retrieveResources()) {
               $r->print(&Apache::loncommon::start_data_table_row().
 =item update_parameter()                        '<td>'.$res->compTitle().'</td>'.
                         '<td>'.$res->symb().'</td>'.
 =item handle_edit_cmd()                        &Apache::loncommon::end_data_table_row());
               $count ++;
 =item editor()          }
           if (!$count) {
 =item process_file_upload()              $r->print(&Apache::loncommon::start_data_table_row().
                         '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
 =item process_secondary_uploads()                        &Apache::loncommon::end_data_table_row()); 
           }
 =item is_supplemental_title()          $r->print(&Apache::loncommon::end_data_table());
       }
 =item parse_supplemental_title()      $r->print(&endContentScreen());
   }
 =item entryline()  
   
 =item tiehash()  sub verifycontent {
       my ($r) = @_;
 =item untiehash()      my $crstype = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
 =item checkonthis()      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
       $r->print(&startContentScreen('tools'));
 check on this      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
      $hashtied=0;
 =item verifycontent()     undef %alreadyseen;
      %alreadyseen=();
 Verify Content     &tiehash();
      
 =item devalidateversioncache() & checkversions()     foreach my $key (keys(%hash)) {
          if ($hash{$key}=~/\.(page|sequence)$/) {
 Check Versions     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
          $r->print('<hr /><span class="LC_error">'.
 =item mark_hash_old()   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
    &unescape($hash{$key}).'</span><br />'.
 =item is_hash_old()   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
      }
 =item changewarning()         }
          if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 =item init_breadcrumbs()             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
          }
 Breadcrumbs for special functions     }
      &untiehash();
 =back     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
       $r->print(&endContentScreen());
 =cut  }
   
   
   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 Documents 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 'courseindex')?' class="active"':'').'><a href="/adm/indexcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Index').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
           $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('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 '.&Apache::loncommon::course_type().' 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') {
    $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');
       $help{'Course Roster'} = &Apache::loncommon::help_open_topic('Docs_Course_Roster');
       $help{'Web Page'} =  &Apache::loncommon::help_open_topic('Docs_Web_Page');
    
       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
   
       $env{'form.folderpath'} = &unescape($env{'form.folderpath'});
       my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
       if (($env{'form.folderpath'}=~/^default/) || ($env{'form.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 '.$crstype.' 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 '.$crstype.' 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 '.$crstype.' 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);
     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' => 'Import 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 Import',
                   'imsl' => 'Import 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('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>
    </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' => ['Import Content',$fileuploadform],
                   'bb' => ['Published Content',$importpubform],
                   'cc' => ['Grading Resources',$gradingform],
                   );
   unless ($container eq 'page') {
       $orderhash{'00'} = ['Newfolder',$newfolderform];
       $orderhash{'dd'} = ['Collaboration',$communityform];
       $orderhash{'ee'} = ['Special Pages',$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' => ['Import Content',$supupdocform],
                   'ff' => ['Special Pages',&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>');
              }
           }
       } 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'} = 'del_'.$position;
               my ($title,$url,@rrest) = 
                   split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$position]]);
               if (&handle_edit_cmd($docuname,$docudom)) {
                   ($errtext,$fatal) = &storemap($docuname,$docudom,$map,1);
                   if ($fatal) {
                       if ($container eq 'page') {
                           $delwarning = &mt('An error occurred updating the contents of the current page.');
                       } else {
                           $delwarning = &mt('An error occurred updating the contents of the current folder.');
                       }
                   } else {
                       $delresult = &mt('Archive file removed.');
                   }
               }
           }
           $env{'form.cmd'} = $currcmd;
       }
       if ($delwarning) {
           $output = '<p class="LC_warning">'.
                      $delwarning.
                      '</p>';
       }
       if ($delresult) {
           $output .= '<p class="LC_info">'.
                      $delresult.
                      '</p>';
       }
       return $output;
   }
   
   sub generate_admin_menu {
       my ($crstype) = @_;
       my $lc_crstype = lc($crstype);
       my ($home,$other,%outhash)=&authorhosts();
       my %lt=&Apache::lonlocal::texthash (
                                            'vc'   => 'Verify Content',
                                            'cv'   => 'Check/Set Resource Versions',
                                            'ls'   => 'List Resource Identifiers',
                                            'imse' => 'Export contents to IMS Archive',
                                            'dcd'  => "Dump $crstype Content to Authoring Space",
                                          );
       my ($candump,$dumpurl);
       if ($home + $other > 0) {
           $candump = 'F';
           if ($home) {
               $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
           } else {
               my @hosts;
               foreach my $aurole (keys(%outhash)) {
                   unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                       push(@hosts,$outhash{$aurole});
                   }
               }
               if (@hosts == 1) {
                   my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
                                  '&amp;role='.
                                  &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
                                  &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
                   $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
               } else {
                   $dumpurl = "javascript:choose_switchserver_window()";
               }
           }
       }
       my @menu=
           ({  categorytitle=>'Administration',
               items =>[
                   {   linktext   => $lt{'vc'},
                       url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
                       permission => 'F',
                       help       => 'Verify_Content',
                       icon       => 'verify.png',
                       linktitle  => 'Verify contents can be retrieved/rendered',
                   },
                   {   linktext => $lt{'cv'},
                       url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
                       permission => 'F',
                       help       => 'Check_Resource_Versions',
                       icon       => 'resversion.png',
                       linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
                   },
                   {   linktext   => $lt{'ls'},
                       url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
                       permission => 'F',
                       #help => '',
                       icon       => 'symbs.png',
                       linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
                   },
                   ]
           },
           {   categorytitle=>'Export',
               items =>[
                   {   linktext   => $lt{'imse'},
                       url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
                       permission => 'F',
                       help       => 'Docs_Export_Course_Docs',
                       icon       => 'imsexport.png',
                       linktitle  => $lt{'imse'},
                   },
                   {   linktext   => $lt{'dcd'},
                       url        => $dumpurl,
                       permission => $candump,
                       #help => '',
                       icon       => 'dump.png',
                       linktitle  => $lt{'dcd'},
                   },
                   ]
           });
       return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
              '<input type="hidden" id="dummy" />'."\n".
              &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
              '</form>';
   }
   
   sub generate_edit_table {
       my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile,
           $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 '.$crstype.' 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.326  
changed lines
  Added in v.1.546


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