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

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

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


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