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

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

Removed from v.1.326  
changed lines
  Added in v.1.484.2.17


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