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

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


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