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

version 1.328, 2009/01/28 13:24:54 version 1.484.2.38, 2013/08/17 00:59:32
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
   package Apache::londocs;
   
 package Apache::londocs;  use strict;
   use Apache::Constants qw(:common :http);
 use strict;  use Apache::imsexport;
 use Apache::Constants qw(:common :http);  use Apache::lonnet;
 use Apache::imsexport;  use Apache::loncommon;
 use Apache::lonnet;  use Apache::lonhtmlcommon;
 use Apache::loncommon;  use LONCAPA::map();
 use LONCAPA::map();  use Apache::lonratedt();
 use Apache::lonratedt();  use Apache::lonxml;
 use Apache::lonxml;  use Apache::lonclonecourse;
 use Apache::lonclonecourse;  use Apache::lonnavmaps;
 use Apache::lonnavmaps;  use Apache::lonnavdisplay();
 use HTML::Entities;  use Apache::lonextresedit();
 use GDBM_File;  use HTML::Entities;
 use Apache::lonlocal;  use HTML::TokeParser;
 use Cwd;  use GDBM_File;
 use LONCAPA qw(:DEFAULT :match);  use Apache::lonlocal;
   use Cwd;
 my $iconpath;  use LONCAPA qw(:DEFAULT :match);
   
 my %hash;  my $iconpath;
   
 my $hashtied;  my %hash;
 my %alreadyseen=();  
   my $hashtied;
 my $hadchanges;  my %alreadyseen=();
   
   my $hadchanges;
 my %help=();  my $suppchanges;
   
   
 sub mapread {  my %help=();
     my ($coursenum,$coursedom,$map)=@_;  
     return  
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.  sub mapread {
      $map);      my ($coursenum,$coursedom,$map)=@_;
 }      return
         &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
 sub storemap {       $map);
     my ($coursenum,$coursedom,$map)=@_;  }
     my ($outtext,$errtext)=  
       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.  sub storemap {
       $map,1);      my ($coursenum,$coursedom,$map,$contentchg)=@_;
     if ($errtext) { return ($errtext,2); }      my $report;
          if (($contentchg) && ($map =~ /^default/)) {
     $hadchanges=1;         $report = 1;
     return ($errtext,0);      }
 }      my ($outtext,$errtext)=
         &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1,$report);
       if ($errtext) { return ($errtext,2); }
 sub authorhosts {  
     my %outhash=();      if ($map =~ /^default/) {
     my $home=0;          $hadchanges=1;
     my $other=0;      } else {
     foreach my $key (keys(%env)) {          $suppchanges=1;
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {      }
     my $role=$1;      return ($errtext,0);
     my $realm=$2;  }
     my ($start,$end)=split(/\./,$env{$key});  
     if (($start) && ($start>time)) { next; }  
     if (($end) && (time>$end)) { next; }  
     my ($ca,$cd);  sub authorhosts {
     if ($1 eq 'au') {      my %outhash=();
  $ca=$env{'user.name'};      my $home=0;
  $cd=$env{'user.domain'};      my $other=0;
     } else {      foreach my $key (keys(%env)) {
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     }      my $role=$1;
     my $allowed=0;      my $realm=$2;
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);      my ($start,$end)=split(/\./,$env{$key});
     my @ids=&Apache::lonnet::current_machine_ids();      if (($start) && ($start>time)) { next; }
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      if (($end) && (time>$end)) { next; }
     if ($allowed) {      my ($ca,$cd);
  $home++;      if ($1 eq 'au') {
  $outhash{'home_'.$ca.'@'.$cd}=1;   $ca=$env{'user.name'};
     } else {   $cd=$env{'user.domain'};
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      } else {
  $other++;   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
     }      }
  }      my $allowed=0;
     }      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
     return ($home,$other,%outhash);      my @ids=&Apache::lonnet::current_machine_ids();
 }      foreach my $id (@ids) {
                   if ($id eq $myhome) {
                       $allowed=1;
 sub dumpbutton {                      last;
     my ($home,$other,%outhash)=&authorhosts();                  }
     my $type = &Apache::loncommon::course_type();              }
     if ($home+$other==0) { return ''; }      if ($allowed) {
     if ($home) {   $home++;
  return '<input type="submit" name="dumpcourse" value="'.   $outhash{'home_'.$ca.':'.$cd}=1;
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      } else {
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
     } else {   $other++;
  return '<div>'.      }
      &mt('Dump '.$type.   }
  ' DOCS to Construction Space: available on other servers').      }
  '</div>';      return ($home,$other,%outhash);
     }  }
 }  
   
 sub clean {  sub clean {
     my ($title)=@_;      my ($title)=@_;
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
     return $title;      return $title;
 }  }
   
   
   
 sub dumpcourse {  sub dumpcourse {
     my ($r) = @_;      my ($r) = @_;
     my $type = &Apache::loncommon::course_type();      my $crstype = &Apache::loncommon::course_type();
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').      $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
       '<form name="dumpdoc" method="post">');                &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      $r->print(&startContentScreen('tools'));
     my ($home,$other,%outhash)=&authorhosts();      my ($home,$other,%outhash)=&authorhosts();
     unless ($home) { return ''; }      unless ($home) {
     my $origcrsid=$env{'request.course.id'};          $r->print(&endContentScreen());
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);          return '';
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {      }
 # Do the dumping      my $origcrsid=$env{'request.course.id'};
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
  $r->print('<h3>'.&mt('Copying Files').'</h3>');  # Do the dumping
  my $title=$env{'form.authorfolder'};   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
  $title=&clean($title);              $r->print(&endContentScreen());
  my %replacehash=();              return '';
  foreach my $key (keys(%env)) {          }
     if ($key=~/^form\.namefor\_(.+)/) {   my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  $replacehash{$1}=$env{$key};   $r->print('<h3>'.&mt('Copying Files').'</h3>');
     }   my $title=$env{'form.authorfolder'};
  }   $title=&clean($title);
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   my %replacehash=();
  $crs=~s/\_/\//g;   foreach my $key (keys(%env)) {
  foreach my $item (keys(%replacehash)) {      if ($key=~/^form\.namefor\_(.+)/) {
     my $newfilename=$title.'/'.$replacehash{$item};   $replacehash{$1}=$env{$key};
     $newfilename=~s/\.(\w+)$//;      }
     my $ext=$1;   }
     $newfilename=&clean($newfilename);   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
     $newfilename.='.'.$ext;   $crs=~s/\_/\//g;
     my @dirs=split(/\//,$newfilename);   foreach my $item (keys(%replacehash)) {
     my $path='/home/'.$ca.'/public_html';      my $newfilename=$title.'/'.$replacehash{$item};
     my $makepath=$path;      $newfilename=~s/\.(\w+)$//;
     my $fail=0;      my $ext=$1;
     for (my $i=0;$i<$#dirs;$i++) {      $newfilename=&clean($newfilename);
  $makepath.='/'.$dirs[$i];      $newfilename.='.'.$ext;
  unless (-e $makepath) {      my @dirs=split(/\//,$newfilename);
     unless(mkdir($makepath,0777)) { $fail=1; }      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
  }      my $makepath=$path;
     }      my $fail=0;
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      for (my $i=0;$i<$#dirs;$i++) {
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {   $makepath.='/'.$dirs[$i];
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {   unless (-e $makepath) {
     print $fh &Apache::lonclonecourse::rewritefile(      unless(mkdir($makepath,0777)) { $fail=1; }
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),   }
      (%replacehash,$crs => '')      }
     );      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
  } else {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     print $fh   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);      print $fh &Apache::lonclonecourse::rewritefile(
        }           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  $fh->close();       (%replacehash,$crs => '')
     } else {      );
  $fail=1;   } else {
     }      print $fh
     if ($fail) {           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');         }
     } else {   $fh->close();
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      } else {
     }   $fail=1;
  }      }
     } else {      if ($fail) {
 # Input form   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  unless ($home==1) {      } else {
     $r->print(   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');      }
  }   }
  foreach my $key (sort(keys(%outhash))) {      } else {
     if ($key=~/^home_(.+)$/) {          $r->print(&mt('Searching ...').'<br />');
  if ($home==1) {          $r->rflush();
     $r->print(  # Input form
   '<input type="hidden" name="authorspace" value="'.$1.'" />');          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
  } else {   unless ($home==1) {
     $r->print('<option value="'.$1.'">'.$1.' - '.      $r->print('<div class="LC_left_float">'.
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');        '<fieldset><legend>'.
  }                        &mt('Select the Authoring Space').
     }                        '</legend><select name="authorspace">');
  }   }
  unless ($home==1) {   foreach my $key (sort(keys(%outhash))) {
     $r->print('</select>');      if ($key=~/^home_(.+)$/) {
  }   if ($home==1) {
  my $title=$origcrsdata{'description'};      $r->print(
  $title=~s/[\/\s]+/\_/gs;    '<input type="hidden" name="authorspace" value="'.$1.'" />');
  $title=&clean($title);   } else {
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'      $r->print('<option value="'.$1.'">'.$1.' - '.
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
  &tiehash();   }
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'      }
                  .&Apache::loncommon::start_data_table()   }
                  .&Apache::loncommon::start_data_table_header_row()   unless ($home==1) {
                  .'<th>'.&mt('Internal Filename').'</th>'      $r->print('</select></fieldset></div>'."\n");
                  .'<th>'.&mt('Title').'</th>'   }
                  .'<th>'.&mt('Save as ...').'</th>'   my $title=$origcrsdata{'description'};
                  .&Apache::loncommon::end_data_table_header_row());   $title=~s/[\/\s]+/\_/gs;
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {   $title=&clean($title);
     $r->print(&Apache::loncommon::start_data_table_row()   $r->print('<div class="LC_left_float">'.
                      .'<td>'.$file.'</td>');                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
     my ($ext)=($file=~/\.(\w+)$/);                    '<input type="text" size="50" name="authorfolder" value="'.
     my $title=$hash{'title_'.$hash{                    $title.'" />'.
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                    '</fieldset></div><br clear="all" />'."\n");
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');   &tiehash();
     if (!$title) {   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
  $title=$file;                   .&Apache::loncommon::start_data_table()
     } else {                   .&Apache::loncommon::start_data_table_header_row()
  $title=~s|/|_|g;                   .'<th>'.&mt('Internal Filename').'</th>'
     }                   .'<th>'.&mt('Title').'</th>'
     $title=~s/\.(\w+)$//;                   .'<th>'.&mt('Save as ...').'</th>'
     $title=&clean($title);                   .&Apache::loncommon::end_data_table_header_row());
     $title.='.'.$ext;   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"      $r->print(&Apache::loncommon::start_data_table_row()
                      .&Apache::loncommon::end_data_table_row());                       .'<td>'.$file.'</td>');
  }      my ($ext)=($file=~/\.(\w+)$/);
  $r->print(&Apache::loncommon::end_data_table());      my $title=$hash{'title_'.$hash{
  &untiehash();   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
  $r->print(      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      if (!$title) {
     }   $title=$file;
 }      } else {
    $title=~s|/|_|g;
       }
       $title=~s/\.(\w+)$//;
 sub exportbutton {      $title=&clean($title);
     my $type = &Apache::loncommon::course_type();      $title.='.'.$ext;
     return '<input type="submit" name="exportcourse" value="'.      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
             &mt('Export '.$type.' to IMS').'" />'.                       .&Apache::loncommon::end_data_table_row());
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');   }
 }   $r->print(&Apache::loncommon::end_data_table());
    &untiehash();
    $r->print(
     '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
 sub exportcourse {      }
     my $r=shift;      $r->print(&endContentScreen());
     my $type = &Apache::loncommon::course_type();  }
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',  
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});  sub group_import {
     my $numdisc = keys(%discussiontime);      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
     my $navmap = Apache::lonnavmaps::navmap->new();      my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
     if (!defined($navmap)) {          %removeparam,$importuploaded,$fixuperrors);
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').      $allmaps = {};
                   '<h2>IMS Export Failed</h2>'.      while (@files) {
                   '<div class="LC_error">'.   my ($name, $url, $residx) = @{ shift(@files) };
                   &mt('Unable to retrieve information about course contents').          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');       && ($caller eq 'londocs')
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});       && (!&Apache::lonnet::stat_file($url))) {
         return;  
     }              my $errtext = '';
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);              my $fatal = 0;
     my $curRes;              my $newmapstr = '<map>'."\n".
     my $outcome;                              '<resource id="1" src="" type="start"></resource>'."\n".
                               '<link from="1" to="2" index="1"></link>'."\n".
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                              '<resource id="2" src="" type="finish"></resource>'."\n".
                                             ['finishexport']);                              '</map>';
     if ($env{'form.finishexport'}) {              $env{'form.output'}=$newmapstr;
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
                                             ['archive','discussion']);                                                  'output',$1.$2);
               if ($result !~ m{^/uploaded/}) {
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');                  $fatal = 2;
         if (@exportitems == 0 && @discussions == 0) {              }
             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';              if ($fatal) {
         } else {                  return ($errtext,$fatal);
             my $now = time;              }
             my %symbs;          }
             my $manifestok = 0;   if ($url) {
             my $imsresources;              if (($caller eq 'londocs') &&
             my $tempexport;                  ($folder =~ /^default/)) {
             my $copyresult;                  if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);                      my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
             if ($manifestok) {                      my $cid = $coursedom.'_'.$coursenum;
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);                      $allmaps =
                 close($ims_manifest);                          &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
                                                                $chome,$cid);
 #Create zip file in prtspool                      $donechk = 1;
                 my $imszipfile = '/prtspool/'.                  }
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.                  if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
                    time.'_'.rand(1000000000).'.zip';                      &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
                 my $cwd = &Cwd::getcwd();                                           \%addedmaps,\%hierarchy,\%titles,$allmaps);
                 my $imszip = '/home/httpd/'.$imszipfile;                      $importuploaded = 1;
                 chdir $tempexport;                  } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");                      next if ($allmaps->{$url});
                 close(OUTPUT);                  }
                 chdir $cwd;              }
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      if (!$residx
                 if ($copyresult) {   || defined($LONCAPA::map::zombies[$residx])) {
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);   $residx = &LONCAPA::map::getresidx($url,$residx);
                 }   push(@LONCAPA::map::order, $residx);
             } else {      }
                 $outcome = '<br />'.&mt('Unfortunately you will not be able to retrieve an IMS archive of this posts at this time, because there was a problem creating a manifest file.').'<br />';      my $ext = 'false';
             }      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
         }      $name = &LONCAPA::map::qtunescape($name);
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));              if ($name eq '') {
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));                  $name = &LONCAPA::map::qtunescape(&mt('Web Page'));
         $r->print($outcome);              }
         $r->print(&Apache::loncommon::end_page());              if ($url =~ m{^/uploaded/$coursedom/$coursenum/((?:docs|supplemental)/(?:default|\d+))/new\.html$}) {
     } else {                  my $filepath = $1;
         my $display;                  my $fname = $name;
         $display = '<form name="exportdoc" method="post">'."\n";                  if ($fname =~ /^\W+$/) {
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');                      $fname = 'web';
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                  } else {
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.                      $fname =~ s/\W/_/g;
                     '<input type="button" value="check all" '.                  }
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.                  if (length($fname > 15)) {
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.                      $fname = substr($fname,0,14);
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.                  }
                     '<td>&nbsp;</td><td>&nbsp;</td>'.                  my $initialtext = &mt('Replace with your own content.');
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.                  my $newhtml = <<END;
                     '</b></legend><input type="button" value="check all"'.  <html>
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.  <head>
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.  <title>$name</title>
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.  </head>
                     '</tr></table>';  <body bgcolor="#ffffff">
         my $curRes;  $initialtext
         my $depth = 0;  </body>
         my $count = 0;  </html>
         my $boards = 0;  END
         my $startcount = 5;                  $env{'form.output'}=$newhtml;
         my %parent = ();                  my $result =
         my %children = ();                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
         my $lastcontainer = $startcount;                                                            'output',
         my @bgcolors = ('#F6F6F6','#FFFFFF');                                                            "$filepath/$residx/$fname.html");
         $display .= '<table cellspacing="0"><tr>'.                  if ($result =~ m{^/uploaded/}) {
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";                      $url = $result;
         if ($numdisc > 0) {                      if ($filepath =~ /^supplemental/) {
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";                          $name = time.'___&&&___'.$env{'user.name'}.'___&&&___'.
         }                                  $env{'user.domain'}.'___&&&___'.$name;
         $display.='&nbsp;</td></tr>';                      }
         while ($curRes = $it->next()) {                  } else {
             if (ref($curRes)) {                      return (&mt('Failed to save new web page.'),1);
                 $count ++;                  }
             }              }
             if ($curRes == $it->BEGIN_MAP()) {              $url  = &LONCAPA::map::qtunescape($url);
                 $depth++;      $LONCAPA::map::resources[$residx] =
                 $parent{$depth} = $lastcontainer;   join(':', ($name, $url, $ext, 'normal', 'res'));
             }   }
             if ($curRes == $it->END_MAP()) {      }
                 $depth--;      if ($importuploaded) {
                 $lastcontainer = $parent{$depth};          my %import_errors;
             }          my %updated = (
             if (ref($curRes)) {                            removefrommap => \%removefrommap,
                 my $symb = $curRes->symb();                            removeparam   => \%removeparam,
                 my $ressymb = $symb;                        );
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {          my ($result,$msgsarray,$lockerror) =
                     unless ($ressymb =~ m|adm/wrapper/adm|) {              &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';          if (keys(%import_errors) > 0) {
                     }              $fixuperrors =
                 }                  '<p span class="LC_warning">'."\n".
                 my $color = $count%2;                  &mt('The following files are either dependencies of a web page or references within a folder and/or composite page for which errors occurred during import:')."\n".
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".                  '<ul>'."\n";
                     '<input type="checkbox" name="archive" value="'.$count.'" ';              foreach my $key (sort(keys(%import_errors))) {
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {                  $fixuperrors .= '<li>'.$key.'</li>'."\n";
                     my $checkitem = $count + $boards + $startcount;              }
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';              $fixuperrors .= '</ul></p>'."\n";
                 }          }
                 $display .= ' />'."\n";          if (ref($msgsarray) eq 'ARRAY') {
                 for (my $i=0; $i<$depth; $i++) {              if (@{$msgsarray} > 0) {
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";                  $fixuperrors .= '<p class="LC_info">'.
                 }                                  join('<br />',@{$msgsarray}).
                 if ($curRes->is_sequence()) {                                  '</p>';
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";              }
                     $lastcontainer = $count + $startcount + $boards;          }
                 } elsif ($curRes->is_page()) {          if ($lockerror) {
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";              $fixuperrors .= '<p class="LC_error">'.
                     $lastcontainer = $count + $startcount + $boards;                              $lockerror.
                 }                              '</p>';
                 my $currelem = $count+$boards+$startcount;          }
                 $children{$parent{$depth}} .= $currelem.':';      }
                 $display .= '&nbsp;'.$curRes->title().'</td>';      my ($errtext,$fatal) =
                 if ($discussiontime{$ressymb} > 0) {          &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
                     $boards ++;      unless ($fatal) {
                     $currelem = $count+$boards+$startcount;          if ($folder =~ /^supplemental/) {
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";              &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
                 } else {          }
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";      }
                 }      return ($errtext,$fatal,$fixuperrors);
             }  }
         }  
         my $scripttag = qq|  sub log_docs {
 <script>      return &Apache::lonnet::write_log('course','docslog',@_);
   }
 function checkAll(field) {  
     if (field.length > 0) {  {
         for (i = 0; i < field.length; i++) {      my @oldresources=();
             field[i].checked = true ;      my @oldorder=();
         }      my $parmidx;
     } else {      my %parmaction=();
         field.checked = true      my %parmvalue=();
     }      my $changedflag;
 }  
                                                                                      sub snapshotbefore {
 function uncheckAll(field) {          @oldresources=@LONCAPA::map::resources;
     if (field.length > 0) {          @oldorder=@LONCAPA::map::order;
         for (i = 0; i < field.length; i++) {          $parmidx=undef;
             field[i].checked = false ;          %parmaction=();
         }          %parmvalue=();
     } else {          $changedflag=0;
         field.checked = false ;      }
     }  
 }      sub remember_parms {
           my ($idx,$parameter,$action,$value)=@_;
 function propagateCheck(item) {          $parmidx=$idx;
     if (document.exportdoc.elements[item].checked == true) {          $parmaction{$parameter}=$action;
         containerCheck(item)          $parmvalue{$parameter}=$value;
     }          $changedflag=1;
 }      }
   
 function containerCheck(item) {      sub log_differences {
     document.exportdoc.elements[item].checked = true          my ($plain)=@_;
     var numitems = $count + $boards + $startcount          my %storehash=('folder' => $plain,
     var parents = new Array(numitems)                         'currentfolder' => $env{'form.folder'});
     for (var i=$startcount; i<numitems; i++) {          if ($parmidx) {
         parents[i] = new Array             $storehash{'parameter_res'}=$oldresources[$parmidx];
     }             foreach my $parm (keys(%parmaction)) {
         |;                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
                 $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
         foreach my $container (sort { $a <=> $b } (keys(%children))) {             }
             my @contents = split(/:/,$children{$container});          }
             for (my $i=0; $i<@contents; $i ++) {          my $maxidx=$#oldresources;
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";          if ($#LONCAPA::map::resources>$#oldresources) {
             }             $maxidx=$#LONCAPA::map::resources;
         }          }
           for (my $idx=0; $idx<=$maxidx; $idx++) {
         $scripttag .= qq|             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
     if (parents[item].length > 0) {                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
         for (var j=0; j<parents[item].length; j++) {                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
             containerCheck(parents[item][j])                $changedflag=1;
         }             }
      }               if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
 }                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
                 $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
 </script>                $changedflag=1;
         |;             }
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',          }
  $scripttag));   $storehash{'maxidx'}=$maxidx;
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));          if ($changedflag) { &log_docs(\%storehash); }
  $r->print($display.'</table>'.      }
                   '<p><input type="hidden" name="finishexport" value="1">'.  }
                   '<input type="submit" name="exportcourse" value="'.  
                   &mt('Export '.$type.' DOCS').'" /></p></form>');  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".
 sub create_ims_store {               '// <![CDATA['."\n".
     my ($now,$manifestok,$outcome,$tempexport) = @_;               &Apache::loncommon::display_filter_js('docslog')."\n".
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
     my $ims_manifest;               &history_tab_js()."\n".
     if (!-e $$tempexport) {               &Apache::lonratedt::editscript('simple')."\n".
         mkdir($$tempexport,0700);               '// ]]>'."\n".
     }               '</script>'."\n";
     $$tempexport .= '/'.$now;      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
     if (!-e $$tempexport) {      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
         mkdir($$tempexport,0700);      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
     }      my %orderhash;
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};      my $container='sequence';
     if (!-e $$tempexport) {      my $pathitem;
         mkdir($$tempexport,0700);      if ($env{'form.folderpath'} =~ /\:1$/) {
     }          $container='page';
     if (!-e "$$tempexport/resources") {      }
         mkdir("$$tempexport/resources",0700);      my $folderpath=$env{'form.folderpath'};
     }      if ($folderpath eq '') {
 # open manifest file          $folderpath = 'default&'.&escape(&mt('Main Content').':::::');
     my $manifest = '/imsmanifest.xml';      }
     my $manifestfilename = $$tempexport.$manifest;      $pathitem = '<input type="hidden" name="folderpath" value="'.
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {                  &HTML::Entities::encode($folderpath,'<>&"').'" />';
         $$manifestok=1;      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
         print $ims_manifest      my $jumpto = $readfile;
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".      $jumpto =~ s{^/}{};
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.      my $tid = 1;
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.      if ($supplementalflag) {
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.          $tid = 2;
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.      }
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.      my ($breadcrumbtrail) = 
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".          &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 '  <metadata>      $r->print($breadcrumbtrail.
     <schema></schema>                &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
     <imsmd:lom>                $readfile));
       <imsmd:general>      my %docslog=&Apache::lonnet::dump('nohist_docslog',
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
         <imsmd:title>                                        $env{'course.'.$env{'request.course.id'}.'.num'});
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>  
         </imsmd:title>      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
       </imsmd:general>  
     </imsmd:lom>      my %saveable_parameters = ('show' => 'scalar',);
   </metadata>'."\n".      &Apache::loncommon::store_course_settings('docs_log',
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".                                                \%saveable_parameters);
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.      &Apache::loncommon::restore_course_settings('docs_log',
 ' structure="hierarchical">'."\n".                                                  \%saveable_parameters);
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'      if (!$env{'form.show'}) { $env{'form.show'}=10; }
     } else {  # FIXME: internationalization seems wrong here
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'      my %lt=('hiddenresource' => 'Resources hidden',
 ;      'encrypturl'     => 'URL hidden',
     }      'randompick'     => 'Randomly pick',
     return $ims_manifest;      'randomorder'    => 'Randomly ordered',
 }      'set'            => 'set to',
       'del'            => 'deleted');
 sub build_package {      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;                   $pathitem."\n".
 # first iterator to look for dependencies                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
     my $curRes;      $r->print('<div class="LC_left_float">'.
     my $count = 0;                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
     my $depth = 0;                &makedocslogform($filter,1).
     my $lastcontainer = 0;                '</fieldset></div><br clear="all" />');
     my %parent = ();      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     my @dependencies = ();                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};                &mt('After').'</th>'.
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};                &Apache::loncommon::end_data_table_header_row());
     while ($curRes = $it->next()) {      my $shown=0;
         if (ref($curRes)) {      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
             $count ++;   if ($env{'form.displayfilter'} eq 'currentfolder') {
         }      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
         if ($curRes == $it->BEGIN_MAP()) {   }
             $depth++;          my @changes=keys(%{$docslog{$id}{'logentry'}});
             $parent{$depth} = $lastcontainer;          if ($env{'form.displayfilter'} eq 'containing') {
         }      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
         if ($curRes == $it->END_MAP()) {   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
             $depth--;      foreach my $key (@changes) {
             $lastcontainer = $parent{$depth};   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
         }      }
         if (ref($curRes)) {      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
             if ($curRes->is_sequence() || $curRes->is_page()) {   }
                 $lastcontainer = $count;          my $count = 0;
             }          my $time =
             if (grep(/^$count$/,@$exportitems)) {              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);          my $plainname =
             }              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
         }                                            $docslog{$id}{'exe_udom'});
     }          my $about_me_link =
 # second iterator to build manifest and store resources              &Apache::loncommon::aboutmewrapper($plainname,
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                                                 $docslog{$id}{'exe_uname'},
     $depth = 0;                                                 $docslog{$id}{'exe_udom'});
     my $prevdepth;          my $send_msg_link='';
     $count = 0;          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
     my $imsresources;               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
     my $pkgdepth;              $send_msg_link ='<br />'.
     while ($curRes = $it->next()) {                  &Apache::loncommon::messagewrapper(&mt('Send message'),
         if ($curRes == $it->BEGIN_MAP()) {                                                     $docslog{$id}{'exe_uname'},
             $prevdepth = $depth;                                                     $docslog{$id}{'exe_udom'});
             $depth++;          }
         }          $r->print(&Apache::loncommon::start_data_table_row());
         if ($curRes == $it->END_MAP()) {          $r->print('<td>'.$time.'</td>
             $prevdepth = $depth;                         <td>'.$about_me_link.
             $depth--;                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
         }                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
                     $send_msg_link.'</td><td>'.
         if (ref($curRes)) {                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
             $count ++;          my $is_supp = 0; 
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {          if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
                 my $symb = $curRes->symb();              $is_supp = 1;
                 my $isvisible = 'true';          }
                 my $resourceref;  # Before
                 if ($curRes->randomout()) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                     $isvisible = 'false';      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
                 }      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
                 unless ($curRes->is_sequence()) {      if ($oldname ne $newname) {
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';                  my $shown = &LONCAPA::map::qtescape($oldname);
                 }                  if ($is_supp) {
                 my $step = $prevdepth - $depth;                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                 if (($step >= 0) && ($count > 1)) {                  }
                     while ($step >= 0) {                  $r->print($shown);
                         print $ims_manifest "\n".'  </item>'."\n";      }
                         $step --;   }
                     }   $r->print('<ul>');
                 }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 $prevdepth = $depth;              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
                   my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
                 my $itementry =                  if ($is_supp) {
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.                  }
               '<title>'.$curRes->title().'</title>';   $r->print('<li>'.$shown.'</li>');
                 print $ims_manifest "\n".$itementry;      }
    }
                 unless ($curRes->is_sequence()) {   $r->print('</ul>');
                     my $content_file;  # After
                     my @hrefs = ();          $r->print('</td><td>');
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);  
                     if ($content_file) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                         $imsresources .= "\n".      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
                      '" type="webcontent" href="'.$content_file.'">'."\n".      if ($oldname ne '' && $oldname ne $newname) {
                      '       <file href="'.$content_file.'" />'."\n";                  my $shown = &LONCAPA::map::qtescape($newname);
                         foreach my $item (@hrefs) {                  if ($is_supp) {
                             $imsresources .=                      $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
                      '        <file href="'.$item.'" />'."\n";                  }
                         }                  $r->print($shown);
                         if (grep(/^$count$/,@$discussions)) {      }
                             my $ressymb = $symb;   }
                             my $mode;   $r->print('<ul>');
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
                                 }                  if ($is_supp) {
                                 $mode = 'board';                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                             }                  }
                             my %extras = (                  $r->print('<li>'.$shown.'</li>');
                                           caller => 'imsexport',      }
                                           tempexport => $tempexport.'/resources',   }
                                           count => $count   $r->print('</ul>');
                                          );   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
                         }      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
                         $imsresources .= '    </resource>'."\n";   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                     }  # FIXME: internationalization seems wrong here
                 }      $r->print('<li>'.
                 $pkgdepth = $depth;        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
             }    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
         }        .'</li>');
     }   }
     while ($pkgdepth > 0) {      }
         print $ims_manifest "    </item>\n";      $r->print('</ul>');
         $pkgdepth --;   }
     }  # End
     my $resource_text = qq|          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
     </organization>          $shown++;
   </organizations>          if (!($env{'form.show'} eq &mt('all')
   <resources>                || $shown<=$env{'form.show'})) { last; }
     $imsresources      }
   </resources>      $r->print(&Apache::loncommon::end_data_table()."\n".
 </manifest>                &makesimpleeditform($pathitem)."\n".
     |;                '</div></div>');
     print $ims_manifest $resource_text;      $r->print(&endContentScreen());
 }  }
   
 sub get_dependencies {  sub update_paste_buffer {
     my ($exportitems,$parent,$depth,$dependencies) = @_;      my ($coursenum,$coursedom,$folder) = @_;
     if ($depth > 1) {      my (@possibles,%removals,%cuts);
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {      if ($env{'form.multiremove'}) {
             push(@{$dependencies},$$parent{$depth});          $env{'form.multiremove'} =~ s/,$//;
             if ($depth > 2) {          map { $removals{$_} = 1; } split(/,/,$env{'form.multiremove'});
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);      }
             }      if (($env{'form.multicopy'}) || ($env{'form.multicut'})) {
         }          if ($env{'form.multicut'}) {
     }              $env{'form.multicut'} =~ s/,$//;
 }              foreach my $item (split(/,/,$env{'form.multicut'})) {
                   unless ($removals{$item}) {
 sub process_content {                      $cuts{$item} = 1;
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;                      push(@possibles,$item.':cut');
     my $content_type;                  }
     my $message;              }
     my @uploads = ();          }
     if ($curRes->is_sequence()) {          if ($env{'form.multicopy'}) {
         $content_type = 'sequence';              $env{'form.multicopy'} =~ s/,$//;
     } elsif ($curRes->is_page()) {              foreach my $item (split(/,/,$env{'form.multicopy'})) {
         $content_type = 'page'; # need to handle individual items in pages.                  unless ($removals{$item} || $cuts{$item}) {
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {                      push(@possibles,$item.':copy'); 
         $content_type = 'syllabus';                  }
         my $contents = &Apache::imsexport::templatedpage($content_type);              }
         if ($contents) {          }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      } elsif ($env{'form.markcopy'}) {
         }          @possibles = split(/,/,$env{'form.markcopy'});
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {      }
         $content_type = 'external';  
         my $title = $curRes->title;      return if (@possibles == 0);
         my $contents =  &Apache::imsexport::external($symb,$title);      return if (!defined($env{'form.copyfolder'}));
         if ($contents) {  
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
         }      $env{'form.copyfolder'});
     } elsif ($symb =~ m-adm/navmaps$-) {      return if ($fatal);
         $content_type =  'navmap';  
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {      my %curr_groups = &Apache::longroup::coursegroups();
         $content_type = 'simplepage';  
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);  # Retrieve current paste buffer suffixes.
         if ($contents) {      my @currpaste = split(/,/,$env{'docs.markedcopies'});
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      my (%pasteurls,@newpaste);
         }  
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {  # Construct identifiers for current contents of user's paste buffer
         $content_type = 'simpleproblem';      if (@currpaste) {
         my $contents =  &Apache::imsexport::simpleproblem($symb);          foreach my $suffix (@currpaste) {
         if ($contents) {               my $cid = $env{'docs.markedcopy_crs_'.$suffix};
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);               my $url = $env{'docs.markedcopy_url_'.$suffix};
         }               if (($cid =~ /^$match_domain(?:_)$match_courseid$/) &&
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {                   ($url ne '')) {
         $content_type = 'examupload';                   $pasteurls{$cid.'_'.$url};
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {               }
         $content_type = 'bulletinboard';          }
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);      }
         if ($contents) {  
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);  # Mark items for copying (skip any items already in user's paste buffer)
         }      my %addtoenv;
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {                    
         $content_type = 'aboutme';      foreach my $item (@possibles) {
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);          my ($orderidx,$cmd) = split(/:/,$item);
         if ($contents) {          next if ($orderidx =~ /\D/);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          next unless (($cmd eq 'cut') || ($cmd eq 'copy') || ($cmd eq 'remove'));
         }          my ($title,$url)=split(':',$LONCAPA::map::resources[$orderidx]);
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {          my %denied = &action_restrictions($coursenum,$coursedom,
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                                            &LONCAPA::map::qtescape($url),
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {                                            $env{'form.folderpath'},\%curr_groups);
         my $canedit = 0;          next if ($denied{'copy'});
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {          $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
             $canedit= 1;          next if (exists($pasteurls{$coursedom.'_'.$coursenum.'_'.$url}));
         }          my ($suffix,$errortxt,$locknotfreed) =
 # only include problem code where current user is author              &new_timebased_suffix($env{'user.domain'},$env{'user.name'},'paste');
         if ($canedit) {          push(@newpaste,$suffix);
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');          if ($locknotfreed) {
         } else {              return $locknotfreed;
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');              last;
         }          }
     } elsif ($symb =~ m-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});
     }      ($title) = &Apache::loncommon::parse_supplemental_title($title);
     if (@uploads > 0) {          }
         foreach my $item (@uploads) {  
             my $uploadmsg = '';          $addtoenv{'docs.markedcopy_title_'.$suffix} = $title,
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');          $addtoenv{'docs.markedcopy_url_'.$suffix}   = $url,
             if ($uploadmsg) {          $addtoenv{'docs.markedcopy_cmd_'.$suffix}   = $cmd,
                 $$copyresult .= $uploadmsg."\n";          $addtoenv{'docs.markedcopy_crs_'.$suffix}   = $env{'request.course.id'};
             }   
         }          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
     }              my $prefix = $1;
     if ($message) {              my $subdir =$2;
         $$copyresult .= $message."\n";              if ($subdir eq '') {
     }                  $subdir = $prefix;
 }              }
               my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
 sub replicate_content {              &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;                                   \%hierarchy,\%titles,\%allmaps);
     my ($map,$ind,$url);              if (ref($hierarchy{$url}) eq 'HASH') {
     if ($caller eq 'templateupload') {                  my ($nested,$nestednames);
         $url = $symb;                  &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
         $url =~ s#//#/#g;                  $nested =~ s/\&$//;
     } else {                  $nestednames =~ s/\Q___&&&___\E$//;
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);                  if ($nested ne '') {
     }                      $addtoenv{'docs.markedcopy_nested_'.$suffix} = $nested;
     my $content;                  }
     my $filename;                  if ($nestednames ne '') {
     my $repstatus;                      $addtoenv{'docs.markedcopy_nestednames_'.$suffix} = $nestednames;
     my $content_name;                  }
     if ($url =~ m-/([^/]+)$-) {              }
         $filename = $1;          }
         if (!-e $tempexport.'/resources') {      }
             mkdir($tempexport.'/resources',0700);      if (@newpaste) {
         }          $addtoenv{'docs.markedcopies'} = join(',',(@currpaste,@newpaste));
         if (!-e $tempexport.'/resources/'.$count) {      }
             mkdir($tempexport.'/resources/'.$count,0700);      &Apache::lonnet::appenv(\%addtoenv);
         }      delete($env{'form.markcopy'});
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;  }
         my $copiedfile;  
         if ($copiedfile = Apache::File->new('>'.$destination)) {  sub recurse_uploaded_maps {
             my $content;      my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
             if ($caller eq 'resource') {      if (ref($hierarchy->{$url}) eq 'HASH') {
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';          my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);          my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
                 $content = &Apache::lonnet::getfile($filepath);          my (@uploaded,@names,%shorter);
                 if ($content eq -1) {          for (my $i=0; $i<@maps; $i++) {
                     $$message = 'Could not copy file '.$filename;              my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
                 } else {              if ($inner ne '') {
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');                  push(@uploaded,$inner);
                     $repstatus = 'ok';                  push(@names,&escape($titles[$i]));
                 }                  $shorter{$maps[$i]} = $inner;
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {              }
                 my $rtncode;          }
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);          $$nestref .= "$dir:".join(',',@uploaded).'&';
                 if ($repstatus eq 'ok') {          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
                     if ($url =~ /\.html?$/i) {          foreach my $map (@maps) {
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');              if ($shorter{$map} ne '') {
                     }                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
                 } else {              }
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";          }
                 }      }
             } elsif ($caller eq 'noedit') {      return;
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.  }
                 $repstatus = 'ok';  
                 $content = 'Not the owner of this resource';  sub print_paste_buffer {
             }      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
             if ($repstatus eq 'ok') {      return if (!defined($env{'docs.markedcopies'}));
                 print $copiedfile $content;  
             }      unless (($env{'form.pastemarked'}) || ($env{'form.clearmarked'})) {
             close($copiedfile);          return if ($env{'docs.markedcopies'} eq '');
         } else {      }
             $$message = 'Could not open destination file for '.$filename."<br />\n";  
         }      my @currpaste = split(/,/,$env{'docs.markedcopies'});
     } else {      my ($pasteitems,@pasteable);
         $$message = 'Could not determine name of file for '.$symb."<br />\n";  
     }  # Construct identifiers for current contents of user's paste buffer
     if ($repstatus eq 'ok') {      foreach my $suffix (@currpaste) {
         $content_name = 'resources/'.$count.'/'.$filename;          next if ($suffix =~ /\D/);
     }          my $cid = $env{'docs.markedcopy_crs_'.$suffix};
     return $content_name;          my $url = $env{'docs.markedcopy_url_'.$suffix};
 }          if (($cid =~ /^$match_domain\_$match_courseid$/) &&
               ($url ne '')) {
 sub extract_media {              my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent,
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;                  $canpaste,$nopaste,$othercrs,$areachange);
     my ($dirpath,$container);              my $extension = (split(/\./,$env{'docs.markedcopy_url_'.$suffix}))[-1];
     my %allfiles = ();              if ($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
     my %codebase = ();                  $is_external = 1;
     if ($url =~ m-(.*/)([^/]+)$-) {              }
         $dirpath = $1;              if ($folder =~ /^supplemental/) {
         $container = $2;                  $canpaste = &supp_pasteable($env{'docs.markedcopy_url_'.$suffix});
     } else {                  unless ($canpaste) {
         $dirpath = $url;                      $nopaste = &mt('Paste into Supplemental Content unavailable.');
         $container = '';                  }
     }              } else {
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);                  $canpaste = 1;
     foreach my $embed_file (keys(%allfiles)) {              }
         my $filename;              if ($canpaste) {
         if ($embed_file =~ m#([^/]+)$#) {                  if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
             $filename = $1;                      my $srcdom = $1;
         } else {                      my $srcnum = $2;
             $filename = $embed_file;                      my $rem = $3;
         }                      if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
         my $newname = 'res/'.$filename;                          $othercourse = 1;
         my ($rtncode,$embed_content,$repstatus);                          if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         my $embed_url;                              if ($canpaste) {
         if ($embed_file =~ m-^/-) {                                  $othercrs = '<br />'.&mt('(from another course)');
             $embed_url = $embed_file;           # points to absolute path                              }
         } else {                          } else {
             if ($embed_file =~ m-https?://-) {                              $canpaste = 0;
                 next;                           # points to url                              $nopaste = &mt('Paste from another course unavailable.'); 
             } else {                          }
                 $embed_url = $dirpath.$embed_file;  # points to relative path                      }
             }                      if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
         }                          my $prefix = $1;
         if ($caller eq 'resource') {                          $parent = $2;
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                            if ($folder !~ /^\Q$prefix\E/) {
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);                              $areachange = 1;
             $embed_content = &Apache::lonnet::getfile($embed_path);                          }
             unless ($embed_content eq -1) {                          $is_uploaded_map = 1;
                 $repstatus = 'ok';                      }
             }                  }
         } elsif ($caller eq 'uploaded') {              }
                          if ($canpaste) {
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);                 push(@pasteable,$suffix);
         }              }
         if ($repstatus eq 'ok') {              my $buffer;
             my $destination = $tempexport.'/resources/'.$count.'/res';              if ($is_external) {
             if (!-e "$destination") {                  $buffer = &mt('External Resource').': '.
                 mkdir($destination,0755);                      &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}).' ('.
             }                      &LONCAPA::map::qtescape($url).')';
             $destination .= '/'.$filename;              } else {
             my $copiedfile;                  my $icon = &Apache::loncommon::icon($extension);
             if ($copiedfile = Apache::File->new('>'.$destination)) {                  if ($extension eq 'sequence' &&
                 print $copiedfile $embed_content;                      $url =~ m{/default_\d+\.sequence$}x) {
                 push(@{$href},'resources/'.$count.'/res/'.$filename);                      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
                 my $attrib_regexp = '';                      $icon .= '/navmap.folder.closed.gif';
                 if (@{$allfiles{$embed_file}} > 1) {                  }
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});                  $buffer = '<img src="'.$icon.'" alt="" class="LC_icon" />'.
                 } else {                            ': '.
                     $attrib_regexp = $allfiles{$embed_file}[0];                            &Apache::loncommon::parse_supplemental_title(
                 }                               &LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix}));
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;              }
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {              $pasteitems .= '<div class="LC_left_float">';
                     $$content =~ s#\Q$embed_file\E#$newname#gi;              my ($options,$onclick);
                 }              if (($canpaste) && (!$areachange) && (!$othercourse) &&
             }                  ($env{'docs.markedcopy_cmd_'.$suffix} eq 'cut')) {
         } else {                  if (($is_uploaded_map) ||
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";                      ($url =~ /(bulletinboard|smppg)$/) ||
         }                      ($url =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
     }                      $options = &paste_options($suffix,$is_uploaded_map,$parent);
     return;                      $onclick= 'onclick="showOptions(this,'."'$suffix'".');" ';
 }                  }
               }
 sub store_template {              $pasteitems .= '<label><input type="checkbox" name="pasting" id="pasting_'.$suffix.'" value="'.$suffix.'" '.$onclick.'/>'.$buffer.'</label>';
     my ($contents,$tempexport,$count,$content_type) = @_;              if ($nopaste) {
     if ($contents) {                   $pasteitems .= $nopaste;   
         if ($tempexport) {              } else {
             if (!-e $tempexport.'/resources') {                  if ($othercrs) {
                 mkdir($tempexport.'/resources',0700);                      $pasteitems .= $othercrs;
             }                  }
             if (!-e $tempexport.'/resources/'.$count) {                  if ($options) {
                 mkdir($tempexport.'/resources/'.$count,0700);                      $pasteitems .= $options;
             }                  }
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';              }
             my $storetemplate;              $pasteitems .= '</div>';
             if ($storetemplate = Apache::File->new('>'.$destination)) {          }
                 print $storetemplate $contents;      }
                 close($storetemplate);      if ($pasteitems eq '') {
             }          &Apache::lonnet::delenv('docs.markedcopies');
             if ($content_type eq 'external') {      }
                 return 'resources/'.$count.'/'.$content_type.'.html';      my ($pasteform,$form_start,$buttons,$form_end);
             } else {      if ($pasteitems) {
                 return 'resources/'.$count.'/'.$content_type.'.xml';          $pasteitems .= '<div style="padding:0;clear:both;margin:0;border:0"></div>';
             }          $form_start = '<form name="pasteform" action="/adm/coursedocs" method="post" onsubmit="return validateClipboard();">';
         }          if (@pasteable) {
     }              $buttons = '<input type="submit" name="pastemarked" value="'.&mt('Paste selected').'" />'.('&nbsp;'x2);
 }          }
           $buttons .= '<input type="submit" name="clearmarked" value="'.&mt('Clear selected').'" />'.
                       '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 sub group_import {          $form_end = '</form>';
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;      } else {
           $pasteitems = &mt('Clipboard is empty');
     while (@files) {      }
  my ($name, $url, $residx) = @{ shift(@files) };      $r->print($form_start
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})               .'<fieldset>'
      && ($caller eq 'londocs')               .'<legend>'.&mt('Clipboard').('&nbsp;' x2).$buttons.'</legend>'
      && (!&Apache::lonnet::stat_file($url))) {               .$pasteitems
                    .'</fieldset>'
             my $errtext = '';               .$form_end);
             my $fatal = 0;  }
             my $newmapstr = '<map>'."\n".  
                             '<resource id="1" src="" type="start"></resource>'."\n".  sub paste_options {
                             '<link from="1" to="2" index="1"></link>'."\n".      my ($suffix,$is_uploaded_map,$parent) = @_;
                             '<resource id="2" src="" type="finish"></resource>'."\n".      my ($copytext,$movetext);
                             '</map>';      if ($is_uploaded_map) {
             $env{'form.output'}=$newmapstr;          $copytext = &mt('Copy to new folder');
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,          $movetext = &mt('Move old');
                                                 'output',$1.$2);      } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /bulletinboard$/) {
             if ($result != m|^/uploaded/|) {          $copytext = &mt('Copy to new board');
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';          $movetext = &mt('Move (not posts)');
                 $fatal = 2;      } elsif ($env{'docs.markedcopy_url_'.$suffix} =~ /smppg$/) {
             }          $copytext = &mt('Copy to new page');
             if ($fatal) {          $movetext = &mt('Move');
                 return ($errtext,$fatal);      } else {
             }          $copytext = &mt('Copy to new file');
         }          $movetext = &mt('Move');
  if ($url) {      }
     if (!$residx      my $output = '<br />'.
  || defined($LONCAPA::map::zombies[$residx])) {                   '<span id="pasteoptionstext_'.$suffix.'" class="LC_fontsize_small LC_nobreak"></span>'.
  $residx = &LONCAPA::map::getresidx($url,$residx);                   '<div id="pasteoptions_'.$suffix.'" class="LC_dccid" style="display:none;"><span class="LC_nobreak">'.('&nbsp;'x 4).
  push(@LONCAPA::map::order, $residx);                   '<label>'.
     }                   '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="new" checked="checked" />'.
     my $ext = 'false';                   $copytext.'</label></span>'.('&nbsp;'x2).' '.
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }                   '<span class="LC_nobreak"><label>'.
     $url  = &LONCAPA::map::qtunescape($url);                   '<input type="radio" name="docs.markedcopy_options_'.$suffix.'" value="move" />'.
     $name = &LONCAPA::map::qtunescape($name);                   $movetext.'</label></span>';
     $LONCAPA::map::resources[$residx] =      if (($is_uploaded_map) && ($env{'docs.markedcopy_nested_'.$suffix})) {
  join(':', ($name, $url, $ext, 'normal', 'res'));          $output .= '<br /><fieldset><legend>'.&mt('Folder to paste contains sub-folders').
  }                     '</legend><table border="0">';
     }          my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);          my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames_'.$suffix});
 }          my $lastdir = $parent;
           my %depths = (
 sub breadcrumbs {                         $lastdir => 0,
     my ($where,$allowed,$type)=@_;                       );
     &Apache::lonhtmlcommon::clear_breadcrumbs();          my (%display,%deps);
     my (@folders);          for (my $i=0; $i<@pastemaps; $i++) {
     if ($env{'form.pagepath'}) {              ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
         @folders = split('&',$env{'form.pagepath'});              my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
     } else {              my @subfolders = split(/,/,$subfolderstr);
         @folders=split('&',$env{'form.folderpath'});              $deps{$lastdir} = \@subfolders;
     }              my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
     my $folderpath;              my $depth = $depths{$lastdir} + 1;
     my $cpinfo='';              my $offset = int($depth * 4);
     my $plain='';              my $indent = ('&nbsp;' x $offset);
     my $randompick=-1;              for (my $j=0; $j<@subfolders; $j++) {
     my $isencrypted=0;                  $depths{$subfolders[$j]} = $depth;
     my $ishidden=0;                  $display{$subfolders[$j]} =
     my $is_random_order=0;                      '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
     while (@folders) {                      '<td><label>'.
  my $folder=shift(@folders);                      '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
     my $foldername=shift(@folders);                      '<label>'.
  if ($folderpath) {$folderpath.='&';}                      '<input type="radio" name="docs.markedcopy_'.$suffix.'_'.$subfolders[$j].'" value="move" />'.
  $folderpath.=$folder.'&'.$foldername;                      &mt('Move old').'</label>'.
  my $url='/adm/coursedocs?folderpath='.                      '</td></tr>';
     &escape($folderpath);               }
     my $name=&unescape($foldername);          }
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername          &recurse_print(\$output,$parent,\%deps,\%display);
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;          $output .= '</table></fieldset>';
     if ($1 ne '') {      }
                $randompick=$1;      $output .= '</div>';
             } else {      return $output;
                $randompick=-1;  }
             }  
             if ($2) { $ishidden=1; }  sub recurse_print {
             if ($3) { $isencrypted=1; }      my ($outputref,$dir,$deps,$display) = @_;
     if ($4 ne '') { $is_random_order = 1; }      $$outputref .= $display->{$dir}."\n";
             if ($folder eq 'supplemental') {      if (ref($deps->{$dir}) eq 'ARRAY') {
                 if ($allowed) {          foreach my $subdir (@{$deps->{$dir}}) {
                     $name = &mt('Supplemental '.$type.' Documents');              &recurse_print($outputref,$subdir,$deps,$display);
                 } else {          }
                     $name = &mt($type.' Documents');      }
                 }  }
             }  
     &Apache::lonhtmlcommon::add_breadcrumb(  sub supp_pasteable {
       {'href'=>$url.$cpinfo,      my ($url) = @_;
        'title'=>$name,      if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
        'text'=>'<font size="+1">'.          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
    $name.'</font>',          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
        'no_mt'=>1,          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
        });          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
  $plain.=$name.' &gt; ';          return 1;
     }      }
     $plain=~s/\&gt\;\s*$//;      return;
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',  }
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);  
 }  sub paste_popup_js {
       my %lt = &Apache::lonlocal::texthash(
 sub log_docs {                                            show => 'Show Options',
     return &Apache::lonnet::instructor_log('docslog',@_);                                            hide => 'Hide Options',
 }                                            none => 'No items selected from clipboard.',
                                           );
 {      return <<"END";
     my @oldresources=();  
     my @oldorder=();  function showPasteOptions(suffix) {
     my $parmidx;      document.getElementById('pasteoptions_'+suffix).style.display='block';
     my %parmaction=();      document.getElementById('pasteoptionstext_'+suffix).innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:hidePasteOptions(\\''+suffix+'\\');" class="LC_menubuttons_link">$lt{'hide'}</a>';
     my %parmvalue=();      return;
     my $changedflag;  }
   
     sub snapshotbefore {  function hidePasteOptions(suffix) {
         @oldresources=@LONCAPA::map::resources;      document.getElementById('pasteoptions_'+suffix).style.display='none';
         @oldorder=@LONCAPA::map::order;      document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
         $parmidx=undef;      return;
         %parmaction=();  }
         %parmvalue=();  
         $changedflag=0;  function showOptions(caller,suffix) {
     }      if (document.getElementById('pasteoptionstext_'+suffix)) {
           if (caller.checked) {
     sub remember_parms {              document.getElementById('pasteoptionstext_'+suffix).innerHTML ='&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:showPasteOptions(\\''+suffix+'\\')" class="LC_menubuttons_link">$lt{'show'}</a>';
         my ($idx,$parameter,$action,$value)=@_;          } else {
         $parmidx=$idx;              document.getElementById('pasteoptionstext_'+suffix).innerHTML ='';
         $parmaction{$parameter}=$action;          }
         $parmvalue{$parameter}=$value;          if (document.getElementById('pasteoptions_'+suffix)) {
         $changedflag=1;              document.getElementById('pasteoptions_'+suffix).style.display='none';
     }          }
       }
     sub log_differences {      return;
         my ($plain)=@_;  }
         my %storehash=('folder' => $plain,  
                        'currentfolder' => $env{'form.folder'});  function validateClipboard() {
         if ($parmidx) {      var numchk = 0;
            $storehash{'parameter_res'}=$oldresources[$parmidx];      if (document.pasteform.pasting.length > 1) {
            foreach my $parm (keys(%parmaction)) {          for (var i=0; i<document.pasteform.pasting.length; i++) {
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};              if (document.pasteform.pasting[i].checked) {
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};                  numchk ++;
            }              }
         }          }
         my $maxidx=$#oldresources;      } else {
         if ($#LONCAPA::map::resources>$#oldresources) {          if (document.pasteform.pasting.type == 'checkbox') {
            $maxidx=$#LONCAPA::map::resources;              if (document.pasteform.pasting.checked) {
         }                  numchk ++; 
         for (my $idx=0; $idx<=$maxidx; $idx++) {              } 
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {          }
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];      }
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];      if (numchk > 0) { 
               $changedflag=1;          return true;
            }      } else {
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {          alert("$lt{'none'}");
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];          return false;
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];      }
               $changedflag=1;  }
            }  
         }  END
  $storehash{'maxidx'}=$maxidx;  
         if ($changedflag) { &log_docs(\%storehash); }  }
     }  
 }  sub do_paste_from_buffer {
       my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
   
   # Array of items in paste buffer
       my (@currpaste,%pastebuffer,%allerrors);
       @currpaste = split(/,/,$env{'docs.markedcopies'});
 sub docs_change_log {  
     my ($r)=@_;  # Early out if paste buffer is empty
     my $folder=$env{'form.folder'};      if (@currpaste == 0) {
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));          return ();
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));      } 
     my %docslog=&Apache::lonnet::dump('nohist_docslog',      map { $pastebuffer{$_} = 1; } @currpaste;
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},  
                                       $env{'course.'.$env{'request.course.id'}.'.num'});  # Array of items selected items to paste
       my @reqpaste = &Apache::loncommon::get_env_multiple('form.pasting');
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }  
   # Early out if nothing selected to paste
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.      if (@reqpaste == 0) {
               '<input type="hidden" name="docslog" value="1" />');          return();
       }
     my %saveable_parameters = ('show' => 'scalar',);      my @topaste;
     &Apache::loncommon::store_course_settings('docs_log',      foreach my $suffix (@reqpaste) {
                                               \%saveable_parameters);          next if ($suffix =~ /\D/);
     &Apache::loncommon::restore_course_settings('docs_log',          next unless (exists($pastebuffer{$suffix}));
                                                 \%saveable_parameters);          push(@topaste,$suffix);
     if (!$env{'form.show'}) { $env{'form.show'}=10; }      }
     my %lt=('hiddenresource' => 'Resources hidden',  
     'encrypturl'     => 'URL hidden',  # Early out if nothing available to paste
     'randompick'     => 'Randomly pick',      if (@topaste == 0) {
     'randomorder'    => 'Randomly ordered',          return();
     'set'            => 'set to',      }
     'del'            => 'deleted');  
     $r->print(&Apache::loncommon::display_filter().      my (%msgs,%before,%after,@dopaste,%is_map,%notinsupp,%notincrs,%duplicate,
               '<input type="hidden" name="folder" value="'.$folder.'" />'.          %prefixchg,%srcdom,%srcnum,%marktomove,$save_err,$lockerrors,$allresult,
               '<input type="submit" value="'.&mt('Display').'" /></form>');          %msgs);
     $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>'.      foreach my $suffix (@topaste) {
               &mt('After').'</th>'.          my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
               &Apache::loncommon::end_data_table_header_row());  # Supplemental content may only include certain types of content
     my $shown=0;  # Early out if pasted content is not supported in Supplemental area
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {          if ($folder =~ /^supplemental/) {
  if ($env{'form.displayfilter'} eq 'currentfolder') {              unless (&supp_pasteable($url)) {
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }                  $notinsupp{$suffix} = 1;
  }                  next;
         my @changes=keys(%{$docslog{$id}{'logentry'}});              }
         if ($env{'form.displayfilter'} eq 'containing') {          }
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.          if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/}) {
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});              my $srcd = $1;
     foreach my $key (@changes) {              my $srcn = $2;
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};  # When paste buffer was populated using an active role in a different course
     }  # check for mdc privilege in the course from which the resource was pasted
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }                      if (($srcd ne $coursedom) || ($srcn ne $coursenum)) {
  }                  unless ($env{"user.priv.cm./$srcd/$srcn"} =~ /\Q:mdc&F\E/) {
         my $count = 0;                      $notincrs{$suffix} = 1;
         my $time =                      next;
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});                  }
         my $plainname =              }
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},              $srcdom{$suffix} = $srcd;
                                           $docslog{$id}{'exe_udom'});              $srcnum{$suffix} = $srcn;
         my $about_me_link =          }
             &Apache::loncommon::aboutmewrapper($plainname,  
                                                $docslog{$id}{'exe_uname'},          push(@dopaste,$suffix);
                                                $docslog{$id}{'exe_udom'});          if ($url=~/\.(page|sequence)$/) {
         my $send_msg_link='';              $is_map{$suffix} = 1; 
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})          }
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {  
             $send_msg_link ='<br />'.          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/([^/]+)}) {
                 &Apache::loncommon::messagewrapper(&mt('Send message'),              my $oldprefix = $1;
                                                    $docslog{$id}{'exe_uname'},  # When pasting content from Main Content to Supplemental Content and vice versa 
                                                    $docslog{$id}{'exe_udom'});  # URLs will contain different paths (which depend on whether pasted item is
         }  # a folder/page or a document.   
         $r->print(&Apache::loncommon::start_data_table_row());              if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
         $r->print('<td>'.$time.'</td>                  $prefixchg{$suffix} = 'docstosupp';
                        <td>'.$about_me_link.              } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.                  $prefixchg{$suffix} = 'supptodocs';
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.              }
                   $send_msg_link.'</td><td>'.  
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');  # If pasting an uploaded map, get list of contained uploaded maps.
 # Before              if ($env{'docs.markedcopy_nested_'.$suffix}) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  my @nested;
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                  my ($type) = ($oldprefix =~ /^(default|supplemental)/);
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];                  my @items = split(/\&/,$env{'docs.markedcopy_nested_'.$suffix});
     if ($oldname ne $newname) {                  my @deps = map { /\d+:([\d,]+$)/ } @items;
  $r->print(&LONCAPA::map::qtescape($oldname));                  foreach my $dep (@deps) {
     }                      if ($dep =~ /,/) {
  }                          push(@nested,split(/,/,$dep));
  $r->print('<ul>');                      } else {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                          push(@nested,$dep);
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {                      }
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');                  }
     }                  foreach my $item (@nested) {
  }                      if ($env{'form.docs.markedcopy_'.$suffix.'_'.$item} eq 'move') {
  $r->print('</ul>');                          push(@{$marktomove{$suffix}},$type.'_'.$item);
 # After                      }
         $r->print('</td><td>');                  }
               }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          }
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];      }
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];  
     if ($oldname ne '' && $oldname ne $newname) {  # Early out if nothing available to paste
  $r->print(&LONCAPA::map::qtescape($newname));      if (@dopaste == 0) {
     }          return ();
  }              }
  $r->print('<ul>');  
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {  # Populate message hash and hashes used for main content <=> supplemental content
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {  # changes    
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');  
     }      %msgs = &Apache::lonlocal::texthash (
  }                  notinsupp => 'Paste failed: content type is not supported within Supplemental Content',
  $r->print('</ul>');                  notincrs  => 'Paste failed: Item is from a different course which you do not have rights to edit.',
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {                  duplicate => 'Paste failed: only one instance of a particular published sequence or page is allowed within each course.',
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');              );
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {  
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {      %before = (
     $r->print('<li>'.                   docstosupp => {
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',                                     map => 'default',
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})                                     doc => 'docs',
       .'</li>');                                 },
  }                   supptodocs => {
     }                                     map => 'supplemental',
     $r->print('</ul>');                                     doc => 'supplemental',
  }                                 },
 # End                );
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());  
         $shown++;      %after = (
         if (!($env{'form.show'} eq &mt('all')                   docstosupp => {
               || $shown<=$env{'form.show'})) { last; }                                     map => 'supplemental',
     }                                     doc => 'supplemental'
     $r->print(&Apache::loncommon::end_data_table());                                 },
 }                   supptodocs => {
                                      map => 'default',
 sub update_paste_buffer {                                     doc => 'docs',
     my ($coursenum,$coursedom) = @_;                                 },
                );
     return if (!defined($env{'form.markcopy'}));  
     return if (!defined($env{'form.copyfolder'}));  # Retrieve information about all course maps in main content area 
     return if ($env{'form.markcopy'} < 0);  
       my $allmaps = {};
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,      if ($folder =~ /^default/) {
     $env{'form.copyfolder'});          $allmaps =
                  &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
     return if ($fatal);                                                   $env{"course.$env{'request.course.id'}.home"},
                                                    $env{'request.course.id'});
 # Mark for copying      }
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);  
     if (&is_supplemental_title($title)) {      my (@toclear,%mapurls,%lockerrs,%msgerrs,%results);
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});  
  ($title) = &parse_supplemental_title($title);  # Loop over the items to paste
     } elsif ($env{'docs.markedcopy_supplemental'}) {      foreach my $suffix (@dopaste) {
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');  # Maps need to be copied first
     }          my (%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};              %dbcopies,%zombies,%params,%docmoves,%mapmoves,%mapchanges,%newsubdir,
               %newurls,%tomove);
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,          if (ref($marktomove{$suffix}) eq 'ARRAY') {
     'docs.markedcopy_url'   => $url});              map { $tomove{$_} = 1; } @{$marktomove{$suffix}};
     delete($env{'form.markcopy'});          }
 }          my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url_'.$suffix});
           my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title_'.$suffix});
 sub print_paste_buffer {          my $oldurl = $url;
     my ($r,$container) = @_;          if ($is_map{$suffix}) {
     return if (!defined($env{'docs.markedcopy_url'}));  # If pasting a map, check if map contains other maps
               my (%hierarchy,%titles);
     $r->print(<<ENDPASTE);              &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>                                   \%addedmaps,\%hierarchy,\%titles,$allmaps);
 ENDPASTE              if ($url=~ m{^/uploaded/}) {
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');                  my $newurl;
                   unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
     my $type;                      ($newurl,my $error) = 
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {                          &get_newmap_url($url,$folder,$prefixchg{$suffix},$coursedom,
  $type = &mt('External Resource');                                          $coursenum,$srcdom{$suffix},$srcnum{$suffix},
  $r->print($type.': '.                                          \$title,$allmaps,\%newurls);
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.                      if ($error) {
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');                          $allerrors{$suffix} = $error;
     }  else {                          next;
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];                      }
  my $icon = &Apache::loncommon::icon($extension);                      if ($newurl ne '') {
  if ($extension eq 'sequence' &&                          if ($newurl ne $url) {
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {                              if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));                                  $newsubdir{$url} = $1;
     $icon .= '/folder_closed.gif';                              }
  }                              $mapchanges{$url} = 1;
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';                          }
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));                      }
     }                  }
     if ($container eq 'page') {                  if (($srcdom{$suffix} ne $coursedom) ||
  $r->print('                      ($srcnum{$suffix} ne $coursenum) ||
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />                      ($prefixchg{$suffix}) || (($newurl ne '') && ($newurl ne $url))) {
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />                      unless (&url_paste_fixups($url,$folder,$prefixchg{$suffix},
 ');                                                $coursedom,$coursenum,$srcdom{$suffix},
     } else {                                                $srcnum{$suffix},$allmaps,\%rewrites,
  $r->print('                                                \%retitles,\%copies,\%dbcopies,
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />                                                \%zombies,\%params,\%mapmoves,
 ');                                                \%mapchanges,\%tomove,\%newsubdir,
     }                                                \%newurls)) {
     $r->print('</p></form>');                          $mapmoves{$url} = 1;
 }                      }
                       $url = $newurl;
 sub do_paste_from_buffer {                  } elsif ($env{'docs.markedcopy_nested_'.$suffix}) {
     my ($coursenum,$coursedom,$folder) = @_;                      &url_paste_fixups($url,$folder,$prefixchg{$suffix},$coursedom,
                                         $coursenum,$srcdom{$suffix},$srcnum{$suffix},
     if (!$env{'form.pastemarked'}) {                                        $allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
         return;                                        \%zombies,\%params,\%mapmoves,\%mapchanges,
     }                                        \%tomove,\%newsubdir,\%newurls); 
                   }
 # paste resource to end of list              } elsif ($url=~m {^/res/}) {
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});  # published map can only exists once, so remove from paste buffer when done
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});                  push(@toclear,$suffix);
 # Maps need to be copied first  # if pasting published map (main content area only) check map not already in course
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {                  if ($folder =~ /^default/) {
  $title=&mt('Copy of').' '.$title;                      if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
  my $newid=$$.int(rand(100)).time;                          $duplicate{$suffix} = 1; 
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);                          next;
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {                      }
             my $path = $1;                  }
             my $prefix = $2;              }
             my $ancestor = $3;          }
             if (length($ancestor) > 10) {          if ($url=~ m{/(bulletinboard|smppg)$}) {
                 $ancestor = substr($ancestor,-10,10);              my $prefix = $1;
             }              #need to copy the db contents to a new one, unless this is a move.
             $oldid = $path.$prefix.$ancestor;              my %info = (
         }                           src  => $url,
         my $counter = 0;                           cdom => $coursedom,
         my $newurl=$oldid.$newid.'.'.$ext;                           cnum => $coursenum,
         my $is_unique = &uniqueness_check($newurl);              );
         while (!$is_unique && $counter < 100) {              unless ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
             $counter ++;                  my (%lockerr,$msg); 
             $newid ++;                  my ($newurl,$result,$errtext) =
             $newurl = $oldid.$newid;                      &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
             $is_unique = &uniqueness_check($newurl);                  if ($result eq 'ok') {
         }                      $url = $newurl;
         if (!$is_unique) {                      $title=&mt('Copy of').' '.$title;
             if ($url=~/\.page$/) {                  } else {
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');                      if ($prefix eq 'smppg') {
             } else {                          $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');                      } elsif ($prefix eq 'bulletinboard') {
             }                          $msg = &mt('Paste failed: An error occurred when copying the bulletin board.').' '.$errtext;
         }                      }
  my $storefn=$newurl;                      $results{$suffix} = $result;
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};                      $msgerrs{$suffix} = $msg;
  my $paste_map_result =                      $lockerrs{$suffix} = $lockerr{$prefix}; 
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,                      next;
        &Apache::lonnet::getfile($url));          }
         if ($paste_map_result eq '/adm/notfound.html') {                  if ($lockerr{$prefix}) {
             if ($url=~/\.page$/) {                      $lockerrs{$suffix} = $lockerr{$prefix};
                 return &mt('Paste failed: an error occurred saving the composite page');                  }
             } else {              }
                 return &mt('Paste failed: an error occurred saving the folder');          }
             }          $title = &LONCAPA::map::qtunescape($title);
         }          my $ext='false';
  $url = $newurl;          if ($url=~m{^http(|s)://}) { $ext='true'; }
     }          if ($env{'docs.markedcopy_supplemental_'.$suffix}) {
 # published maps can only exists once, so remove it from paste buffer when done              if ($folder !~ /^supplemental/) {
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {                  (undef,undef,$title) =
  &Apache::lonnet::delenv('docs\\.markedcopy');                      &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental_'.$suffix});
     }              }
     if ($url=~ m{/smppg$}) {          } else {
  my $db_name = &Apache::lonsimplepage::get_db_name($url);              if ($folder=~/^supplemental/) {
  if ($db_name =~ /^smppage_/) {                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     #simple pages, need to copy the db contents to a new one.                         $env{'user.domain'}.'___&&&___'.$title;
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);              }
     my $now = time();          }
     $db_name =~ s{_\d*$ }{_$now}x;  
     my $result=&Apache::lonnet::put($db_name,\%contents,  # For uploaded files (excluding pages/sequences) path in copied file is changed
     $coursedom,$coursenum);  # if paste is from Main to Supplemental (or vice versa), or if pasting between
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;  # courses.
     $title=&mt('Copy of').' '.$title;  
  }          unless ($is_map{$suffix}) {
     }              my $newidx;
     $title = &LONCAPA::map::qtunescape($title);  # Now insert the URL at the bottom
     my $ext='false';              $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
     if ($url=~m{^http(|s)://}) { $ext='true'; }              if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
     $url       = &LONCAPA::map::qtunescape($url);                  my $relpath = $1;
 # Now insert the URL at the bottom                  if ($relpath ne '') {
     my $newidx = &LONCAPA::map::getresidx($url);                      my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
     if ($env{'docs.markedcopy_supplemental'}) {                      my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
         if ($folder =~ /^supplemental/) {                      my $newprefix = $newloc;
             $title = $env{'docs.markedcopy_supplemental'};                      if ($newloc eq 'default') {
         } else {                          $newprefix = 'docs';
             (undef,undef,$title) =                      }
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});                      if ($newdocsdir eq '') {
         }                          $newdocsdir = 'default';
     } else {                      }
         if ($folder=~/^supplemental/) {                      if (($prefixchg{$suffix}) ||
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                          ($srcdom{$suffix} ne $coursedom) || 
                   $env{'user.domain'}.'___&&&___'.$title;                          ($srcnum{$suffix} ne $coursenum) ||
         }                          ($env{'form.docs.markedcopy_options_'.$suffix} ne 'move')) {
     }                          my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
                           $url =
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';                              &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
     push(@LONCAPA::map::order, $newidx);                                                                 &Apache::lonnet::getfile($oldurl));
     return 'ok';                          if ($url eq '/adm/notfound.html') {
 # Store the result                              $msgs{$suffix} = &mt('Paste failed: an error occurred saving the file.');
 }                              next;
                           } else {
 sub uniqueness_check {                              my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
     my ($newurl) = @_;                              $newsubpath =~ s{/+$}{/};
     my $unique = 1;                              $docmoves{$oldurl} = $newsubpath;
     foreach my $res (@LONCAPA::map::order) {                          }
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                      }
         $url=&LONCAPA::map::qtescape($url);                  }
         if ($newurl eq $url) {              }
             $unique = 0;              $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
             last;                                                    ':'.$ext.':normal:res';
         }              push(@LONCAPA::map::order,$newidx);
     }  # Store the result
     return $unique;              my ($errtext,$fatal) =
 }                  &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
               if ($fatal) {
 my %parameter_type = ( 'randompick'     => 'int_pos',                  $save_err .= $errtext;
        'hiddenresource' => 'string_yesno',                  $allresult = 'fail';
        'encrypturl'     => 'string_yesno',              }
        'randomorder'    => 'string_yesno',);          }
 my $valid_parameters_re = join('|',keys(%parameter_type));  
 # set parameters  # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
 sub update_parameter {          unless ($allresult eq 'fail') {
               my %updated = (
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);                              rewrites      => \%rewrites,
                               zombies       => \%zombies,
     my $which = $env{'form.changeparms'};                              removefrommap => \%removefrommap,
     my $idx = $env{'form.setparms'};                              removeparam   => \%removeparam,
     if ($env{'form.'.$which.'_'.$idx}) {                              dbcopies      => \%dbcopies,
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}                              retitles      => \%retitles,
                                      : 'yes';                            );
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,              my %info = (
       $parameter_type{$which});                             newsubdir => \%newsubdir,
  &remember_parms($idx,$which,'set',$value);                             params    => \%params,
     } else {                         );
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);              if ($prefixchg{$suffix}) {
                   $info{'before'} = $before{$prefixchg{$suffix}};
  &remember_parms($idx,$which,'del');                  $info{'after'} = $after{$prefixchg{$suffix}};
     }              }
     return 1;              my %moves = (
 }                             copies   => \%copies,
                              docmoves => \%docmoves,
                              mapmoves => \%mapmoves,
 sub handle_edit_cmd {                          );
     my ($coursenum,$coursedom) =@_;              (my $result,$msgs{$suffix},my $lockerror) =
                   &apply_fixups($folder,$is_map{$suffix},$coursedom,$coursenum,$errors,
     my ($cmd,$idx)=split('_',$env{'form.cmd'});                                \%updated,\%info,\%moves,$prefixchg{$suffix},$oldurl,
                                 $url,'paste');
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];              $lockerrors .= $lockerror;
     my ($title, $url, @rrest) = split(':', $ratstr);              if ($result eq 'ok') {
                   if ($is_map{$suffix}) {
     if ($cmd eq 'del') {                      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&                                                      $folder.'.'.$container);
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {                      if ($fatal) {
     &Apache::lonnet::removeuploadedurl($url);                          $allresult = 'failread';
  } else {                      } else {
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                          if ($#LONCAPA::map::order<1) {
  }                              my $idx=&LONCAPA::map::getresidx();
  splice(@LONCAPA::map::order, $idx, 1);                              if ($idx<=0) { $idx=1; }
                               $LONCAPA::map::order[0]=$idx;
     } elsif ($cmd eq 'cut') {                              $LONCAPA::map::resources[$idx]='';
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                          }
  splice(@LONCAPA::map::order, $idx, 1);                          my $newidx = &LONCAPA::map::getresidx(&LONCAPA::map::qtunescape($url));
                           $LONCAPA::map::resources[$newidx]=$title.':'.&LONCAPA::map::qtunescape($url).
     } elsif ($cmd eq 'up'                                                            ':'.$ext.':normal:res';
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {                          push(@LONCAPA::map::order,$newidx);
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];  
   # Store the result
     } elsif ($cmd eq 'down'                          my ($errtext,$fatal) = 
      && defined($LONCAPA::map::order[$idx+1])) {                              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];                          if ($fatal) {
                               $save_err .= $errtext;
     } elsif ($cmd eq 'rename') {                              $allresult = 'failstore';
                           }
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});                      } 
  if ($comment=~/\S/) {                  }
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=                  if ($env{'form.docs.markedcopy_options_'.$suffix} eq 'move') {
  $comment.':'.join(':', $url, @rrest);                       push(@toclear,$suffix);
  }                  }
 # Devalidate title cache              }
  my $renamed_url=&LONCAPA::map::qtescape($url);          }
  &Apache::lonnet::devalidate_title_cache($renamed_url);      }
     } else {      &clear_from_buffer(\@toclear,\@currpaste);
  return 0;      my $msgsarray;
     }      foreach my $suffix (keys(%msgs)) {
     return 1;           if (ref($msgs{$suffix}) eq 'ARRAY') {
 }               $msgsarray .= join(',',@{$msgs{$suffix}});
            }
 sub editor {      }
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;      return ($allresult,$save_err,$msgsarray,$lockerrors);
   }
     my $container= ($env{'form.pagepath'}) ? 'page'  
                            : 'sequence';  sub do_buffer_empty {
       my @currpaste = split(/,/,$env{'docs.markedcopies'});
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,      if (@currpaste == 0) {
     $folder.'.'.$container);          return &mt('Clipboard is already empty');
     return $errtext if ($fatal);      }
       my @toclear = &Apache::loncommon::get_env_multiple('form.pasting');
     if ($#LONCAPA::map::order<1) {      if (@toclear == 0) {
  my $idx=&LONCAPA::map::getresidx();          return &mt('Nothing selected to clear from clipboard');
  if ($idx<=0) { $idx=1; }      }
         $LONCAPA::map::order[0]=$idx;      my $numdel = &clear_from_buffer(\@toclear,\@currpaste);
         $LONCAPA::map::resources[$idx]='';      if ($numdel) {
     }          return &mt('[quant,_1,item] cleared from clipboard',$numdel);
          } else {
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=          return &mt('Clipboard unchanged');
  &breadcrumbs($folder,$allowed,$type);      }
     $r->print($breadcrumbtrail);      return;
      }
 # ------------------------------------------------------------ Process commands  
   sub clear_from_buffer {
 # ---------------- if they are for this folder and user allowed to make changes      my ($toclear,$currpaste) = @_;
     if (($allowed) && ($env{'form.folder'} eq $folder)) {      return unless ((ref($toclear) eq 'ARRAY') && (ref($currpaste) eq 'ARRAY'));
 # set parameters and change order      my %pastebuffer;
  &snapshotbefore();      map { $pastebuffer{$_} = 1; } @{$currpaste};
       my $numdel = 0;
  if (&update_parameter()) {      foreach my $suffix (@{$toclear}) {
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          next if ($suffix =~ /\D/);
     return $errtext if ($fatal);          next unless (exists($pastebuffer{$suffix}));
  }          my $regexp = 'docs.markedcopy_[a-z]+_'.$suffix;
           if (&Apache::lonnet::delenv($regexp,1) eq 'ok') {
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {              delete($pastebuffer{$suffix});
 # change order              $numdel ++;
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);          }
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);      }
       my $newbuffer = join(',',sort(keys(%pastebuffer)));
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      &Apache::lonnet::appenv({'docs.markedcopies' => $newbuffer});
     return $errtext if ($fatal);      return $numdel;
  }  }
       
  if ($env{'form.pastemarked'}) {  sub get_newmap_url {
             my $paste_res =      my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);          $titleref,$allmaps,$newurls) = @_;
             if ($paste_res eq 'ok') {      my $newurl;
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);      if ($url=~ m{^/uploaded/}) {
                 return $errtext if ($fatal);          $$titleref=&mt('Copy of').' '.$$titleref;
             } elsif ($paste_res ne '') {      }
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');      my $now = time;
             }      my $suffix=$$.int(rand(100)).$now;
  }      my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
       if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
  $r->print($upload_output);          my $path = $1;
           my $prefix = $2;
  if (&handle_edit_cmd()) {          my $ancestor = $3;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          if (length($ancestor) > 10) {
     return $errtext if ($fatal);              $ancestor = substr($ancestor,-10,10);
  }          }
 # Group import/search          my $newid;
  if ($env{'form.importdetail'}) {          if ($prefixchg) {
     my @imports;              if ($folder =~ /^supplemental/) {
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {                  $prefix =~ s/^default/supplemental/;
  if (defined($item)) {              } else {
     my ($name,$url,$residx)=                  $prefix =~ s/^supplemental/default/;
  map {&unescape($_)} split(/\=/,$item);              }
     push(@imports, [$name, $url, $residx]);          }
  }          if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
     }              $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,          } else {
     $container,'londocs',@imports);              $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
     return $errtext if ($fatal);          }
  }          my $counter = 0;
 # Loading a complete map          my $is_unique = &uniqueness_check($newurl);
  if ($env{'form.loadmap'}) {          if ($folder =~ /^default/) {
     if ($env{'form.importmap'}=~/\w/) {              if ($allmaps->{$newurl}) {
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {                  $is_unique = 0;
     my ($title,$url,$ext,$type)=split(/\:/,$res);              }
     my $idx=&LONCAPA::map::getresidx($url);          }
     $LONCAPA::map::resources[$idx]=$res;          while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;              $counter ++;
  }              $suffix ++;
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,              if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
     $folder.'.'.$container);                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
  return $errtext if ($fatal);              } else {
     } else {                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');              }
               $is_unique = &uniqueness_check($newurl);
     }          }
  }          if ($is_unique) {
  &log_differences($plain);              $newurls->{$newurl} = 1;
     }          } else {
 # ---------------------------------------------------------------- End commands              if ($url=~/\.page$/) {
 # ---------------------------------------------------------------- Print screen                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
     my $idx=0;              } else {
     my $shown=0;                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {              }
  $r->print('<p>'.&mt('Parameters').':<ul>'.          }
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').      }
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').      return ($newurl);
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').  }
   '</ul></p>');  
     }                                                                                                      sub dbcopy {
     if ($randompick>=0) {      my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
  $r->print('<p>'.&mt('Caution: this folder is set to randomly pick a subset of resources. Adding or removing resources from this folder will change the set of resources that the students see, resulting in spurious or missing credit for completed problems, not limited to ones you modify. Do not modify the contents of this folder if it is in active student use.').'</p>');      my ($url,$result,$errtext);
     }      my $url = $dbref->{'src'};
     if ($is_random_order) {      if (ref($dbref) eq 'HASH') {
  $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');          if ($url =~ m{/(smppg|bulletinboard)$}) {
     }              my $prefix = $1;
     $r->print('<table class="LC_docs_editor">');              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
     foreach my $res (@LONCAPA::map::order) {                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                  my $db_name;
  $name=&LONCAPA::map::qtescape($name);                  my $marker = (split(m{/},$url))[4];
  $url=&LONCAPA::map::qtescape($url);                  $marker=~s/\D//g;
  unless ($name) {  $name=(split(/\//,$url))[-1]; }                  if ($dbref->{'src'} =~ m{/smppg$}) {
  unless ($name) { $idx++; next; }                      $db_name =
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,                          &Apache::lonsimplepage::get_db_name($url,$marker,
      $coursenum));                                                              $dbref->{'cdom'},
  $idx++;                                                              $dbref->{'cnum'});
  $shown++;                  } else {
     }                      $db_name = 'bulletinpage_'.$marker;
     unless ($shown) {                  }
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');                  my ($suffix,$freedlock,$error) =
     }                      &Apache::lonnet::get_timebased_id($prefix,'num','templated',
     $r->print("\n</table>\n");                                                        $coursedom,$coursenum,
     if ($allowed) {                                                        'concat');
         &print_paste_buffer($r,$container);                  if (!$suffix) {
     }                      if ($prefix eq 'smppg') {
     return;                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
 }                      } else {
                           $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a bulletin board [_1].',$url);
 sub process_file_upload {                      }
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;                      if ($error) {
 # upload a file, if present                          $errtext .= '<br />'.$error;
     my $parseaction;                      }
    if ($env{'form.parserflag'}) {                  } else {
         $parseaction = 'parse';                      #need to copy the db contents to a new one.
     }                      my %contents=&Apache::lonnet::dump($db_name,
     my $phase_status;                                                         $dbref->{'cdom'},
     my $folder=$env{'form.folder'};                                                         $dbref->{'cnum'});
     if ($folder eq '') {                      if (exists($contents{'uploaded.photourl'})) {
         $folder='default';                          my $photo = $contents{'uploaded.photourl'};
     }                          my ($subdir,$fname) =
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {                              ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
         my $errtext='';                          my $newphoto;
         my $fatal=0;                          if ($fname ne '') {
         my $container='sequence';                              my $content = &Apache::lonnet::getfile($photo);
         if ($env{'form.pagepath'}) {                              unless ($content eq '-1') {
             $container='page';                                  $env{'form.'.$suffix.'.photourl'} = $content;
         }                                  $newphoto =
         ($errtext,$fatal)=                                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                                  delete($env{'form.'.$suffix.'.photourl'});
         if ($#LONCAPA::map::order<1) {                              }
             $LONCAPA::map::order[0]=1;                          }
             $LONCAPA::map::resources[1]='';                          if ($newphoto =~ m{^/uploaded/}) {
         }                              $contents{'uploaded.photourl'} = $newphoto;
         if ($fatal) {                          }
             return 'failed';                      }
         }                      $db_name =~ s{_\d*$ }{_$suffix}x;
         my $destination = 'docs/';                      $result=&Apache::lonnet::put($db_name,\%contents,
         if ($folder =~ /^supplemental/) {                                                   $coursedom,$coursenum);
             $destination = 'supplemental/';                      if ($result eq 'ok') {
         }                          $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
         if (($folder eq 'default') || ($folder eq 'supplemental')) {                      }
             $destination .= 'default/';                  }
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {                  if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
             $destination .=  $2.'/';                      $lockerrorsref->{$prefix} =
         }                          '<div class="LC_error">'.
 # this is for a course, not a user, so set coursedoc flag                          &mt('There was a problem removing a lockfile.');
 # probably the only place in the system where this should be "1"                      if ($prefix eq 'smppg') {
         my $newidx=&LONCAPA::map::getresidx();                          $lockerrorsref->{$prefix} .=
         $destination .= $newidx;                              ' '.&mt('This will prevent creation of additional simple pages in this course.');
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,                      } else {
  $parseaction,$allfiles,                          $lockerrorsref->{$prefix} .= ' '.&mt('This will prevent creation of additional bulletin boards in this course.');
  $codebase);                      }
         my $ext='false';                      $lockerrorsref->{$prefix} .= ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
         if ($url=~m{^http://}) { $ext='true'; }                                                       '<a href="/adm/helpdesk" target="_helpdesk">','</a>').
  $url     = &LONCAPA::map::qtunescape($url);                                                   '</div>';
         my $comment=$env{'form.comment'};                  }
  $comment = &LONCAPA::map::qtunescape($comment);              }
         if ($folder=~/^supplemental/) {          } elsif ($url =~ m{/syllabus$}) {
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
                   $env{'user.domain'}.'___&&&___'.$comment;                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
         }                  if (($dbref->{'cdom'} ne $coursedom) ||
                       ($dbref->{'cnum'} ne $coursenum)) {
         $LONCAPA::map::resources[$newidx]=                      my %contents=&Apache::lonnet::dump('syllabus',
     $comment.':'.$url.':'.$ext.':normal:res';                                                         $dbref->{'cdom'},
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;                                                         $dbref->{'cnum'});
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,                      $result=&Apache::lonnet::put('syllabus',\%contents,
     $folder.'.'.$container);                                                   $coursedom,$coursenum);
         if ($fatal) {                  }
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';              }
             return 'failed';          }
         } else {      }
             if ($parseaction eq 'parse') {      return ($url,$result,$errtext);
                 my $total_embedded = keys(%{$allfiles});  }
                 if ($total_embedded > 0) {  
                     my $num = 0;  sub uniqueness_check {
     my $state = '      my ($newurl) = @_;
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />      my $unique = 1;
    <input type="hidden" name="cmd" value="upload_embedded" />      foreach my $res (@LONCAPA::map::order) {
    <input type="hidden" name="newidx" value="'.$newidx.'" />          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />          $url=&LONCAPA::map::qtescape($url);
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';          if ($newurl eq $url) {
     $phase_status = 'phasetwo';              $unique = 0;
               last;
                     $$upload_output .=          }
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.      }
  &Apache::loncommon::ask_for_embedded_content(      return $unique;
                             '/adm/coursedocs',$state,$allfiles,$codebase);  }
                 } else {  
                     $$upload_output .= 'No embedded items identified<br />';  sub contained_map_check {
                 }      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
             }          $allmaps) = @_;
         }      my $content = &Apache::lonnet::getfile($url);
     }      unless ($content eq '-1') {
     return $phase_status;          my $parser = HTML::TokeParser->new(\$content);
 }          $parser->attr_encoded(1);
           while (my $token = $parser->get_token) {
 sub process_secondary_uploads {              next if ($token->[0] ne 'S');
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;              if ($token->[1] eq 'resource') {
     my $folder=$env{'form.folder'};                  next if ($token->[2]->{'type'} eq 'zombie');
     my $destination = 'docs/';                  my $ressrc = $token->[2]->{'src'};
     if ($folder =~ /^supplemental/) {                  if ($folder =~ /^supplemental/) {
         $destination = 'supplemental/';                      unless (&supp_pasteable($ressrc)) {
     }                          $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     if (($folder eq 'default') || ($folder eq 'supplemental')) {                          next;
         $destination .= 'default/';                      }
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {                  }
         $destination .=  $2.'/';                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
     }                      if ($1 eq 'uploaded') {
     $destination .= $newidx;                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
     my ($url,$filename);                          $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);                      } else {
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});                          if ($allmaps->{$ressrc}) {
     return $filename;                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 }                          } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
                               $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 sub is_supplemental_title {                          } else {
     my ($title) = @_;                              $addedmaps->{$ressrc} = [$url];
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);                          }
 }                      }
                       &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
 sub parse_supplemental_title {                                           $addedmaps,$hierarchy,$titles,$allmaps);
     my ($title) = @_;                  }
               } elsif ($token->[1] eq 'param') {
     my ($foldertitle,$renametitle);                  if ($folder =~ /^supplemental/) {
     if ($title =~ /&amp;&amp;&amp;/) {                      if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
  $title = &HTML::Entites::decode($title);                          push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
     }                      } else {
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
  $renametitle=$4;                      }
  my ($time,$uname,$udom) = ($1,$2,$3);                  }
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);              }
  my $name =  &Apache::loncommon::plainname($uname,$udom);          }
  $name = &HTML::Entities::encode($name,'"<>&\'');      }
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.      return;
     $name.': <br />'.$foldertitle;  }
     }  
     if (wantarray) {  sub url_paste_fixups {
  return ($title,$foldertitle,$renametitle);      my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
     }          $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
     return $title;          $mapchanges,$tomove,$newsubdir,$newurls) = @_;
 }      my $checktitle;
       if (($prefixchg) &&
 # --------------------------------------------------------------- An entry line          ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
           $checktitle = 1;
 sub entryline {      }
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;      my $skip;
       if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
     my ($foldertitle,$pagetitle,$renametitle);          my $mapid = $1.$2;
     if (&is_supplemental_title($title)) {          if ($tomove->{$mapid}) {
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);              $skip = 1;
  $pagetitle = $foldertitle;          }
     } else {      }
  $title=&HTML::Entities::encode($title,'"<>&\'');      my $file = &Apache::lonnet::getfile($oldurl);
  $renametitle=$title;      return if ($file eq '-1');
  $foldertitle=$title;      my $parser = HTML::TokeParser->new(\$file);
  $pagetitle=$title;      $parser->attr_encoded(1);
     }      my $changed = 0;
       while (my $token = $parser->get_token) {
     my $orderidx=$LONCAPA::map::order[$index];          next if ($token->[0] ne 'S');
              if ($token->[1] eq 'resource') {
               my $ressrc = $token->[2]->{'src'};
     $renametitle=~s/\\/\\\\/g;              next if ($ressrc eq '');
     $renametitle=~s/\&quot\;/\\\"/g;              my $id = $token->[2]->{'id'};
     $renametitle=~s/ /%20/g;              my $title = $token->[2]->{'title'};
     my $line='<tr>';              if ($checktitle) {
     my ($form_start,$form_end);                  if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
 # Edit commands                      $retitles->{$oldurl}{$id} = $ressrc;
     my ($container, $type, $esc_path, $path, $symb);                  }
     if ($env{'form.folderpath'}) {              }
  $type = 'folder';              next if ($token->[2]->{'type'} eq 'external');
         $container = 'sequence';              if ($token->[2]->{'type'} eq 'zombie') {
  $esc_path=&escape($env{'form.folderpath'});                  next if ($skip);
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                  $zombies->{$oldurl}{$id} = $ressrc;
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');                  $changed = 1;
     }              } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
     if ($env{'form.pagepath'}) {                  my $srcdom = $1;
         $type = $container = 'page';                  my $srcnum = $2;
         $esc_path=&escape($path = $env{'form.pagepath'});                  my $rem = $3;
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');                  my $newurl;
         $symb=&escape($env{'form.pagesymb'});                  my $mapname;
     }                  if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
     my $cpinfo='';                      my $prefix = $1;
     if ($allowed) {                      $mapname = $prefix.$2;
  my $incindex=$index+1;                      if ($tomove->{$mapname}) {
  my $selectbox='';                          &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
  if (($folder!~/^supplemental/) &&                                            $srcdom,$srcnum,$allmaps,$rewrites,
     ($#LONCAPA::map::order>0) &&                                            $retitles,$copies,$dbcopies,$zombies,
     ((split(/\:/,                                            $params,$mapmoves,$mapchanges,$tomove,
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]                                            $newsubdir,$newurls);
      ne '') &&                          next;
     ((split(/\:/,                      } else {
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]                          ($newurl,my $error) =
      ne '')) {                              &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
     $selectbox=                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.                          if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
  '<select name="newpos" onChange="this.form.submit()">';                              $newsubdir->{$ressrc} = $1;
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {                          }
  if ($i==$incindex) {                          if ($error) {
     $selectbox.='<option value="" selected="1">('.$i.')</option>';                              next;
  } else {                          }
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';                      }
  }                  }
     }                  if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
     $selectbox.='</select>';                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
  }                     
  my %lt=&Apache::lonlocal::texthash(                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
                 'up' => 'Move Up',                          $rewrites->{$oldurl}{$id} = $ressrc;
  'dw' => 'Move Down',                          $mapchanges->{$ressrc} = 1;
  'rm' => 'Remove',                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
                 'ct' => 'Cut',                                                    $cnum,$srcdom,$srcnum,$allmaps,
  'rn' => 'Rename',                                                    $rewrites,$retitles,$copies,$dbcopies,
  'cp' => 'Copy');                                                    $zombies,$params,$mapmoves,$mapchanges,
  my $nocopy=0;                                                    $tomove,$newsubdir,$newurls)) {
         my $nocut=0;                              $mapmoves->{$ressrc} = 1;
         if ($url=~/\.(page|sequence)$/) {                          }
     if ($url =~ m{/res/}) {                          $changed = 1;
  # no copy for published maps                      } else {
  $nocopy = 1;                          $rewrites->{$oldurl}{$id} = $ressrc;
     } else {                          $copies->{$oldurl}{$ressrc} = $id;
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {                          $changed = 1;
     my ($title,$url,$ext,$type)=split(/\:/,$item);                      }
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {                  }
  $nocopy=1;              } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
  last;                  next if ($skip);
     }                  my $srcdom = $1;
  }                  my $srcnum = $2;
     }                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
  }                      $rewrites->{$oldurl}{$id} = $ressrc;
         if ($url=~/^\/res\/lib\/templates\//) {                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
            $nocopy=1;                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
            $nocut=1;                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
         }                      $changed = 1;
         my $copylink='&nbsp;';                  }
         my $cutlink='&nbsp;';              } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
                   if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
  my $skip_confirm = 0;                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
  if ( $folder =~ /^supplemental/                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
      || ($url =~ m{( /smppg$                      $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
     |/syllabus$                      $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
     |/aboutme$                      $changed = 1;
     |/navmaps$                  }
     |/bulletinboard$              } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
     |\.html$                  next if ($skip);
     |^/adm/wrapper/ext)}x)) {                  my $srcdom = $1;
     $skip_confirm = 1;                  my $srcnum = $2;
  }                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
                       $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
  if (!$nocopy) {                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
     $copylink=(<<ENDCOPY);                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>                      $changed = 1;
 ENDCOPY                  }
         }              }
  if (!$nocut) {          } elsif ($token->[1] eq 'param') {
     $cutlink=(<<ENDCUT);              next if ($skip);
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>              my $to = $token->[2]->{'to'}; 
 ENDCUT              if ($to ne '') {
         }                  if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
  $form_start = (<<END);                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
    <form  action="/adm/coursedocs" method="post">                  } else {
    <input type="hidden" name="${type}path" value="$path" />                      @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
    <input type="hidden" name="${type}symb" value="$symb" />                  }
    <input type="hidden" name="setparms" value="$orderidx" />              }
    <input type="hidden" name="changeparms" value="0" />          }
 END      }
         $form_end = '</form>';      return $changed;
  $line.=(<<END);  }
 <td>  
    <table class="LC_docs_entry_move">  sub apply_fixups {
       <tr>      my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
          <td>          $oldurl,$url,$caller) = @_;
             <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>      my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
          </td>          %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
       </tr>          %lockerrors,$lockmsg);
       <tr>      if (ref($updated) eq 'HASH') {
         <td>          if (ref($updated->{'rewrites'}) 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>              %rewrites = %{$updated->{'rewrites'}};
         </td>          }
       </tr>          if (ref($updated->{'zombies'}) eq 'HASH') {
     </table>              %zombies = %{$updated->{'zombies'}};
 </td>          }
 <td>          if (ref($updated->{'removefrommap'}) eq 'HASH') {
    $form_start              %removefrommap = %{$updated->{'removefrommap'}};
    $selectbox          }
    $form_end          if (ref($updated->{'removeparam'}) eq 'HASH') {
 </td>              %removeparam = %{$updated->{'removeparam'}};
 <td class="LC_docs_entry_commands">          }
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>          if (ref($updated->{'dbcopies'}) eq 'HASH') {
 $cutlink              %dbcopies = %{$updated->{'dbcopies'}};
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>          }
 $copylink          if (ref($updated->{'retitles'}) eq 'HASH') {
 </td>              %retitles = %{$updated->{'retitles'}};
 END          }
       }
     }      if (ref($info) eq 'HASH') {
 # Figure out what kind of a resource this is          if (ref($info->{'newsubdir'}) eq 'HASH') {
     my ($extension)=($url=~/\.(\w+)$/);              %newsubdir = %{$info->{'newsubdir'}};
     my $uploaded=($url=~/^\/*uploaded\//);          }
     my $icon=&Apache::loncommon::icon($url);          if (ref($info->{'params'}) eq 'HASH') {
     my $isfolder=0;              %params = %{$info->{'params'}};
     my $ispage=0;          }
     my $folderarg;          if (ref($info->{'before'}) eq 'HASH') {
     my $pagearg;              %before = %{$info->{'before'}};
     my $pagefile;          }
     if ($uploaded) {          if (ref($info->{'after'}) eq 'HASH') {
  if ($extension eq 'sequence') {              %after = %{$info->{'after'}};
     $icon=$iconpath.'/folder_closed.gif';          }
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;      }
     $url='/adm/coursedocs?';      if (ref($moves) eq 'HASH') {
     $folderarg=$1;          if (ref($moves->{'copies'}) eq 'HASH') {
     $isfolder=1;              %copies = %{$moves->{'copies'}};
         } elsif ($extension eq 'page') {          }
             $icon=$iconpath.'/page.gif';          if (ref($moves->{'docmoves'}) eq 'HASH') {
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;              %docmoves = %{$moves->{'docmoves'}};
             $pagearg=$1;          }
             $url='/adm/coursedocs?';          if (ref($moves->{'mapmoves'}) eq 'HASH') {
             $ispage=1;              %mapmoves = %{$moves->{'mapmoves'}};
  } else {          }
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);      }
  }      foreach my $key (keys(%copies),keys(%docmoves)) {
     }          my @allcopies;
              if (exists($copies{$key})) {
     my $orig_url = $url;              if (ref($copies{$key}) eq 'HASH') {
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});                  my %added;
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {                  foreach my $innerkey (keys(%{$copies{$key}})) {
  my $symb=&Apache::lonnet::symbclean(                      if (($innerkey ne '') && (!$added{$innerkey})) {
           &Apache::lonnet::declutter('uploaded/'.                          push(@allcopies,$innerkey);
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.                          $added{$innerkey} = 1;
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.                      }
            '.sequence').                  }
            '___'.$residx.'___'.                  undef(%added);
    &Apache::lonnet::declutter($url));              }
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);          }
  $url=&Apache::lonnet::clutter($url);          if ($key eq $oldurl) {
  if ($url=~/^\/*uploaded\//) {              if ((exists($docmoves{$key}))) {
     $url=~/\.(\w+)$/;                  unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
     my $embstyle=&Apache::loncommon::fileembstyle($1);                      push(@allcopies,$oldurl);
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {                  }
  $url='/adm/wrapper'.$url;              }
     } elsif ($embstyle eq 'ssi') {          }
  #do nothing with these          if (@allcopies > 0) {
     } elsif ($url!~/\.(sequence|page)$/) {              foreach my $item (@allcopies) {
  $url='/adm/coursedocs/showdoc'.$url;                  my ($relpath,$oldsubdir,$fname) = 
     }                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
  } elsif ($url=~m|^/ext/|) {                  if ($fname ne '') {
     $url='/adm/wrapper'.$url;                      my $content = &Apache::lonnet::getfile($item);
     $external = 1;                      unless ($content eq '-1') {
  }                          my $storefn;
         if (&Apache::lonnet::symbverify($symb,$url)) {                          if (($key eq $oldurl) && (exists($docmoves{$key}))) {
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                              $storefn = $docmoves{$key};
         } else {                          } else {
             $url='';                              $storefn = $relpath;
         }                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
  if ($container eq 'page') {                              if ($prefixchg && $before{'doc'} && $after{'doc'}) {
     my $symb=$env{'form.pagesymb'};                                  $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
                                       }
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);                              if ($newsubdir{$key}) {
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                                  $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
  }                              }
     }                          }
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');                          &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
     if ($isfolder || $extension eq 'sequence') {                          my $copyurl = 
  my $foldername=&escape($foldertitle);                              &Apache::lonclonecourse::writefile($env{'request.course.id'},
  my $folderpath=$env{'form.folderpath'};                                                                 $storefn.$fname,$content);
  if ($folderpath) { $folderpath.='&' };                          if ($copyurl eq '/adm/notfound.html') {
 # Append randompick number, hidden, and encrypted with ":" to foldername,                              if (exists($docmoves{$oldurl})) {
 # so it gets transferred between levels                                  return &mt('Paste failed: an error occurred copying the file.');
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,                              } elsif (ref($errors) eq 'HASH') {
                                               'parameter_randompick'))[0]                                  $errors->{$item} = 1;
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                              }
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)                          }
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                      }
                                               'parameter_encrypturl'))[0]=~/^yes$/i)                  }
                                                .':'.((&LONCAPA::map::getparameter($orderidx,              }
                                               'parameter_randomorder'))[0]=~/^yes$/i);          }
  $url.='folderpath='.&escape($folderpath).$cpinfo;      }
  $parameterset='<label>'.&mt('Randomly Pick: ').      foreach my $key (keys(%mapmoves)) {
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.          my $storefn=$key;
     (&LONCAPA::map::getparameter($orderidx,          $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                                               'parameter_randompick'))[0].          if ($prefixchg && $before{'map'} && $after{'map'}) {
                                               '" />'.              $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';          }
     my $ro_set=          if ($newsubdir{$key}) {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
  $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 $mapcontent = &Apache::lonnet::getfile($key);
     }          if ($mapcontent eq '-1') {
     if ($ispage) {              if (ref($errors) eq 'HASH') {
         my $pagename=&escape($pagetitle);                  $errors->{$key} = 1;
         my $pagepath;              }
         my $folderpath=$env{'form.folderpath'};          } else {
         if ($folderpath) { $pagepath = $folderpath.'&' };              my $newmap =
         $pagepath.=$pagearg.'&'.$pagename;                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
  my $symb=$env{'form.pagesymb'};                                                     $mapcontent);
  if (!$symb) {              if ($newmap eq '/adm/notfound.html') {
     my $path='uploaded/'.                  if (ref($errors) eq 'HASH') {
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.                      $errors->{$key} = 1;
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';                  }
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',              }
        $residx,          }
        $path.$pagearg.'.page');      }
  }      my %updates;
  $url.='pagepath='.&escape($pagepath).      if ($is_map) {
     '&amp;pagesymb='.&escape($symb).$cpinfo;          if (ref($updated) eq 'HASH') {
     }              foreach my $type (keys(%{$updated})) {
     if ($external) {                  if (ref($updated->{$type}) eq 'HASH') {
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';                      foreach my $key (keys(%{$updated->{$type}})) {
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';                          $updates{$key} = 1;
     } else {                      }
  undef($external);                  }
     }              }
     $line.='          }
   <td class="LC_docs_entry_icon">          foreach my $key (keys(%updates)) {
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'              my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
   </td>              if (ref($rewrites{$key}) eq 'HASH') {
   <td class="LC_docs_entry_title">                  %torewrite = %{$rewrites{$key}};
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."              }
   </td>";              if (ref($retitles{$key}) eq 'HASH') {
     if (($allowed) && ($folder!~/^supplemental/)) {                  %toretitle = %{$retitles{$key}};
   my %lt=&Apache::lonlocal::texthash(              }
        'hd' => 'Hidden',              if (ref($removefrommap{$key}) eq 'HASH') {
        'ec' => 'URL hidden');                  %toremove = %{$removefrommap{$key}};
  my $enctext=              }
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');              if (ref($removeparam{$key}) eq 'HASH') {
  my $hidtext=                  %remparam = %{$removeparam{$key}};
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');              }
  $line.=(<<ENDPARMS);              if (ref($zombies{$key}) eq 'HASH') {
   <td class="LC_docs_entry_parameter">                  %zombie = %{$zombies{$key}};
     $form_start              }
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>              if (ref($dbcopies{$key}) eq 'HASH') {
     $form_end                  foreach my $idx (keys(%{$dbcopies{$key}})) {
   </td>                      if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
   <td class="LC_docs_entry_parameter">                          my ($newurl,$result,$errtext) =
     $form_start                              &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>                          if ($result eq 'ok') {
     $form_end                              $newdb{$idx} = $newurl;
   </td>                          } elsif (ref($errors) eq 'HASH') {
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>                              $errors->{$key} = 1;
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>                          }
 ENDPARMS                          push(@msgs,$errtext);
     }                      }
     $line.="</tr>";                  }
     return $line;              }
 }              if (ref($params{$key}) eq 'HASH') {
                   %currparam = %{$params{$key}};
 =pod              }
               my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
 =item tiehash()              if ($fatal) {
                   return ($errtext);
 tie the hash              }
               for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
 =cut                  if (defined($LONCAPA::map::zombies[$i])) {
                       my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
 sub tiehash {                      if ($zombie{$i} eq $src) {
     my ($mode)=@_;                          undef($LONCAPA::map::zombies[$i]);
     $hashtied=0;                      }
     if ($env{'request.course.fn'}) {                  }
  if ($mode eq 'write') {              }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",              for (my $i=0; $i<@LONCAPA::map::order; $i++) {
     &GDBM_WRCREAT(),0640)) {                  my $idx = $LONCAPA::map::order[$i];
                 $hashtied=2;                  if (defined($LONCAPA::map::resources[$idx])) {
     }                      my $changed;
  } else {                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                      if ((exists($toremove{$idx})) && 
     &GDBM_READER(),0640)) {                          ($toremove{$idx} eq &LONCAPA::map::qtescape($src))) {
                 $hashtied=1;                          splice(@LONCAPA::map::order,$i,1);
     }                          if (ref($currparam{$idx}) eq 'ARRAY') {
  }                              foreach my $name (@{$currparam{$idx}}) {
     }                                      &LONCAPA::map::delparameter($idx,'parameter_'.$name);
 }                              }
                           }
 sub untiehash {                          next;
     if ($hashtied) { untie %hash; }                      }
     $hashtied=0;                      my $origsrc = $src;
     return OK;                      if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
 }                          if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
                               $changed = 1;
                           }
                       }
                       if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
 sub checkonthis {                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
     my ($r,$url,$level,$title)=@_;                          if ($origsrc =~ m{^/uploaded/}) {
     $url=&unescape($url);                              if ($prefixchg && $before{'map'} && $after{'map'}) {
     $alreadyseen{$url}=1;                                  if ($src =~ /\.(page|sequence)$/) {
     $r->rflush();                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {                                  } else {
        $r->print("\n<br />");                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
        if ($level==0) {                                  }
            $r->print("<br />");                              }
        }                              if ($origsrc =~ /\.(page|sequence)$/) {
        for (my $i=0;$i<=$level*5;$i++) {                                  if ($newsubdir{$origsrc}) {
            $r->print('&nbsp;');                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
        }                                  }
        $r->print('<a href="'.$url.'" target="cat">'.                              } elsif ($newsubdir{$key}) {
  ($title?$title:$url).'</a> ');                                  $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
        if ($url=~/^\/res\//) {                              }
   my $result=&Apache::lonnet::repcopy(                          }
                               &Apache::lonnet::filelocation('',$url));                          $changed = 1;
           if ($result eq 'ok') {                      } elsif ($newdb{$idx} ne '') {
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');                          $src = $newdb{$idx};
              $r->rflush();                          $changed = 1;
              &Apache::lonnet::countacc($url);                      }
              $url=~/\.(\w+)$/;                      if ($changed) {
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {                          $LONCAPA::map::resources[$idx] = join(':',($title,&LONCAPA::map::qtunescape($src),$ext,$type));
  $r->print('<br />');                      }
                  $r->rflush();                  }
                  for (my $i=0;$i<=$level*5;$i++) {              }
                      $r->print('&nbsp;');              foreach my $idx (keys(%remparam)) {
                  }                  if (ref($remparam{$idx}) eq 'ARRAY') {
                  $r->print('- '.&mt('Rendering:').' ');                      foreach my $name (@{$remparam{$idx}}) {   
  my ($errorcount,$warningcount)=split(/:/,                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
        &Apache::lonnet::ssi_body($url,                      }
        ('grade_target'=>'web',                  }
  'return_only_error_and_warning_counts' => 1)));              }
                  if (($errorcount) ||              if (values(%lockerrors) > 0) {
                      ($warningcount)) {                  $lockmsg = join('<br />',values(%lockerrors));
      if ($errorcount) {              }
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.              my $storefn;
                           &mt('[quant,_1,error]',$errorcount).'</span>');              if ($key eq $oldurl) {
                      }                  $storefn = $url;
      if ($warningcount) {                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                         $r->print('<span class="LC_warning">'.              } else {
                           &mt('[quant,_1,warning]',$warningcount).'</span>');                  $storefn = $key;
                      }                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                  } else {                  if ($prefixchg && $before{'map'} && $after{'map'}) {
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');                      $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
                  }                  }
                  $r->rflush();                  if ($newsubdir{$key}) {
              }                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
      my $dependencies=                  }
                 &Apache::lonnet::metadata($url,'dependencies');              }
              foreach my $dep (split(/\,/,$dependencies)) {              my $report;
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {              if ($folder !~ /^supplemental/) {
                     &checkonthis($r,$dep,$level+1);                  $report = 1;
                  }              }
              }              (my $outtext,$errtext) =
           } elsif ($result eq 'unavailable') {                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');              if ($errtext) {
           } elsif ($result eq 'not_found') {                  if ($caller eq 'paste') {
       unless ($url=~/\$/) {                      return (&mt('Paste failed: an error occurred saving the folder or page.'));
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');                  }
       } else {              }
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');          }
       }      }
           } else {      return ('ok',\@msgs,$lockmsg);
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');  }
           }  
        }  sub copy_dependencies {
     }      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
 }      my $content;
       if (ref($contentref)) {
           $content = $$contentref;
       } else {
 =pod          $content = &Apache::lonnet::getfile($item);
       }
 =item list_symbs()      unless ($content eq '-1') {
           my $mm = new File::MMagic;
 List Symbs          my $mimetype = $mm->checktype_contents($content);
           if ($mimetype eq 'text/html') {
 =cut              my (%allfiles,%codebase,$state);
               my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
 sub list_symbs {              if ($res eq 'ok') {
     my ($r) = @_;                  my ($numexisting,$numpathchanges,$existing);
                   (undef,$numexisting,$numpathchanges,$existing) =
     my $type = &Apache::loncommon::course_type();                      &Apache::loncommon::ask_for_embedded_content(
     $r->print(&Apache::loncommon::start_page('Symb List'));                          '/adm/coursedocs',$state,\%allfiles,\%codebase,
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));                          {'error_on_invalid_names'   => 1,
     my $navmap = Apache::lonnavmaps::navmap->new();                           'ignore_remote_references' => 1,
     if (!defined($navmap)) {                           'docs_url'                 => $item,
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.                           'context'                  => 'paste'});
                   '<div class="LC_error">'.                  if ($numexisting > 0) {
                   &mt('Unable to retrieve information about course contents').                      if (ref($existing) eq 'HASH') {
                   '</div>');                          foreach my $dep (keys(%{$existing})) {
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                              my $depfile = $dep;
     } else {                              unless ($depfile =~ m{^\Q$relpath\E}) {
         $r->print("<pre>\n");                                  $depfile = $relpath.$dep;
         foreach my $res ($navmap->retrieveResources()) {                              }
     $r->print($res->compTitle()."\t".$res->symb()."\n");                              my $depcontent = &Apache::lonnet::getfile($depfile);
         }                              unless ($depcontent eq '-1') {
         $r->print("\n</pre>\n");                                  my $storedep = $dep;
     }                                  $storedep =~ s{^\Q$relpath\E}{};
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');                                  my $dep_url =
 }                                      &Apache::lonclonecourse::writefile(
                                           $env{'request.course.id'},
                                           $storefn.$storedep,$depcontent);
 sub verifycontent {                                  if ($dep_url eq '/adm/notfound.html') {
     my ($r) = @_;                                      if (ref($errors) eq 'HASH') {
     my $type = &Apache::loncommon::course_type();                                          $errors->{$depfile} = 1;
    my $loaderror=&Apache::lonnet::overloaderror($r);                                      }
    if ($loaderror) { return $loaderror; }                                  } else {
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));                                  }
    $hashtied=0;                              }
    undef %alreadyseen;                          }
    %alreadyseen=();                      }
    &tiehash();                  }
    foreach my $key (keys(%hash)) {              }
        if ($hash{$key}=~/\.(page|sequence)$/) {          }
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {      }
        $r->print('<hr /><span class="LC_error">'.      return;
  &mt('The following sequence or page is included more than once in your '.$type.': ').  }
  &unescape($hash{$key}).'</span><br />'.  
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));  my %parameter_type = ( 'randompick'     => 'int_pos',
    }         'hiddenresource' => 'string_yesno',
        }         'encrypturl'     => 'string_yesno',
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {         'randomorder'    => 'string_yesno',);
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});  my $valid_parameters_re = join('|',keys(%parameter_type));
        }  # set parameters
    }  sub update_parameter {
    &untiehash();      if ($env{'form.changeparms'} eq 'all') {
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.          my (@allidx,@allmapidx,%allchecked,%currchecked);
      &mt('Return to DOCS').'</a>');          %allchecked = (
 }                           'hiddenresource' => {},
                            'encrypturl'     => {},
                            'randompick'     => {},
 sub devalidateversioncache {                           'randomorder'    => {},
     my $src=shift;                        );
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.          foreach my $which (keys(%allchecked)) {
   &Apache::lonnet::clutter($src));              $env{'form.all'.$which} =~ s/,$//;
 }              if ($which eq 'randompick') {
                   foreach my $item (split(/,/,$env{'form.all'.$which})) {
 sub checkversions {                      my ($res,$value) = split(/:/,$item);
     my ($r) = @_;                      if ($value =~ /^\d+$/) {
     my $type = &Apache::loncommon::course_type();                          $allchecked{$which}{$res} = $value;
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));                      }
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));                  }
     my $header='';              } else {
     my $startsel='';                  if ($env{'form.all'.$which}) {
     my $monthsel='';                      map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.all'.$which});
     my $weeksel='';                  }
     my $daysel='';              }
     my $allsel='';          }
     my %changes=();          my $haschanges = 0;
     my $starttime=0;          foreach my $res (@LONCAPA::map::order) {
     my $haschanged=0;              my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     my %setversions=&Apache::lonnet::dump('resourceversions',              $name=&LONCAPA::map::qtescape($name);
   $env{'course.'.$env{'request.course.id'}.'.domain'},              $url=&LONCAPA::map::qtescape($url);
   $env{'course.'.$env{'request.course.id'}.'.num'});              next unless ($name && $url);
               my $is_map;
     $hashtied=0;              if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
     &tiehash();                  $is_map = 1;
     my %newsetversions=();              }
     if ($env{'form.setmostrecent'}) {              foreach my $which (keys(%allchecked)) {
  $haschanged=1;                  if (($which eq 'randompick' || $which eq 'randomorder')) {
  foreach my $key (keys(%hash)) {                      next if (!$is_map);
     if ($key=~/^ids\_(\/res\/.+)$/) {                  }
  $newsetversions{$1}='mostrecent';                  my $oldvalue = 0;
                 &devalidateversioncache($1);                  my $newvalue = 0;
     }                  if ($allchecked{$which}{$res}) {
  }                      $newvalue = $allchecked{$which}{$res};
     } elsif ($env{'form.setcurrent'}) {                  }
  $haschanged=1;                  my $current = (&LONCAPA::map::getparameter($res,'parameter_'.$which))[0];
  foreach my $key (keys(%hash)) {                  if ($which eq 'randompick') {
     if ($key=~/^ids\_(\/res\/.+)$/) {                      if ($current =~ /^(\d+)$/) {
  my $getvers=&Apache::lonnet::getversion($1);                          $oldvalue = $1;
  if ($getvers>0) {                      }
     $newsetversions{$1}=$getvers;                  } else {
     &devalidateversioncache($1);                      if ($current =~ /^yes$/i) {
  }                          $oldvalue = 1;
     }                      }
  }                  }
     } elsif ($env{'form.setversions'}) {                  if ($oldvalue ne $newvalue) {
  $haschanged=1;                      $haschanges = 1;
  foreach my $key (keys(%env)) {                      if ($newvalue) {
     if ($key=~/^form\.set_version_(.+)$/) {                          my $storeval = 'yes';
  my $src=$1;                          if ($which eq 'randompick') {
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {                              $storeval = $newvalue;
     $newsetversions{$src}=$env{$key};                          }
     &devalidateversioncache($src);                          &LONCAPA::map::storeparameter($res,'parameter_'.$which,
  }                                                        $storeval,
     }                                                        $parameter_type{$which});
  }                          &remember_parms($res,$which,'set',$storeval);
     }                      } elsif ($oldvalue) {
     if ($haschanged) {                          &LONCAPA::map::delparameter($res,'parameter_'.$which);
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,                          &remember_parms($res,$which,'del');
   $env{'course.'.$env{'request.course.id'}.'.domain'},                      }
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {                  }
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');              }
  } else {          }
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');          return $haschanges;
  }      } else {
  &mark_hash_old();          return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     }  
     &changewarning($r,'');          my $which = $env{'form.changeparms'};
     if ($env{'form.timerange'} eq 'all') {          my $idx = $env{'form.setparms'};
 # show all documents          if ($env{'form.'.$which.'_'.$idx}) {
  $header=&mt('All Documents in '.$type);      my $value = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
  $allsel=1;                                           : 'yes';
  foreach my $key (keys(%hash)) {      &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
     if ($key=~/^ids\_(\/res\/.+)$/) {            $parameter_type{$which});
  my $src=$1;      &remember_parms($idx,$which,'set',$value);
  $changes{$src}=1;          } else {
     }      &LONCAPA::map::delparameter($idx,'parameter_'.$which);
  }  
     } else {      &remember_parms($idx,$which,'del');
 # show documents which changed          }
  %changes=&Apache::lonnet::dump          return 1;
  ('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'}) {  sub handle_edit_cmd {
  $env{'form.timerange'}=604800;      my ($coursenum,$coursedom) =@_;
     }      if ($env{'form.cmd'} eq '') {
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '          return 0;
  .&mt('seconds');      }
     if ($env{'form.timerange'}==-1) {      my ($cmd,$idx)=split('_',$env{'form.cmd'});
  $seltext='since start of course';  
  $startsel='selected';      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  $env{'form.timerange'}=time;      my ($title, $url, @rrest) = split(':', $ratstr);
     }  
     $starttime=time-$env{'form.timerange'};      if ($cmd eq 'remove') {
     if ($env{'form.timerange'}==2592000) {   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      ($url!~/$LONCAPA::assess_page_seq_re/)) {
  $monthsel='selected';      &Apache::lonnet::removeuploadedurl($url);
     } elsif ($env{'form.timerange'}==604800) {   } else {
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  $weeksel='selected';   }
     } elsif ($env{'form.timerange'}==86400) {   splice(@LONCAPA::map::order, $idx, 1);
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  
  $daysel='selected';      } elsif ($cmd eq 'cut') {
     }   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     $header=&mt('Content changed').' '.$seltext;   splice(@LONCAPA::map::order, $idx, 1);
  } else {  
     $header=&mt('No content modifications yet.');      } elsif ($cmd eq 'up'
  }       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     }   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
     %setversions=&Apache::lonnet::dump('resourceversions',  
   $env{'course.'.$env{'request.course.id'}.'.domain'},      } elsif ($cmd eq 'down'
   $env{'course.'.$env{'request.course.id'}.'.num'});       && defined($LONCAPA::map::order[$idx+1])) {
     my %lt=&Apache::lonlocal::texthash   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
       ('st' => 'Version changes since start of '.$type,  
        'lm' => 'Version changes since last Month',      } elsif ($cmd eq 'rename') {
        'lw' => 'Version changes since last Week',   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
        'sy' => 'Version changes since Yesterday',   if ($comment=~/\S/) {
                'al' => 'All Resources (possibly large output)',      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
        'sd' => 'Display',   $comment.':'.join(':', $url, @rrest);
        'fi' => 'File',   }
        'md' => 'Modification Date',  # Devalidate title cache
                'mr' => 'Most recently published Version',   my $renamed_url=&LONCAPA::map::qtescape($url);
        've' => 'Version used in '.$type,   &Apache::lonnet::devalidate_title_cache($renamed_url);
                'vu' => 'Set Version to be used in '.$type,  
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      } else {
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',   return 0;
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      }
        'di' => 'Differences');      return 1;
     $r->print(<<ENDHEADERS);  }
 <form action="/adm/coursedocs" method="post">  
 <input type="hidden" name="versions" value="1" />  sub editor {
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />          $supplementalflag,$orderhash,$iconpath,$pathitem)=@_;
 <select name="timerange">      my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
 <option value='all' $allsel>$lt{'al'}</option>      if ($allowed) {
 <option value="-1" $startsel>$lt{'st'}</option>          (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
 <option value="2592000" $monthsel>$lt{'lm'}</option>           $is_random_order,$container) =
 <option value="604800" $weeksel>$lt{'lw'}</option>              &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
 <option value="86400" $daysel>$lt{'sy'}</option>          $r->print($breadcrumbtrail);
 </select>      } elsif ($env{'form.folderpath'} =~ /\:1$/) {
 <input type="submit" name="display" value="$lt{'sd'}" />          $container = 'page'; 
 <h3>$header</h3>      } else {
 <input type="submit" name="setversions" value="$lt{'sv'}" />          $container = 'sequence';
 <table border="0">      }
 ENDHEADERS  
     foreach my $key (sort(keys(%changes))) {      my $jumpto;
  if ($changes{$key}>$starttime) {  
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);      unless ($supplementalflag) {
     my $currentversion=&Apache::lonnet::getversion($key);          $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
     if ($currentversion<0) {      }
  $currentversion=&mt('Could not be determined.');  
     }      unless ($allowed) {
     my $linkurl=&Apache::lonnet::clutter($key);          $randompick = -1;
     $r->print(      }
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.  
       &Apache::lonnet::gettitle($linkurl).      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                       '</b></font></td></tr>'.      $folder.'.'.$container);
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      return $errtext if ($fatal);
                       '<td colspan="4">'.  
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.      if ($#LONCAPA::map::order<1) {
       '</a></td></tr>'.   my $idx=&LONCAPA::map::getresidx();
                       '<tr><td></td>'.   if ($idx<=0) { $idx=1; }
                       '<td title="'.$lt{'md'}.'">'.          $LONCAPA::map::order[0]=$idx;
       &Apache::lonlocal::locallocaltime(          $LONCAPA::map::resources[$idx]='';
                            &Apache::lonnet::metadata($root.'.'.$extension,      }
                                                      'lastrevisiondate')  
                                                         ).  # ------------------------------------------------------------ Process commands
                       '</td>'.  
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.  # ---------------- if they are for this folder and user allowed to make changes
                       '<font size="+1">'.$currentversion.'</font>'.      if (($allowed) && ($env{'form.folder'} eq $folder)) {
                       '</span></td>'.  # set parameters and change order
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.   &snapshotbefore();
                       '<font size="+1">');  
 # Used in course   if (&update_parameter()) {
     my $usedversion=$hash{'version_'.$linkurl};      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      return $errtext if ($fatal);
  $r->print($usedversion);   }
     } else {  
  $r->print($currentversion);   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
     }  # change order
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
                       '<span class="LC_nobreak">Use: ');      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
 # Set version  
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
       'set_version_'.$linkurl,      return $errtext if ($fatal);
       ('select_form_order' =>   }
        ['',1..$currentversion,'mostrecent'],  
        '' => '',   if ($env{'form.pastemarked'}) {
        'mostrecent' => 'most recent',              my %paste_errors;
        map {$_,$_} (1..$currentversion))));              my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
     $r->print('</span></td></tr><tr><td></td>');                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
     my $lastold=1;                                        \%paste_errors);
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {              if (ref($pastemsgarray) eq 'ARRAY') {
  my $url=$root.'.'.$prevvers.'.'.$extension;                  if (@{$pastemsgarray} > 0) {
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                      $r->print('<p class="LC_info">'.
     $starttime) {                                join('<br />',@{$pastemsgarray}).
     $lastold=$prevvers;                                '</p>');
  }                  }
     }              }
             #              if ($lockerror) {
             # Code to figure out how many version entries should go in                  $r->print('<p class="LC_error">'.
             # each of the four columns                            $lockerror.
             my $entries_per_col = 0;                            '</p>');
             my $num_entries = ($currentversion-$lastold);              }
             if ($num_entries % 4 == 0) {              if ($save_error ne '') {
                 $entries_per_col = $num_entries/4;                  return $save_error; 
             } else {              }
                 $entries_per_col = $num_entries/4 + 1;              if ($paste_res) {
             }                  my %errortext = &Apache::lonlocal::texthash (
             my $entries_count = 0;                                      fail      => 'Storage of folder contents failed',
             $r->print('<td valign="top"><font size="-2">');                                      failread  => 'Reading folder contents failed',
             my $cols_output = 1;                                      failstore => 'Storage of folder contents failed',
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {                                  );
  my $url=$root.'.'.$prevvers.'.'.$extension;                  if ($errortext{$paste_res}) {
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).                      $r->print('<p class="LC_error">'.$errortext{$paste_res}.'</p>');
   '">'.&mt('Version').' '.$prevvers.'</a> ('.                  }
   &Apache::lonlocal::locallocaltime(              }
                                 &Apache::lonnet::metadata($url,              if (keys(%paste_errors) > 0) {
                                                           'lastrevisiondate')                  $r->print('<p class="LC_warning">'."\n".
                                                             ).                            &mt('The following files are either dependencies of a web page or references within a folder and/or composite page which could not be copied during the paste operation:')."\n".
   ')');                            '<ul>'."\n");
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {                  foreach my $key (sort(keys(%paste_errors))) {
                     $r->print(' <a href="/adm/diff?filename='.                      $r->print('<li>'.$key.'</li>'."\n");
       &Apache::lonnet::clutter($root.'.'.$extension).                  }
       '&versionone='.$prevvers.                  $r->print('</ul></p>'."\n");
       '">'.&mt('Diffs').'</a>');              }
  }   } elsif ($env{'form.clearmarked'}) {
  $r->print('</span><br />');              my $output = &do_buffer_empty();
                 if (++$entries_count % $entries_per_col == 0) {              if ($output) {
                     $r->print('</font></td>');                  $r->print('<p class="LC_info">'.$output.'</p>');
                     if ($cols_output != 4) {              }
                         $r->print('<td valign="top"><font size="-2">');          }
                         $cols_output++;  
                     }   $r->print($upload_output);
                 }  
     }  # Rename, cut, copy or remove a single resource
             while($cols_output++ < 4) {   if (&handle_edit_cmd()) {
                 $r->print('</font></td><td><font>')              my $contentchg;
             }              if ($env{'form.cmd'} =~ m{^(del|cut)_}) {
     $r->print('</font></td></tr>'."\n");                  $contentchg = 1;
  }              }
     }      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
     $r->print('</table></form>');      return $errtext if ($fatal);
     $r->print('<h1>'.&mt('Done').'.</h1>');   }
   
     &untiehash();  # Cut, copy and/or remove multiple resources
 }          if ($env{'form.multichange'}) {
               my %allchecked = (
 sub mark_hash_old {                                 cut     => {},
     my $retie_hash=0;                                 remove  => {},
     if ($hashtied) {                               );
  $retie_hash=1;              my $needsupdate;
  &untiehash();              foreach my $which (keys(%allchecked)) {
     }                  $env{'form.multi'.$which} =~ s/,$//;
     &tiehash('write');                  if ($env{'form.multi'.$which}) {
     $hash{'old'}=1;                      map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.multi'.$which});
     &untiehash();                      if (ref($allchecked{$which}) eq 'HASH') {
     if ($retie_hash) { &tiehash(); }                          $needsupdate += scalar(keys(%{$allchecked{$which}}));
 }                      }
                   }
 sub is_hash_old {              }
     my $untie_hash=0;              if ($needsupdate) {
     if (!$hashtied) {                  my $haschanges = 0;
  $untie_hash=1;                  my %curr_groups = &Apache::longroup::coursegroups();
  &tiehash();                  my $total = scalar(@LONCAPA::map::order) - 1; 
     }                  for (my $i=$total; $i>=0; $i--) {
     my $return=$hash{'old'};                      my $res = $LONCAPA::map::order[$i];
     if ($untie_hash) { &untiehash(); }                      my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     return $return;                      $name=&LONCAPA::map::qtescape($name);
 }                      $url=&LONCAPA::map::qtescape($url);
                       next unless ($name && $url);
 sub changewarning {                      my %denied =
     my ($r,$postexec,$message,$url)=@_;                          &action_restrictions($coursenum,$coursedom,$url,
     if (!&is_hash_old()) { return; }                                               $env{'form.folderpath'},\%curr_groups);
     my $pathvar='folderpath';                      foreach my $which (keys(%allchecked)) {
     my $path=&escape($env{'form.folderpath'});                          next if ($denied{$which});
     if (!defined($url)) {                          next unless ($allchecked{$which}{$res});
  if (defined($env{'form.pagepath'})) {                          if ($which eq 'remove') {
     $pathvar='pagepath';                              if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
     $path=&escape($env{'form.pagepath'});                                  ($url!~/$LONCAPA::assess_page_seq_re/)) {
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                                  &Apache::lonnet::removeuploadedurl($url);
  }                              } else {
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                                  &LONCAPA::map::makezombie($res);
     }                              }
     my $course_type = &Apache::loncommon::course_type();                              splice(@LONCAPA::map::order,$i,1);
     if (!defined($message)) {                              $haschanges ++;
  $message='Changes will become active for your current session after [_1], or the next time you log in.';                          } elsif ($which eq 'cut') {
     }                              &LONCAPA::map::makezombie($res);
     $r->print("\n\n".                              splice(@LONCAPA::map::order,$i,1);
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".                              $haschanges ++;
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.                          }
 '<input type="hidden" name="orgurl" value="'.$url.                      }
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.                  }
 &mt($message,' <input type="hidden" name="'.                  if ($haschanges) {
     $env{'request.role'}.'" value="1" /><input type="button" value="'.                      ($errtext,$fatal) = 
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').                          &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
 $help{'Caching'}.'</span></h3></form>'."\n\n");                      return $errtext if ($fatal);
 }                  }
               }
           }
 sub init_breadcrumbs {  
     my ($form,$text)=@_;  # Group import/search
     &Apache::lonhtmlcommon::clear_breadcrumbs();   if ($env{'form.importdetail'}) {
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",      my @imports;
     text=>"Edit ".&Apache::loncommon::course_type(),      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
     faq=>273,   if (defined($item)) {
     bug=>'Instructor Interface',      my ($name,$url,$residx)=
                                             help => 'Docs_Adding_Course_Doc'});   map { &unescape($_); } split(/\=/,$item);
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',                      if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
     text=>$text,                          my ($suffix,$errortxt,$locknotfreed) =
     faq=>273,                              &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
     bug=>'Instructor Interface'});                          if ($locknotfreed) {
 }                              $r->print($locknotfreed);
                           }
                           if ($suffix) {
                               $url =~ s/_new\./_$suffix./; 
                           } else {
 sub handler {                              return $errortxt;
     my $r = shift;                          }
     &Apache::loncommon::content_type($r,'text/html');                      } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
     $r->send_http_header;                          my $type = $1;
     return OK if $r->header_only;                          my ($suffix,$errortxt,$locknotfreed) =
     my $type = &Apache::loncommon::course_type();                              &new_timebased_suffix($coursedom,$coursenum,$type);
                           if ($locknotfreed) {
                               $r->print($locknotfreed);
 # --------------------------------------------- Initialize help topics for this                          }
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',                          if ($suffix) {
                'Adding_External_Resource','Navigate_Content',                              $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
                'Adding_Folders','Docs_Overview', 'Load_Map',                          } else {
                'Supplemental','Score_Upload_Form','Adding_Pages',                              return $errortxt;
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',                          }
                'Check_Resource_Versions','Verify_Content') {                      } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);                          if ($supplementalflag) {
     }                              next unless ($1 eq 'supplemental');
     # Composite help files                              if ($folder eq 'supplemental') {
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(                                  next unless ($2 eq 'default');
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');                              } else {
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(                                  next unless ($folder eq 'supplemental_'.$2);
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');                              }
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(                          } else {
     'Option_Response_Simple');                              next unless ($1 eq 'docs');
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(                              if ($folder eq 'default') {
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');                                  next unless ($2 eq 'default');
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(                              } else {
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');                                  next unless ($folder eq 'default_'.$2);
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');                              }
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');                          }
                       }
 # does this user have privileges to modify docs      push(@imports, [$name, $url, $residx]);
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});   }
   if ($allowed && $env{'form.verify'}) {      }
       &init_breadcrumbs('verify','Verify Content');              ($errtext,$fatal,my $fixuperrors) =
       &verifycontent($r);                  &group_import($coursenum, $coursedom, $folder,$container,
   } elsif ($allowed && $env{'form.listsymbs'}) {                                'londocs',@imports);
       &init_breadcrumbs('listsymbs','List Symbs');      return $errtext if ($fatal);
       &list_symbs($r);              if ($fixuperrors) {
   } elsif ($allowed && $env{'form.docslog'}) {                  $r->print($fixuperrors);
       &init_breadcrumbs('docslog','Show Log');              }
       &docs_change_log($r);   }
   } elsif ($allowed && $env{'form.versions'}) {  # Loading a complete map
       &init_breadcrumbs('versions','Check/Set Resource Versions');   if ($env{'form.loadmap'}) {
       &checkversions($r);      if ($env{'form.importmap'}=~/\w/) {
   } elsif ($allowed && $env{'form.dumpcourse'}) {   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');      my ($title,$url,$ext,$type)=split(/\:/,$res);
       &dumpcourse($r);      my $idx=&LONCAPA::map::getresidx($url);
   } elsif ($allowed && $env{'form.exportcourse'}) {      $LONCAPA::map::resources[$idx]=$res;
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
       &exportcourse($r);   }
   } else {   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 # is this a standard course?      $folder.'.'.$container,1);
    return $errtext if ($fatal);
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);      } else {
     my $forcestandard = 0;   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
     my $forcesupplement;  
     my $script='';      }
     my $showdoc=0;   }
     my $containertag;   &log_differences($plain);
     my $uploadtag;      }
   # ---------------------------------------------------------------- End commands
   # ---------------------------------------------------------------- Print screen
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      my $idx=0;
     ['folderpath','pagepath',      my $shown=0;
      'pagesymb']);      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
 # No folderpath, no pagepath, see if we have something stored   $r->print('<div class="LC_Box">'.
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
         &Apache::loncommon::restore_course_settings('docs_folderpath',    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
                                               {'folderpath' => 'scalar'});    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
     }    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
     if (!$env{'form.folderpath'}) {    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
         &Apache::loncommon::restore_course_settings('docs_folderpath',    '</ol>');
                                               {'pagepath' => 'scalar'});          if ($randompick>=0) {
     }              $r->print('<p class="LC_warning">'
     if ($env{'form.pagepath'}) {                   .&mt('Caution: this folder is set to randomly pick a subset'
        $env{'form.folderpath'}='';                       .' of resources. Adding or removing resources from this'
     }                       .' folder will change the set of resources that the'
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {                       .' students see, resulting in spurious or missing credit'
         $env{'form.folderpath'} = 'supplemental&'.                       .' for completed problems, not limited to ones you'
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.                       .' modify. Do not modify the contents of this folder if'
                                   $env{'form.folderpath'};                       .' it is in active student use.')
     }                   .'</p>'
     &Apache::loncommon::store_course_settings('docs_folderpath',              );
                                                 {'pagepath' => 'scalar',          }
                                                  'folderpath' => 'scalar'});          if ($is_random_order) {
     if ($env{'form.folderpath'}) {              $r->print('<p class="LC_warning">'
  my (@folderpath)=split('&',$env{'form.folderpath'});                   .&mt('Caution: this folder is set to randomly order its'
  $env{'form.foldername'}=&unescape(pop(@folderpath));                       .' contents. Adding or removing resources from this folder'
  $env{'form.folder'}=pop(@folderpath);                       .' will change the order of resources shown.')
     }                   .'</p>'
     if ($env{'form.pagepath'}) {              );
         my (@pagepath)=split('&',$env{'form.pagepath'});          }
         $env{'form.pagename'}=&unescape(pop(@pagepath));          $r->print('</div>');
         $env{'form.folder'}=pop(@pagepath);      }
         $containertag = '<input type="hidden" name="pagepath" value="" />'.  
     '<input type="hidden" name="pagesymb" value="" />';      my ($to_show,$output,@allidx,@allmapidx,%filters,%lists,%curr_groups);
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.      %filters =  (
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';                    canremove      => [],
     }                    cancut         => [],
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {                    cancopy        => [],
        $showdoc='/'.$1;                    hiddenresource => [],
     }                    encrypturl     => [],
     unless ($showdoc) { # got called from remote                    randomorder    => [],
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||                    randompick     => [],
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {                  );
            $forcestandard = 1;      %curr_groups = &Apache::longroup::coursegroups();
        }      &Apache::loncommon::start_data_table_count(); #setup a row counter 
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);      foreach my $res (@LONCAPA::map::order) {
           my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
        if ($allowed) {          $name=&LONCAPA::map::qtescape($name);
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);          $url=&LONCAPA::map::qtescape($url);
          $script=&Apache::lonratedt::editscript('simple');          unless ($name) {  $name=(split(/\//,$url))[-1]; }
        }          unless ($name) { $idx++; next; }
     } else { # got called in sequence from course          push(@allidx,$res);
        $allowed=0;          if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
     }              push(@allmapidx,$res);
           }
 # get course data          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};                                $coursenum,$coursedom,$crstype,
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};                                $pathitem,$supplementalflag,$container,
                                 \%filters,\%curr_groups);
 # get personal data          $idx++;
     my $uname=$env{'user.name'};          $shown++;
     my $udom=$env{'user.domain'};      }
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));      &Apache::loncommon::end_data_table_count();
   
 # graphics settings      my $need_save;
       if (($allowed) || ($supplementalflag && $folder eq 'supplemental')) {
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");          my $toolslink;
           if ($allowed || &Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
     if ($allowed) {              $toolslink = '<table><tr><td>'
  $script .= &editing_js($udom,$uname);                         .&Apache::loncommon::help_open_menu('Navigation Screen',
     }                                                             'Navigation_Screen',undef,'RAT')
 # -------------------------------------------------------------------- Body tag                         .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';                         .'<td align="left"><ul id="LC_toolbar">'
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];                         .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,                         .'id="LC_content_toolbar_edittoplevel" '
     {'force_register' => $showdoc,                         .'class="LC_toolbarItem" '
                                      'bread_crumbs' => $brcrum}).                         .'title="'.&mt('Supplemental Content Editor').'">'
       &Apache::loncommon::help_open_menu('','',273,'RAT'));                         .'</a></li></ul></td></tr></table><br />';
            }
   my %allfiles = ();          if ($shown) {
   my %codebase = ();              if ($allowed) {
   my ($upload_result,$upload_output);                  $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
   if ($allowed) {                            .&Apache::loncommon::start_data_table(undef,'contentlist')
       if (($env{'form.uploaddoc.filename'}) &&                            .&Apache::loncommon::start_data_table_header_row()
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {                            .'<th colspan="2">'.&mt('Move').'</th>'
 # Process file upload - phase one - upload and parse primary file.                              .'<th colspan="2">'.&mt('Actions').'</th>'
   undef($hadchanges);                            .'<th>'.&mt('Document').'</th>';
           $upload_result = &process_file_upload(\$upload_output,$coursenum,                  if ($folder !~ /^supplemental/) {
  $coursedom,\%allfiles,                      $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
  \%codebase,$1);                  }
   if ($hadchanges) {                  $to_show .= &Apache::loncommon::end_data_table_header_row();
       &mark_hash_old();                  if ($folder !~ /^supplemental/) {
   }                      $lists{'canhide'} = join(',',@allidx);
           if ($upload_result eq 'phasetwo') {                      $lists{'canrandomlyorder'} = join(',',@allmapidx);
               $r->print($upload_output);                      my @possfilters = ('canremove','cancut','cancopy','hiddenresource','encrypturl',
           }                                         'randomorder','randompick');
       } elsif ($env{'form.phasetwo'}) {                      foreach my $item (@possfilters) {
           my %newname = ();                          if (ref($filters{$item}) eq 'ARRAY') {
           my %origname = ();                              if (@{$filters{$item}} > 0) {
           my %attribs = ();                                  $lists{$item} = join(',',@{$filters{$item}});
           my $updateflag = 0;                              }
           my $residx = $env{'form.newidx'};                          }
           my $primary_url = &unescape($env{'form.primaryurl'});                      }
 # Process file upload - phase two - gather secondary files.                      if (@allidx > 0) {
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {                          my $path;
               if ($env{'form.embedded_item_'.$i.'.filename'}) {                          if ($env{'form.folderpath'}) {
                   my $javacodebase;                              $path =
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);                                  &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});                          }
                   if (exists($env{'form.embedded_codebase_'.$i})) {                          if (@allidx > 1) {
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});                                $to_show .=
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;                                  &Apache::loncommon::continue_data_table_row().
                   }                                  '<td colspan="2">&nbsp;</td>'.
                   my @attributes = ();                                  '<td>'.
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {                                  &multiple_check_form('actions',\%lists).
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});                                  '</td>'.
                   } else {                                  '<td>&nbsp;</td>'.
                       @attributes = ($env{'form.embedded_attrib_'.$i});                                  '<td>&nbsp;</td>'.
                   }                                  '<td colspan="4">'.
                   foreach my $attr (@attributes) {                                  &multiple_check_form('settings',\%lists).
                       push(@{$attribs{$i}},&unescape($attr));                                  '</td>'.
                   }                                  &Apache::loncommon::end_data_table_row();
                   if ($javacodebase) {                               $need_save = 1;
                       $codebase{$i} = $javacodebase;                          }
                       $codebase{$i} =~ s#/$##;                      }
                       $updateflag = 1;                  }
                   }                  $to_show .= $output.' '
               }                             .&Apache::loncommon::end_data_table()
               unless ($newname{$i} eq $origname{$i}) {                             .'<br style="line-height:2px;" />'
                   $updateflag = 1;                             .&Apache::loncommon::end_scrollbox();
               }              } else {
           }                  $to_show .= $toolslink
 # Process file upload - phase three - modify primary file                             .&Apache::loncommon::start_data_table('LC_tableOfContent')
           if ($updateflag) {                             .$output.' '
               my ($content,$rtncode);                             .&Apache::loncommon::end_data_table();
               my $updateflag = 0;              }
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);          } else {
               if ($getstatus eq 'ok') {              if (!$allowed) {
                   foreach my $item (keys(%newname)) {                  $to_show .= $toolslink;
                       if ($newname{$item} ne $origname{$item}) {              }
                           my $attrib_regexp = '';              $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
                           if (@{$attribs{$item}} > 1) {                         .'<div class="LC_info" id="contentlist">'
                               $attrib_regexp = join('|',@{$attribs{$item}});                         .&mt('Currently empty')
                           } else {                         .'</div>'
                               $attrib_regexp = $attribs{$item}[0];                         .&Apache::loncommon::end_scrollbox();
                           }          }
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {      } else {
                           }          if ($shown) {
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;              $to_show = '<div>'
                       }                        .&Apache::loncommon::start_data_table('LC_tableOfContent')
                       if (exists($codebase{$item})) {                        .$output
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs                        .&Apache::loncommon::end_data_table()
                       }                        .'</div>';
                   }          } else {
 # Save edited file.              $to_show = '<div class="LC_info" id="contentlist">'
                   my $saveresult;                        .&mt('Currently empty')
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};                        .'</div>'
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};          }
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);      }
               } else {      my $tid = 1;
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);      if ($supplementalflag) {
               }          $tid = 2;
           }      }
       }      if ($allowed) {
   }          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
           $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,
   unless ($showdoc ||  $upload_result eq 'phasetwo') {                                         $jumpto,$readfile,$need_save,"$folder.$container"));
 # -----------------------------------------------------------------------------          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
        my %lt=&Apache::lonlocal::texthash(      } else {
                 'uplm' => 'Upload a new main '.lc($type).' document',          $r->print($to_show);
                 'upls' => 'Upload a new supplemental '.lc($type).' document',      }
                 'impp' => 'Import a document',      return;
                 'pubd' => 'Published Documents',  }
  'copm' => 'All documents out of a published map into this folder',  
                 'upld' => 'Upload Document',  sub multiple_check_form {
                 'srch' => 'Search',      my ($caller,$listsref) = @_;
                 'impo' => 'Import',      return unless (ref($listsref) eq 'HASH');
  'book' => 'Import Bookmarks',      my $output =
                 'selm' => 'Select Map',      '<form action="/adm/coursedocs" method="post" name="togglemult'.$caller.'">'.
                 'load' => 'Load Map',      '<span class="LC_nobreak" style="font-size:x-small;font-weight:bold;">'.
                 'reco' => 'Recover Deleted Resources',      '<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>'.
                 'newf' => 'New Folder',      '<div id="multi'.$caller.'" style="display:none;margin:0;padding:0;border:0">'.
                 'newp' => 'New Composite Page',      '<form action="/adm/coursedocs" method="post" name="cumulative'.$caller.'">'."\n".
                 'extr' => 'External Resource',      '<fieldset id="allfields'.$caller.'" style="display:none"><legend style="font-size:x-small;">'.&mt('check/uncheck all').'</legend>'."\n";
                 'syll' => 'Syllabus',      if ($caller eq 'settings') {
                 'navc' => 'Navigate Contents',          $output .= 
                 'sipa' => 'Simple Page',              '<table><tr>'.
                 'sipr' => 'Simple Problem',              '<td class="LC_docs_entry_parameter">'.
                 'drbx' => 'Drop Box',              '<span class="LC_nobreak"><label>'.
                 'scuf' => 'Score Upload Form',              '<input type="checkbox" name="hiddenresourceall" id="hiddenresourceall" onclick="propagateState(this.form,'."'hiddenresource'".')" />'.&mt('Hidden').
                 'bull' => 'Bulletin Board',              '</label></span></td>'.
                 'mypi' => 'My Personal Info',              '<td class="LC_docs_entry_parameter">'.
                 'grpo' => 'Group Files',              '<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="" />'.
                 'rost' => 'Course Roster',              '</span></td>'.
  'abou' => 'About User',              '</tr>'."\n".
                 'imsf' => 'Import IMS package',              '<tr>'.
                 'file' =>  'File',              '<td class="LC_docs_entry_parameter">'.
                 'title' => 'Title',              '<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').
                 'comment' => 'Comment',              '</label></span>'.
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',              '</td></tr></table>'."\n";
  'nd' => 'New Document',      } else {
  'pm' => 'Published Map',          $output .=
  'sd' => 'Special Document',              '<table><tr>'.
  'mo' => 'More Options',              '<td class="LC_docs_entry_parameter">'.
  'hao' => 'Hide all Options'              '<span class="LC_nobreak LC_docs_remove">'.
   );              '<label><input type="checkbox" name="removeall" id="removeall" onclick="propagateState(this.form,'."'remove'".')" />'.&mt('Remove').
 # -----------------------------------------------------------------------------              '</label></span></td>'.
  my $fileupload=(<<FIUP);              '<td class="LC_docs_entry_parameter">'.
  $lt{'file'}:<br />              '<span class="LC_nobreak LC_docs_cut">'.
  <input type="file" name="uploaddoc" size="40" />              '<label><input type="checkbox" name="cut" id="cutall" onclick="propagateState(this.form,'."'cut'".');" />'.&mt('Cut').
 FIUP              '</label></span></td>'."\n".
               '<td class="LC_docs_entry_parameter">'.
  my $checkbox=(<<CHBO);              '<span class="LC_nobreak LC_docs_copy">'.
  <!-- <label>$lt{'parse'}?              '<label><input type="checkbox" name="copyall" id="copyall" onclick="propagateState(this.form,'."'copy'".')" />'.&mt('Copy').
  <input type="checkbox" name="parserflag" />              '</label></span></td>'.
  </label> -->              '</tr></table>'."\n";
  <label>      }
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}      $output .= 
  </label>          '</fieldset>'.
 CHBO          '<input type="hidden" name="allidx" value="'.$listsref->{'canhide'}.'" />';
       if ($caller eq 'settings') {
  my $fileuploadform=(<<FUFORM);          $output .= 
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">          '<input type="hidden" name="allmapidx" value="'.$listsref->{'canrandomlyorder'}.'" />'."\n".
  $fileupload          '<input type="hidden" name="currhiddenresource" value="'.$listsref->{'hiddenresource'}.'" />'."\n".
  <br />          '<input type="hidden" name="currencrypturl" value="'.$listsref->{'encrypturl'}.'" />'."\n".
  $lt{'title'}:<br />          '<input type="hidden" name="currrandomorder" value="'.$listsref->{'randomorder'}.'" />'."\n".
  <input type="text" size="50" name="comment" />          '<input type="hidden" name="currrandompick" value="'.$listsref->{'randompick'}.'" />'."\n";
  $uploadtag      } elsif ($caller eq 'actions') {
  <input type="hidden" name="cmd" value="upload_default" />          $output .=
  <br />          '<input type="hidden" name="allremoveidx" id="allremoveidx" value="'.$listsref->{'canremove'}.'" />'.
  <span class="LC_nobreak">          '<input type="hidden" name="allcutidx" id="allcutidx" value="'.$listsref->{'cancut'}.'" />'.
  $checkbox          '<input type="hidden" name="allcopyidx" id="allcopyidx" value="'.$listsref->{'cancopy'}.'" />';
  </span>      }
  <br />      $output .= 
  <br />          '</form>'.
  <span class="LC_nobreak">          '</div>';
  <input type="submit" value="$lt{'upld'}" />      return $output;
  $help{'Uploading_From_Harddrive'}  }
  </span>  
  </form>  sub process_file_upload {
 FUFORM      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd,$crstype) = @_;
   # upload a file, if present
  my $simpleeditdefaultform=(<<SEDFFORM);      my $filesize = length($env{'form.uploaddoc'});
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">      if (!$filesize) {
  $lt{'pubd'}<br />          $$upload_output = '<div class="LC_error">'.
  $uploadtag                             &mt('Unable to upload [_1]. (size = [_2] bytes)',
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />                            '<span class="LC_filename">'.$env{'form.uploaddoc.filename'}.'</span>',
  <br />                            $filesize).'<br />'.
  <span class="LC_nobreak">                            &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />                            '</div>';
  $help{'Importing_LON-CAPA_Resource'}          return;
  </span>      }
  <br />      my $quotatype = 'unofficial';
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />      if ($crstype eq 'Community') {
  <hr />          $quotatype = 'community';
  <p>      } elsif ($env{'course.'.$coursedom.'_'.$coursenum.'.internal.instcode'}) {
  $lt{'copm'}<br />          $quotatype = 'official';
  <input type="text" size="40" name="importmap" /><br />      }
  <span class="LC_nobreak"><input type="button"      if (&Apache::loncommon::get_user_quota($coursenum,$coursedom,'course',$quotatype)) {
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"          $filesize = int($filesize/1000); #expressed in kb
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />          $$upload_output = &Apache::loncommon::excess_filesize_warning($coursenum,$coursedom,'course',
  $help{'Load_Map'}</span>                                                                        $env{'form.uploaddoc.filename'},$filesize,'upload');
  </p>          return if ($$upload_output);
  </form>      }
 SEDFFORM      my ($parseaction,$showupload,$nextphase,$mimetype);
       if ($env{'form.parserflag'}) {
  my $extresourcesform=(<<ERFORM);          $parseaction = 'parse';
  <form action="/adm/coursedocs" method="post" name="newext">      }
  $uploadtag      my $folder=$env{'form.folder'};
  <input type="hidden" name="importdetail" value="" />      if ($folder eq '') {
  <span class="LC_nobreak">          $folder='default';
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"      }
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  </span>          my $errtext='';
  </form>          my $fatal=0;
 ERFORM          my $container='sequence';
           if ($env{'form.folderpath'} =~ /:1$/) {
     if ($allowed) {              $container='page';
  &update_paste_buffer($coursenum,$coursedom);          }
        my %lt=&Apache::lonlocal::texthash(          ($errtext,$fatal)=
  'vc' => 'Verify Content',              &mapread($coursenum,$coursedom,$folder.'.'.$container);
  'cv' => 'Check/Set Resource Versions',          if ($#LONCAPA::map::order<1) {
  'ls' => 'List Symbs',              $LONCAPA::map::order[0]=1;
                                          'sl' => 'Show Log'              $LONCAPA::map::resources[1]='';
   );          }
           my $destination = 'docs/';
        my $folderpath=$env{'form.folderpath'};          if ($folder =~ /^supplemental/) {
        if (!$folderpath) {              $destination = 'supplemental/';
    if ($env{'form.folder'} eq '' ||          }
        $env{'form.folder'} eq 'supplemental') {          if (($folder eq 'default') || ($folder eq 'supplemental')) {
        $folderpath='default&'.              $destination .= 'default/';
    &escape(&mt('Main '.$type.' Documents'));          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
    }              $destination .=  $2.'/';
        }          }
        unless ($env{'form.pagepath'}) {          if ($fatal) {
            $containertag = '<input type="hidden" name="folderpath" value="" />';              $$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>';
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';              return;
        }          }
        $r->print(&generate_admin_options($containertag,$uploadtag,\%lt,\%help,\%env));  # this is for a course, not a user, so set context to coursedoc.
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',          my $newidx=&LONCAPA::map::getresidx();
      &mt('Editing the Table of Contents for your '.$type)));          $destination .= $newidx;
     }          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
 # --------------------------------------------------------- Standard documents   $parseaction,$allfiles,
     $r->print('<table class="LC_docs_documents">');   $codebase,undef,undef,undef,undef,
                                                   undef,undef,\$mimetype);
     if (($standard) && ($allowed) && (!$forcesupplement)) {          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
  $r->print('<tr><td class="LC_docs_document">');              my $stored = $1;
 #  '<h2>'.&mt('Main Course Documents').              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');                            $stored.'</span>').'</p>';
        my $folder=$env{'form.folder'};          } else {
        if ($folder eq '' || $folder eq 'supplemental') {              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
            $folder='default';              
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
            $uploadtag = '<input type="hidden" name="folderpath" value="'.              return;
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';          }
        }          my $ext='false';
        my $postexec='';          if ($url=~m{^http://}) { $ext='true'; }
        if ($folder eq 'default') {   $url     = &LONCAPA::map::qtunescape($url);
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');          my $comment=$env{'form.comment'};
        } else {   $comment = &LONCAPA::map::qtunescape($comment);
            #$postexec='self.close();';          if ($folder=~/^supplemental/) {
        }                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
        $hadchanges=0;                    $env{'user.domain'}.'___&&&___'.$comment;
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,          }
    $upload_output,$type);  
        if ($error) {          $LONCAPA::map::resources[$newidx]=
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');      $comment.':'.$url.':'.$ext.':normal:res';
        }          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
        if ($hadchanges) {          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
    &mark_hash_old();      $folder.'.'.$container,1);
        }          if ($fatal) {
        &changewarning($r,$postexec);              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.              return;
                      '.sequence';          } else {
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
                      '.page';                  $$upload_output = $showupload;
  my $container='sequence';                  my $total_embedded = scalar(keys(%{$allfiles}));
  if ($env{'form.pagepath'}) {                  if ($total_embedded > 0) {
     $container='page';                      my $uploadphase = 'upload_embedded';
  }                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
                       my ($embedded,$num) = 
                           &Apache::loncommon::ask_for_embedded_content(
                               '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
  my $recoverform=(<<RFORM);                      if ($embedded) {
  <form action="/adm/groupsort" method="post" name="recover">                          if ($num) {
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />                              $$upload_output .=
  </form>           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
 RFORM                              $nextphase = $uploadphase;
                           } else {
  my $imspform=(<<IMSPFORM);                              $$upload_output .= $embedded;
  <form action="/adm/imsimportdocs" method="post" name="ims">                          }
  <input type="hidden" name="folder" value="$folder" />                      } else {
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
  </form>                      }
 IMSPFORM                  } else {
                       $$upload_output .= &mt('No embedded items identified').'<br />';
  my $newnavform=(<<NNFORM);                  }
  <form action="/adm/coursedocs" method="post" name="newnav">                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
  $uploadtag              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
  <input type="hidden" name="importdetail"                  $nextphase = 'decompress_uploaded';
  value="$lt{'navc'}=/adm/navmaps" />                  my $position = scalar(@LONCAPA::map::order)-1;
  <span class="LC_nobreak">                  my $noextract = &return_to_editor();
  <input name="newnav" type="submit" value="$lt{'navc'}" />                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
  $help{'Navigate_Content'}                  my %archiveitems = (
  </span>                      folderpath => $env{'form.folderpath'},
  </form>                      cmd        => $nextphase,
 NNFORM                      newidx     => $newidx,
  my $newsmppageform=(<<NSPFORM);                      position   => $position,
  <form action="/adm/coursedocs" method="post" name="newsmppg">                      phase      => $nextphase,
  $uploadtag                      comment    => $comment,
  <input type="hidden" name="importdetail" value="" />                  );
  <span class="LC_nobreak">                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
  <input name="newsmppg" type="button" value="$lt{'sipa'}"                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}                  $$upload_output = $showupload.
  </span>                                    &Apache::loncommon::decompress_form($mimetype,
  </form>                                        $archiveurl,'/adm/coursedocs',$noextract,
 NSPFORM                                        \%archiveitems,\@current);
               }
  my $newsmpproblemform=(<<NSPROBFORM);          }
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">      }
  $uploadtag      return $nextphase;
  <input type="hidden" name="importdetail" value="" />  }
  <span class="LC_nobreak">  
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"  sub get_dir_list {
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}      my ($url,$coursenum,$coursedom,$newidx) = @_;
  </span>      my ($destination,$dir_root) = &embedded_destination();
  </form>      my ($dirlistref,$listerror) =  
           &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
 NSPROBFORM      my @dir_lines;
       my $dirptr=16384;
  my $newdropboxform=(<<NDBFORM);      if (ref($dirlistref) eq 'ARRAY') {
  <form action="/adm/coursedocs" method="post" name="newdropbox">          foreach my $dir_line (sort
  $uploadtag                                  {
  <input type="hidden" name="importdetail" value="" />                                my ($afile)=split('&',$a,2);
  <span class="LC_nobreak">                                          my ($bfile)=split('&',$b,2);
  <input name="newdropbox" type="button" value="$lt{'drbx'}"                                return (lc($afile) cmp lc($bfile));
  onClick="javascript:makedropbox();" />                            } (@{$dirlistref})) {
  </span>                      my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
  </form>              $filename =~ s/\s+$//;
 NDBFORM              next if ($filename =~ /^\.\.?$/); 
               my $isdir = 0;
  my $newexuploadform=(<<NEXUFORM);              if ($dirptr&$testdir) {
  <form action="/adm/coursedocs" method="post" name="newexamupload">                  $isdir = 1;
  $uploadtag              }
  <input type="hidden" name="importdetail" value="" />              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
  <span class="LC_nobreak">          }
  <input name="newexamupload" type="button" value="$lt{'scuf'}"      }
  onClick="javascript:makeexamupload();" />      return @dir_lines;
  $help{'Score_Upload_Form'}  }
  </span>  
  </form>  sub is_supplemental_title {
 NEXUFORM      my ($title) = @_;
       return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
  my $newbulform=(<<NBFORM);  }
  <form action="/adm/coursedocs" method="post" name="newbul">  
  $uploadtag  # --------------------------------------------------------------- An entry line
  <input type="hidden" name="importdetail" value="" />  
  <span class="LC_nobreak">  sub entryline {
  <input name="newbulletin" type="button" value="$lt{'bull'}"      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
  onClick="javascript:makebulboard();" />          $crstype,$pathitem,$supplementalflag,$container,$filtersref,$currgroups)=@_;
  $help{'Bulletin Board'}      my ($foldertitle,$renametitle);
  </span>      if (&is_supplemental_title($title)) {
  </form>   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
 NBFORM      } else {
    $title=&HTML::Entities::encode($title,'"<>&\'');
  my $newaboutmeform=(<<NAMFORM);   $renametitle=$title;
  <form action="/adm/coursedocs" method="post" name="newaboutme">   $foldertitle=$title;
  $uploadtag      }
  <input type="hidden" name="importdetail"  
  value="$plainname=/adm/$udom/$uname/aboutme" />      my $orderidx=$LONCAPA::map::order[$index];
  <span class="LC_nobreak">  
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      $renametitle=~s/\\/\\\\/g;
  $help{'My Personal Info'}      $renametitle=~s/\&quot\;/\\\"/g;
  </span>      $renametitle=~s/ /%20/g;
  </form>      my $line=&Apache::loncommon::start_data_table_row();
 NAMFORM      my ($form_start,$form_end,$form_common,$form_param);
   # Edit commands
  my $newaboutsomeoneform=(<<NASOFORM);      my ($esc_path, $path, $symb);
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">      if ($env{'form.folderpath'}) {
  $uploadtag   $esc_path=&escape($env{'form.folderpath'});
  <input type="hidden" name="importdetail" value="" />   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  <span class="LC_nobreak">   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"      }
  onClick="javascript:makeabout();" />      my $isexternal;
  </span>      if ($residx) {
  </form>          my $currurl = $url;
 NASOFORM          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
           if ($currurl =~ m{^/adm/wrapper/ext/}) {
               $isexternal = 1;
  my $newrosterform=(<<NROSTFORM);          }
  <form action="/adm/coursedocs" method="post" name="newroster">          if (!$supplementalflag) {
  $uploadtag              my $path = 'uploaded/'.
  <input type="hidden" name="importdetail"                         $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
  value="$lt{'rost'}=/adm/viewclasslist" />                         $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
  <span class="LC_nobreak">              $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
  <input name="newroster" type="submit" value="$lt{'rost'}" />                                                   $residx,
  $help{'Course Roster'}                                                   &Apache::lonnet::declutter($currurl));
  </span>          }
  </form>      }
 NROSTFORM      my ($renamelink,%lt,$ishash);
       if (ref($filtersref) eq 'HASH') {
        $r->print(<<ENDFORM);          $ishash = 1;
       }
 <ul class="LC_TabContent">  
 <li>$lt{'nd'}</li>      if ($allowed) {
 <li>$lt{'pm'}</li>          $form_start = '
 <li>$lt{'pubd'}</li>     <form action="/adm/coursedocs" method="post">
 <li>$lt{'sd'}</li>  ';
 <li>$lt{'mo'}</li>          $form_common=(<<END);
 <li>$lt{'hao'}</li>     <input type="hidden" name="folderpath" value="$path" />
 </ul>     <input type="hidden" name="symb" value="$symb" />
   END
 <table class="LC_docs_adddocs">          $form_param=(<<END);
 <!-- <tr>     <input type="hidden" name="setparms" value="$orderidx" />
 <th>$lt{'uplm'}</th>     <input type="hidden" name="changeparms" value="0" />
 <th>$lt{'impp'}</th>  END
 <th>$lt{'spec'}</th>          $form_end = '</form>';
 </tr> -->  
 <tr>   my $incindex=$index+1;
 <td>   my $selectbox='';
 $fileuploadform   if (($#LONCAPA::map::order>0) &&
 </td>      ((split(/\:/,
 <td>       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
 $simpleeditdefaultform       ne '') &&
 <hr />      ((split(/\:/,
 $recoverform       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
 ENDFORM       ne '')) {
        unless ($env{'form.pagepath'}) {      $selectbox=
    $r->print(<<ENDFORM);   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
 <hr />   '<select name="newpos" onchange="this.form.submit()">';
 $extresourcesform      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
  <br />   if ($i==$incindex) {
 $imspform      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
 ENDFORM   } else {
        }      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
        $r->print('</td><td>');   }
        unless ($env{'form.pagepath'}) {      }
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      $selectbox.='</select>';
    }
    %lt=&Apache::lonlocal::texthash(
                   'up' => 'Move Up',
  my $newpageform=(<<NPFORM);   'dw' => 'Move Down',
  <form action="/adm/coursedocs" method="post" name="newpage">   'rm' => 'Remove',
  <input type="hidden" name="folderpath" value="$path" />                  'ct' => 'Cut',
  <input type="hidden" name="importdetail" value="" />   'rn' => 'Rename',
  <span class="LC_nobreak">   'cp' => 'Copy',
  <input name="newpage" type="button"                  'ex' => 'External Resource',
  onClick="javascript:makenewpage(this.form,'$pageseq');"                  'ed' => 'Edit',
  value="$lt{'newp'}" />$help{'Adding_Pages'}                  'pr' => 'Preview',
  </span>                  'sv' => 'Save',
  </form>                  'ul' => 'URL',
 NPFORM                  'ti' => 'Title', 
                   );
  my $newfolderform=(<<NFFORM);   my %denied = &action_restrictions($coursenum,$coursedom,$url,
  <form action="/adm/coursedocs" method="post" name="newfolder">                                            $env{'form.folderpath'},
  <input type="hidden" name="folderpath" value="$path" />                                            $currgroups);
  <input type="hidden" name="importdetail" value="" />          my ($copylink,$cutlink,$removelink);
  <span class="LC_nobreak">   my $skip_confirm = 0;
  <input name="newfolder" type="button"   if ( $folder =~ /^supplemental/
  onClick="javascript:makenewfolder(this.form,'$folderseq');"       || ($url =~ m{( /smppg$
  value="$lt{'newf'}" />$help{'Adding_Folders'}      |/syllabus$
  </span>      |/aboutme$
  </form>      |/navmaps$
 NFFORM      |/bulletinboard$
       |\.html$)}x)
  my $newsylform=(<<NSYLFORM);               || $isexternal) {
  <form action="/adm/coursedocs" method="post" name="newsyl">      $skip_confirm = 1;
  $uploadtag   }
  <input type="hidden" name="importdetail"  
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />   if ($denied{'copy'}) {
  <span class="LC_nobreak">              $copylink=(<<ENDCOPY)
  <input name="newsyl" type="submit" value="$lt{'syll'}" />  <span style="visibility: hidden;">$lt{'cp'}</span>
  $help{'Syllabus'}  ENDCOPY
  </span>          } else {
  </form>              my $formname = 'edit_copy_'.$orderidx;
 NSYLFORM              my $js = "javascript:checkForSubmit(document.forms.renameform,'copy','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
       $copylink=(<<ENDCOPY);
  my $newgroupfileform=(<<NGFFORM);  <form name="$formname" method="post" action="/adm/coursedocs">
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">  $form_common
  $uploadtag  <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>
  <input type="hidden" name="importdetail"  $form_end
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />  ENDCOPY
  <span class="LC_nobreak">              if (($ishash) && (ref($filtersref->{'cancopy'}) eq 'ARRAY')) {
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />                  push(@{$filtersref->{'cancopy'}},$orderidx);
  $help{'Group Files'}              }
  </span>          }
  </form>   if ($denied{'cut'}) {
 NGFFORM              $cutlink=(<<ENDCUT);
   <span style="visibility: hidden;">$lt{'ct'}</span>
   ENDCUT
            $r->print(<<ENDFORM);          } else {
 <br />              my $formname = 'edit_cut_'.$orderidx;
 $newfolderform              my $js = "javascript:checkForSubmit(document.forms.renameform,'cut','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm,'$container','$folder');";
 <br />      $cutlink=(<<ENDCUT);
 $newpageform  <form name="$formname" method="post" action="/adm/coursedocs">
 <br />  $form_common
 $newsylform  <input type="hidden" name="skip_$orderidx" id="skip_cut_$orderidx" value="$skip_confirm" />
 <br />  <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>
 $newnavform  $form_end
 <br />  ENDCUT
 $newsmppageform              if (($ishash) && (ref($filtersref->{'cancut'}) eq 'ARRAY')) {
 <br />                  push(@{$filtersref->{'cancut'}},$orderidx);
 $newsmpproblemform              }
 <br />          }
 $newdropboxform          if ($denied{'remove'}) {
 <br />              $removelink=(<<ENDREM);
 $newexuploadform  <span style="visibility: hidden;">$lt{'rm'}</a>
 <br />  ENDREM
 $newbulform          } else {
 <br />              my $formname = 'edit_remove_'.$orderidx;
 $newaboutmeform              my $js = "javascript:checkForSubmit(document.forms.renameform,'remove','actions','$orderidx','$esc_path','$index','$renametitle',$skip_confirm);";
 <br />              $removelink=(<<ENDREM);
 $newaboutsomeoneform  <form name="$formname" method="post" action="/adm/coursedocs">
 <br />  $form_common
 $newgroupfileform  <input type="hidden" name="skip_$orderidx" id="skip_remove_$orderidx" value="$skip_confirm" />
 <br />  <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>
 $newrosterform  $form_end
 ENDFORM  ENDREM
        }              if (($ishash) && (ref($filtersref->{'canremove'}) eq 'ARRAY')) {
        if ($env{'form.pagepath'}) {                  push(@{$filtersref->{'canremove'}},$orderidx);
            $r->print(<<ENDBLOCK);              }
 $newsmpproblemform          }
 <br />          $renamelink=(<<ENDREN);
 $newexuploadform  <a href='javascript:changename("$esc_path","$index","$renametitle");' class="LC_docs_rename">$lt{'rn'}</a>
 ENDBLOCK  ENDREN
        }   $line.=(<<END);
        $r->print('</td></tr>'."\n".  <td>
 '</table>');  <div class="LC_docs_entry_move">
        $r->print('</td></tr>');    <a href='/adm/coursedocs?cmd=up_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
     }      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
 # ----------------------------------------------------- Supplemental documents    </a>
     if (!$forcestandard) {  </div>
        $r->print('<tr><td class="LC_docs_document">');  <div class="LC_docs_entry_move">
 # '<h2>'.&mt('Supplemental Course Documents').    <a href='/adm/coursedocs?cmd=down_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
        my $folder=$env{'form.folder'};    </a>
        unless ($folder=~/^supplemental/) {  </div>
    $folder='supplemental';  </td>
        }  <td>
        if ($folder =~ /^supplemental$/ &&     $form_start
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {     $form_param
           $env{'form.folderpath'} = 'supplemental&'.     $form_common
                                     &escape(&mt('Supplemental '.$type.' Documents'));     $selectbox
        }     $form_end
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);  </td>
        if ($error) {  <td class="LC_docs_entry_commands LC_nobreak">
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');  $removelink
        }  $cutlink
        if ($allowed) {  $copylink
    my $folderseq=  </td>
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.  END
        '.sequence';      }
   # Figure out what kind of a resource this is
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      my ($extension)=($url=~/\.(\w+)$/);
       my $uploaded=($url=~/^\/*uploaded\//);
  my $supupdocform=(<<SUPDOCFORM);      my $icon=&Apache::loncommon::icon($url);
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">      my $isfolder;
  $fileupload      my $ispage;
  <br />      my $containerarg;
  <br />      if ($uploaded) {
  <span class="LC_nobreak">          if (($extension eq 'sequence') || ($extension eq 'page')) {
  $checkbox              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
  </span>              $containerarg = $1;
  <br /><br />      if ($extension eq 'sequence') {
  $lt{'comment'}:<br />          $icon=$iconpath.'navmap.folder.closed.gif';
  <textarea cols=50 rows=4 name='comment'>                  $isfolder=1;
  </textarea>              } else {
  <br />                  $icon=$iconpath.'page.gif';
  <input type="hidden" name="folderpath" value="$path" />                  $ispage=1;
  <input type="hidden" name="cmd" value="upload_supplemental" />              }
  <span class="LC_nobreak">              if ($allowed) {
  <input type="submit" value="$lt{'upld'}" />                  $url='/adm/coursedocs?';
  $help{'Uploading_From_Harddrive'}              } else {
  </span>                  $url='/adm/supplemental?';
  </form>              }
 SUPDOCFORM   } else {
       &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
  my $supnewfolderform=(<<SNFFORM);   }
  <form action="/adm/coursedocs" method="post" name="supnewfolder">      }
  <input type="hidden" name="folderpath" value="$path" />  
  <input type="hidden" name="importdetail" value="" />      my ($editlink,$extresform);
  <span class="LC_nobreak">      my $orig_url = $url;
  <input name="newfolder" type="button"      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
  value="$lt{'newf'}" /> $help{'Adding_Folders'}      if (!$supplementalflag && $residx && $symb) {
  </span>          if ((!$isfolder) && (!$ispage)) {
  </form>      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 SNFFORM      $url=&Apache::lonnet::clutter($url);
       if ($url=~/^\/*uploaded\//) {
           $url=~/\.(\w+)$/;
  my $supnewextform=(<<SNEFORM);          my $embstyle=&Apache::loncommon::fileembstyle($1);
  <form action="/adm/coursedocs" method="post" name="supnewext">          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
  <input type="hidden" name="folderpath" value="$path" />      $url='/adm/wrapper'.$url;
  <input type="hidden" name="importdetail" value="" />          } elsif ($embstyle eq 'ssi') {
  <span class="LC_nobreak">      #do nothing with these
  <input name="newext" type="button"          } elsif ($url!~/\.(sequence|page)$/) {
  onClick="javascript:makenewext('supnewext');"      $url='/adm/coursedocs/showdoc'.$url;
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}          }
  </span>      } elsif ($url=~m|^/ext/|) {
  </form>          $url='/adm/wrapper'.$url;
 SNEFORM      }
               if (&Apache::lonnet::symbverify($symb,$url)) {
  my $supnewsylform=(<<SNSFORM);          $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  <form action="/adm/coursedocs" method="post" name="supnewsyl">              } else {
  <input type="hidden" name="folderpath" value="$path" />                  $url='';
  <input type="hidden" name="importdetail"              }
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />   }
  <span class="LC_nobreak">      }
  <input name="newsyl" type="submit" value="$lt{'syll'}" />      my ($rand_pick_text,$rand_order_text);
  $help{'Syllabus'}      if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
  </span>   my $foldername=&escape($foldertitle);
  </form>   my $folderpath=$env{'form.folderpath'};
 SNSFORM   if ($folderpath) { $folderpath.='&' };
           if (!$allowed && $supplementalflag) {
  my $supnewaboutmeform=(<<SNAMFORM);              $folderpath.=$containerarg.'&'.$foldername;
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">              $url.='folderpath='.&escape($folderpath);
  <input type="hidden" name="folderpath" value="$path" />          } else {
  <input type="hidden" name="importdetail"  # Append randompick number, hidden, and encrypted with ":" to foldername,
  value="$plainname=/adm/$udom/$uname/aboutme" />  # so it gets transferred between levels
  <span class="LC_nobreak">      $folderpath.=$containerarg.'&'.$foldername.
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />                                                ':'.(&LONCAPA::map::getparameter($orderidx,
  $help{'My Personal Info'}                                                'parameter_randompick'))[0]
  </span>                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  </form>                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
 SNAMFORM                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                                                 'parameter_encrypturl'))[0]=~/^yes$/i)
    $r->print(<<ENDSUPFORM);                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
 <ul class="LC_TabContent">                                                'parameter_randomorder'))[0]=~/^yes$/i)
 <li>$lt{'nd'}</li>                                                 .':'.$ispage;
 <li>$lt{'sd'}</li>      $url.='folderpath='.&escape($folderpath);
 <li>$lt{'hao'}</li>              my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
 </ul>                                                          'parameter_randompick'))[0];
 <table class="LC_docs_adddocs">              my $rpckchk;
 <tr><td>              if ($rpicknum) {
 $supupdocform                  $rpckchk = ' checked="checked"';
 </td>                  if (($ishash) && (ref($filtersref->{'randompick'}) eq 'ARRAY')) {
 <td>                      push(@{$filtersref->{'randompick'}},$orderidx.':'.$rpicknum);
 $supnewfolderform                  }
 <br />              }
 $supnewextform              my $formname = 'edit_randompick_'.$orderidx;
 <br />      $rand_pick_text = 
 $supnewsylform  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
 <br />  $form_param."\n".
 $supnewaboutmeform  $form_common."\n".
 </td></tr>  '<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.'">';
 </table></td></tr>              if ($rpicknum ne '') {
 ENDSUPFORM                  $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
        }              }
     }              $rand_pick_text .= '</span></span>'.
     $r->print('</table>');                                 $form_end;
     if ($allowed) {              my $ro_set;
  $r->print('              if ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i) {
 <form method="post" name="extimport" action="/adm/coursedocs">                  $ro_set = 'checked="checked"';
   <input type="hidden" name="title" />                  if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
   <input type="hidden" name="url" />                      push(@{$filtersref->{'randomorder'}},$orderidx);
   <input type="hidden" name="useform" />                  }
   <input type="hidden" name="residx" />              }
 </form>');              my $formname = 'edit_rorder_'.$orderidx;
     }      $rand_order_text = 
   } else {  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
       unless ($upload_result eq 'phasetwo') {  $form_param."\n".
 # -------------------------------------------------------- This is showdoc mode  $form_common."\n".
           $r->print("<h1>".&mt('Uploaded Document').' - '.  '<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>'.
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.  $form_end;
 &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>');      } elsif ($supplementalflag && !$allowed) {
       }          $url .= ($url =~ /\?/) ? '&amp;':'?';
   }          $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
  }          if ($title) {
  $r->print(&Apache::loncommon::end_page());              $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
  return OK;          }
 }          if ($isexternal && $orderidx) {
               $url .= '&amp;idx='.$orderidx;
 sub generate_admin_options {          }
   my ($containertag,$uploadtag,$lt_ref,$help_ref,$env_ref) = @_;      }
   my %lt = %{$lt_ref};      my ($tdalign,$tdwidth);
   my %help = %{$help_ref};      if ($allowed) {
   my %env = %{$env_ref};          my $fileloc = 
   my $dumpbut=&dumpbutton();              &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
   my $exportbut=&exportbutton();          if ($isexternal) {
   return (<<ENDOPTIONFORM);              ($editlink,$extresform) = 
  <form name="renameform" method="post" action="/adm/coursedocs">                  &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
    <input type="hidden" name="title" />          } elsif (!$isfolder && !$ispage) {
    <input type="hidden" name="cmd" />              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
    <input type="hidden" name="markcopy" />                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
    <input type="hidden" name="copyfolder" />              if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
    $containertag                  my $jscall = 
  </form>                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
  <form name="simpleedit" method="post" action="/adm/coursedocs">                                                              $switchserver,
    <input type="hidden" name="importdetail" value="" />                                                              $forceedit,
    $uploadtag                                                              undef,$symb,
  </form>                                                              &escape($env{'form.folderpath'}),
  <form action="/adm/coursedocs" method="post" name="courseverify">                                                              $renametitle,'','',1);
    <ul style="list-style-type:none">                  if ($jscall) {
        <li>                      $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
            <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}                                  $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
        </li>                  }
        <li>              }
            <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}          }
        </li>          $tdalign = ' align="right" valign="top"';
        <li>          $tdwidth = ' width="80%"';
            $dumpbut      }
        </li>      my $reinit;
        <li>      if ($crstype eq 'Community') {
            $exportbut          $reinit = &mt('(re-initialize community to access)');
        </li>      } else {
        <li>          $reinit = &mt('(re-initialize course to access)');
           <input type="submit" name="listsymbs" value="$lt{'ls'}" />      }
         </li>      $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
         <li>      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
           <input type="hidden" name="folder" value="$env{'form.folder'}" />         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
           <input type="submit" name="docslog" value="$lt{'sl'}" />      } elsif ($url) {
         </li>         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
    </ul>                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
  </form>      } else {
  <div style="clear: both; height: 0px;">&nbsp;</div>         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
 ENDOPTIONFORM      }
 }      $line.='</span></td><td'.$tdwidth.'>';
       if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 sub generate_edit_table {         $line.='<a href="'.$url.'">'.$title.'</a>';
     my ($optionhash_ref,$namehash_ref,$orderhash_ref) = @_;      } elsif ($url) {
     my %optionhash = %{$optionhash_ref};         #id verlinkt mit inhalt         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
     my %namehash = %{$namehash_ref};             #name verlinkt mit id                                               $title,600,500);
     my %orderhash = %{$orderhash_ref};           #name mit kürzel verlinkt mit name      } else {
     my $form;         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
     $form = '<div class="LC_ContentBoxSpecial"><h4 class="LC_hcell">'.&mt('Upload Course Documents').'<h4>';      }
     $form .= '<ul class="LC_TabContent">';      $line.="$extresform</td>";
     foreach my $name (sort(keys(%orderhash))){      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
         if($name eq 'zz_hide'){      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
             $form .= '<li><a onclick="hideAllSection();" href="#">'.&mt($orderhash{$name}).'</a></li>';      if (($allowed) && ($folder!~/^supplemental/)) {
         }else{    my %lt=&Apache::lonlocal::texthash(
             $form .= '<li><a onclick="popUpSection(\''.$namehash{$orderhash{$name}}.'\');" href="#">'.&mt($orderhash{$name}).'</a></li>';         'hd' => 'Hidden',
         }         'ec' => 'URL hidden');
     }          my ($enctext,$hidtext);
     foreach my $field (keys(%optionhash)){          if ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i) {
         $form .= '<div id="'.$field.'" class="LC_ContentBox LC_hideThis">'.$optionhash{$field}.'</div>';              $enctext = ' checked="checked"';
     }              if (($ishash) && (ref($filtersref->{'encrypturl'}) eq 'ARRAY')) {
     $form .= '</div>';                  push(@{$filtersref->{'encrypturl'}},$orderidx);
     return $form;              }
 }          }
           if ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i) {
 sub editing_js {              $hidtext = ' checked="checked"';
     my ($udom,$uname) = @_;              if (($ishash) && (ref($filtersref->{'randomorder'}) eq 'ARRAY')) {
     my $now = time();                  push(@{$filtersref->{'hiddenresource'}},$orderidx);
     my %lt = &Apache::lonlocal::texthash(              }
                                           p_mnf => 'Name of New Folder',          }
                                           t_mnf => 'New Folder',          my $formhidden = 'edit_hiddenresource_'.$orderidx;
                                           p_mnp => 'Name of New Page',          my $formurlhidden = 'edit_encrypturl_'.$orderidx;
                                           t_mnp => 'New Page',   $line.=(<<ENDPARMS);
                                           p_mxu => 'Title for the Uploaded Score',    <td class="LC_docs_entry_parameter">
                                           p_msp => 'Title for the Page',      <form action="/adm/coursedocs" method="post" name="$formhidden">
                                           p_msb => 'Title for the Problem',      $form_param
                                           p_mdb => 'Title for the Drop Box',      $form_common
                                           p_mbb => 'Title for the Bulletin Board',      <label><input type="checkbox" name="hiddenresource_$orderidx" id="hiddenresource_$orderidx" onclick="checkForSubmit(this.form,'hiddenresource','settings');" $hidtext /> $lt{'hd'}</label>
                                           p_mab => "Enter user:domain for User's 'About Me' Page",      $form_end
                                           p_mab2 => "About [_99]",      <br />
                                           p_mab_alrt1 => 'Not a valid user:domain',      <form action="/adm/coursedocs" method="post" name="$formurlhidden">
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',      $form_param
                                           p_chn => 'New Title',      $form_common
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',      <label><input type="checkbox" name="encrypturl_$orderidx" id="encrypturl_$orderidx" onclick="checkForSubmit(this.form,'encrypturl','settings');" $enctext /> $lt{'ec'}</label>
                                           p_rmr2a => 'Remove[_99]',      $form_end
                                           p_rmr2b => '?[_99]',    </td>
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',                                        $rand_order_text</td>
                                           p_ctr2a => 'Cut[_98]',  ENDPARMS
                                           p_ctr2b => '?[_98]'      }
                                         );      $line.=&Apache::loncommon::end_data_table_row();
       return $line;
     return <<ENDNEWSCRIPT;  }
 function makenewfolder(targetform,folderseq) {  
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');  sub action_restrictions {
     if (foldername) {      my ($cnum,$cdom,$url,$folderpath,$currgroups) = @_;
        targetform.importdetail.value=escape(foldername)+"="+folderseq;      my %denied = (
         targetform.submit();                     cut    => 0,
     }                     copy   => 0,
 }                     remove => 0,
                    );
 function makenewpage(targetform,folderseq) {      if ($url=~ m{^/res/.+\.(page|sequence)$}) {
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');          # no copy for published maps
     if (pagename) {          $denied{'copy'} = 1;
         targetform.importdetail.value=escape(pagename)+"="+folderseq;      } elsif ($url=~m{^/res/lib/templates/}) {
         targetform.submit();         $denied{'copy'} = 1;
     }         $denied{'cut'} = 1;
 }      } elsif ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
           if ($folderpath =~ /^default&[^\&]+$/) {
 function makenewext(targetname) {              if ((ref($currgroups) eq 'HASH') && (keys(%{$currgroups}) > 0)) {
     this.document.forms.extimport.useform.value=targetname;                  $denied{'remove'} = 1;
     this.document.forms.extimport.title.value='';              }
     this.document.forms.extimport.url.value='';              $denied{'cut'} = 1;
     this.document.forms.extimport.residx.value='';              $denied{'copy'} = 1;
     window.open('/adm/rat/extpickframe.html');          }
 }      } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
           my $group = $1;
 function edittext(targetname,residx,title,url) {          if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
     this.document.forms.extimport.useform.value=targetname;              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
     this.document.forms.extimport.residx.value=residx;                  $denied{'remove'} = 1;
     this.document.forms.extimport.url.value=url;              }
     this.document.forms.extimport.title.value=title;          }
     window.open('/adm/rat/extpickframe.html');          $denied{'cut'} = 1;
 }          $denied{'copy'} = 1;
       } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
 function makeexamupload() {          my $group = $1;
    var title=prompt('$lt{"p_mxu"}');          if ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
    if (title) {              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
     this.document.forms.newexamupload.importdetail.value=                  my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
  escape(title)+'=/res/lib/templates/examupload.problem';                  if (keys(%groupsettings) > 0) {
     this.document.forms.newexamupload.submit();                      $denied{'remove'} = 1;
    }                  }
 }                  $denied{'cut'} = 1;
                   $denied{'copy'} = 1;
 function makesmppage() {              }
    var title=prompt('$lt{"p_msp"}');          }
    if (title) {      } elsif ($folderpath =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
     this.document.forms.newsmppg.importdetail.value=          my $group = $1;
  escape(title)+'=/adm/$udom/$uname/$now/smppg';          if ($url =~ /group_boards_\Q$group\E/) {
     this.document.forms.newsmppg.submit();              if ((ref($currgroups) eq 'HASH') && (exists($currgroups->{$group}))) {
    }                  my %groupsettings = &Apache::longroup::get_group_settings($currgroups->{$group});
 }                  if (keys(%groupsettings) > 0) {
                       if (ref($groupsettings{'functions'}) eq 'HASH') {
 function makesmpproblem() {                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
    var title=prompt('$lt{"p_msb"}');                              $denied{'remove'} = 1;
    if (title) {                          }
     this.document.forms.newsmpproblem.importdetail.value=                      }
  escape(title)+'=/res/lib/templates/simpleproblem.problem';                  }
     this.document.forms.newsmpproblem.submit();                  $denied{'cut'} = 1;
    }                  $denied{'copy'} = 1;
 }              }
           }
 function makedropbox() {      }
    var title=prompt('$lt{"p_mdb"}');      return %denied;
    if (title) {  }
     this.document.forms.newdropbox.importdetail.value=  
         escape(title)+'=/res/lib/templates/DropBox.problem';  sub new_timebased_suffix {
     this.document.forms.newdropbox.submit();      my ($dom,$num,$type,$area,$container) = @_;
    }      my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
 }      if ($type eq 'paste') {
           $prefix = $type;
 function makebulboard() {          $namespace = 'courseeditor';
    var title=prompt('$lt{"p_mbb"}');      } elsif ($type eq 'map') {
    if (title) {          $prefix = 'docs';
     this.document.forms.newbul.importdetail.value=          if ($area eq 'supplemental') {
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';              $prefix = 'supp';
     this.document.forms.newbul.submit();          }
    }          $prefix .= $container;
 }          $namespace = 'uploadedmaps';
       } else {
 function makeabout() {          $prefix = $type;
    var user=prompt("$lt{'p_mab'}");          $namespace = 'templated';
    if (user) {      }
        var comp=new Array();      $idtype = 'concat';
        comp=user.split(':');      my ($suffix,$freedlock,$error) =
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {          &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,$dom,$num);
    if ((comp[0]) && (comp[1])) {      if (!$suffix) {
        this.document.forms.newaboutsomeone.importdetail.value=          if ($type eq 'paste') {
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';              $errtext = &mt('Failed to acquire a unique timestamp-based suffix when adding to the paste buffer.');
        this.document.forms.newaboutsomeone.submit();          } elsif ($type eq 'map') {
    } else {              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
                alert("$lt{'p_mab_alrt1'}");          } elsif ($type eq 'smppg') {
            }              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
        } else {          } else {
            alert("$lt{'p_mab_alrt2'}");              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new bulletin board.');
        }          }
    }          if ($error) {
 }              $errtext .= '<br />'.$error;
           }
 function makeims() {      }
     var caller = document.forms.ims.folder.value;      if ($freedlock ne 'ok') {
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";          $locknotfreed =
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");              '<div class="LC_error">'.
     newWindow.location.href = newlocation;              &mt('There was a problem removing a lockfile.').' ';
 }          if ($type eq 'paste') {
               &mt('This will prevent use of the paste buffer until th next log-in.');
           } elsif ($type eq 'map') {
 function finishpick() {              &mt('This will prevent creation of additional folders or composite pages in this course.');
     var title=this.document.forms.extimport.title.value;          } elsif ($type eq 'smppg') {
     var url=this.document.forms.extimport.url.value;              $locknotfreed .=
     var form=this.document.forms.extimport.useform.value;                  &mt('This will prevent creation of additional simple pages in this course.');
     var residx=this.document.forms.extimport.residx.value;          } else {
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');              $locknotfreed .=
 }                  &mt('This will prevent creation of additional bulletin boards in this course.');
           }
 function changename(folderpath,index,oldtitle,container,pagesymb) {          unless ($type eq 'paste') {
     var title=prompt('$lt{"p_chn"}',oldtitle);              $locknotfreed .=
     if (title) {                  ' '.&mt('Please contact the [_1]helpdesk[_2] for assistance.',
  this.document.forms.renameform.markcopy.value=-1;                          '<a href="/adm/helpdesk" target="_helpdesk">','</a>');
  this.document.forms.renameform.title.value=title;          }
  this.document.forms.renameform.cmd.value='rename_'+index;          $locknotfreed .= '</div>';
         if (container == 'sequence') {      }
     this.document.forms.renameform.folderpath.value=folderpath;      return ($suffix,$errtext,$locknotfreed);
         }  }
         if (container == 'page') {  
             this.document.forms.renameform.pagepath.value=folderpath;  =pod
             this.document.forms.renameform.pagesymb.value=pagesymb;  
         }  =item tiehash()
         this.document.forms.renameform.submit();  
     }  tie the hash
 }  
   =cut
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {  
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {  sub tiehash {
  this.document.forms.renameform.markcopy.value=-1;      my ($mode)=@_;
  this.document.forms.renameform.cmd.value='del_'+index;      $hashtied=0;
         if (container == 'sequence') {      if ($env{'request.course.fn'}) {
             this.document.forms.renameform.folderpath.value=folderpath;   if ($mode eq 'write') {
         }      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
         if (container == 'page') {      &GDBM_WRCREAT(),0640)) {
             this.document.forms.renameform.pagepath.value=folderpath;                  $hashtied=2;
             this.document.forms.renameform.pagesymb.value=pagesymb;      }
         }   } else {
         this.document.forms.renameform.submit();      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     }      &GDBM_READER(),0640)) {
 }                  $hashtied=1;
       }
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {   }
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {      }
  this.document.forms.renameform.cmd.value='cut_'+index;  }
  this.document.forms.renameform.markcopy.value=index;  
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;  sub untiehash {
         if (container == 'sequence') {      if ($hashtied) { untie %hash; }
             this.document.forms.renameform.folderpath.value=folderpath;      $hashtied=0;
         }      return OK;
         if (container == 'page') {  }
             this.document.forms.renameform.pagepath.value=folderpath;  
             this.document.forms.renameform.pagesymb.value=pagesymb;  
         }  
         this.document.forms.renameform.submit();  
     }  sub checkonthis {
 }      my ($r,$url,$level,$title)=@_;
       $url=&unescape($url);
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {      $alreadyseen{$url}=1;
     this.document.forms.renameform.markcopy.value=index;      $r->rflush();
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
     if (container == 'sequence') {         $r->print("\n<br />");
  this.document.forms.renameform.folderpath.value=folderpath;         if ($level==0) {
     }             $r->print("<br />");
     if (container == 'page') {         }
  this.document.forms.renameform.pagepath.value=folderpath;         for (my $i=0;$i<=$level*5;$i++) {
  this.document.forms.renameform.pagesymb.value=pagesymb;             $r->print('&nbsp;');
     }         }
     this.document.forms.renameform.submit();         $r->print('<a href="'.$url.'" target="cat">'.
 }   ($title?$title:$url).'</a> ');
          if ($url=~/^\/res\//) {
     my $result=&Apache::lonnet::repcopy(
 ENDNEWSCRIPT                                &Apache::lonnet::filelocation('',$url));
 }            if ($result eq 'ok') {
 1;               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 __END__               $r->rflush();
                &Apache::lonnet::countacc($url);
                $url=~/\.(\w+)$/;
 =head1 NAME               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
    $r->print('<br />');
 Apache::londocs.pm                   $r->rflush();
                    for (my $i=0;$i<=$level*5;$i++) {
 =head1 SYNOPSIS                       $r->print('&nbsp;');
                    }
 This is part of the LearningOnline Network with CAPA project                   $r->print('- '.&mt('Rendering:').' ');
 described at http://www.lon-capa.org.   my ($errorcount,$warningcount)=split(/:/,
          &Apache::lonnet::ssi_body($url,
 =head1 SUBROUTINES         ('grade_target'=>'web',
    'return_only_error_and_warning_counts' => 1)));
 =over                   if (($errorcount) ||
                        ($warningcount)) {
 =item %help=()       if ($errorcount) {
                           $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
 Available help topics                            &mt('[quant,_1,error]',$errorcount).'</span>');
                        }
 =item mapread()       if ($warningcount) {
                           $r->print('<span class="LC_warning">'.
 Mapread read maps into LONCAPA::map:: global arrays                            &mt('[quant,_1,warning]',$warningcount).'</span>');
 @order and @resources, determines status                       }
 sets @order - pointer to resources in right order                   } else {
 sets @resources - array with the resources with correct idx                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                    }
 =item authorhosts()                   $r->rflush();
                }
 Return hash with valid author names       my $dependencies=
                   &Apache::lonnet::metadata($url,'dependencies');
 =item dumpbutton()               foreach my $dep (split(/\,/,$dependencies)) {
    if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 Generate "dump" button                      &checkonthis($r,$dep,$level+1);
                    }
 =item clean()               }
             } elsif ($result eq 'unavailable') {
 =item dumpcourse()               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
             } elsif ($result eq 'not_found') {
     Actually dump course        unless ($url=~/\$/) {
     $r->print('<span class="LC_error">'.&mt('not found').'</span>');
         } else {
 =item exportbutton()    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
         }
     Generate "export" button            } else {
                $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
 =item exportcourse()            }
          }
 =item create_ims_store()      }
   }
 =item build_package()  
   
 =item get_dependencies()  
   =pod
 =item process_content()  
   =item list_symbs()
 =item replicate_content()  
   List Content Identifiers
 =item extract_media()  
   =cut
 =item store_template()  
   sub list_symbs {
 =item group_import()      my ($r) = @_;
   
     Imports the given (name, url) resources into the course      my $crstype = &Apache::loncommon::course_type();
     coursenum, coursedom, and folder must precede the list      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
 =item breadcrumbs()      $r->print(&startContentScreen('tools'));
       my $navmap = Apache::lonnavmaps::navmap->new();
 =item log_docs()      if (!defined($navmap)) {
           $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
 =item docs_change_log()                    '<div class="LC_error">'.
                     &mt('Unable to retrieve information about course contents').
 =item update_paste_buffer()                    '</div>');
           &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
 =item print_paste_buffer()      } else {
           $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
 =item do_paste_from_buffer()                    &Apache::loncommon::start_data_table().
                     &Apache::loncommon::start_data_table_header_row().
 =item update_parameter()                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
                     &Apache::loncommon::end_data_table_header_row()."\n");
 =item handle_edit_cmd()          my $count;
           foreach my $res ($navmap->retrieveResources()) {
 =item editor()              $r->print(&Apache::loncommon::start_data_table_row().
                         '<td>'.$res->compTitle().'</td>'.
 =item process_file_upload()                        '<td>'.$res->symb().'</td>'.
                         &Apache::loncommon::end_data_table_row());
 =item process_secondary_uploads()              $count ++;
           }
 =item is_supplemental_title()          if (!$count) {
               $r->print(&Apache::loncommon::start_data_table_row().
 =item parse_supplemental_title()                        '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
                         &Apache::loncommon::end_data_table_row()); 
 =item entryline()          }
           $r->print(&Apache::loncommon::end_data_table());
 =item tiehash()      }
       $r->print(&endContentScreen());
 =item untiehash()  }
   
 =item checkonthis()  
   sub verifycontent {
 check on this      my ($r) = @_;
       my $crstype = &Apache::loncommon::course_type();
 =item verifycontent()      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Content'));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Content'));
 Verify Content      $r->print(&startContentScreen('tools'));
       $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
 =item devalidateversioncache() & checkversions()     $hashtied=0;
      undef %alreadyseen;
 Check Versions     %alreadyseen=();
      &tiehash();
 =item mark_hash_old()     
      foreach my $key (keys(%hash)) {
 =item is_hash_old()         if ($hash{$key}=~/\.(page|sequence)$/) {
      if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
 =item changewarning()         $r->print('<hr /><span class="LC_error">'.
    &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
 =item init_breadcrumbs()   &unescape($hash{$key}).'</span><br />'.
    &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
 Breadcrumbs for special functions     }
          }
 =back         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
              &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
 =cut         }
      }
      &untiehash();
      $r->print('<p class="LC_success">'.&mt('Done').'</p>');
       $r->print(&endContentScreen());
   }
   
   
   sub devalidateversioncache {
       my $src=shift;
       &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
     &Apache::lonnet::clutter($src));
   }
   
   sub checkversions {
       my ($r) = @_;
       my $crstype = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
       $r->print(&startContentScreen('tools'));
   
       my $header='';
       my $startsel='';
       my $monthsel='';
       my $weeksel='';
       my $daysel='';
       my $allsel='';
       my %changes=();
       my $starttime=0;
       my $haschanged=0;
       my %setversions=&Apache::lonnet::dump('resourceversions',
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
   
       $hashtied=0;
       &tiehash();
       my %newsetversions=();
       if ($env{'form.setmostrecent'}) {
    $haschanged=1;
    foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
    $newsetversions{$1}='mostrecent';
                   &devalidateversioncache($1);
       }
    }
       } elsif ($env{'form.setcurrent'}) {
    $haschanged=1;
    foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
    my $getvers=&Apache::lonnet::getversion($1);
    if ($getvers>0) {
       $newsetversions{$1}=$getvers;
       &devalidateversioncache($1);
    }
       }
    }
       } elsif ($env{'form.setversions'}) {
    $haschanged=1;
    foreach my $key (keys(%env)) {
       if ($key=~/^form\.set_version_(.+)$/) {
    my $src=$1;
    if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
       $newsetversions{$src}=$env{$key};
       &devalidateversioncache($src);
    }
       }
    }
       }
       if ($haschanged) {
           if (&Apache::lonnet::put('resourceversions',\%newsetversions,
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
       $r->print(&Apache::loncommon::confirmwrapper(
                   &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
    } else {
       $r->print(&Apache::loncommon::confirmwrapper(
                   &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
    }
    &mark_hash_old();
       }
       &changewarning($r,'');
       if ($env{'form.timerange'} eq 'all') {
   # show all documents
    $header=&mt('All content in '.$crstype);
    $allsel=' selected="selected"';
    foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
    my $src=$1;
    $changes{$src}=1;
       }
    }
       } else {
   # show documents which changed
    %changes=&Apache::lonnet::dump
    ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
                        $env{'course.'.$env{'request.course.id'}.'.num'});
    my $firstkey=(keys(%changes))[0];
    unless ($firstkey=~/^error\:/) {
       unless ($env{'form.timerange'}) {
    $env{'form.timerange'}=604800;
       }
       my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
    .&mt('seconds');
       if ($env{'form.timerange'}==-1) {
    $seltext='since start of course';
    $startsel=' selected="selected"';
    $env{'form.timerange'}=time;
       }
       $starttime=time-$env{'form.timerange'};
       if ($env{'form.timerange'}==2592000) {
    $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $monthsel=' selected="selected"';
       } elsif ($env{'form.timerange'}==604800) {
    $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $weeksel=' selected="selected"';
       } elsif ($env{'form.timerange'}==86400) {
    $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $daysel=' selected="selected"';
       }
       $header=&mt('Content changed').' '.$seltext;
    } else {
       $header=&mt('No content modifications yet.');
    }
       }
       %setversions=&Apache::lonnet::dump('resourceversions',
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
       my %lt=&Apache::lonlocal::texthash
         ('st' => 'Version changes since start of '.$crstype,
          'lm' => 'Version changes since last Month',
          'lw' => 'Version changes since last Week',
          'sy' => 'Version changes since Yesterday',
                  'al' => 'All Resources (possibly large output)',
                  'cd' => 'Change display', 
          'sd' => 'Display',
          'fi' => 'File',
          'md' => 'Modification Date',
                  'mr' => 'Most recently published Version',
          've' => 'Version used in '.$crstype,
                  'vu' => 'Set Version to be used in '.$crstype,
   'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
   'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
   'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
          'di' => 'Differences',
          'save' => 'Save changes',
                  'vers' => 'Version choice(s) for specific resources', 
          'act' => 'Actions');
       $r->print(<<ENDHEADERS);
   <h4 class="LC_info">$header</h4>
   <form action="/adm/coursedocs" method="post">
   <input type="hidden" name="versions" value="1" />
   <div class="LC_left_float">
   <fieldset>
   <legend>$lt{'cd'}</legend>
   <select name="timerange">
   <option value='all'$allsel>$lt{'al'}</option>
   <option value="-1"$startsel>$lt{'st'}</option>
   <option value="2592000"$monthsel>$lt{'lm'}</option>
   <option value="604800"$weeksel>$lt{'lw'}</option>
   <option value="86400"$daysel>$lt{'sy'}</option>
   </select>
   <input type="submit" name="display" value="$lt{'sd'}" />
   </fieldset>
   </div>
   <div class="LC_left_float">
   <fieldset>
   <legend>$lt{'act'}</legend>
   $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
   $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
   </fieldset>
   </div>
   <br clear="all" />
   <hr />
   <h4>$lt{'vers'}</h4>
   <input type="submit" name="setversions" value="$lt{'save'}" />
   ENDHEADERS
       #number of columns for version history
       $r->print(
           &Apache::loncommon::start_data_table().
           &Apache::loncommon::start_data_table_header_row().
           '<th>'.&mt('Resources').'</th>'.
           "<th>$lt{'mr'}</th>".
           "<th>$lt{'ve'}</th>".
           "<th>$lt{'vu'}</th>".
           '<th>'.&mt('History').'</th>'.
           &Apache::loncommon::end_data_table_header_row()
       );
       foreach my $key (sort(keys(%changes))) {
           #excludes not versionable problems from resource version history:
           next unless ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/);
           my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
           my $currentversion=&Apache::lonnet::getversion($key);
           if ($currentversion<0) {
               $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
           }
           my $linkurl=&Apache::lonnet::clutter($key);
           $r->print(
               &Apache::loncommon::start_data_table_row().
               '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
               '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
               '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
               &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
               '<td align="right">'
           );
           # Used in course
           my $usedversion=$hash{'version_'.$linkurl};
           if (($usedversion) && ($usedversion ne 'mostrecent')) {
                   if ($usedversion != $currentversion) {
                       $r->print('<span class="LC_warning">'.$usedversion.'</span>');
                   } else {
                       $r->print($usedversion);
                   }
               } else {
                   $r->print($currentversion);
               }
           $r->print('</td><td title="'.$lt{'vu'}.'">');
           # Set version
           $r->print(&Apache::loncommon::select_form(
               $setversions{$linkurl},
               'set_version_'.$linkurl,
               {'select_form_order' => ['',1..$currentversion,'mostrecent'],
                '' => '',
                'mostrecent' => &mt('most recent'),
                map {$_,$_} (1..$currentversion)}));
           my $lastold=1;
           for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
               my $url=$root.'.'.$prevvers.'.'.$extension;
               if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
                   $lastold=$prevvers;
               }
           }
           $r->print('</td>');
           # List all available versions
           $r->print('<td valign="top"><span class="LC_fontsize_medium">');
           for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
               my $url=$root.'.'.$prevvers.'.'.$extension;
               $r->print(
                   '<span class="LC_nobreak">'
                  .'<a href="'.&Apache::lonnet::clutter($url).'">'
                  .&mt('Version [_1]',$prevvers).'</a>'
                  .' ('.&Apache::lonlocal::locallocaltime(
                            &Apache::lonnet::metadata($url,'lastrevisiondate'))
                  .')');
               if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
                   $r->print(
                       ' <a href="/adm/diff?filename='.
                       &Apache::lonnet::clutter($root.'.'.$extension).
                       &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
                       '" target="diffs">'.&mt('Diffs').'</a>');
               }
               $r->print('</span><br />');
           }
           $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
       }
       $r->print(
           &Apache::loncommon::end_data_table().
           '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
           '</form>'
       );
   
       &untiehash();
       $r->print(&endContentScreen());
   }
   
   sub mark_hash_old {
       my $retie_hash=0;
       if ($hashtied) {
    $retie_hash=1;
    &untiehash();
       }
       &tiehash('write');
       $hash{'old'}=1;
       &untiehash();
       if ($retie_hash) { &tiehash(); }
   }
   
   sub is_hash_old {
       my $untie_hash=0;
       if (!$hashtied) {
    $untie_hash=1;
    &tiehash();
       }
       my $return=$hash{'old'};
       if ($untie_hash) { &untiehash(); }
       return $return;
   }
   
   sub changewarning {
       my ($r,$postexec,$message,$url)=@_;
       if (!&is_hash_old()) { return; }
       my $pathvar='folderpath';
       my $path=&escape($env{'form.folderpath'});
       if (!defined($url)) {
    $url='/adm/coursedocs?'.$pathvar.'='.$path;
       }
       my $course_type = &Apache::loncommon::course_type();
       if (!defined($message)) {
    $message='Changes will become active for your current session after [_1], or the next time you log in.';
       }
       $r->print("\n\n".
   '<script type="text/javascript">'."\n".
   '// <![CDATA['."\n".
   'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
   '// ]]>'."\n".
   '</script>'."\n".
   '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
   '<input type="hidden" name="orgurl" value="'.$url.
   '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
   &mt($message,' <input type="hidden" name="'.
       $env{'request.role'}.'" value="1" /><input type="button" value="'.
       &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
   $help{'Caching'}.'</p></form>'."\n\n");
   }
   
   
   sub init_breadcrumbs {
       my ($form,$text)=@_;
       &Apache::lonhtmlcommon::clear_breadcrumbs();
       &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
       text=>&Apache::loncommon::course_type().' Editor',
       faq=>273,
       bug=>'Instructor Interface',
                                               help => 'Docs_Adding_Course_Doc'});
       &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
       text=>$text,
       faq=>273,
       bug=>'Instructor Interface'});
   }
   
   # subroutine to list form elements
   sub create_list_elements {
      my @formarr = @_;
      my $list = '';
      foreach my $button (@formarr){
           foreach my $picture (keys(%{$button})) {
               $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
           }
      }
      return $list;
   }
   
   # subroutine to create ul from list elements
   sub create_form_ul {
      my $list = shift;
      my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
      return $ul;
   }
   
   #
   # Start tabs
   #
   
   sub startContentScreen {
       my ($mode) = @_;
       my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
       if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
           $output .= '<li'.(($mode eq 'navmaps')?' class="active"':'').'><a href="/adm/navmaps"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Overview').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
           $output .= '<li'.(($mode eq 'coursesearch')?' class="active"':'').'><a href="/adm/searchcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Search').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
           $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
       } else {
           $output .= '<li '.(($mode eq 'docs')?' class="active"':'').' id="tabbededitor"><a href="/adm/coursedocs?forcestandard=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Main Content Editor').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
           $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
           $output .= '<li '.(($mode eq 'tools')?' class="active"':'').'><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
                      '><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>';
       }
       $output .= "\n".'</ul>'."\n";
       $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
                  '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
                  '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
       return $output;
   }
   
   #
   # End tabs
   #
   
   sub endContentScreen {
       return '</div></div></div>';
   }
   
   sub supplemental_base {
       return 'supplemental&'.&escape(&mt('Supplemental Content'));
   }
   
   sub handler {
       my $r = shift;
       &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
       return OK if $r->header_only;
   
   # get course data
       my $crstype = &Apache::loncommon::course_type();
       my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
   
   # graphics settings
       $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
   
   #
   # --------------------------------------------- Initialize help topics for this
       foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
                  'Adding_External_Resource','Navigate_Content',
                  'Adding_Folders','Docs_Overview', 'Load_Map',
                  'Supplemental','Score_Upload_Form','Adding_Pages',
                  'Importing_LON-CAPA_Resource','Importing_IMS_Course',
                          'Uploading_From_Harddrive',
                  'Check_Resource_Versions','Verify_Content',
                          'Course_Roster','Web_Page','Dropbox') {
    $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
       }
       # Composite help files
       $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
       $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
       $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
       'Option_Response_Simple');
       $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
       $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
     'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
       $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
       $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
    
       my $allowed;
   # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
       unless ($r->uri eq '/adm/supplemental') {
           # does this user have privileges to modify content.  
           $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
       }
   
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
                                               'inhibitmenu']);
     if ($allowed && $env{'form.chooseserver'}) {
         &choose_dump_server($r);
         return OK;
     } elsif ($allowed && $env{'form.verify'}) {
         &init_breadcrumbs('verify','Verify Content');
         &verifycontent($r);
     } elsif ($allowed && $env{'form.listsymbs'}) {
         &init_breadcrumbs('listsymbs','List Content IDs');
         &list_symbs($r);
     } elsif ($allowed && $env{'form.docslog'}) {
         &init_breadcrumbs('docslog','Show Log');
         my $folder = $env{'form.folder'};
         if ($folder eq '') {
             $folder='default';
         }
         &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
     } elsif ($allowed && $env{'form.versions'}) {
         &init_breadcrumbs('versions','Check/Set Resource Versions');
         &checkversions($r);
     } elsif ($allowed && $env{'form.dumpcourse'}) {
         &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
         &dumpcourse($r);
     } elsif ($allowed && $env{'form.exportcourse'}) {
         &init_breadcrumbs('exportcourse','IMS Export');
         &Apache::imsexport::exportcourse($r);
     } else {
   #
   # Done catching special calls
   # The whole rest is for course and supplemental documents and utilities menu
   # Get the parameters that may be needed
   #
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                               ['folderpath',
                                                'forcesupplement','forcestandard',
                                                'tools','symb','command','supppath']);
   
   # standard=1: this is a "new-style" course with an uploaded map as top level
   # standard=2: this is a "old-style" course, and there is nothing we can do
   
       my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
   
   # Decide whether this should display supplemental or main content or utilities
   # supplementalflag=1: show supplemental documents
   # supplementalflag=0: show standard documents
   # toolsflag=1: show utilities
   
       $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 Content').':::::');
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => $env{'form.command'}});
      } elsif ($env{'form.command'} eq 'editsupp') {
          $env{'form.folderpath'} = 'supplemental&'.
                                     &escape('Supplemental Content');
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/supplemental'});
      } elsif ($env{'form.command'} eq 'contents') {
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/navmaps'});
      } elsif ($env{'form.command'} eq 'home') {
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/menu'});
      }
   
   
   # Where do we store these for when we come back?
       my $stored_folderpath='docs_folderpath';
       if ($supplementalflag) {
          $stored_folderpath='docs_sup_folderpath';
       }
   
   # No folderpath, and in edit mode, see if we have something stored
       if ((!$env{'form.folderpath'}) && $allowed) {
           &Apache::loncommon::restore_course_settings($stored_folderpath,
                                             {'folderpath' => 'scalar'});
           unless (&unescape($env{'form.folderpath'}) =~ m{^(default|supplemental)&}) {
               undef($env{'form.folderpath'});
           }
       }
      
   # If we are not allowed to make changes, all we can see are supplemental docs
       if (!$allowed) {
           unless ($env{'form.folderpath'} =~ /^supplemental/) {
               $env{'form.folderpath'} = &supplemental_base();
           }
       }
   # Make the zeroth entry in supplemental docs page paths, so we can get to top level
       if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
           $env{'form.folderpath'} = &supplemental_base()
                                     .'&'.
                                     $env{'form.folderpath'};
       }
   # If after all of this, we still don't have any paths, make them
       unless ($env{'form.folderpath'}) {
          if ($supplementalflag) {
             $env{'form.folderpath'}=&supplemental_base();
          } else {
             $env{'form.folderpath'}='default&'.&escape(&mt('Main Content').
                                     ':::::');
          }
       }
   
   # Store this
       unless ($toolsflag) {
           if ($allowed) {
               &Apache::loncommon::store_course_settings($stored_folderpath,
                                                         {'folderpath' => 'scalar'});
           }
           my $folderpath;
           if ($env{'form.folderpath'}) {
               $folderpath = $env{'form.folderpath'};
       my (@folders)=split('&',$env{'form.folderpath'});
       $env{'form.foldername'}=&unescape(pop(@folders));
               if ($env{'form.foldername'} =~ /\:1$/) {
                   $container = 'page';
               } else {
                   $container = 'sequence';
               }
       $env{'form.folder'}=pop(@folders);
           } else {
               if ($env{'form.folder'} eq '' ||
                   $env{'form.folder'} eq 'supplemental') {
                   $folderpath='default&'.
                               &escape(&mt('Main Content').':::::');
               }
           }
           $containertag = '<input type="hidden" name="folderpath" value="" />';
           $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
           if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
              $showdoc='/'.$1;
           }
           if ($showdoc) { # got called in sequence from course
       $allowed=0; 
           } else {
               if ($allowed) {
                   &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                   $script=&Apache::lonratedt::editscript('simple');
               }
           }
       }
   
   # get personal data
       my $uname=$env{'user.name'};
       my $udom=$env{'user.domain'};
       my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
   
       if ($allowed) {
           if ($toolsflag) {
               $script .= &inject_data_js();
               my ($home,$other,%outhash)=&authorhosts();
               if (!$home && $other) {
                   my @hosts;
                   foreach my $aurole (keys(%outhash)) {
                       unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                           push(@hosts,$outhash{$aurole});
                       }
                   }
                   $script .= &dump_switchserver_js(@hosts); 
               }
           } else {
               my @tabids;
               if ($supplementalflag) {
                   @tabids = ('002','ee2','ff2');
               } else {
                   @tabids = ('aa1','bb1','cc1','ff1');
                   unless ($env{'form.folderpath'} =~ /\:1$/) {
                       unshift(@tabids,'001');
                       push(@tabids,('dd1','ee1'));
                   }
               }
               my $tabidstr = join("','",@tabids);
       $script .= &editing_js($udom,$uname,$supplementalflag).
                          &history_tab_js().
                          &inject_data_js().
                          &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr).
                          &Apache::lonextresedit::extedit_javascript();
               $addentries = {
                               onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
                             };
           }
           $script .= &paste_popup_js(); 
           my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
                                &mt('Switch server?');
           
   
       }
   # -------------------------------------------------------------------- Body tag
       $script = '<script type="text/javascript">'."\n"
                 .'// <![CDATA['."\n"
                 .$script."\n"
                 .'// ]]>'."\n"
                 .'</script>'."\n";
   
       # Breadcrumbs
       &Apache::lonhtmlcommon::clear_breadcrumbs();
   
       if ($showdoc) {
           $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
                                                   {'force_register' => $showdoc,}));
       } elsif ($r->uri eq '/adm/supplemental') {
           my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype);
           $r->print(&Apache::loncommon::start_page("Supplemental $crstype Content",undef,
                                                   {'bread_crumbs' => $brcrum,}));
       } else {
           &Apache::lonhtmlcommon::add_breadcrumb({
               href=>"/adm/coursedocs",text=>"$crstype Contents"});
           $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
                                                    {'add_entries'    => $addentries}
                                                   )
                    .&Apache::loncommon::help_open_menu('','',273,'RAT')
                    .&Apache::lonhtmlcommon::breadcrumbs(
                        'Editing '.$crstype.' Contents',
                        'Docs_Adding_Course_Doc')
           );
       }
   
     my %allfiles = ();
     my %codebase = ();
     my ($upload_result,$upload_output,$uploadphase);
     if ($allowed) {
         if (($env{'form.uploaddoc.filename'}) &&
     ($env{'form.cmd'}=~/^upload_(\w+)/)) {
             my $context = $1; 
             # Process file upload - phase one - upload and parse primary file.
     undef($hadchanges);
             $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
                                                 \%allfiles,\%codebase,$context,$crstype);
     if ($hadchanges) {
         &mark_hash_old();
     }
             $r->print($upload_output);
         } elsif ($env{'form.phase'} eq 'upload_embedded') {
             # Process file upload - phase two - upload embedded objects 
             $uploadphase = 'check_embedded';
             my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
             my $state = &embedded_form_elems($uploadphase,$primaryurl,
                                              $env{'form.newidx'});
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
             my $actionurl = '/adm/coursedocs';
             my ($result,$flag) = 
                 &Apache::loncommon::upload_embedded('coursedoc',$destination,
                     $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
                     $actionurl);
             $r->print($result.&return_to_editor());
         } elsif ($env{'form.phase'} eq 'check_embedded') {
             # Process file upload - phase three - modify references in HTML file
             $uploadphase = 'modified_orightml';
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $result = 
                 &Apache::loncommon::modify_html_refs('coursedoc',$destination,
                                                      $docuname,$docudom,undef,
                                                      $dir_root);
             $r->print($result.&return_to_editor());   
         } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
             $uploadphase = 'decompress_phase_one';
             $r->print(&decompression_phase_one().
                       &return_to_editor());
         } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
             $uploadphase = 'decompress_phase_two';
             $r->print(&decompression_phase_two().
                       &return_to_editor());
         }
     }
   
     if ($allowed && $toolsflag) {
         $r->print(&startContentScreen('tools'));
         $r->print(&generate_admin_menu($crstype));
         $r->print(&endContentScreen());
     } elsif ((!$showdoc) && (!$uploadphase)) {
   # -----------------------------------------------------------------------------
          my %lt=&Apache::lonlocal::texthash(
    'copm' => 'All documents out of a published map into this folder',
                   'upfi' => 'Upload File',
                   'upld' => 'Upload Content',
                   'srch' => 'Search',
                   'impo' => 'Import',
    'lnks' => 'Import from Stored Links',
                   'impm' => 'Import from Assembled Map',
                   'selm' => 'Select Map',
                   'load' => 'Load Map',
                   'newf' => 'New Folder',
                   'newp' => 'New Composite Page',
                   'syll' => 'Syllabus',
                   'navc' => 'Table of Contents',
                   'sipa' => 'Simple Course Page',
                   'sipr' => 'Simple Problem',
                   'webp' => 'Blank Web Page (editable)',
                   'drbx' => 'Drop Box',
                   'scuf' => 'External Scores (handgrade, upload, clicker)',
                   'bull' => 'Discussion Board',
                   'mypi' => 'My Personal Information Page',
                   'grpo' => 'Group Portfolio',
                   'rost' => 'Course Roster',
                   'abou' => 'Personal Information Page for a User',
                   'imsf' => 'IMS Upload',
                   'imsl' => 'Upload IMS package',
                   'cms'  => 'Origin of IMS package',
                   'se'   => 'Select',
                   'file' =>  'File',
                   'title' => 'Title',
                   'comment' => 'Comment',
                   'parse' => 'Upload embedded images/multimedia files if HTML file',
     );
   # -----------------------------------------------------------------------------
    my $fileupload=(<<FIUP);
    $lt{'file'}:<br />
    <input type="file" name="uploaddoc" size="40" />
   FIUP
   
    my $checkbox=(<<CHBO);
    <!-- <label>$lt{'parse'}?
    <input type="checkbox" name="parserflag" />
    </label> -->
    <label>
    <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
    </label>
   CHBO
           my $imsfolder = $env{'form.folder'};
           if ($imsfolder eq '') {
               $imsfolder = 'default';  
           }
           my $imspform=(<<IMSFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
           $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
           <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
           <fieldset id="uploadimsform" style="display: none;">
           <legend>$lt{'imsf'}</legend>
           $fileupload
           <br />
           <p>
           $lt{'cms'}:&nbsp; 
           <select name="source">
           <option value="-1" selected="selected">$lt{'se'}</option>
           <option value="bb5">Blackboard 5</option>
           <option value="bb6">Blackboard 6</option>
           <option value="angel5">ANGEL 5.5</option>
           <option value="webctce4">WebCT 4 Campus Edition</option>
           </select>
           <input type="hidden" name="folder" value="$imsfolder" />
           </p>
           <input type="hidden" name="phase" value="one" />
           <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" />
           </fieldset>
           </form>
   IMSFORM
   
    my $fileuploadform=(<<FUFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
           <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
           <fieldset id="uploaddocform" style="display: none;">
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="aa" />
    $fileupload
    <br />
    $lt{'title'}:<br />
    <input type="text" size="60" name="comment" />
    $pathitem
    <input type="hidden" name="cmd" value="upload_default" />
    <br />
    <span class="LC_nobreak" style="float:left">
    $checkbox
    </span>
           <br clear="all" />
           <input type="submit" value="$lt{'upld'}" />
           </fieldset>
           </form>
   FUFORM
   
    my $importpubform=(<<SEDFFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleMap('map');">
           $lt{'impm'}</a>$help{'Load_Map'}
    <form action="/adm/coursedocs" method="post" name="mapimportform">
           <fieldset id="importmapform" style="display: none;">
           <legend>$lt{'impm'}</legend>
    <input type="hidden" name="active" value="bb" />
           $lt{'copm'}<br />
           <span class="LC_nobreak">
           <input type="text" name="importmap" size="40" value="" 
           onfocus="this.blur();openbrowser('mapimportform','importmap','sequence,page','');" />
           &nbsp;<a href="javascript:openbrowser('mapimportform','importmap','sequence,page','');">$lt{'selm'}</a></span><br />
           <input type="submit" name="loadmap" value="$lt{'load'}" />
           </fieldset>
           </form>
   
   SEDFFORM
    my @importpubforma = (
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => $pathitem."<a class='LC_menubuttons_link' href='javascript:groupsearch()'>$lt{'srch'}</a>" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{impo}.'"  onclick="javascript:groupimport();"/>' => "<a class='LC_menubuttons_link' href='javascript:groupimport();'>$lt{'impo'}</a>$help{'Importing_LON-CAPA_Resource'}" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{lnks}.'" onclick="javascript:open_StoredLinks_Import();" />' => "<a class='LC_menubuttons_link' href='javascript:open_StoredLinks_Import();'>$lt{'lnks'}</a>" },
           { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/sequence.png" alt="'.$lt{impm}.'" onclick="javascript:toggleMap(\'map\');" />' => $importpubform }
    );
    $importpubform = &create_form_ul(&create_list_elements(@importpubforma));
           my $extresourcesform =
               &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
       if ($allowed) {
           my $folder = $env{'form.folder'};
           if ($folder eq '') {
               $folder='default';
           }
    my $output = &update_paste_buffer($coursenum,$coursedom,$folder);
           if ($output) {
               $r->print($output);
           }
    $r->print(<<HIDDENFORM);
    <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
      <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
      <input type="hidden" name="copyfolder" />
      $containertag
    </form>
   
   HIDDENFORM
           $r->print(&makesimpleeditform($pathitem)."\n".
                     &makedocslogform($pathitem."\n".
                                      '<input type="hidden" name="folder" value="'.
                                      $env{'form.folder'}.'" />'."\n"));
       }
   
   # Generate the tabs
       my ($mode,$needs_end);
       if (($supplementalflag) && (!$allowed)) {
           my @folders = split('&',$env{'form.folderpath'});
           unless (@folders > 2) {
               &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
               $needs_end = 1;
           }
       } else {
           $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
           $needs_end = 1;
       }
   
   #
   
       my $savefolderpath;
   
       if ($allowed) {
          my $folder=$env{'form.folder'};
          if ($folder eq '' || $supplementalflag) {
              $folder='default';
      $savefolderpath = $env{'form.folderpath'};
      $env{'form.folderpath'}='default&'.&escape(&mt('Main Content'));
              $pathitem = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
          my $postexec='';
          if ($folder eq 'default') {
              $r->print('<script type="text/javascript">'."\n"
                       .'// <![CDATA['."\n"
                       .'this.window.name="loncapaclient";'."\n"
                       .'// ]]>'."\n"
                       .'</script>'."\n"
          );
          } else {
              #$postexec='self.close();';
          }
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.page';
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
   
    my $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'navc'}=/adm/navmaps" />
    <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
    $help{'Navigate_Content'}
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
    $help{'Simple Page'}
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
    $help{'Simple Problem'}
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
           $help{'Dropbox'}
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
    $help{'Score_Upload_Form'}
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
    $help{'Bulletin Board'}
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
    </form>
   NASOFORM
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'rost'}=/adm/viewclasslist" />
    <a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
    $help{'Course_Roster'}
    </form>
   NROSTFORM
   
           my $newwebpage;
           if ($folder =~ /^default_?(\d*)$/) {
               $newwebpage = "/uploaded/$coursedom/$coursenum/docs/";
               if ($1) {
                   $newwebpage .= $1;
               } else {
                   $newwebpage .= 'default';
               }
               $newwebpage .= '/new.html';
           }
           my $newwebpageform =(<<NWEBFORM);
           <form action="/adm/coursedocs" method="post" name="newwebpage">
           <input type="hidden" name="active" value="cc" />
           $pathitem
           <input type="hidden" name="importdetail" value="$newwebpage" />
           <a class="LC_menubuttons_link" href="javascript:makewebpage();">$lt{'webp'}</a>
           $help{'Web_Page'}
           </form>
   NWEBFORM
    
   
   my $specialdocumentsform;
   my @specialdocumentsforma;
   my $gradingform;
   my @gradingforma;
   my $communityform;
   my @communityforma;
   my $newfolderform;
   my $newfolderb;
   
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $newpageform=(<<NPFORM);
    <form action="/adm/coursedocs" method="post" name="newpage">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="cc" />
    <a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
    $help{'Adding_Pages'}
    </form>
   NPFORM
   
   
    $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="aa" />
    <a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
   
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
    $help{'Group Portfolio'}
    </form>
   NGFFORM
    @specialdocumentsforma=(
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage();" />'=>$newwebpageform},
           );
           $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
   
   
           my @importdoc = (
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform}
           );
           unless ($container eq 'page') {
               push(@importdoc,
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform}
               );
           }
           push(@importdoc,
               {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'doc\');" />'=>$fileuploadform}
           );
           $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc));
   
           @gradingforma=(
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
   
           );
           $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
   
           @communityforma=(
          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
           );
           $communityform = &create_form_ul(&create_list_elements(@communityforma));
   
   my %orderhash = (
                   'aa' => ['Upload',$fileuploadform],
                   'bb' => ['Import',$importpubform],
                   'cc' => ['Grading',$gradingform],
                   );
   unless ($container eq 'page') {
       $orderhash{'00'} = ['Newfolder',$newfolderform];
       $orderhash{'dd'} = ['Collaboration',$communityform];
       $orderhash{'ee'} = ['Other',$specialdocumentsform];
   }
   
    $hadchanges=0;
          unless (($supplementalflag || $toolsflag)) {
             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                 $supplementalflag,\%orderhash,$iconpath,$pathitem);
             if ($error) {
                $r->print('<p><span class="LC_error">'.$error.'</span></p>');
             }
             if ($hadchanges) {
                &mark_hash_old();
             }
   
             &changewarning($r,'');
           }
       }
   
   # Supplemental documents start here
   
          my $folder=$env{'form.folder'};
          unless ($supplementalflag) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = &supplemental_base();
          } elsif ($allowed) {
     $env{'form.folderpath'} = $savefolderpath;
          }
          $pathitem = '<input type="hidden" name="folderpath" value="'.
                       &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_new.sequence';
   
    my $supupdocform=(<<SUPDOCFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppdoc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
    <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
           <fieldset id="uploadsuppdocform" style="display: none;">
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="ee" />
    $fileupload
    <br />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br /><br />
    $lt{'comment'}:<br />
    <textarea cols="50" rows="4" name="comment"></textarea>
    <br />
    $pathitem
    <input type="hidden" name="cmd" value="upload_supplemental" />
           <input type='submit' value="$lt{'upld'}" />
           </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="active" value="ee" />
           $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
    $help{'Adding_Folders'}
    </form>
   SNFFORM
   
           my $supextform =
               &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="active" value="ff" />
           $pathitem
    <input type="hidden" name="importdetail" 
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="supnewaboutme">
    <input type="hidden" name="active" value="ff" />
           $pathitem
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   SNAMFORM
   
           my $supwebpage;
           if ($folder =~ /^supplemental_?(\d*)$/) {
               $supwebpage = "/uploaded/$coursedom/$coursenum/supplemental/";
               if ($1) {
                   $supwebpage .= $1;
               } else {
                   $supwebpage .= 'default';
               }
               $supwebpage .= '/new.html';
           }
           my $supwebpageform =(<<SWEBFORM);
           <form action="/adm/coursedocs" method="post" name="supwebpage">
           <input type="hidden" name="active" value="cc" />
           $pathitem
           <input type="hidden" name="importdetail" value="$supwebpage" />
           <a class="LC_menubuttons_link" href="javascript:makewebpage('supp');">$lt{'webp'}</a>
           $help{'Web_Page'}
           </form>
   SWEBFORM
   
   
   my @specialdocs = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.supnewsyl.submit()" />'
               =>$supnewsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
               =>$supnewaboutmeform},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage('."'supp'".');" />'=>$supwebpageform},
   
    );
   my @supimportdoc = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:toggleUpload(\'suppext\')" />'
               =>$supextform},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
               =>$supupdocform},
                      );
   
   $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
   my %suporderhash = (
    '00' => ['Supnewfolder', $supnewfolderform],
                   'ee' => ['Upload',$supupdocform],
                   'ff' => ['Other',&create_form_ul(&create_list_elements(@specialdocs))]
                   );
           if ($supplementalflag) {
              my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                  $supplementalflag,\%suporderhash,$iconpath,$pathitem);
              if ($error) {
                 $r->print('<p><span class="LC_error">'.$error.'</span></p>');
              } else {
                  if ($suppchanges) {
                      my %servers = &Apache::lonnet::internet_dom_servers($coursedom);
                      my @ids=&Apache::lonnet::current_machine_ids();
                      foreach my $server (keys(%servers)) {
                          next if (grep(/^\Q$server\E$/,@ids));
                          my $hashid=$coursenum.':'.$coursedom;
                          &Apache::lonnet::remote_devalidate_cache($server,'suppcount',$hashid);
                      }
                      &Apache::lonnet::get_numsuppfiles($coursenum,$coursedom,1);
                      undef($suppchanges);
                  }
              }
           }
       } elsif ($supplementalflag) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,'',$iconpath,$pathitem);
           if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
       }
   
       if ($needs_end) {
           $r->print(&endContentScreen());
       }
   
       if ($allowed) {
    $r->print('
   <form method="post" name="extimport" action="/adm/coursedocs">
     <input type="hidden" name="title" />
     <input type="hidden" name="url" />
     <input type="hidden" name="useform" />
     <input type="hidden" name="residx" />
   </form>');
       }
     } elsif ($showdoc) {
   # -------------------------------------------------------- This is showdoc mode
         $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p class="LC_warning">'.
   &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
                   &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
     }
    }
    $r->print(&Apache::loncommon::end_page());
    return OK;
   }
   
   sub embedded_form_elems {
       my ($phase,$primaryurl,$newidx) = @_;
       my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
       return <<STATE;
       <input type="hidden" name="folderpath" value="$folderpath" />
       <input type="hidden" name="cmd" value="upload_embedded" />
       <input type="hidden" name="newidx" value="$newidx" />
       <input type="hidden" name="phase" value="$phase" />
       <input type="hidden" name="primaryurl" value="$primaryurl" />
   STATE
   }
   
   sub embedded_destination {
       my $folder=$env{'form.folder'};
       my $destination = 'docs/';
       if ($folder =~ /^supplemental/) {
           $destination = 'supplemental/';
       }
       if (($folder eq 'default') || ($folder eq 'supplemental')) {
           $destination .= 'default/';
       } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
           $destination .=  $2.'/';
       }
       $destination .= $env{'form.newidx'};
       my $dir_root = '/userfiles';
       return ($destination,$dir_root);
   }
   
   sub return_to_editor {
       my $actionurl = '/adm/coursedocs';
       return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
              '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
              '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
              '</a></p>';
   }
   
   sub decompression_info {
       my ($destination,$dir_root) = &embedded_destination();
       my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
       my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
       my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $container='sequence';
       my ($pathitem,$hiddenelem);
       my @hiddens = ('newidx','comment','position','folderpath');
       if ($env{'form.folderpath'} =~ /\:1$/) {
           $container='page';
       }
       unshift(@hiddens,$pathitem);
       foreach my $item (@hiddens) {
           if ($env{'form.'.$item}) {
               $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
                              $env{'form.'.$item}.'" />'."\n";
           }
       }
       return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
               $hiddenelem);
   }
   
   sub decompression_phase_one {
       my ($dir,$file,$warning,$error,$output);
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/\E(?:docs|supplemental)/(?:default|\d+).*/([^/]+)$}) {
           $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
       } else {
           my $file = $1;
           $output = 
               &Apache::loncommon::process_decompression($docudom,$docuname,$file,
                                                         $destination,$dir_root,
                                                         $hiddenelem);
           if ($env{'form.autoextract_camtasia'}) {
               $output .= &remove_archive($docudom,$docuname,$container);
           }
       }
       if ($error) {
           $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                      $error.'</p>'."\n";
       }
       if ($warning) {
           $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
       }
       return $output;
   }
   
   sub decompression_phase_two {
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       my $output;
       if ($env{'form.archivedelete'}) {
           $output = &remove_archive($docudom,$docuname,$container);
       }
       $output .= 
           &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
                                                       $destination,$dir_root,$hiddenelem);
       return $output;
   }
   
   sub remove_archive {
       my ($docudom,$docuname,$container) = @_;
       my $map = $env{'form.folder'}.'.'.$container;
       my ($output,$delwarning,$delresult,$url);
       my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
       if ($fatal) {
           if ($container eq 'page') {
               $delwarning = &mt('An error occurred retrieving the contents of the current page.');
           } else {
               $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
           }
           $delwarning .= &mt('As a result the archive file has not been removed.');
       } else {
           my $currcmd = $env{'form.cmd'};
           my $position = $env{'form.position'};
           if ($position > 0) { 
               $env{'form.cmd'} = '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 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.328  
changed lines
  Added in v.1.484.2.38


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