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

version 1.326, 2009/01/28 11:51:22 version 1.484.2.26, 2013/03/17 17:21:34
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
   package Apache::londocs;
   
 package Apache::londocs;  use strict;
   use Apache::Constants qw(:common :http);
 use strict;  use Apache::imsexport;
 use Apache::Constants qw(:common :http);  use Apache::lonnet;
 use Apache::imsexport;  use Apache::loncommon;
 use Apache::lonnet;  use Apache::lonhtmlcommon;
 use Apache::loncommon;  use LONCAPA::map();
 use LONCAPA::map();  use Apache::lonratedt();
 use Apache::lonratedt();  use Apache::lonxml;
 use Apache::lonxml;  use Apache::lonclonecourse;
 use Apache::lonclonecourse;  use Apache::lonnavmaps;
 use Apache::lonnavmaps;  use Apache::lonnavdisplay();
 use HTML::Entities;  use Apache::lonextresedit();
 use GDBM_File;  use HTML::Entities;
 use Apache::lonlocal;  use HTML::TokeParser;
 use Cwd;  use GDBM_File;
 use LONCAPA qw(:DEFAULT :match);  use Apache::lonlocal;
   use Cwd;
 my $iconpath;  use LONCAPA qw(:DEFAULT :match);
   
 my %hash;  my $iconpath;
   
 my $hashtied;  my %hash;
 my %alreadyseen=();  
   my $hashtied;
 my $hadchanges;  my %alreadyseen=();
   
   my $hadchanges;
 my %help=();  
   
   my %help=();
 sub mapread {  
     my ($coursenum,$coursedom,$map)=@_;  
     return  sub mapread {
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map)=@_;
      $map);      return
 }        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
        $map);
 sub storemap {  }
     my ($coursenum,$coursedom,$map)=@_;  
     my ($outtext,$errtext)=  sub storemap {
       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map,$contentchg)=@_;
       $map,1);      my $report;
     if ($errtext) { return ($errtext,2); }      if (($contentchg) && ($map =~ /^default/)) {
             $report = 1;
     $hadchanges=1;      }
     return ($errtext,0);      my ($outtext,$errtext)=
 }        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1,$report);
       if ($errtext) { return ($errtext,2); }
   
 sub authorhosts {      $hadchanges=1;
     my %outhash=();      return ($errtext,0);
     my $home=0;  }
     my $other=0;  
     foreach my $key (keys(%env)) {  
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {  
     my $role=$1;  sub authorhosts {
     my $realm=$2;      my %outhash=();
     my ($start,$end)=split(/\./,$env{$key});      my $home=0;
     if (($start) && ($start>time)) { next; }      my $other=0;
     if (($end) && (time>$end)) { next; }      foreach my $key (keys(%env)) {
     my ($ca,$cd);   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     if ($1 eq 'au') {      my $role=$1;
  $ca=$env{'user.name'};      my $realm=$2;
  $cd=$env{'user.domain'};      my ($start,$end)=split(/\./,$env{$key});
     } else {      if (($start) && ($start>time)) { next; }
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);      if (($end) && (time>$end)) { next; }
     }      my ($ca,$cd);
     my $allowed=0;      if ($1 eq 'au') {
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);   $ca=$env{'user.name'};
     my @ids=&Apache::lonnet::current_machine_ids();   $cd=$env{'user.domain'};
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      } else {
     if ($allowed) {   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  $home++;      }
  $outhash{'home_'.$ca.'@'.$cd}=1;      my $allowed=0;
     } else {      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      my @ids=&Apache::lonnet::current_machine_ids();
  $other++;      foreach my $id (@ids) {
     }                  if ($id eq $myhome) {
  }                      $allowed=1;
     }                      last;
     return ($home,$other,%outhash);                  }
 }              }
       if ($allowed) {
    $home++;
 sub dumpbutton {   $outhash{'home_'.$ca.':'.$cd}=1;
     my ($home,$other,%outhash)=&authorhosts();      } else {
     my $type = &Apache::loncommon::course_type();   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
     if ($home+$other==0) { return ''; }   $other++;
     if ($home) {      }
  return '<div>'.   }
     '<input type="submit" name="dumpcourse" value="'.      }
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      return ($home,$other,%outhash);
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs').  }
     '</div>';  
     } else {  
  return '<div>'.  sub clean {
      &mt('Dump '.$type.      my ($title)=@_;
  ' DOCS to Construction Space: available on other servers').      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
  '</div>';      return $title;
     }  }
 }  
   
 sub clean {  
     my ($title)=@_;  sub dumpcourse {
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;      my ($r) = @_;
     return $title;      my $crstype = &Apache::loncommon::course_type();
 }      $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
                 &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
       $r->print(&startContentScreen('tools'));
       my ($home,$other,%outhash)=&authorhosts();
 sub dumpcourse {      unless ($home) {
     my ($r) = @_;          $r->print(&endContentScreen());
     my $type = &Apache::loncommon::course_type();          return '';
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').      }
       '<form name="dumpdoc" method="post">');      my $origcrsid=$env{'request.course.id'};
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my ($home,$other,%outhash)=&authorhosts();      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     unless ($home) { return ''; }  # Do the dumping
     my $origcrsid=$env{'request.course.id'};   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);              $r->print(&endContentScreen());
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {              return '';
 # Do the dumping          }
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }   my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   my $title=$env{'form.authorfolder'};
  my $title=$env{'form.authorfolder'};   $title=&clean($title);
  $title=&clean($title);   my %replacehash=();
  my %replacehash=();   foreach my $key (keys(%env)) {
  foreach my $key (keys(%env)) {      if ($key=~/^form\.namefor\_(.+)/) {
     if ($key=~/^form\.namefor\_(.+)/) {   $replacehash{$1}=$env{$key};
  $replacehash{$1}=$env{$key};      }
     }   }
  }   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   $crs=~s/\_/\//g;
  $crs=~s/\_/\//g;   foreach my $item (keys(%replacehash)) {
  foreach my $item (keys(%replacehash)) {      my $newfilename=$title.'/'.$replacehash{$item};
     my $newfilename=$title.'/'.$replacehash{$item};      $newfilename=~s/\.(\w+)$//;
     $newfilename=~s/\.(\w+)$//;      my $ext=$1;
     my $ext=$1;      $newfilename=&clean($newfilename);
     $newfilename=&clean($newfilename);      $newfilename.='.'.$ext;
     $newfilename.='.'.$ext;      my @dirs=split(/\//,$newfilename);
     my @dirs=split(/\//,$newfilename);      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
     my $path='/home/'.$ca.'/public_html';      my $makepath=$path;
     my $makepath=$path;      my $fail=0;
     my $fail=0;      for (my $i=0;$i<$#dirs;$i++) {
     for (my $i=0;$i<$#dirs;$i++) {   $makepath.='/'.$dirs[$i];
  $makepath.='/'.$dirs[$i];   unless (-e $makepath) {
  unless (-e $makepath) {      unless(mkdir($makepath,0777)) { $fail=1; }
     unless(mkdir($makepath,0777)) { $fail=1; }   }
  }      }
     }      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {      print $fh &Apache::lonclonecourse::rewritefile(
     print $fh &Apache::lonclonecourse::rewritefile(           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),       (%replacehash,$crs => '')
      (%replacehash,$crs => '')      );
     );   } else {
  } else {      print $fh
     print $fh           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);         }
        }   $fh->close();
  $fh->close();      } else {
     } else {   $fail=1;
  $fail=1;      }
     }      if ($fail) {
     if ($fail) {   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');      } else {
     } else {   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      }
     }   }
  }      } else {
     } else {          $r->print(&mt('Searching ...').'<br />');
 # Input form          $r->rflush();
  unless ($home==1) {  # Input form
     $r->print(          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');   unless ($home==1) {
  }      $r->print('<div class="LC_left_float">'.
  foreach my $key (sort(keys(%outhash))) {        '<fieldset><legend>'.
     if ($key=~/^home_(.+)$/) {                        &mt('Select the Authoring Space').
  if ($home==1) {                        '</legend><select name="authorspace">');
     $r->print(   }
   '<input type="hidden" name="authorspace" value="'.$1.'" />');   foreach my $key (sort(keys(%outhash))) {
  } else {      if ($key=~/^home_(.+)$/) {
     $r->print('<option value="'.$1.'">'.$1.' - '.   if ($home==1) {
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');      $r->print(
  }    '<input type="hidden" name="authorspace" value="'.$1.'" />');
     }   } else {
  }      $r->print('<option value="'.$1.'">'.$1.' - '.
  unless ($home==1) {        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
     $r->print('</select>');   }
  }      }
  my $title=$origcrsdata{'description'};   }
  $title=~s/[\/\s]+/\_/gs;   unless ($home==1) {
  $title=&clean($title);      $r->print('</select></fieldset></div>'."\n");
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'   }
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');   my $title=$origcrsdata{'description'};
  &tiehash();   $title=~s/[\/\s]+/\_/gs;
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'   $title=&clean($title);
                  .&Apache::loncommon::start_data_table()   $r->print('<div class="LC_left_float">'.
                  .&Apache::loncommon::start_data_table_header_row()                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
                  .'<th>'.&mt('Internal Filename').'</th>'                    '<input type="text" size="50" name="authorfolder" value="'.
                  .'<th>'.&mt('Title').'</th>'                    $title.'" />'.
                  .'<th>'.&mt('Save as ...').'</th>'                    '</fieldset></div><br clear="all" />'."\n");
                  .&Apache::loncommon::end_data_table_header_row());   &tiehash();
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
     $r->print(&Apache::loncommon::start_data_table_row()                   .&Apache::loncommon::start_data_table()
                      .'<td>'.$file.'</td>');                   .&Apache::loncommon::start_data_table_header_row()
     my ($ext)=($file=~/\.(\w+)$/);                   .'<th>'.&mt('Internal Filename').'</th>'
     my $title=$hash{'title_'.$hash{                   .'<th>'.&mt('Title').'</th>'
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                   .'<th>'.&mt('Save as ...').'</th>'
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');                   .&Apache::loncommon::end_data_table_header_row());
     if (!$title) {   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  $title=$file;      $r->print(&Apache::loncommon::start_data_table_row()
     } else {                       .'<td>'.$file.'</td>');
  $title=~s|/|_|g;      my ($ext)=($file=~/\.(\w+)$/);
     }      my $title=$hash{'title_'.$hash{
     $title=~s/\.(\w+)$//;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     $title=&clean($title);      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
     $title.='.'.$ext;      if (!$title) {
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"   $title=$file;
                      .&Apache::loncommon::end_data_table_row());      } else {
  }   $title=~s|/|_|g;
  $r->print(&Apache::loncommon::end_data_table());      }
  &untiehash();      $title=~s/\.(\w+)$//;
  $r->print(      $title=&clean($title);
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      $title.='.'.$ext;
     }      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
 }                       .&Apache::loncommon::end_data_table_row());
    }
    $r->print(&Apache::loncommon::end_data_table());
    &untiehash();
 sub exportbutton {   $r->print(
     my $type = &Apache::loncommon::course_type();    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
     return '<div>'.      }
             '<input type="submit" name="exportcourse" value="'.      $r->print(&endContentScreen());
             &mt('Export '.$type.' to IMS').'" />'.  }
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs').'</div>';  
 }  sub group_import {
       my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
       my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
           %removeparam,$importuploaded,$fixuperrors);
 sub exportcourse {      $allmaps = {};
     my $r=shift;      while (@files) {
     my $type = &Apache::loncommon::course_type();   my ($name, $url, $residx) = @{ shift(@files) };
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});       && ($caller eq 'londocs')
     my $numdisc = keys(%discussiontime);       && (!&Apache::lonnet::stat_file($url))) {
     my $navmap = Apache::lonnavmaps::navmap->new();  
     if (!defined($navmap)) {              my $errtext = '';
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').              my $fatal = 0;
                   '<h2>IMS Export Failed</h2>'.              my $newmapstr = '<map>'."\n".
                   '<div class="LC_error">'.                              '<resource id="1" src="" type="start"></resource>'."\n".
                   &mt('Unable to retrieve information about course contents').                              '<link from="1" to="2" index="1"></link>'."\n".
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');                              '<resource id="2" src="" type="finish"></resource>'."\n".
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                              '</map>';
         return;              $env{'form.output'}=$newmapstr;
     }              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);                                                  'output',$1.$2);
     my $curRes;              if ($result != m|^/uploaded/|) {
     my $outcome;                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
                   $fatal = 2;
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              }
                                             ['finishexport']);              if ($fatal) {
     if ($env{'form.finishexport'}) {                  return ($errtext,$fatal);
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              }
                                             ['archive','discussion']);          }
    if ($url) {
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');              if (($caller eq 'londocs') &&
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');                  ($folder =~ /^default/)) {
         if (@exportitems == 0 && @discussions == 0) {                  unless ($donechk) {
             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';                      my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
         } else {                      my $cid = $coursedom.'_'.$coursenum;
             my $now = time;                      $allmaps =
             my %symbs;                          &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
             my $manifestok = 0;                                                               $chome,$cid);
             my $imsresources;                      $donechk = 1;
             my $tempexport;                  }
             my $copyresult;                  if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);                      &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
             if ($manifestok) {                                           \%addedmaps,\%hierarchy,\%titles,$allmaps);
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);                      $importuploaded = 1;
                 close($ims_manifest);                  } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                       next if ($allmaps->{$url});
 #Create zip file in prtspool                  }
                 my $imszipfile = '/prtspool/'.              }
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.      if (!$residx
                    time.'_'.rand(1000000000).'.zip';   || defined($LONCAPA::map::zombies[$residx])) {
                 my $cwd = &Cwd::getcwd();   $residx = &LONCAPA::map::getresidx($url,$residx);
                 my $imszip = '/home/httpd/'.$imszipfile;   push(@LONCAPA::map::order, $residx);
                 chdir $tempexport;      }
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");      my $ext = 'false';
                 close(OUTPUT);      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
                 chdir $cwd;      $url  = &LONCAPA::map::qtunescape($url);
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      $name = &LONCAPA::map::qtunescape($name);
                 if ($copyresult) {      $LONCAPA::map::resources[$residx] =
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);   join(':', ($name, $url, $ext, 'normal', 'res'));
                 }   }
             } else {      }
                 $outcome = '<br />'.&mt('Unfortunately you will not be able to retrieve an IMS archive of this posts at this time, because there was a problem creating a manifest file.').'<br />';      if ($importuploaded) {
             }          my %import_errors;
         }          my %updated = (
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));                            removefrommap => \%removefrommap,
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));                            removeparam   => \%removeparam,
         $r->print($outcome);                        );
         $r->print(&Apache::loncommon::end_page());          my ($result,$msgsarray,$lockerror) =
     } else {              &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
         my $display;          if (keys(%import_errors) > 0) {
         $display = '<form name="exportdoc" method="post">'."\n";              $fixuperrors =
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');                  '<p span class="LC_warning">'."\n".
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                  &mt('The following files are either dependencies of a web page or references within a folder and/or composite page for which errors occurred during import:')."\n".
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.                  '<ul>'."\n";
                     '<input type="button" value="check all" '.              foreach my $key (sort(keys(%import_errors))) {
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.                  $fixuperrors .= '<li>'.$key.'</li>'."\n";
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.              }
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.              $fixuperrors .= '</ul></p>'."\n";
                     '<td>&nbsp;</td><td>&nbsp;</td>'.          }
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.          if (ref($msgsarray) eq 'ARRAY') {
                     '</b></legend><input type="button" value="check all"'.              if (@{$msgsarray} > 0) {
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.                  $fixuperrors .= '<p class="LC_info">'.
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.                                  join('<br />',@{$msgsarray}).
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.                                  '</p>';
                     '</tr></table>';              }
         my $curRes;          }
         my $depth = 0;          if ($lockerror) {
         my $count = 0;              $fixuperrors .= '<p class="LC_error">'.
         my $boards = 0;                              $lockerror.
         my $startcount = 5;                              '</p>';
         my %parent = ();          }
         my %children = ();      }
         my $lastcontainer = $startcount;      my ($errtext,$fatal) =
         my @bgcolors = ('#F6F6F6','#FFFFFF');          &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
         $display .= '<table cellspacing="0"><tr>'.      return ($errtext,$fatal,$fixuperrors);
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";  }
         if ($numdisc > 0) {  
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";  sub log_docs {
         }      return &Apache::lonnet::write_log('course','docslog',@_);
         $display.='&nbsp;</td></tr>';  }
         while ($curRes = $it->next()) {  
             if (ref($curRes)) {  {
                 $count ++;      my @oldresources=();
             }      my @oldorder=();
             if ($curRes == $it->BEGIN_MAP()) {      my $parmidx;
                 $depth++;      my %parmaction=();
                 $parent{$depth} = $lastcontainer;      my %parmvalue=();
             }      my $changedflag;
             if ($curRes == $it->END_MAP()) {  
                 $depth--;      sub snapshotbefore {
                 $lastcontainer = $parent{$depth};          @oldresources=@LONCAPA::map::resources;
             }          @oldorder=@LONCAPA::map::order;
             if (ref($curRes)) {          $parmidx=undef;
                 my $symb = $curRes->symb();          %parmaction=();
                 my $ressymb = $symb;          %parmvalue=();
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {          $changedflag=0;
                     unless ($ressymb =~ m|adm/wrapper/adm|) {      }
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';  
                     }      sub remember_parms {
                 }          my ($idx,$parameter,$action,$value)=@_;
                 my $color = $count%2;          $parmidx=$idx;
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".          $parmaction{$parameter}=$action;
                     '<input type="checkbox" name="archive" value="'.$count.'" ';          $parmvalue{$parameter}=$value;
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {          $changedflag=1;
                     my $checkitem = $count + $boards + $startcount;      }
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';  
                 }      sub log_differences {
                 $display .= ' />'."\n";          my ($plain)=@_;
                 for (my $i=0; $i<$depth; $i++) {          my %storehash=('folder' => $plain,
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";                         'currentfolder' => $env{'form.folder'});
                 }          if ($parmidx) {
                 if ($curRes->is_sequence()) {             $storehash{'parameter_res'}=$oldresources[$parmidx];
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";             foreach my $parm (keys(%parmaction)) {
                     $lastcontainer = $count + $startcount + $boards;                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
                 } elsif ($curRes->is_page()) {                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";             }
                     $lastcontainer = $count + $startcount + $boards;          }
                 }          my $maxidx=$#oldresources;
                 my $currelem = $count+$boards+$startcount;          if ($#LONCAPA::map::resources>$#oldresources) {
                 $children{$parent{$depth}} .= $currelem.':';             $maxidx=$#LONCAPA::map::resources;
                 $display .= '&nbsp;'.$curRes->title().'</td>';          }
                 if ($discussiontime{$ressymb} > 0) {          for (my $idx=0; $idx<=$maxidx; $idx++) {
                     $boards ++;             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
                     $currelem = $count+$boards+$startcount;                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
                 } else {                $changedflag=1;
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";             }
                 }             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
             }                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
         }                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
         my $scripttag = qq|                $changedflag=1;
 <script>             }
           }
 function checkAll(field) {   $storehash{'maxidx'}=$maxidx;
     if (field.length > 0) {          if ($changedflag) { &log_docs(\%storehash); }
         for (i = 0; i < field.length; i++) {      }
             field[i].checked = true ;  }
         }  
     } else {  sub docs_change_log {
         field.checked = true      my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
     }      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 }      my $js = '<script type="text/javascript">'."\n".
                                                                                               '// <![CDATA['."\n".
 function uncheckAll(field) {               &Apache::loncommon::display_filter_js('docslog')."\n".
     if (field.length > 0) {               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
         for (i = 0; i < field.length; i++) {               &history_tab_js()."\n".
             field[i].checked = false ;               &Apache::lonratedt::editscript('simple')."\n".
         }               '// ]]>'."\n".
     } else {               '</script>'."\n";
         field.checked = false ;      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
     }      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
 }      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
       my %orderhash;
 function propagateCheck(item) {      my $container='sequence';
     if (document.exportdoc.elements[item].checked == true) {      my $pathitem;
         containerCheck(item)      if ($env{'form.folderpath'} =~ /\:1$/) {
     }          $container='page';
 }      }
       my $folderpath=$env{'form.folderpath'};
 function containerCheck(item) {      if ($folderpath eq '') {
     document.exportdoc.elements[item].checked = true          $folderpath = 'default&'.&escape(&mt('Main '.$crstype.' Documents').':::::');
     var numitems = $count + $boards + $startcount      }
     var parents = new Array(numitems)      $pathitem = '<input type="hidden" name="folderpath" value="'.
     for (var i=$startcount; i<numitems; i++) {                  &HTML::Entities::encode($folderpath,'<>&"').'" />';
         parents[i] = new Array      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
     }      my $jumpto = $readfile;
         |;      $jumpto =~ s{^/}{};
       my $tid = 1;
         foreach my $container (sort { $a <=> $b } (keys(%children))) {      if ($supplementalflag) {
             my @contents = split(/:/,$children{$container});          $tid = 2;
             for (my $i=0; $i<@contents; $i ++) {      }
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";      my ($breadcrumbtrail) = 
             }          &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
         }      $r->print($breadcrumbtrail.
                 &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
         $scripttag .= qq|                $readfile));
     if (parents[item].length > 0) {      my %docslog=&Apache::lonnet::dump('nohist_docslog',
         for (var j=0; j<parents[item].length; j++) {                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
             containerCheck(parents[item][j])                                        $env{'course.'.$env{'request.course.id'}.'.num'});
         }  
      }        if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 }  
       my %saveable_parameters = ('show' => 'scalar',);
 </script>      &Apache::loncommon::store_course_settings('docs_log',
         |;                                                \%saveable_parameters);
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',      &Apache::loncommon::restore_course_settings('docs_log',
  $scripttag));                                                  \%saveable_parameters);
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));      if (!$env{'form.show'}) { $env{'form.show'}=10; }
  $r->print($display.'</table>'.  # FIXME: internationalization seems wrong here
                   '<p><input type="hidden" name="finishexport" value="1">'.      my %lt=('hiddenresource' => 'Resources hidden',
                   '<input type="submit" name="exportcourse" value="'.      'encrypturl'     => 'URL hidden',
                   &mt('Export '.$type.' DOCS').'" /></p></form>');      'randompick'     => 'Randomly pick',
     }      'randomorder'    => 'Randomly ordered',
 }      'set'            => 'set to',
       'del'            => 'deleted');
 sub create_ims_store {      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
     my ($now,$manifestok,$outcome,$tempexport) = @_;                   $pathitem."\n".
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
     my $ims_manifest;                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
     if (!-e $$tempexport) {      $r->print('<div class="LC_left_float">'.
         mkdir($$tempexport,0700);                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
     }                &makedocslogform($filter,1).
     $$tempexport .= '/'.$now;                '</fieldset></div><br clear="all" />');
     if (!-e $$tempexport) {      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
         mkdir($$tempexport,0700);                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
     }                &mt('After').'</th>'.
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};                &Apache::loncommon::end_data_table_header_row());
     if (!-e $$tempexport) {      my $shown=0;
         mkdir($$tempexport,0700);      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     }   if ($env{'form.displayfilter'} eq 'currentfolder') {
     if (!-e "$$tempexport/resources") {      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
         mkdir("$$tempexport/resources",0700);   }
     }          my @changes=keys(%{$docslog{$id}{'logentry'}});
 # open manifest file          if ($env{'form.displayfilter'} eq 'containing') {
     my $manifest = '/imsmanifest.xml';      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
     my $manifestfilename = $$tempexport.$manifest;   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      foreach my $key (@changes) {
         $$manifestok=1;   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
         print $ims_manifest      }
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.   }
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.          my $count = 0;
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.          my $time =
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.          my $plainname =
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
 '  <metadata>                                            $docslog{$id}{'exe_udom'});
     <schema></schema>          my $about_me_link =
     <imsmd:lom>              &Apache::loncommon::aboutmewrapper($plainname,
       <imsmd:general>                                                 $docslog{$id}{'exe_uname'},
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>                                                 $docslog{$id}{'exe_udom'});
         <imsmd:title>          my $send_msg_link='';
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
         </imsmd:title>               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
       </imsmd:general>              $send_msg_link ='<br />'.
     </imsmd:lom>                  &Apache::loncommon::messagewrapper(&mt('Send message'),
   </metadata>'."\n".                                                     $docslog{$id}{'exe_uname'},
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".                                                     $docslog{$id}{'exe_udom'});
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.          }
 ' structure="hierarchical">'."\n".          $r->print(&Apache::loncommon::start_data_table_row());
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'          $r->print('<td>'.$time.'</td>
     } else {                         <td>'.$about_me_link.
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
 ;                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
     }                    $send_msg_link.'</td><td>'.
     return $ims_manifest;                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
 }          my $is_supp = 0; 
           if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
 sub build_package {              $is_supp = 1;
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;          }
 # first iterator to look for dependencies  # Before
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     my $curRes;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     my $count = 0;      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
     my $depth = 0;      if ($oldname ne $newname) {
     my $lastcontainer = 0;                  my $shown = &LONCAPA::map::qtescape($oldname);
     my %parent = ();                  if ($is_supp) {
     my @dependencies = ();                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};                  }
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};                  $r->print($shown);
     while ($curRes = $it->next()) {      }
         if (ref($curRes)) {   }
             $count ++;   $r->print('<ul>');
         }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
         if ($curRes == $it->BEGIN_MAP()) {              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
             $depth++;                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
             $parent{$depth} = $lastcontainer;                  if ($is_supp) {
         }                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
         if ($curRes == $it->END_MAP()) {                  }
             $depth--;   $r->print('<li>'.$shown.'</li>');
             $lastcontainer = $parent{$depth};      }
         }   }
         if (ref($curRes)) {   $r->print('</ul>');
             if ($curRes->is_sequence() || $curRes->is_page()) {  # After
                 $lastcontainer = $count;          $r->print('</td><td>');
             }  
             if (grep(/^$count$/,@$exportitems)) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
             }      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
         }      if ($oldname ne '' && $oldname ne $newname) {
     }                  my $shown = &LONCAPA::map::qtescape($newname);
 # second iterator to build manifest and store resources                  if ($is_supp) {
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                      $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
     $depth = 0;                  }
     my $prevdepth;                  $r->print($shown);
     $count = 0;      }
     my $imsresources;   }
     my $pkgdepth;   $r->print('<ul>');
     while ($curRes = $it->next()) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
         if ($curRes == $it->BEGIN_MAP()) {              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
             $prevdepth = $depth;                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
             $depth++;                  if ($is_supp) {
         }                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
         if ($curRes == $it->END_MAP()) {                  }
             $prevdepth = $depth;                  $r->print('<li>'.$shown.'</li>');
             $depth--;      }
         }   }
    $r->print('</ul>');
         if (ref($curRes)) {   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
             $count ++;      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
                 my $symb = $curRes->symb();   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                 my $isvisible = 'true';  # FIXME: internationalization seems wrong here
                 my $resourceref;      $r->print('<li>'.
                 if ($curRes->randomout()) {        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
                     $isvisible = 'false';    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
                 }        .'</li>');
                 unless ($curRes->is_sequence()) {   }
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';      }
                 }      $r->print('</ul>');
                 my $step = $prevdepth - $depth;   }
                 if (($step >= 0) && ($count > 1)) {  # End
                     while ($step >= 0) {          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
                         print $ims_manifest "\n".'  </item>'."\n";          $shown++;
                         $step --;          if (!($env{'form.show'} eq &mt('all')
                     }                || $shown<=$env{'form.show'})) { last; }
                 }      }
                 $prevdepth = $depth;      $r->print(&Apache::loncommon::end_data_table()."\n".
                 &makesimpleeditform($pathitem)."\n".
                 my $itementry =                '</div></div>');
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.      $r->print(&endContentScreen());
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.  }
               '<title>'.$curRes->title().'</title>';  
                 print $ims_manifest "\n".$itementry;  sub update_paste_buffer {
       my ($coursenum,$coursedom,$folder) = @_;
                 unless ($curRes->is_sequence()) {  
                     my $content_file;      return if (!defined($env{'form.markcopy'}));
                     my @hrefs = ();      return if (!defined($env{'form.copyfolder'}));
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);      return if ($env{'form.markcopy'} < 0);
                     if ($content_file) {  
                         $imsresources .= "\n".      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.      $env{'form.copyfolder'});
                      '" type="webcontent" href="'.$content_file.'">'."\n".  
                      '       <file href="'.$content_file.'" />'."\n";      return if ($fatal);
                         foreach my $item (@hrefs) {  
                             $imsresources .=  # Mark for copying
                      '        <file href="'.$item.'" />'."\n";      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
                         }      if (&is_supplemental_title($title)) {
                         if (grep(/^$count$/,@$discussions)) {          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
                             my $ressymb = $symb;   ($title) = &Apache::loncommon::parse_supplemental_title($title);
                             my $mode;      } elsif ($env{'docs.markedcopy_supplemental'}) {
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {          &Apache::lonnet::delenv('docs.markedcopy_supplemental');
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {      }
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
                                 }  
                                 $mode = 'board';      (my $cmd,undef)=split('_',$env{'form.cmd'});
                             }  
                             my %extras = (      my %addtoenv = (
                                           caller => 'imsexport',                      'docs.markedcopy_title' => $title,
                                           tempexport => $tempexport.'/resources',                      'docs.markedcopy_url'   => $url,
                                           count => $count                      'docs.markedcopy_cmd'   => $cmd,
                                          );                     );
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);      &Apache::lonnet::delenv('docs.markedcopy_nested');
                         }      &Apache::lonnet::delenv('docs.markedcopy_nestednames');
                         $imsresources .= '    </resource>'."\n";      if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
                     }          my $prefix = $1;
                 }          my $subdir =$2;
                 $pkgdepth = $depth;          if ($subdir eq '') {
             }              $subdir = $prefix;
         }          }
     }          my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
     while ($pkgdepth > 0) {          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
         print $ims_manifest "    </item>\n";                               \%hierarchy,\%titles,\%allmaps);
         $pkgdepth --;          if (ref($hierarchy{$url}) eq 'HASH') {
     }              my ($nested,$nestednames);
     my $resource_text = qq|              &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
     </organization>              $nested =~ s/\&$//;
   </organizations>              $nestednames =~ s/\Q___&&&___\E$//;
   <resources>              if ($nested ne '') {
     $imsresources                  $addtoenv{'docs.markedcopy_nested'} = $nested;
   </resources>              }
 </manifest>              if ($nestednames ne '') {
     |;                  $addtoenv{'docs.markedcopy_nestednames'} = $nestednames;
     print $ims_manifest $resource_text;              }
 }          }
       }
 sub get_dependencies {      &Apache::lonnet::appenv(\%addtoenv);
     my ($exportitems,$parent,$depth,$dependencies) = @_;      delete($env{'form.markcopy'});
     if ($depth > 1) {  }
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {  
             push(@{$dependencies},$$parent{$depth});  sub recurse_uploaded_maps {
             if ($depth > 2) {      my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);      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}}));
     }          my (@uploaded,@names,%shorter);
 }          for (my $i=0; $i<@maps; $i++) {
               my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
 sub process_content {              if ($inner ne '') {
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;                  push(@uploaded,$inner);
     my $content_type;                  push(@names,&escape($titles[$i]));
     my $message;                  $shorter{$maps[$i]} = $inner;
     my @uploads = ();              }
     if ($curRes->is_sequence()) {          }
         $content_type = 'sequence';          $$nestref .= "$dir:".join(',',@uploaded).'&';
     } elsif ($curRes->is_page()) {          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
         $content_type = 'page'; # need to handle individual items in pages.          foreach my $map (@maps) {
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {              if ($shorter{$map} ne '') {
         $content_type = 'syllabus';                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
         my $contents = &Apache::imsexport::templatedpage($content_type);              }
         if ($contents) {          }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      }
         }      return;
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {  }
         $content_type = 'external';  
         my $title = $curRes->title;  sub print_paste_buffer {
         my $contents =  &Apache::imsexport::external($symb,$title);      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
         if ($contents) {      return if (!defined($env{'docs.markedcopy_url'}));
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);  
         }      my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent);
     } elsif ($symb =~ m-adm/navmaps$-) {      my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
         $content_type =  'navmap';      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {          $is_external = 1;
         $content_type = 'simplepage';      }
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);  
         if ($contents) {      my ($canpaste,$nopaste,$othercrs,$areachange);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      if ($folder =~ /^supplemental/) {
         }          $canpaste = &supp_pasteable($env{'docs.markedcopy_url'});
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {          unless ($canpaste) {
         $content_type = 'simpleproblem';              $nopaste = &mt('Paste into Supplemental Content unavailable for this type of content.');
         my $contents =  &Apache::imsexport::simpleproblem($symb);          } 
         if ($contents) {      } else {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          $canpaste = 1;
         }      }
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {  
         $content_type = 'examupload';      if ($canpaste) {
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {          if ($env{'docs.markedcopy_url'} =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
         $content_type = 'bulletinboard';              my $srcdom = $1;
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);              my $srcnum = $2;
         if ($contents) {              my $rem = $3;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
         }                  $othercourse = 1;
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {                  if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         $content_type = 'aboutme';                      if ($canpaste) {
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);                          $othercrs = '<br />'.&mt('(from another course).');  
         if ($contents) {                      }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);                  } else {
         }                      $canpaste = 0;
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {                      $nopaste = &mt('Paste from another course unavailable.') 
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                  }
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {              }
         my $canedit = 0;              if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {                  my $prefix = $1;
             $canedit= 1;                  $parent = $2;
         }                  if ($folder !~ /^\Q$prefix\E/) {
 # only include problem code where current user is author                      $areachange = 1;
         if ($canedit) {                  }
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');                  $is_uploaded_map = 1;
         } else {              }
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');          }
         }      }
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {  
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');      $r->print('<fieldset>'
     }               .'<legend>'.&mt('Clipboard').'</legend>');
     if (@uploads > 0) {      my ($type,$buffer);
         foreach my $item (@uploads) {      if ($is_external) {
             my $uploadmsg = '';          $type = &mt('External Resource');
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');          $buffer = $type.': '.
             if ($uploadmsg) {                    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
                 $$copyresult .= $uploadmsg."\n";                    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')';
             }      } else {
         }          my $icon = &Apache::loncommon::icon($extension);
     }          if ($extension eq 'sequence' &&
     if ($message) {              $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
         $$copyresult .= $message."\n";              $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     }              $icon .= '/navmap.folder.closed.gif';
 }          }
           $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
 sub replicate_content {          $buffer = $icon.$type.': '.  &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'}));
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;      }
     my ($map,$ind,$url);      if ($canpaste) {
     if ($caller eq 'templateupload') {          $r->print('<form name="pasteform" action="/adm/coursedocs" method="post">'.$buffer);
         $url = $symb;          if ((!$areachange) && (!$othercourse) &&
         $url =~ s#//#/#g;              ($env{'docs.markedcopy_cmd'} eq 'cut')) {
     } else {              if (($is_uploaded_map) ||
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);                  ($env{'docs.markedcopy_url'} =~ /(bulletinboard|smppg)$/) ||
     }                  ($env{'docs.markedcopy_url'} =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
     my $content;                  my ($copytext,$movetext);
     my $filename;                  if ($is_uploaded_map) {
     my $repstatus;                      $copytext = &mt('Copy to new folder');
     my $content_name;                      $movetext = &mt('Move old folder');
     if ($url =~ m-/([^/]+)$-) {                  } elsif ($env{'docs.markedcopy_url'} =~ /bulletinboard$/) {
         $filename = $1;                      $copytext = &mt('Copy to new bulletin board (not posts)');
         if (!-e $tempexport.'/resources') {                      $movetext = &mt('Move old bulletin board (not posts)');
             mkdir($tempexport.'/resources',0700);                  } elsif ($env{'docs.markedcopy_url'} =~ /smppg$/) {
         }                      $copytext = &mt('Copy to new simple page');
         if (!-e $tempexport.'/resources/'.$count) {                      $movetext = &mt('Move old simple page');
             mkdir($tempexport.'/resources/'.$count,0700);                  } else {
         }                      $copytext = &mt('Copy to new uploaded document');
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;                      $movetext = &mt('Move old uploaded document');
         my $copiedfile;                  }
         if ($copiedfile = Apache::File->new('>'.$destination)) {                  $r->print(('&nbsp;'x 4).'<span id="pasteoptionstext">'.
             my $content;                            '<a href="javascript:showPasteOptions();" class="LC_menubuttons_link">'.
             if ($caller eq 'resource') {                            &mt('Show Paste Options').'</a></span><br />'.
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                            '<div id="pasteoptions" class="LC_dccid">'.('&nbsp;'x 4).
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);                            '<label>'.
                 $content = &Apache::lonnet::getfile($filepath);                            '<input type="radio" name="docs.markedcopy_options" value="new" checked="checked" />'.
                 if ($content eq -1) {                            $copytext.'</label>'.('&nbsp;' x2).
                     $$message = 'Could not copy file '.$filename;                            '<label>'.   
                 } else {                            '<input type="radio" name="docs.markedcopy_options" value="move" />'.
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');                            $movetext.'</label><br />');
                     $repstatus = 'ok';                  if (($is_uploaded_map) && ($env{'docs.markedcopy_nested'})) {
                 }                      $r->print('<br />'.&mt('Folder to paste contains sub-folders').
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {                                '<br /><table border="0">');
                 my $rtncode;                      my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested'});
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);                      my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames'});
                 if ($repstatus eq 'ok') {                      my $lastdir = $parent;
                     if ($url =~ /\.html?$/i) {                      my %depths = (
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');                                     $lastdir => 0,
                     }                                   );
                 } else {                      my (%display,%deps); 
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";                      for (my $i=0; $i<@pastemaps; $i++) {
                 }                          ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
             } elsif ($caller eq 'noedit') {                          my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.                          my @subfolders = split(/,/,$subfolderstr);
                 $repstatus = 'ok';                          $deps{$lastdir} = \@subfolders;
                 $content = 'Not the owner of this resource';                          my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
             }                          my $depth = $depths{$lastdir} + 1;
             if ($repstatus eq 'ok') {                          my $offset = int($depth * 4);
                 print $copiedfile $content;                          my $indent = ('&nbsp;' x $offset);
             }                          for (my $j=0; $j<@subfolders; $j++) {
             close($copiedfile);                              $depths{$subfolders[$j]} = $depth;
         } else {                              $display{$subfolders[$j]} = 
             $$message = 'Could not open destination file for '.$filename."<br />\n";                                    '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
         }                                    '<td><label>'.
     } else {                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
         $$message = 'Could not determine name of file for '.$symb."<br />\n";                                    '<label>'.
     }                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="move" />'.
     if ($repstatus eq 'ok') {                                    &mt('Move old').'</label>'.
         $content_name = 'resources/'.$count.'/'.$filename;                                    '</td></tr>';
     }                          }
     return $content_name;                      }
 }                      &recurse_print($r,$parent,\%deps,\%display);
                       $r->print('</table>');
 sub extract_media {                  }
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;                  $r->print('</div>');
     my ($dirpath,$container);              }
     my %allfiles = ();          }
     my %codebase = ();          $r->print('<br /><input type="submit" name="pastemarked" value="'.&mt('Paste').'" />'.$othercrs);
     if ($url =~ m-(.*/)([^/]+)$-) {          $r->print('
         $dirpath = $1;          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
         $container = $2;  ');
     } else {          $r->print('</form>');
         $dirpath = $url;      } else {
         $container = '';          $r->print(&mt('Paste buffer contains:').' '.$buffer.
     }                    '<br /><p class="LC_info">'.$nopaste.'</p>');
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);      }
     foreach my $embed_file (keys(%allfiles)) {      $r->print('</fieldset>');
         my $filename;  }
         if ($embed_file =~ m#([^/]+)$#) {  
             $filename = $1;  sub recurse_print {
         } else {      my ($r,$dir,$deps,$display) = @_;
             $filename = $embed_file;      $r->print($display->{$dir}."\n");
         }      if (ref($deps->{$dir}) eq 'ARRAY') {
         my $newname = 'res/'.$filename;          foreach my $subdir (@{$deps->{$dir}}) {
         my ($rtncode,$embed_content,$repstatus);              &recurse_print($r,$subdir,$deps,$display);
         my $embed_url;          }
         if ($embed_file =~ m-^/-) {      }
             $embed_url = $embed_file;           # points to absolute path  }
         } else {  
             if ($embed_file =~ m-https?://-) {  sub supp_pasteable {
                 next;                           # points to url      my ($url) = @_;
             } else {      if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
                 $embed_url = $dirpath.$embed_file;  # points to relative path          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
             }          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
         }          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
         if ($caller eq 'resource') {          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';            return 1;
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);      }
             $embed_content = &Apache::lonnet::getfile($embed_path);      return;
             unless ($embed_content eq -1) {  }
                 $repstatus = 'ok';  
             }  sub paste_popup_js {
         } elsif ($caller eq 'uploaded') {      my %lt = &Apache::lonlocal::texthash(
                                                        show => 'Show Paste Options',
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);                                            hide => 'Hide Paste Options',
         }                                          );
         if ($repstatus eq 'ok') {      return <<"END";
             my $destination = $tempexport.'/resources/'.$count.'/res';  
             if (!-e "$destination") {  function showPasteOptions() {
                 mkdir($destination,0755);      document.getElementById('pasteoptions').style.display='block';
             }      document.getElementById('pasteoptions').style.textAlign='left';
             $destination .= '/'.$filename;      document.getElementById('pasteoptions').style.textFace='normal';
             my $copiedfile;      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:hidePasteOptions();" class="LC_menubuttons_link">$lt{'hide'}</a><br />';
             if ($copiedfile = Apache::File->new('>'.$destination)) {      return;
                 print $copiedfile $embed_content;  }
                 push(@{$href},'resources/'.$count.'/res/'.$filename);  
                 my $attrib_regexp = '';  function hidePasteOptions() {
                 if (@{$allfiles{$embed_file}} > 1) {      document.getElementById('pasteoptions').style.display='none';
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:showPasteOptions()" class="LC_menubuttons_link">$lt{'show'}</a>';
                 } else {      return;
                     $attrib_regexp = $allfiles{$embed_file}[0];  }
                 }  
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;  END
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {  
                     $$content =~ s#\Q$embed_file\E#$newname#gi;  }
                 }  
             }  
         } else {  sub do_paste_from_buffer {
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";      my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
         }  
     }  # Early out if paste buffer is empty
     return;      if (!$env{'form.pastemarked'}) {
 }          return ();
       }
 sub store_template {  
     my ($contents,$tempexport,$count,$content_type) = @_;  # Supplemental content may only include certain types of content
     if ($contents) {  # Early out if pasted content is not supported in Supplemental area
         if ($tempexport) {      if ($folder =~ /^supplemental/) {
             if (!-e $tempexport.'/resources') {          unless (&supp_pasteable($env{'docs.markedcopy_url'})) {
                 mkdir($tempexport.'/resources',0700);              return (&mt('Paste failed: content type is not supported within Supplemental Content'));
             }          }
             if (!-e $tempexport.'/resources/'.$count) {      }
                 mkdir($tempexport.'/resources/'.$count,0700);  
             }  # Prepare to paste resource at end of list
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
             my $storetemplate;      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
             if ($storetemplate = Apache::File->new('>'.$destination)) {  
                 print $storetemplate $contents;      my ($is_map,$srcdom,$srcnum,$prefixchg,%before,%after,%mapchanges,%tomove);
                 close($storetemplate);      if ($url=~/\.(page|sequence)$/) {
             }          $is_map = 1; 
             if ($content_type eq 'external') {      }
                 return 'resources/'.$count.'/'.$content_type.'.html';      if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/([^/]+)}) {
             } else {          $srcdom = $1;
                 return 'resources/'.$count.'/'.$content_type.'.xml';          $srcnum = $2;
             }          my $oldprefix = $3;
         }  # 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 (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
               unless ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
                   return (&mt('Paste failed: Item is from a different course which you do not have rights to edit.'));
 sub group_import {              }
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;          }
   # When pasting content from Main Content to Supplemental Content and vice versa 
     while (@files) {  # URLs will contain different paths (which depend on whether pasted item is
  my ($name, $url, $residx) = @{ shift(@files) };  # a folder/page or a document.   
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})          if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
      && ($caller eq 'londocs')              $prefixchg = 1;
      && (!&Apache::lonnet::stat_file($url))) {              %before = ( map => 'default',
                               doc => 'docs');
             my $errtext = '';              %after =  ( map => 'supplemental',
             my $fatal = 0;                          doc => 'supplemental' );
             my $newmapstr = '<map>'."\n".          } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
                             '<resource id="1" src="" type="start"></resource>'."\n".              $prefixchg = 1;
                             '<link from="1" to="2" index="1"></link>'."\n".              %before = ( map => 'supplemental',
                             '<resource id="2" src="" type="finish"></resource>'."\n".                          doc => 'supplemental');
                             '</map>';              %after  = ( map => 'default',
             $env{'form.output'}=$newmapstr;                          doc => 'docs');
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,          }
                                                 'output',$1.$2);  
             if ($result != m|^/uploaded/|) {  # If pasting an uploaded map, get list of contained uploaded maps.
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';          my @nested;
                 $fatal = 2;          if ($env{'docs.markedcopy_nested'}) {
             }              my ($type) = ($oldprefix =~ /^(default|supplemental)/);
             if ($fatal) {              my @items = split(/\&/,$env{'docs.markedcopy_nested'});
                 return ($errtext,$fatal);              my @deps = map { /\d+:([\d,]+$)/ } @items;
             }              foreach my $dep (@deps) {
         }                  if ($dep =~ /,/) {
  if ($url) {                      push(@nested,split(/,/,$dep));
     if (!$residx                  } else {
  || defined($LONCAPA::map::zombies[$residx])) {                      push(@nested,$dep);
  $residx = &LONCAPA::map::getresidx($url,$residx);                  }
  push(@LONCAPA::map::order, $residx);              }
     }              foreach my $item (@nested) {
     my $ext = 'false';                  if ($env{'form.docs.markedcopy_'.$item} eq 'move') {
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }                      $tomove{$type.'_'.$item} = 1;
     $url  = &LONCAPA::map::qtunescape($url);                  }
     $name = &LONCAPA::map::qtunescape($name);              }
     $LONCAPA::map::resources[$residx] =          }
  join(':', ($name, $url, $ext, 'normal', 'res'));      }
  }  
     }  # Maps need to be copied first
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);      my ($oldurl,%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
 }          %dbcopies,%zombies,%params,%docmoves,%mapmoves,%newsubdir,%newurls);
       $oldurl = $url;
 sub breadcrumbs {      if ($is_map) {
     my ($where,$allowed,$type)=@_;  # If pasting a map, check if map contains other maps
     &Apache::lonhtmlcommon::clear_breadcrumbs();          my ($allmaps,%hierarchy,%titles);
     my (@folders);          $allmaps = {};
     if ($env{'form.pagepath'}) {          if ($folder =~ /^default/) {
         @folders = split('&',$env{'form.pagepath'});              $allmaps =
     } else {                  &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
         @folders=split('&',$env{'form.folderpath'});                                                       $env{"course.$env{'request.course.id'}.home"},
     }                                                       $env{'request.course.id'});
     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,
     if ($4 ne '') { $is_random_order = 1; }                                            $coursenum,$srcdom,$srcnum,$allmaps,
             if ($folder eq 'supplemental') {                                            \%rewrites,\%retitles,\%copies,\%dbcopies,
                 if ($allowed) {                                            \%zombies,\%params,\%mapmoves,\%mapchanges,\%tomove,
                     $name = &mt('Supplemental '.$type.' Documents');                                            \%newsubdir,\%newurls)) {
                 } else {                      $mapmoves{$url} = 1;
                     $name = &mt($type.' Documents');                  }
                 }                  $url = $newurl;
             }              } elsif ($env{'docs.markedcopy_nested'}) {
     &Apache::lonhtmlcommon::add_breadcrumb(                  &url_paste_fixups($url,$folder,$prefixchg,$coursedom,$coursenum,
       {'href'=>$url.$cpinfo,                                    $srcdom,$srcnum,$allmaps,\%rewrites,
        'title'=>$name,                                    \%retitles,\%copies,\%dbcopies,\%zombies,\%params,\%mapmoves,
        'text'=>'<font size="+1">'.                                    \%mapchanges,\%tomove,\%newsubdir,\%newurls);
    $name.'</font>',              }
        'no_mt'=>1,          } elsif ($url=~m {^/res/}) {
        });  # published maps can only exists once, so remove it from paste buffer when done
  $plain.=$name.' &gt; ';              &Apache::lonnet::delenv('docs.markedcopy');
     }  # if pasting published map (main content are only) check map is not already in course
     $plain=~s/\&gt\;\s*$//;              if ($folder =~ /^default/) {
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',                  if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);                      return (&mt('Paste failed: only one instance of a particular published sequence or page is allowed within each course.'));
 }                  }
               }
 sub log_docs {          }
     return &Apache::lonnet::instructor_log('docslog',@_);      }
 }      my $lockerrors;
       if ($url=~ m{/(bulletinboard|smppg)$}) {
 {          my $prefix = $1;
     my @oldresources=();          #need to copy the db contents to a new one, unless this is a move.
     my @oldorder=();          my %info = (
     my $parmidx;                       src  => $url,
     my %parmaction=();                       cdom => $coursedom,
     my %parmvalue=();                       cnum => $coursenum,
     my $changedflag;          );
           my (%lockerr,$msg);
     sub snapshotbefore {          unless ($env{'form.docs.markedcopy_options'} eq 'move') {
         @oldresources=@LONCAPA::map::resources;              my ($newurl,$result,$errtext) =
         @oldorder=@LONCAPA::map::order;                  &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
         $parmidx=undef;              if ($result eq 'ok') {
         %parmaction=();                  $url = $newurl;
         %parmvalue=();                  $title=&mt('Copy of').' '.$title;
         $changedflag=0;              } else {
     }                  if ($prefix eq 'smppg') {
                       $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
     sub remember_parms {                  } elsif ($prefix eq 'bulletinboard') {
         my ($idx,$parameter,$action,$value)=@_;                      $msg = &mt('Paste failed: An error occurred when copying the bulletin board.').' '.$errtext;
         $parmidx=$idx;                  }
         $parmaction{$parameter}=$action;                  return ($result,undef,[$msg],$lockerr{$prefix});
         $parmvalue{$parameter}=$value;              }
         $changedflag=1;              if ($lockerr{$prefix}) {
     }                  $lockerrors = $lockerr{$prefix};
               }
     sub log_differences {          }
         my ($plain)=@_;      }
         my %storehash=('folder' => $plain,      $title = &LONCAPA::map::qtunescape($title);
                        'currentfolder' => $env{'form.folder'});      my $ext='false';
         if ($parmidx) {      if ($url=~m{^http(|s)://}) { $ext='true'; }
            $storehash{'parameter_res'}=$oldresources[$parmidx];      $url       = &LONCAPA::map::qtunescape($url);
            foreach my $parm (keys(%parmaction)) {  
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};  # For uploaded files (excluding pages/sequences) path in copied file is changed
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};  # if paste is from Main to Supplemental (or vice versa), or if pasting between
            }  # courses.
         }  
         my $maxidx=$#oldresources;      my $newidx;
         if ($#LONCAPA::map::resources>$#oldresources) {      unless ($is_map) {
            $maxidx=$#LONCAPA::map::resources;  # Now insert the URL at the bottom
         }          $newidx = &LONCAPA::map::getresidx($url);
         for (my $idx=0; $idx<=$maxidx; $idx++) {          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {              my $relpath = $1;
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];              if ($relpath ne '') {
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];                  my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
               $changedflag=1;                  my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
            }                  my $newprefix = $newloc;
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {                  if ($newloc eq 'default') {
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];                      $newprefix = 'docs';
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];                  }
               $changedflag=1;                  if ($newdocsdir eq '') {
            }                      $newdocsdir = 'default';
         }                  }
  $storehash{'maxidx'}=$maxidx;                  if (($prefixchg) ||
         if ($changedflag) { &log_docs(\%storehash); }                      ($srcdom ne $coursedom) || ($srcnum ne $coursenum) ||
     }                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
 }                      my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
                       $url =
                           &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
                                                              &Apache::lonnet::getfile($oldurl));
                       if ($url eq '/adm/notfound.html') {
                           return (&mt('Paste failed: an error occurred saving the file.'));
 sub docs_change_log {                      } else {
     my ($r)=@_;                          my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
     my $folder=$env{'form.folder'};                          $newsubpath =~ s{/+$}{/};
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));                          $docmoves{$oldurl} = $newsubpath;
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));                      }
     my %docslog=&Apache::lonnet::dump('nohist_docslog',                  }
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},              }
                                       $env{'course.'.$env{'request.course.id'}.'.num'});          }
       }
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }  # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
       my ($result,$save_err);
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.      my %updated = (
               '<input type="hidden" name="docslog" value="1" />');                      rewrites      => \%rewrites,
                       zombies       => \%zombies,
     my %saveable_parameters = ('show' => 'scalar',);                      removefrommap => \%removefrommap,
     &Apache::loncommon::store_course_settings('docs_log',                      removeparam   => \%removeparam,
                                               \%saveable_parameters);                      dbcopies      => \%dbcopies,
     &Apache::loncommon::restore_course_settings('docs_log',                      retitles      => \%retitles,
                                                 \%saveable_parameters);                    );
     if (!$env{'form.show'}) { $env{'form.show'}=10; }      my %info = (
     my %lt=('hiddenresource' => 'Resources hidden',                     newsubdir => \%newsubdir,
     'encrypturl'     => 'URL hidden',                     params    => \%params,
     'randompick'     => 'Randomly pick',                     before    => \%before,
     'randomorder'    => 'Randomly ordered',                     after     => \%after,
     'set'            => 'set to',                 );
     'del'            => 'deleted');      my %moves = (
     $r->print(&Apache::loncommon::display_filter().                     copies   => \%copies,
               '<input type="hidden" name="folder" value="'.$folder.'" />'.                     docmoves => \%docmoves,
               '<input type="submit" value="'.&mt('Display').'" /></form>');                     mapmoves => \%mapmoves,
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().                  );
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.      ($result,my $msgsarray,my $lockerror) =
               &mt('After').'</th>'.          &apply_fixups($folder,$is_map,$coursedom,$coursenum,$errors,
               &Apache::loncommon::end_data_table_header_row());                        \%updated,\%info,\%moves,$prefixchg,$oldurl,$url,'paste');
     my $shown=0;      $lockerrors .= $lockerror;
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {      if ($result eq 'ok') {
  if ($env{'form.displayfilter'} eq 'currentfolder') {          if ($is_map) { 
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }              my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  }                                              $folder.'.'.$container);
         my @changes=keys(%{$docslog{$id}{'logentry'}});              return ($errtext,$save_err,$msgsarray,$lockerrors) if ($fatal);
         if ($env{'form.displayfilter'} eq 'containing') {  
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.              if ($#LONCAPA::map::order<1) {
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});                  my $idx=&LONCAPA::map::getresidx();
     foreach my $key (@changes) {                  if ($idx<=0) { $idx=1; }
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};                  $LONCAPA::map::order[0]=$idx;
     }                  $LONCAPA::map::resources[$idx]='';
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }                      }
  }              $newidx = &LONCAPA::map::getresidx($url);
         my $count = 0;          }
         my $time =          if ($env{'docs.markedcopy_supplemental'}) {
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});              if ($folder !~ /^supplemental/) {
         my $plainname =                  (undef,undef,$title) =
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},                      &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental'});
                                           $docslog{$id}{'exe_udom'});              }
         my $about_me_link =          } else {
             &Apache::loncommon::aboutmewrapper($plainname,              if ($folder=~/^supplemental/) {
                                                $docslog{$id}{'exe_uname'},                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
                                                $docslog{$id}{'exe_udom'});                         $env{'user.domain'}.'___&&&___'.$title;
         my $send_msg_link='';              }
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})          }
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {          $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
             $send_msg_link ='<br />'.          push(@LONCAPA::map::order, $newidx);
                 &Apache::loncommon::messagewrapper(&mt('Send message'),  
                                                    $docslog{$id}{'exe_uname'},  # Store the result
                                                    $docslog{$id}{'exe_udom'});          my ($errtext,$fatal) = 
         }              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
         $r->print(&Apache::loncommon::start_data_table_row());          if ($fatal) {
         $r->print('<td>'.$time.'</td>              $save_err = $errtext;
                        <td>'.$about_me_link.          }
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.      }
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.     
                   $send_msg_link.'</td><td>'.      if ($env{'form.docs.markedcopy_options'} eq 'move') {
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');          &Apache::lonnet::delenv('docs.markedcopy');
 # Before          &Apache::lonnet::delenv('docs.markedcopy_nested');
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          &Apache::lonnet::delenv('docs.markedcopy_nestednames');
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];      }
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];      return ($result,$save_err,$msgsarray,$lockerrors);
     if ($oldname ne $newname) {  }
  $r->print(&LONCAPA::map::qtescape($oldname));  
     }  sub get_newmap_url {
  }      my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
  $r->print('<ul>');          $titleref,$allmaps,$newurls) = @_;
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {      my $newurl;
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {      if ($url=~ m{^/uploaded/}) {
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');          $$titleref=&mt('Copy of').' '.$$titleref;
     }      }
  }      my $now = time;
  $r->print('</ul>');      my $suffix=$$.int(rand(100)).$now;
 # After      my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
         $r->print('</td><td>');      if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
           my $path = $1;
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          my $prefix = $2;
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];          my $ancestor = $3;
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];          if (length($ancestor) > 10) {
     if ($oldname ne '' && $oldname ne $newname) {              $ancestor = substr($ancestor,-10,10);
  $r->print(&LONCAPA::map::qtescape($newname));          }
     }          my $newid;
  }                  if ($prefixchg) {
  $r->print('<ul>');              if ($folder =~ /^supplemental/) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  $prefix =~ s/^default/supplemental/;
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {              } else {
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');                  $prefix =~ s/^supplemental/default/;
     }              }
  }          }
  $r->print('</ul>');          if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {              $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');          } else {
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {              $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {          }
     $r->print('<li>'.          my $counter = 0;
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',          my $is_unique = &uniqueness_check($newurl);
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})          if ($folder =~ /^default/) {
       .'</li>');              if ($allmaps->{$newurl}) {
  }                  $is_unique = 0;
     }              }
     $r->print('</ul>');          }
  }          while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
 # End              $counter ++;
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());              $suffix ++;
         $shown++;              if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
         if (!($env{'form.show'} eq &mt('all')                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
               || $shown<=$env{'form.show'})) { last; }              } else {
     }                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
     $r->print(&Apache::loncommon::end_data_table());              }
 }              $is_unique = &uniqueness_check($newurl);
           }
 sub update_paste_buffer {          if ($is_unique) {
     my ($coursenum,$coursedom) = @_;              $newurls->{$newurl} = 1;
           } else {
     return if (!defined($env{'form.markcopy'}));              if ($url=~/\.page$/) {
     return if (!defined($env{'form.copyfolder'}));                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
     return if ($env{'form.markcopy'} < 0);              } else {
                   return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,              }
     $env{'form.copyfolder'});          }
          }
     return if ($fatal);      return ($newurl);
   }
 # Mark for copying  
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);  sub dbcopy {
     if (&is_supplemental_title($title)) {      my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});      my ($url,$result,$errtext);
  ($title) = &parse_supplemental_title($title);      my $url = $dbref->{'src'};
     } elsif ($env{'docs.markedcopy_supplemental'}) {      if (ref($dbref) eq 'HASH') {
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');          if ($url =~ m{/(smppg|bulletinboard)$}) {
     }              my $prefix = $1;
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
                   ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,                  my $db_name;
     'docs.markedcopy_url'   => $url});                  my $marker = (split(m{/},$url))[4];
     delete($env{'form.markcopy'});                  $marker=~s/\D//g;
 }                  if ($dbref->{'src'} =~ m{/smppg$}) {
                       $db_name =
 sub print_paste_buffer {                          &Apache::lonsimplepage::get_db_name($url,$marker,
     my ($r,$container) = @_;                                                              $dbref->{'cdom'},
     return if (!defined($env{'docs.markedcopy_url'}));                                                              $dbref->{'cnum'});
                   } else {
     $r->print(<<ENDPASTE);                      $db_name = 'bulletinpage_'.$marker;
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>                  }
 ENDPASTE                  my ($suffix,$freedlock,$error) =
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');                      &Apache::lonnet::get_timebased_id($prefix,'num','templated',
                                                         $coursedom,$coursenum,
     my $type;                                                        'concat');
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {                  if (!$suffix) {
  $type = &mt('External Resource');                      if ($prefix eq 'smppg') {
  $r->print($type.': '.                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.                      } else {
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a bulletin board [_1].',$url);
     }  else {                      }
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];                      if ($error) {
  my $icon = &Apache::loncommon::icon($extension);                          $errtext .= '<br />'.$error;
  if ($extension eq 'sequence' &&                      }
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {                  } else {
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));                      #need to copy the db contents to a new one.
     $icon .= '/folder_closed.gif';                      my %contents=&Apache::lonnet::dump($db_name,
  }                                                         $dbref->{'cdom'},
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';                                                         $dbref->{'cnum'});
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));                      if (exists($contents{'uploaded.photourl'})) {
     }                          my $photo = $contents{'uploaded.photourl'};
     if ($container eq 'page') {                          my ($subdir,$fname) =
  $r->print('                              ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />                          my $newphoto;
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />                          if ($fname ne '') {
 ');                              my $content = &Apache::lonnet::getfile($photo);
     } else {                              unless ($content eq '-1') {
  $r->print('                                  $env{'form.'.$suffix.'.photourl'} = $content;
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />                                  $newphoto =
 ');                                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
     }                                  delete($env{'form.'.$suffix.'.photourl'});
     $r->print('</p></form>');                              }
 }                          }
                           if ($newphoto =~ m{^/uploaded/}) {
 sub do_paste_from_buffer {                              $contents{'uploaded.photourl'} = $newphoto;
     my ($coursenum,$coursedom,$folder) = @_;                          }
                       }
     if (!$env{'form.pastemarked'}) {                      $db_name =~ s{_\d*$ }{_$suffix}x;
         return;                      $result=&Apache::lonnet::put($db_name,\%contents,
     }                                                   $coursedom,$coursenum);
                       if ($result eq 'ok') {
 # paste resource to end of list                          $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});                      }
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});                  }
 # Maps need to be copied first                  if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {                      $lockerrorsref->{$prefix} =
  $title=&mt('Copy of').' '.$title;                          '<div class="LC_error">'.
  my $newid=$$.int(rand(100)).time;                          &mt('There was a problem removing a lockfile.');
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);                      if ($prefix eq 'smppg') {
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {                          $lockerrorsref->{$prefix} .=
             my $path = $1;                              &mt('This will prevent creation of additional simple pages in this course.');
             my $prefix = $2;                      } else {
             my $ancestor = $3;                          $lockerrorsref->{$prefix} .= &mt('This will prevent creation of additional bulletin boards in this course.');
             if (length($ancestor) > 10) {                      }
                 $ancestor = substr($ancestor,-10,10);                      $lockerrorsref->{$prefix} .= &mt('Please contact the domain coordinator for your LON-CAPA domain.').'</div>';
             }                  }
             $oldid = $path.$prefix.$ancestor;              }
         }          } elsif ($url =~ m{/syllabus$}) {
         my $counter = 0;              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
         my $newurl=$oldid.$newid.'.'.$ext;                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
         my $is_unique = &uniqueness_check($newurl);                  if (($dbref->{'cdom'} ne $coursedom) ||
         while (!$is_unique && $counter < 100) {                      ($dbref->{'cnum'} ne $coursenum)) {
             $counter ++;                      my %contents=&Apache::lonnet::dump('syllabus',
             $newid ++;                                                         $dbref->{'cdom'},
             $newurl = $oldid.$newid;                                                         $dbref->{'cnum'});
             $is_unique = &uniqueness_check($newurl);                      $result=&Apache::lonnet::put('syllabus',\%contents,
         }                                                   $coursedom,$coursenum);
         if (!$is_unique) {                  }
             if ($url=~/\.page$/) {              }
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');          }
             } else {      }
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');      return ($url,$result,$errtext);
             }  }
         }  
  my $storefn=$newurl;  sub uniqueness_check {
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};      my ($newurl) = @_;
  my $paste_map_result =      my $unique = 1;
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,      foreach my $res (@LONCAPA::map::order) {
        &Apache::lonnet::getfile($url));          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
         if ($paste_map_result eq '/adm/notfound.html') {          $url=&LONCAPA::map::qtescape($url);
             if ($url=~/\.page$/) {          if ($newurl eq $url) {
                 return &mt('Paste failed: an error occurred saving the composite page');              $unique = 0;
             } else {              last;
                 return &mt('Paste failed: an error occurred saving the folder');          }
             }      }
         }      return $unique;
  $url = $newurl;  }
     }  
 # published maps can only exists once, so remove it from paste buffer when done  sub contained_map_check {
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
  &Apache::lonnet::delenv('docs\\.markedcopy');          $allmaps) = @_;
     }      my $content = &Apache::lonnet::getfile($url);
     if ($url=~ m{/smppg$}) {      unless ($content eq '-1') {
  my $db_name = &Apache::lonsimplepage::get_db_name($url);          my $parser = HTML::TokeParser->new(\$content);
  if ($db_name =~ /^smppage_/) {          $parser->attr_encoded(1);
     #simple pages, need to copy the db contents to a new one.          while (my $token = $parser->get_token) {
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);              next if ($token->[0] ne 'S');
     my $now = time();              if ($token->[1] eq 'resource') {
     $db_name =~ s{_\d*$ }{_$now}x;                  next if ($token->[2]->{'type'} eq 'zombie');
     my $result=&Apache::lonnet::put($db_name,\%contents,                  my $ressrc = $token->[2]->{'src'};
     $coursedom,$coursenum);                  if ($folder =~ /^supplemental/) {
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;                      unless (&supp_pasteable($ressrc)) {
     $title=&mt('Copy of').' '.$title;                          $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
  }                          next;
     }                      }
     $title = &LONCAPA::map::qtunescape($title);                  }
     my $ext='false';                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
     if ($url=~m{^http(|s)://}) { $ext='true'; }                      if ($1 eq 'uploaded') {
     $url       = &LONCAPA::map::qtunescape($url);                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
 # Now insert the URL at the bottom                          $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
     my $newidx = &LONCAPA::map::getresidx($url);                      } else {
     if ($env{'docs.markedcopy_supplemental'}) {                          if ($allmaps->{$ressrc}) {
         if ($folder =~ /^supplemental/) {                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
             $title = $env{'docs.markedcopy_supplemental'};                          } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
         } else {                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
             (undef,undef,$title) =                          } else {
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});                              $addedmaps->{$ressrc} = [$url];
         }                          }
     } else {                      }
         if ($folder=~/^supplemental/) {                      &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                                           $addedmaps,$hierarchy,$titles,$allmaps);
                   $env{'user.domain'}.'___&&&___'.$title;                  }
         }              } elsif ($token->[1] eq 'param') {
     }                  if ($folder =~ /^supplemental/) {
                       if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';                          push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
     push(@LONCAPA::map::order, $newidx);                      } else {
     return 'ok';                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
 # Store the result                      }
 }                  }
               }
 sub uniqueness_check {          }
     my ($newurl) = @_;      }
     my $unique = 1;      return;
     foreach my $res (@LONCAPA::map::order) {  }
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);  
         $url=&LONCAPA::map::qtescape($url);  sub url_paste_fixups {
         if ($newurl eq $url) {      my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
             $unique = 0;          $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
             last;              $mapchanges,$tomove,$newsubdir,$newurls) = @_;
         }      my $checktitle;
     }      if (($prefixchg) &&
     return $unique;          ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
 }          $checktitle = 1;
       }
 my %parameter_type = ( 'randompick'     => 'int_pos',      my $skip;
        'hiddenresource' => 'string_yesno',      if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
        'encrypturl'     => 'string_yesno',          my $mapid = $1.$2;
        'randomorder'    => 'string_yesno',);          if ($tomove->{$mapid}) {
 my $valid_parameters_re = join('|',keys(%parameter_type));              $skip = 1;
 # set parameters          }
 sub update_parameter {      }
       my $file = &Apache::lonnet::getfile($oldurl);
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);      return if ($file eq '-1');
       my $parser = HTML::TokeParser->new(\$file);
     my $which = $env{'form.changeparms'};      $parser->attr_encoded(1);
     my $idx = $env{'form.setparms'};      my $changed = 0;
     if ($env{'form.'.$which.'_'.$idx}) {      while (my $token = $parser->get_token) {
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}          next if ($token->[0] ne 'S');
                                      : 'yes';          if ($token->[1] eq 'resource') {
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,              my $ressrc = $token->[2]->{'src'};
       $parameter_type{$which});              next if ($ressrc eq '');
  &remember_parms($idx,$which,'set',$value);              my $id = $token->[2]->{'id'};
     } else {              my $title = $token->[2]->{'title'};
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);              if ($checktitle) {
                   if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
  &remember_parms($idx,$which,'del');                      $retitles->{$oldurl}{$id} = $ressrc;
     }                  }
     return 1;              }
 }              next if ($token->[2]->{'type'} eq 'external');
               if ($token->[2]->{'type'} eq 'zombie') {
                   next if ($skip);  
 sub handle_edit_cmd {                  $zombies->{$oldurl}{$id} = $ressrc;
     my ($coursenum,$coursedom) =@_;                  $changed = 1;
               } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
     my ($cmd,$idx)=split('_',$env{'form.cmd'});                  my $srcdom = $1;
                   my $srcnum = $2;
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];                  my $rem = $3;
     my ($title, $url, @rrest) = split(':', $ratstr);                  my $newurl;
                   my $mapname;
     if ($cmd eq 'del') {                  if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&                      my $prefix = $1;
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {                      $mapname = $prefix.$2;
     &Apache::lonnet::removeuploadedurl($url);                      if ($tomove->{$mapname}) {
  } else {                          &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                                            $srcdom,$srcnum,$allmaps,$rewrites,
  }                                            $retitles,$copies,$dbcopies,$zombies,
  splice(@LONCAPA::map::order, $idx, 1);                                            $params,$mapmoves,$mapchanges,$tomove,
                                             $newsubdir,$newurls);
     } elsif ($cmd eq 'cut') {                          next;
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                      } else {
  splice(@LONCAPA::map::order, $idx, 1);                          ($newurl,my $error) =
                               &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
     } elsif ($cmd eq 'up'                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {                          if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];                              $newsubdir->{$ressrc} = $1;
                           }
     } elsif ($cmd eq 'down'                          if ($error) {
      && defined($LONCAPA::map::order[$idx+1])) {                              next;
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];                          }
                       }
     } elsif ($cmd eq 'rename') {                  }
                   if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
  if ($comment=~/\S/) {                     
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
  $comment.':'.join(':', $url, @rrest);                          $rewrites->{$oldurl}{$id} = $ressrc;
  }                          $mapchanges->{$ressrc} = 1;
 # Devalidate title cache                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
  my $renamed_url=&LONCAPA::map::qtescape($url);                                                    $cnum,$srcdom,$srcnum,$allmaps,
  &Apache::lonnet::devalidate_title_cache($renamed_url);                                                    $rewrites,$retitles,$copies,$dbcopies,
     } else {                                                    $zombies,$params,$mapmoves,$mapchanges,
  return 0;                                                    $tomove,$newsubdir,$newurls)) {
     }                              $mapmoves->{$ressrc} = 1;
     return 1;                          }
 }                          $changed = 1;
                       } else {
 sub editor {                          $rewrites->{$oldurl}{$id} = $ressrc;
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;                          $copies->{$oldurl}{$ressrc} = $id;
                           $changed = 1;
     my $container= ($env{'form.pagepath'}) ? 'page'                      }
                            : 'sequence';                  }
               } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,                  next if ($skip);  
     $folder.'.'.$container);                  my $srcdom = $1;
     return $errtext if ($fatal);                  my $srcnum = $2;
                   if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
     if ($#LONCAPA::map::order<1) {                      $rewrites->{$oldurl}{$id} = $ressrc;
  my $idx=&LONCAPA::map::getresidx();                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
  if ($idx<=0) { $idx=1; }                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
         $LONCAPA::map::order[0]=$idx;                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
         $LONCAPA::map::resources[$idx]='';                      $changed = 1;
     }                  }
                  } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=                  if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
  &breadcrumbs($folder,$allowed,$type);                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
     $r->print($breadcrumbtrail);                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
                          $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
 # ------------------------------------------------------------ Process commands                      $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
                       $changed = 1;
 # ---------------- if they are for this folder and user allowed to make changes                  }
     if (($allowed) && ($env{'form.folder'} eq $folder)) {              } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
 # set parameters and change order                  next if ($skip);
  &snapshotbefore();                  my $srcdom = $1;
                   my $srcnum = $2;
  if (&update_parameter()) {                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
     return $errtext if ($fatal);                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
  }                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
                       $changed = 1;
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {                  }
 # change order              }
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);          } elsif ($token->[1] eq 'param') {
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);              next if ($skip);
               my $to = $token->[2]->{'to'}; 
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);              if ($to ne '') {
     return $errtext if ($fatal);                  if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
  }                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
                       } else {
  if ($env{'form.pastemarked'}) {                      @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
             my $paste_res =                  }
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);              }
             if ($paste_res eq 'ok') {          }
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);      }
                 return $errtext if ($fatal);      return $changed;
             } elsif ($paste_res ne '') {  }
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');  
             }  sub apply_fixups {
  }      my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
           $oldurl,$url,$caller) = @_;
  $r->print($upload_output);      my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
           %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
  if (&handle_edit_cmd()) {          %lockerrors,$lockmsg);
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      if (ref($updated) eq 'HASH') {
     return $errtext if ($fatal);          if (ref($updated->{'rewrites'}) eq 'HASH') {
  }              %rewrites = %{$updated->{'rewrites'}};
 # Group import/search          }
  if ($env{'form.importdetail'}) {          if (ref($updated->{'zombies'}) eq 'HASH') {
     my @imports;              %zombies = %{$updated->{'zombies'}};
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {          }
  if (defined($item)) {          if (ref($updated->{'removefrommap'}) eq 'HASH') {
     my ($name,$url,$residx)=              %removefrommap = %{$updated->{'removefrommap'}};
  map {&unescape($_)} split(/\=/,$item);          }
     push(@imports, [$name, $url, $residx]);          if (ref($updated->{'removeparam'}) eq 'HASH') {
  }              %removeparam = %{$updated->{'removeparam'}};
     }          }
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,          if (ref($updated->{'dbcopies'}) eq 'HASH') {
     $container,'londocs',@imports);              %dbcopies = %{$updated->{'dbcopies'}};
     return $errtext if ($fatal);          }
  }          if (ref($updated->{'retitles'}) eq 'HASH') {
 # Loading a complete map              %retitles = %{$updated->{'retitles'}};
  if ($env{'form.loadmap'}) {          }
     if ($env{'form.importmap'}=~/\w/) {      }
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {      if (ref($info) eq 'HASH') {
     my ($title,$url,$ext,$type)=split(/\:/,$res);          if (ref($info->{'newsubdir'}) eq 'HASH') {
     my $idx=&LONCAPA::map::getresidx($url);              %newsubdir = %{$info->{'newsubdir'}};
     $LONCAPA::map::resources[$idx]=$res;          }
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;          if (ref($info->{'params'}) eq 'HASH') {
  }              %params = %{$info->{'params'}};
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,          }
     $folder.'.'.$container);          if (ref($info->{'before'}) eq 'HASH') {
  return $errtext if ($fatal);              %before = %{$info->{'before'}};
     } else {          }
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');          if (ref($info->{'after'}) eq 'HASH') {
               %after = %{$info->{'after'}};
     }          }
  }      }
  &log_differences($plain);      if (ref($moves) eq 'HASH') {
     }          if (ref($moves->{'copies'}) eq 'HASH') {
 # ---------------------------------------------------------------- End commands              %copies = %{$moves->{'copies'}};
 # ---------------------------------------------------------------- Print screen          }
     my $idx=0;          if (ref($moves->{'docmoves'}) eq 'HASH') {
     my $shown=0;              %docmoves = %{$moves->{'docmoves'}};
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {          }
  $r->print('<p>'.&mt('Parameters').':<ul>'.          if (ref($moves->{'mapmoves'}) eq 'HASH') {
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').              %mapmoves = %{$moves->{'mapmoves'}};
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').          }
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').      }
   '</ul></p>');      foreach my $key (keys(%copies),keys(%docmoves)) {
     }                                                                                                              my @allcopies;
     if ($randompick>=0) {          if (exists($copies{$key})) {
  $r->print('<p>'.&mt('Caution: this folder is set to randomly pick a subset of resources. Adding or removing resources from this folder will change the set of resources that the students see, resulting in spurious or missing credit for completed problems, not limited to ones you modify. Do not modify the contents of this folder if it is in active student use.').'</p>');              if (ref($copies{$key}) eq 'HASH') {
     }                  my %added;
     if ($is_random_order) {                  foreach my $innerkey (keys(%{$copies{$key}})) {
  $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');                      if (($innerkey ne '') && (!$added{$innerkey})) {
     }                          push(@allcopies,$innerkey);
     $r->print('<table class="LC_docs_editor">');                          $added{$innerkey} = 1;
     foreach my $res (@LONCAPA::map::order) {                      }
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                  }
  $name=&LONCAPA::map::qtescape($name);                  undef(%added);
  $url=&LONCAPA::map::qtescape($url);              }
  unless ($name) {  $name=(split(/\//,$url))[-1]; }          }
  unless ($name) { $idx++; next; }          if ($key eq $oldurl) {
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,              if ((exists($docmoves{$key}))) {
      $coursenum));                  unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
  $idx++;                      push(@allcopies,$oldurl);
  $shown++;                  }
     }              }
     unless ($shown) {          }
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');          if (@allcopies > 0) {
     }              foreach my $item (@allcopies) {
     $r->print("\n</table>\n");                  my ($relpath,$oldsubdir,$fname) = 
     if ($allowed) {                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
         &print_paste_buffer($r,$container);                  if ($fname ne '') {
     }                      my $content = &Apache::lonnet::getfile($item);
     return;                      unless ($content eq '-1') {
 }                          my $storefn;
                           if (($key eq $oldurl) && (exists($docmoves{$key}))) {
 sub process_file_upload {                              $storefn = $docmoves{$key};
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;                          } else {
 # upload a file, if present                              $storefn = $relpath;
     my $parseaction;                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
    if ($env{'form.parserflag'}) {                              if ($prefixchg && $before{'doc'} && $after{'doc'}) {
         $parseaction = 'parse';                                  $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
     }                              }
     my $phase_status;                              if ($newsubdir{$key}) {
     my $folder=$env{'form.folder'};                                  $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
     if ($folder eq '') {                              }
         $folder='default';                          }
     }                          &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {                          my $copyurl = 
         my $errtext='';                              &Apache::lonclonecourse::writefile($env{'request.course.id'},
         my $fatal=0;                                                                 $storefn.$fname,$content);
         my $container='sequence';                          if ($copyurl eq '/adm/notfound.html') {
         if ($env{'form.pagepath'}) {                              if (exists($docmoves{$oldurl})) {
             $container='page';                                  return &mt('Paste failed: an error occurred copying the file.');
         }                              } elsif (ref($errors) eq 'HASH') {
         ($errtext,$fatal)=                                  $errors->{$item} = 1;
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                              }
         if ($#LONCAPA::map::order<1) {                          }
             $LONCAPA::map::order[0]=1;                      }
             $LONCAPA::map::resources[1]='';                  }
         }              }
         if ($fatal) {          }
             return 'failed';      }
         }      foreach my $key (keys(%mapmoves)) {
         my $destination = 'docs/';          my $storefn=$key;
         if ($folder =~ /^supplemental/) {          $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
             $destination = 'supplemental/';          if ($prefixchg && $before{'map'} && $after{'map'}) {
         }              $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
         if (($folder eq 'default') || ($folder eq 'supplemental')) {          }
             $destination .= 'default/';          if ($newsubdir{$key}) {
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
             $destination .=  $2.'/';          }
         }          my $mapcontent = &Apache::lonnet::getfile($key);
 # this is for a course, not a user, so set coursedoc flag          if ($mapcontent eq '-1') {
 # probably the only place in the system where this should be "1"              if (ref($errors) eq 'HASH') {
         my $newidx=&LONCAPA::map::getresidx();                  $errors->{$key} = 1;
         $destination .= $newidx;              }
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,          } else {
  $parseaction,$allfiles,              my $newmap =
  $codebase);                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
         my $ext='false';                                                     $mapcontent);
         if ($url=~m{^http://}) { $ext='true'; }              if ($newmap eq '/adm/notfound.html') {
  $url     = &LONCAPA::map::qtunescape($url);                  if (ref($errors) eq 'HASH') {
         my $comment=$env{'form.comment'};                      $errors->{$key} = 1;
  $comment = &LONCAPA::map::qtunescape($comment);                  }
         if ($folder=~/^supplemental/) {              }
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.          }
                   $env{'user.domain'}.'___&&&___'.$comment;      }
         }      my %updates;
       if ($is_map) {
         $LONCAPA::map::resources[$newidx]=          if (ref($updated) eq 'HASH') {
     $comment.':'.$url.':'.$ext.':normal:res';              foreach my $type (keys(%{$updated})) {
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;                  if (ref($updated->{$type}) eq 'HASH') {
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,                      foreach my $key (keys(%{$updated->{$type}})) {
     $folder.'.'.$container);                          $updates{$key} = 1;
         if ($fatal) {                      }
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';                  }
             return 'failed';              }
         } else {          }
             if ($parseaction eq 'parse') {          foreach my $key (keys(%updates)) {
                 my $total_embedded = keys(%{$allfiles});              my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
                 if ($total_embedded > 0) {              if (ref($rewrites{$key}) eq 'HASH') {
                     my $num = 0;                  %torewrite = %{$rewrites{$key}};
     my $state = '              }
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />              if (ref($retitles{$key}) eq 'HASH') {
    <input type="hidden" name="cmd" value="upload_embedded" />                  %toretitle = %{$retitles{$key}};
    <input type="hidden" name="newidx" value="'.$newidx.'" />              }
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />              if (ref($removefrommap{$key}) eq 'HASH') {
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';                  %toremove = %{$removefrommap{$key}};
     $phase_status = 'phasetwo';              }
               if (ref($removeparam{$key}) eq 'HASH') {
                     $$upload_output .=                  %remparam = %{$removeparam{$key}};
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.              }
  &Apache::loncommon::ask_for_embedded_content(              if (ref($zombies{$key}) eq 'HASH') {
                             '/adm/coursedocs',$state,$allfiles,$codebase);                  %zombie = %{$zombies{$key}};
                 } else {              }
                     $$upload_output .= 'No embedded items identified<br />';              if (ref($dbcopies{$key}) eq 'HASH') {
                 }                  foreach my $idx (keys(%{$dbcopies{$key}})) {
             }                      if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
         }                          my ($newurl,$result,$errtext) =
     }                              &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
     return $phase_status;                          if ($result eq 'ok') {
 }                              $newdb{$idx} = $newurl;
                           } elsif (ref($errors) eq 'HASH') {
 sub process_secondary_uploads {                              $errors->{$key} = 1;
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;                          }
     my $folder=$env{'form.folder'};                          push(@msgs,$errtext);
     my $destination = 'docs/';                      }
     if ($folder =~ /^supplemental/) {                  }
         $destination = 'supplemental/';              }
     }              if (ref($params{$key}) eq 'HASH') {
     if (($folder eq 'default') || ($folder eq 'supplemental')) {                  %currparam = %{$params{$key}};
         $destination .= 'default/';              }
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {              my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
         $destination .=  $2.'/';              if ($fatal) {
     }                  return ($errtext);
     $destination .= $newidx;              }
     my ($url,$filename);              for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);                  if (defined($LONCAPA::map::zombies[$i])) {
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
     return $filename;                      if ($zombie{$i} eq $src) {
 }                          undef($LONCAPA::map::zombies[$i]);
                       }
 sub is_supplemental_title {                  }
     my ($title) = @_;              }
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);              for (my $i=0; $i<@LONCAPA::map::order; $i++) {
 }                  my $idx = $LONCAPA::map::order[$i];
                   if (defined($LONCAPA::map::resources[$idx])) {
 sub parse_supplemental_title {                      my $changed;
     my ($title) = @_;                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
                       if ((exists($toremove{$idx})) && ($toremove{$idx} eq $src)) {
     my ($foldertitle,$renametitle);                          splice(@LONCAPA::map::order,$i,1);
     if ($title =~ /&amp;&amp;&amp;/) {                          if (ref($currparam{$idx}) eq 'ARRAY') {
  $title = &HTML::Entites::decode($title);                              foreach my $name (@{$currparam{$idx}}) {
     }                                  &LONCAPA::map::delparameter($idx,'parameter_'.$name);
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {                              }
  $renametitle=$4;                          }
  my ($time,$uname,$udom) = ($1,$2,$3);                          next;
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);                      }
  my $name =  &Apache::loncommon::plainname($uname,$udom);                      my $origsrc = $src;
  $name = &HTML::Entities::encode($name,'"<>&\'');                      if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.                          if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
     $name.': <br />'.$foldertitle;                              $changed = 1;
     }                          }
     if (wantarray) {                      }
  return ($title,$foldertitle,$renametitle);                      if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
     }                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
     return $title;                          if ($origsrc =~ m{^/uploaded/}) {
 }                              if ($prefixchg && $before{'map'} && $after{'map'}) {
                                   if ($src =~ /\.(page|sequence)$/) {
 # --------------------------------------------------------------- An entry line                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
                                   } else {
 sub entryline {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;                                  }
                               }
     my ($foldertitle,$pagetitle,$renametitle);                              if ($origsrc =~ /\.(page|sequence)$/) {
     if (&is_supplemental_title($title)) {                                  if ($newsubdir{$origsrc}) {
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
  $pagetitle = $foldertitle;                                  }
     } else {                              } elsif ($newsubdir{$key}) {
  $title=&HTML::Entities::encode($title,'"<>&\'');                                  $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
  $renametitle=$title;                              }
  $foldertitle=$title;                          }
  $pagetitle=$title;                          $changed = 1;
     }                      } elsif ($newdb{$idx} ne '') {
                           $src = $newdb{$idx};
     my $orderidx=$LONCAPA::map::order[$index];                          $changed = 1;
                          }
                       if ($changed) {
     $renametitle=~s/\\/\\\\/g;                          $LONCAPA::map::resources[$idx] = join(':',($title,$src,$ext,$type));
     $renametitle=~s/\&quot\;/\\\"/g;                      }
     $renametitle=~s/ /%20/g;                  }
     my $line='<tr>';              }
     my ($form_start,$form_end);              foreach my $idx (keys(%remparam)) {
 # Edit commands                  if (ref($remparam{$idx}) eq 'ARRAY') {
     my ($container, $type, $esc_path, $path, $symb);                      foreach my $name (@{$remparam{$idx}}) {   
     if ($env{'form.folderpath'}) {                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
  $type = 'folder';                      }
         $container = 'sequence';                  }
  $esc_path=&escape($env{'form.folderpath'});              }
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');              if (values(%lockerrors) > 0) {
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');                  $lockmsg = join('<br />',values(%lockerrors));
     }              }
     if ($env{'form.pagepath'}) {              my $storefn;
         $type = $container = 'page';              if ($key eq $oldurl) {
         $esc_path=&escape($path = $env{'form.pagepath'});                  $storefn = $url;
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
         $symb=&escape($env{'form.pagesymb'});              } else {
     }                  $storefn = $key;
     my $cpinfo='';                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     if ($allowed) {                  if ($prefixchg && $before{'map'} && $after{'map'}) {
  my $incindex=$index+1;                      $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
  my $selectbox='';                  }
  if (($folder!~/^supplemental/) &&                  if ($newsubdir{$key}) {
     ($#LONCAPA::map::order>0) &&                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
     ((split(/\:/,                  }
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]              }
      ne '') &&              my $report;
     ((split(/\:/,              if ($folder !~ /^supplemental/) {
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]                  $report = 1;
      ne '')) {              }
     $selectbox=              (my $outtext,$errtext) =
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
  '<select name="newpos" onChange="this.form.submit()">';              if ($errtext) {
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {                  if ($caller eq 'paste') {
  if ($i==$incindex) {                      return (&mt('Paste failed: an error occurred saving the folder or page.'));
     $selectbox.='<option value="" selected="1">('.$i.')</option>';                  }
  } else {              }
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';          }
  }      }
     }      return ('ok',\@msgs,$lockmsg);
     $selectbox.='</select>';  }
  }  
  my %lt=&Apache::lonlocal::texthash(  sub copy_dependencies {
                 'up' => 'Move Up',      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
  'dw' => 'Move Down',      my $content;
  'rm' => 'Remove',      if (ref($contentref)) {
                 'ct' => 'Cut',          $content = $$contentref;
  'rn' => 'Rename',      } else {
  'cp' => 'Copy');          $content = &Apache::lonnet::getfile($item);
  my $nocopy=0;      }
         my $nocut=0;      unless ($content eq '-1') {
         if ($url=~/\.(page|sequence)$/) {          my $mm = new File::MMagic;
     if ($url =~ m{/res/}) {          my $mimetype = $mm->checktype_contents($content);
  # no copy for published maps          if ($mimetype eq 'text/html') {
  $nocopy = 1;              my (%allfiles,%codebase,$state);
     } else {              my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {              if ($res eq 'ok') {
     my ($title,$url,$ext,$type)=split(/\:/,$item);                  my ($numexisting,$numpathchanges,$existing);
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {                  (undef,$numexisting,$numpathchanges,$existing) =
  $nocopy=1;                      &Apache::loncommon::ask_for_embedded_content(
  last;                          '/adm/coursedocs',$state,\%allfiles,\%codebase,
     }                          {'error_on_invalid_names'   => 1,
  }                           'ignore_remote_references' => 1,
     }                           'docs_url'                 => $item,
  }                           'context'                  => 'paste'});
         if ($url=~/^\/res\/lib\/templates\//) {                  if ($numexisting > 0) {
            $nocopy=1;                      if (ref($existing) eq 'HASH') {
            $nocut=1;                          foreach my $dep (keys(%{$existing})) {
         }                              my $depfile = $dep;
         my $copylink='&nbsp;';                              unless ($depfile =~ m{^\Q$relpath\E}) {
         my $cutlink='&nbsp;';                                  $depfile = $relpath.$dep;
                               }
  my $skip_confirm = 0;                              my $depcontent = &Apache::lonnet::getfile($depfile);
  if ( $folder =~ /^supplemental/                              unless ($depcontent eq '-1') {
      || ($url =~ m{( /smppg$                                  my $storedep = $dep;
     |/syllabus$                                  $storedep =~ s{^\Q$relpath\E}{};
     |/aboutme$                                  my $dep_url =
     |/navmaps$                                      &Apache::lonclonecourse::writefile(
     |/bulletinboard$                                          $env{'request.course.id'},
     |\.html$                                          $storefn.$storedep,$depcontent);
     |^/adm/wrapper/ext)}x)) {                                  if ($dep_url eq '/adm/notfound.html') {
     $skip_confirm = 1;                                      if (ref($errors) eq 'HASH') {
  }                                          $errors->{$depfile} = 1;
                                       }
  if (!$nocopy) {                                  } else {
     $copylink=(<<ENDCOPY);                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>                                  }
 ENDCOPY                              }
         }                          }
  if (!$nocut) {                      }
     $cutlink=(<<ENDCUT);                  }
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>              }
 ENDCUT          }
         }      }
  $form_start = (<<END);      return;
    <form  action="/adm/coursedocs" method="post">  }
    <input type="hidden" name="${type}path" value="$path" />  
    <input type="hidden" name="${type}symb" value="$symb" />  my %parameter_type = ( 'randompick'     => 'int_pos',
    <input type="hidden" name="setparms" value="$orderidx" />         'hiddenresource' => 'string_yesno',
    <input type="hidden" name="changeparms" value="0" />         'encrypturl'     => 'string_yesno',
 END         'randomorder'    => 'string_yesno',);
         $form_end = '</form>';  my $valid_parameters_re = join('|',keys(%parameter_type));
  $line.=(<<END);  # set parameters
 <td>  sub update_parameter {
    <table class="LC_docs_entry_move">  
       <tr>      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
          <td>  
             <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" /></a>      my $which = $env{'form.changeparms'};
          </td>      my $idx = $env{'form.setparms'};
       </tr>      if ($env{'form.'.$which.'_'.$idx}) {
       <tr>   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
         <td>                                       : 'yes';
            <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" /></a>   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
         </td>        $parameter_type{$which});
       </tr>   &remember_parms($idx,$which,'set',$value);
     </table>      } else {
 </td>   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
 <td>  
    $form_start   &remember_parms($idx,$which,'del');
    $selectbox      }
    $form_end      return 1;
 </td>  }
 <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>  
 $cutlink  sub handle_edit_cmd {
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>      my ($coursenum,$coursedom) =@_;
 $copylink      my ($cmd,$idx)=split('_',$env{'form.cmd'});
 </td>  
 END      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
       my ($title, $url, @rrest) = split(':', $ratstr);
     }  
 # Figure out what kind of a resource this is      if ($cmd eq 'del') {
     my ($extension)=($url=~/\.(\w+)$/);   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
     my $uploaded=($url=~/^\/*uploaded\//);      ($url!~/$LONCAPA::assess_page_seq_re/)) {
     my $icon=&Apache::loncommon::icon($url);      &Apache::lonnet::removeuploadedurl($url);
     my $isfolder=0;   } else {
     my $ispage=0;      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     my $folderarg;   }
     my $pagearg;   splice(@LONCAPA::map::order, $idx, 1);
     my $pagefile;  
     if ($uploaded) {      } elsif ($cmd eq 'cut') {
  if ($extension eq 'sequence') {   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     $icon=$iconpath.'/folder_closed.gif';   splice(@LONCAPA::map::order, $idx, 1);
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;  
     $url='/adm/coursedocs?';      } elsif ($cmd eq 'up'
     $folderarg=$1;       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     $isfolder=1;   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
         } elsif ($extension eq 'page') {  
             $icon=$iconpath.'/page.gif';      } elsif ($cmd eq 'down'
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;       && defined($LONCAPA::map::order[$idx+1])) {
             $pagearg=$1;   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
             $url='/adm/coursedocs?';  
             $ispage=1;      } elsif ($cmd eq 'rename') {
  } else {  
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
  }   if ($comment=~/\S/) {
     }      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
       $comment.':'.join(':', $url, @rrest);
     my $orig_url = $url;   }
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});  # Devalidate title cache
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {   my $renamed_url=&LONCAPA::map::qtescape($url);
  my $symb=&Apache::lonnet::symbclean(   &Apache::lonnet::devalidate_title_cache($renamed_url);
           &Apache::lonnet::declutter('uploaded/'.      } else {
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.   return 0;
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.      }
            '.sequence').      return 1;
            '___'.$residx.'___'.  }
    &Apache::lonnet::declutter($url));  
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);  sub editor {
  $url=&Apache::lonnet::clutter($url);      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
  if ($url=~/^\/*uploaded\//) {          $supplementalflag,$orderhash,$iconpath,$pathitem)=@_;
     $url=~/\.(\w+)$/;      my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
     my $embstyle=&Apache::loncommon::fileembstyle($1);      if ($allowed) {
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {          (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
  $url='/adm/wrapper'.$url;           $is_random_order,$container) =
     } elsif ($embstyle eq 'ssi') {              &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
  #do nothing with these          $r->print($breadcrumbtrail);
     } elsif ($url!~/\.(sequence|page)$/) {      } elsif ($env{'form.folderpath'} =~ /\:1$/) {
  $url='/adm/coursedocs/showdoc'.$url;          $container = 'page'; 
     }      } else {
  } elsif ($url=~m|^/ext/|) {          $container = 'sequence';
     $url='/adm/wrapper'.$url;      }
     $external = 1;  
  }      my $jumpto;
         if (&Apache::lonnet::symbverify($symb,$url)) {  
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);      unless ($supplementalflag) {
         } else {          $jumpto = "'uploaded/$coursedom/$coursenum/$folder.$container'";
             $url='';      }
         }  
  if ($container eq 'page') {      unless ($allowed) {
     my $symb=$env{'form.pagesymb'};          $randompick = -1;
               }
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);  
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  }      $folder.'.'.$container);
     }      return $errtext if ($fatal);
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');  
     if ($isfolder || $extension eq 'sequence') {      if ($#LONCAPA::map::order<1) {
  my $foldername=&escape($foldertitle);   my $idx=&LONCAPA::map::getresidx();
  my $folderpath=$env{'form.folderpath'};   if ($idx<=0) { $idx=1; }
  if ($folderpath) { $folderpath.='&' };          $LONCAPA::map::order[0]=$idx;
 # Append randompick number, hidden, and encrypted with ":" to foldername,          $LONCAPA::map::resources[$idx]='';
 # so it gets transferred between levels      }
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,  
                                               'parameter_randompick'))[0]  # ------------------------------------------------------------ Process commands
                                                .':'.((&LONCAPA::map::getparameter($orderidx,  
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)  # ---------------- if they are for this folder and user allowed to make changes
                                                .':'.((&LONCAPA::map::getparameter($orderidx,      if (($allowed) && ($env{'form.folder'} eq $folder)) {
                                               'parameter_encrypturl'))[0]=~/^yes$/i)  # set parameters and change order
                                                .':'.((&LONCAPA::map::getparameter($orderidx,   &snapshotbefore();
                                               'parameter_randomorder'))[0]=~/^yes$/i);  
  $url.='folderpath='.&escape($folderpath).$cpinfo;   if (&update_parameter()) {
  $parameterset='<label>'.&mt('Randomly Pick: ').      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.      return $errtext if ($fatal);
     (&LONCAPA::map::getparameter($orderidx,   }
                                               'parameter_randompick'))[0].  
                                               '" />'.   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';  # change order
     my $ro_set=      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
  $rand_order_text ='  
 <span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" onClick="this.form.changeparms.value=\'randomorder\';this.form.submit()" '.$ro_set.' /> '.&mt('Random Order').' </label></span>';        ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     }      return $errtext if ($fatal);
     if ($ispage) {   }
         my $pagename=&escape($pagetitle);  
         my $pagepath;   if ($env{'form.pastemarked'}) {
         my $folderpath=$env{'form.folderpath'};              my %paste_errors;
         if ($folderpath) { $pagepath = $folderpath.'&' };              my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
         $pagepath.=$pagearg.'&'.$pagename;                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
  my $symb=$env{'form.pagesymb'};                                        \%paste_errors);
  if (!$symb) {                  if (ref($pastemsgarray) eq 'ARRAY') {
     my $path='uploaded/'.                      if (@{$pastemsgarray} > 0) {
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.  
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';                          $r->print('<p class="LC_info">'.
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',                                    join('<br />',@{$pastemsgarray}).
        $residx,                                    '</p>');
        $path.$pagearg.'.page');                      }
  }                  }
  $url.='pagepath='.&escape($pagepath).                  if ($lockerror) {
     '&amp;pagesymb='.&escape($symb).$cpinfo;                      $r->print('<p class="LC_error">'.
     }                                $lockerror.
     if ($external) {                                '</p>');
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';                  }
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';                  if ($save_error ne '') {
     } else {                      return $save_error; 
  undef($external);                  }
     }              if ($paste_res ne 'ok') {
     $line.='                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
   <td class="LC_docs_entry_icon">              }
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'              if (keys(%paste_errors) > 0) {
   </td>                  $r->print('<p span class="LC_warning">'."\n".
   <td class="LC_docs_entry_title">                            &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".
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."                            '<ul>'."\n");
   </td>";                  foreach my $key (sort(keys(%paste_errors))) {
     if (($allowed) && ($folder!~/^supplemental/)) {                      $r->print('<li>'.$key.'</li>'."\n");
   my %lt=&Apache::lonlocal::texthash(                  }
        'hd' => 'Hidden',                  $r->print('</ul></p>'."\n");
        'ec' => 'URL hidden');              }
  my $enctext=   }
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');  
  my $hidtext=   $r->print($upload_output);
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');  
  $line.=(<<ENDPARMS);   if (&handle_edit_cmd()) {
   <td class="LC_docs_entry_parameter">              my $contentchg;
     $form_start              if ($env{'form.cmd'} =~ /^(del|cut)_/) {
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>                  $contentchg = 1;
     $form_end              }
   </td>      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
   <td class="LC_docs_entry_parameter">      return $errtext if ($fatal);
     $form_start   }
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>  # Group import/search
     $form_end   if ($env{'form.importdetail'}) {
   </td>      my @imports;
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>   if (defined($item)) {
 ENDPARMS      my ($name,$url,$residx)=
     }   map { &unescape($_); } split(/\=/,$item);
     $line.="</tr>";                      if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
     return $line;                          my ($suffix,$errortxt,$locknotfreed) = 
 }                              &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
                           if ($locknotfreed) {
 =pod                              $r->print($locknotfreed);
                           }
 =item tiehash()                          if ($suffix) {
                               $url =~ s/_new\./_$suffix./; 
 tie the hash                          } else {
                               return $errortxt;
 =cut                          }
                       } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
 sub tiehash {                          my $type = $1;
     my ($mode)=@_;                          my ($suffix,$errortxt,$locknotfreed) =
     $hashtied=0;                              &new_timebased_suffix($coursedom,$coursenum,$type);
     if ($env{'request.course.fn'}) {                          if ($locknotfreed) {
  if ($mode eq 'write') {                              $r->print($locknotfreed);
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                          }
     &GDBM_WRCREAT(),0640)) {                          if ($suffix) {
                 $hashtied=2;                              $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
     }                          } else {
  } else {                              return $errortxt;
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                          }
     &GDBM_READER(),0640)) {                      }
                 $hashtied=1;      push(@imports, [$name, $url, $residx]);
     }   }
  }      }
     }                  ($errtext,$fatal,my $fixuperrors) =
 }                  &group_import($coursenum, $coursedom, $folder,$container,
                                 'londocs',@imports);
 sub untiehash {      return $errtext if ($fatal);
     if ($hashtied) { untie %hash; }              if ($fixuperrors) {
     $hashtied=0;                  $r->print($fixuperrors);
     return OK;              }
 }   }
   # 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'}))) {
 sub checkonthis {      my ($title,$url,$ext,$type)=split(/\:/,$res);
     my ($r,$url,$level,$title)=@_;      my $idx=&LONCAPA::map::getresidx($url);
     $url=&unescape($url);      $LONCAPA::map::resources[$idx]=$res;
     $alreadyseen{$url}=1;      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
     $r->rflush();   }
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
        $r->print("\n<br />");      $folder.'.'.$container,1);
        if ($level==0) {   return $errtext if ($fatal);
            $r->print("<br />");      } else {
        }   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
        for (my $i=0;$i<=$level*5;$i++) {  
            $r->print('&nbsp;');      }
        }   }
        $r->print('<a href="'.$url.'" target="cat">'.   &log_differences($plain);
  ($title?$title:$url).'</a> ');      }
        if ($url=~/^\/res\//) {  # ---------------------------------------------------------------- End commands
   my $result=&Apache::lonnet::repcopy(  # ---------------------------------------------------------------- Print screen
                               &Apache::lonnet::filelocation('',$url));      my $idx=0;
           if ($result eq 'ok') {      my $shown=0;
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
              $r->rflush();   $r->print('<div class="LC_Box">'.
              &Apache::lonnet::countacc($url);            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
              $url=~/\.(\w+)$/;    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
  $r->print('<br />');    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
                  $r->rflush();    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
                  for (my $i=0;$i<=$level*5;$i++) {    '</ol>');
                      $r->print('&nbsp;');          if ($randompick>=0) {
                  }              $r->print('<p class="LC_warning">'
                  $r->print('- '.&mt('Rendering:').' ');                   .&mt('Caution: this folder is set to randomly pick a subset'
  my ($errorcount,$warningcount)=split(/:/,                       .' of resources. Adding or removing resources from this'
        &Apache::lonnet::ssi_body($url,                       .' folder will change the set of resources that the'
        ('grade_target'=>'web',                       .' students see, resulting in spurious or missing credit'
  'return_only_error_and_warning_counts' => 1)));                       .' for completed problems, not limited to ones you'
                  if (($errorcount) ||                       .' modify. Do not modify the contents of this folder if'
                      ($warningcount)) {                       .' it is in active student use.')
      if ($errorcount) {                   .'</p>'
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.              );
                           &mt('[quant,_1,error]',$errorcount).'</span>');          }
                      }          if ($is_random_order) {
      if ($warningcount) {              $r->print('<p class="LC_warning">'
                         $r->print('<span class="LC_warning">'.                   .&mt('Caution: this folder is set to randomly order its'
                           &mt('[quant,_1,warning]',$warningcount).'</span>');                       .' contents. Adding or removing resources from this folder'
                      }                       .' will change the order of resources shown.')
                  } else {                   .'</p>'
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');              );
                  }          }
                  $r->rflush();          $r->print('</div>');
              }      }
      my $dependencies=  
                 &Apache::lonnet::metadata($url,'dependencies');      my ($to_show,$output);
              foreach my $dep (split(/\,/,$dependencies)) {  
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {      &Apache::loncommon::start_data_table_count(); #setup a row counter 
                     &checkonthis($r,$dep,$level+1);      foreach my $res (@LONCAPA::map::order) {
                  }          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
              }          $name=&LONCAPA::map::qtescape($name);
           } elsif ($result eq 'unavailable') {          $url=&LONCAPA::map::qtescape($url);
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');          unless ($name) {  $name=(split(/\//,$url))[-1]; }
           } elsif ($result eq 'not_found') {          unless ($name) { $idx++; next; }
       unless ($url=~/\$/) {          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');                                $coursenum,$coursedom,$crstype,
       } else {                                $pathitem,$supplementalflag,$container);
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');          $idx++;
       }          $shown++;
           } else {      }
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');      &Apache::loncommon::end_data_table_count();
           }  
        }      if (($allowed) || ($supplementalflag && $folder eq 'supplemental')) {
     }          my $toolslink = '<table><tr><td>'
 }                         .&Apache::loncommon::help_open_menu('Navigation Screen',
                                                              'Navigation_Screen',undef,'RAT')
                          .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
                          .'<td align="left"><ul id="LC_toolbar">'
 =pod                         .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
                          .'id="LC_content_toolbar_edittoplevel" '
 =item list_symbs()                         .'class="LC_toolbarItem" '
                          .'title="'.&mt('Supplemental Content Editor').'">'
 List Symbs                         .'</a></li></ul></td></tr></table><br />';
           if ($shown) {
 =cut              if ($allowed) {
                   $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
 sub list_symbs {                            .&Apache::loncommon::start_data_table(undef,'contentlist')
     my ($r) = @_;                            .&Apache::loncommon::start_data_table_header_row()
                             .'<th colspan="2">'.&mt('Move').'</th>'
     my $type = &Apache::loncommon::course_type();                            .'<th>'.&mt('Actions').'</th>'
     $r->print(&Apache::loncommon::start_page('Symb List'));                            .'<th colspan="2">'.&mt('Document').'</th>';
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));                  if ($folder !~ /^supplemental/) {
     my $navmap = Apache::lonnavmaps::navmap->new();                      $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
     if (!defined($navmap)) {                  }
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.                  $to_show .= &Apache::loncommon::end_data_table_header_row()
                   '<div class="LC_error">'.                             .$output.' '
                   &mt('Unable to retrieve information about course contents').                             .&Apache::loncommon::end_data_table()
                   '</div>');                             .'<br style="line-height:2px;" />'
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                             .&Apache::loncommon::end_scrollbox();
     } else {              } else {
         $r->print("<pre>\n");                  $to_show .= $toolslink
         foreach my $res ($navmap->retrieveResources()) {                             .&Apache::loncommon::start_data_table('LC_tableOfContent')
     $r->print($res->compTitle()."\t".$res->symb()."\n");                             .$output.' '
         }                             .&Apache::loncommon::end_data_table();
         $r->print("\n</pre>\n");              }
     }          } else {
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');              if (!$allowed) {
 }                  $to_show .= $toolslink;
               }
               $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
 sub verifycontent {                         .'<div class="LC_info" id="contentlist">'
     my ($r) = @_;                         .&mt('Currently no documents.')
     my $type = &Apache::loncommon::course_type();                         .'</div>'
    my $loaderror=&Apache::lonnet::overloaderror($r);                         .&Apache::loncommon::end_scrollbox();
    if ($loaderror) { return $loaderror; }          }
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));      } else {
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));          if ($shown) {
    $hashtied=0;              $to_show = '<div>'
    undef %alreadyseen;                        .&Apache::loncommon::start_data_table('LC_tableOfContent')
    %alreadyseen=();                        .$output
    &tiehash();                        .&Apache::loncommon::end_data_table()
    foreach my $key (keys(%hash)) {                        .'</div>';
        if ($hash{$key}=~/\.(page|sequence)$/) {          } else {
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {              $to_show = '<div class="LC_info" id="contentlist">'
        $r->print('<hr /><span class="LC_error">'.                        .&mt('Currently no documents.')
  &mt('The following sequence or page is included more than once in your '.$type.': ').                        .'</div>'
  &unescape($hash{$key}).'</span><br />'.          }
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));      }
    }      my $tid = 1;
        }      if ($supplementalflag) {
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {          $tid = 2;
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});      }
        }      if ($allowed) {
    }          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
    &untiehash();          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,$jumpto,
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.                                         $readfile));
      &mt('Return to DOCS').'</a>');          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
 }      } else {
           $r->print($to_show);
       }
 sub devalidateversioncache {      return;
     my $src=shift;  }
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.  
   &Apache::lonnet::clutter($src));  sub process_file_upload {
 }      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
   # upload a file, if present
 sub checkversions {      my ($parseaction,$showupload,$nextphase,$mimetype);
     my ($r) = @_;      if ($env{'form.parserflag'}) {
     my $type = &Apache::loncommon::course_type();          $parseaction = 'parse';
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));      }
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));      my $folder=$env{'form.folder'};
     my $header='';      if ($folder eq '') {
     my $startsel='';          $folder='default';
     my $monthsel='';      }
     my $weeksel='';      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
     my $daysel='';          my $errtext='';
     my $allsel='';          my $fatal=0;
     my %changes=();          my $container='sequence';
     my $starttime=0;          if ($env{'form.folderpath'} =~ /:1$/) {
     my $haschanged=0;              $container='page';
     my %setversions=&Apache::lonnet::dump('resourceversions',          }
   $env{'course.'.$env{'request.course.id'}.'.domain'},          ($errtext,$fatal)=
   $env{'course.'.$env{'request.course.id'}.'.num'});                &mapread($coursenum,$coursedom,$folder.'.'.$container);
           if ($#LONCAPA::map::order<1) {
     $hashtied=0;              $LONCAPA::map::order[0]=1;
     &tiehash();              $LONCAPA::map::resources[1]='';
     my %newsetversions=();          }
     if ($env{'form.setmostrecent'}) {          if ($fatal) {
  $haschanged=1;              $$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>';
  foreach my $key (keys(%hash)) {              return;
     if ($key=~/^ids\_(\/res\/.+)$/) {          }
  $newsetversions{$1}='mostrecent';          my $destination = 'docs/';
                 &devalidateversioncache($1);          if ($folder =~ /^supplemental/) {
     }              $destination = 'supplemental/';
  }          }
     } elsif ($env{'form.setcurrent'}) {          if (($folder eq 'default') || ($folder eq 'supplemental')) {
  $haschanged=1;              $destination .= 'default/';
  foreach my $key (keys(%hash)) {          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
     if ($key=~/^ids\_(\/res\/.+)$/) {              $destination .=  $2.'/';
  my $getvers=&Apache::lonnet::getversion($1);          }
  if ($getvers>0) {  # this is for a course, not a user, so set context to coursedoc.
     $newsetversions{$1}=$getvers;          my $newidx=&LONCAPA::map::getresidx();
     &devalidateversioncache($1);          $destination .= $newidx;
  }          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
     }   $parseaction,$allfiles,
  }   $codebase,undef,undef,undef,undef,
     } elsif ($env{'form.setversions'}) {                                                  undef,undef,\$mimetype);
  $haschanged=1;          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
  foreach my $key (keys(%env)) {              my $stored = $1;
     if ($key=~/^form\.set_version_(.+)$/) {              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
  my $src=$1;                            $stored.'</span>').'</p>';
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {          } else {
     $newsetversions{$src}=$env{$key};              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
     &devalidateversioncache($src);              
  }              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
     }              return;
  }          }
     }          my $ext='false';
     if ($haschanged) {          if ($url=~m{^http://}) { $ext='true'; }
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,   $url     = &LONCAPA::map::qtunescape($url);
   $env{'course.'.$env{'request.course.id'}.'.domain'},          my $comment=$env{'form.comment'};
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {   $comment = &LONCAPA::map::qtunescape($comment);
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');          if ($folder=~/^supplemental/) {
  } else {                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');                    $env{'user.domain'}.'___&&&___'.$comment;
  }          }
  &mark_hash_old();  
     }          $LONCAPA::map::resources[$newidx]=
     &changewarning($r,'');      $comment.':'.$url.':'.$ext.':normal:res';
     if ($env{'form.timerange'} eq 'all') {          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
 # show all documents          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
  $header=&mt('All Documents in '.$type);      $folder.'.'.$container,1);
  $allsel=1;          if ($fatal) {
  foreach my $key (keys(%hash)) {              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
     if ($key=~/^ids\_(\/res\/.+)$/) {              return;
  my $src=$1;          } else {
  $changes{$src}=1;              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
     }                  $$upload_output = $showupload;
  }                  my $total_embedded = scalar(keys(%{$allfiles}));
     } else {                  if ($total_embedded > 0) {
 # show documents which changed                      my $uploadphase = 'upload_embedded';
  %changes=&Apache::lonnet::dump                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
                      $env{'course.'.$env{'request.course.id'}.'.num'});                      my ($embedded,$num) = 
  my $firstkey=(keys(%changes))[0];                          &Apache::loncommon::ask_for_embedded_content(
  unless ($firstkey=~/^error\:/) {                              '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
     unless ($env{'form.timerange'}) {                      if ($embedded) {
  $env{'form.timerange'}=604800;                          if ($num) {
     }                              $$upload_output .=
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
  .&mt('seconds');                              $nextphase = $uploadphase;
     if ($env{'form.timerange'}==-1) {                          } else {
  $seltext='since start of course';                              $$upload_output .= $embedded;
  $startsel='selected';                          }
  $env{'form.timerange'}=time;                      } else {
     }                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
     $starttime=time-$env{'form.timerange'};                      }
     if ($env{'form.timerange'}==2592000) {                  } else {
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                      $$upload_output .= &mt('No embedded items identified').'<br />';
  $monthsel='selected';                  }
     } elsif ($env{'form.timerange'}==604800) {                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
  $weeksel='selected';                  $nextphase = 'decompress_uploaded';
     } elsif ($env{'form.timerange'}==86400) {                  my $position = scalar(@LONCAPA::map::order)-1;
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                  my $noextract = &return_to_editor();
  $daysel='selected';                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
     }                  my %archiveitems = (
     $header=&mt('Content changed').' '.$seltext;                      folderpath => $env{'form.folderpath'},
  } else {                      cmd        => $nextphase,
     $header=&mt('No content modifications yet.');                      newidx     => $newidx,
  }                      position   => $position,
     }                      phase      => $nextphase,
     %setversions=&Apache::lonnet::dump('resourceversions',                      comment    => $comment,
   $env{'course.'.$env{'request.course.id'}.'.domain'},                  );
   $env{'course.'.$env{'request.course.id'}.'.num'});                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
     my %lt=&Apache::lonlocal::texthash                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
       ('st' => 'Version changes since start of '.$type,                  $$upload_output = $showupload.
        'lm' => 'Version changes since last Month',                                    &Apache::loncommon::decompress_form($mimetype,
        'lw' => 'Version changes since last Week',                                        $archiveurl,'/adm/coursedocs',$noextract,
        'sy' => 'Version changes since Yesterday',                                        \%archiveitems,\@current);
                'al' => 'All Resources (possibly large output)',              }
        'sd' => 'Display',          }
        'fi' => 'File',      }
        'md' => 'Modification Date',      return $nextphase;
                'mr' => 'Most recently published Version',  }
        've' => 'Version used in '.$type,  
                'vu' => 'Set Version to be used in '.$type,  sub get_dir_list {
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      my ($url,$coursenum,$coursedom,$newidx) = @_;
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      my ($destination,$dir_root) = &embedded_destination();
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      my ($dirlistref,$listerror) =  
        'di' => 'Differences');          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
     $r->print(<<ENDHEADERS);      my @dir_lines;
 <form action="/adm/coursedocs" method="post">      my $dirptr=16384;
 <input type="hidden" name="versions" value="1" />      if (ref($dirlistref) eq 'ARRAY') {
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />          foreach my $dir_line (sort
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />                            {
 <select name="timerange">                                my ($afile)=split('&',$a,2);
 <option value='all' $allsel>$lt{'al'}</option>                                my ($bfile)=split('&',$b,2);
 <option value="-1" $startsel>$lt{'st'}</option>                                return (lc($afile) cmp lc($bfile));
 <option value="2592000" $monthsel>$lt{'lm'}</option>                            } (@{$dirlistref})) {
 <option value="604800" $weeksel>$lt{'lw'}</option>              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
 <option value="86400" $daysel>$lt{'sy'}</option>              $filename =~ s/\s+$//;
 </select>              next if ($filename =~ /^\.\.?$/); 
 <input type="submit" name="display" value="$lt{'sd'}" />              my $isdir = 0;
 <h3>$header</h3>              if ($dirptr&$testdir) {
 <input type="submit" name="setversions" value="$lt{'sv'}" />                  $isdir = 1;
 <table border="0">              }
 ENDHEADERS              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
     foreach my $key (sort(keys(%changes))) {          }
  if ($changes{$key}>$starttime) {      }
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);      return @dir_lines;
     my $currentversion=&Apache::lonnet::getversion($key);  }
     if ($currentversion<0) {  
  $currentversion=&mt('Could not be determined.');  sub is_supplemental_title {
     }      my ($title) = @_;
     my $linkurl=&Apache::lonnet::clutter($key);      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
     $r->print(  }
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.  
       &Apache::lonnet::gettitle($linkurl).  # --------------------------------------------------------------- An entry line
                       '</b></font></td></tr>'.  
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.  sub entryline {
                       '<td colspan="4">'.      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.          $crstype,$pathitem,$supplementalflag,$container)=@_;
       '</a></td></tr>'.      my ($foldertitle,$renametitle);
                       '<tr><td></td>'.      if (&is_supplemental_title($title)) {
                       '<td title="'.$lt{'md'}.'">'.   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
       &Apache::lonlocal::locallocaltime(      } else {
                            &Apache::lonnet::metadata($root.'.'.$extension,   $title=&HTML::Entities::encode($title,'"<>&\'');
                                                      'lastrevisiondate')   $renametitle=$title;
                                                         ).   $foldertitle=$title;
                       '</td>'.      }
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.  
                       '<font size="+1">'.$currentversion.'</font>'.      my $orderidx=$LONCAPA::map::order[$index];
                       '</span></td>'.  
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.      $renametitle=~s/\\/\\\\/g;
                       '<font size="+1">');      $renametitle=~s/\&quot\;/\\\"/g;
 # Used in course      $renametitle=~s/ /%20/g;
     my $usedversion=$hash{'version_'.$linkurl};      my $line=&Apache::loncommon::start_data_table_row();
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      my ($form_start,$form_end,$form_common);
  $r->print($usedversion);  # Edit commands
     } else {      my ($type, $esc_path, $path, $symb);
  $r->print($currentversion);      if ($container eq 'page') {
     }          $type = 'page';
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.      } else {
                       '<span class="LC_nobreak">Use: ');          $type = 'folder';
 # Set version      }
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},      if ($env{'form.folderpath'}) {
       'set_version_'.$linkurl,   $esc_path=&escape($env{'form.folderpath'});
       ('select_form_order' =>   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
        ['',1..$currentversion,'mostrecent'],   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
        '' => '',      }
        'mostrecent' => 'most recent',      my $isexternal;
        map {$_,$_} (1..$currentversion))));      if ($residx) {
     $r->print('</span></td></tr><tr><td></td>');          my $currurl = $url;
     my $lastold=1;          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {          if ($currurl =~ m{^/adm/wrapper/ext/}) {
  my $url=$root.'.'.$prevvers.'.'.$extension;              $isexternal = 1;
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<          }
     $starttime) {          if (!$supplementalflag) {
     $lastold=$prevvers;              my $path = 'uploaded/'.
  }                         $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
     }                         $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
             #              $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
             # Code to figure out how many version entries should go in                                                   $residx,
             # each of the four columns                                                   &Apache::lonnet::declutter($currurl));
             my $entries_per_col = 0;          }
             my $num_entries = ($currentversion-$lastold);      }
             if ($num_entries % 4 == 0) {      my ($renamelink,%lt);
                 $entries_per_col = $num_entries/4;      if ($allowed) {
             } else {   my $incindex=$index+1;
                 $entries_per_col = $num_entries/4 + 1;   my $selectbox='';
             }   if (($#LONCAPA::map::order>0) &&
             my $entries_count = 0;      ((split(/\:/,
             $r->print('<td valign="top"><font size="-2">');       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
             my $cols_output = 1;       ne '') &&
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {      ((split(/\:/,
  my $url=$root.'.'.$prevvers.'.'.$extension;       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).       ne '')) {
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      $selectbox=
   &Apache::lonlocal::locallocaltime(   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
                                 &Apache::lonnet::metadata($url,   '<select name="newpos" onchange="this.form.submit()">';
                                                           'lastrevisiondate')      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
                                                             ).   if ($i==$incindex) {
   ')');      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {   } else {
                     $r->print(' <a href="/adm/diff?filename='.      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
       &Apache::lonnet::clutter($root.'.'.$extension).   }
       '&versionone='.$prevvers.      }
       '">'.&mt('Diffs').'</a>');      $selectbox.='</select>';
  }   }
  $r->print('</span><br />');   %lt=&Apache::lonlocal::texthash(
                 if (++$entries_count % $entries_per_col == 0) {                  'up' => 'Move Up',
                     $r->print('</font></td>');   'dw' => 'Move Down',
                     if ($cols_output != 4) {   'rm' => 'Remove',
                         $r->print('<td valign="top"><font size="-2">');                  'ct' => 'Cut',
                         $cols_output++;   'rn' => 'Rename',
                     }   'cp' => 'Copy',
                 }                  'ex' => 'External Resource',
     }                  'ed' => 'Edit',
             while($cols_output++ < 4) {                  'pr' => 'Preview',
                 $r->print('</font></td><td><font>')                  'sv' => 'Save',
             }                  'ul' => 'URL',
     $r->print('</font></td></tr>'."\n");                  'ti' => 'Title', 
  }                  );
     }   my $nocopy=0;
     $r->print('</table></form>');          my $nocut=0;
     $r->print('<h1>'.&mt('Done').'.</h1>');          my $noremove=0;
           if ($url=~ m{^/res/.+\.(page|sequence)$}) {
     &untiehash();      # no copy for published maps
 }      $nocopy=1;
    }
 sub mark_hash_old {          if ($url=~/^\/res\/lib\/templates\//) {
     my $retie_hash=0;             $nocopy=1;
     if ($hashtied) {             $nocut=1;
  $retie_hash=1;          }
  &untiehash();          my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
     }          my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
     &tiehash('write');          if ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
     $hash{'old'}=1;              if ($env{'form.folderpath'} =~ /^default&[^\&]+$/) {
     &untiehash();                  my %curr_groups = &Apache::longroup::coursegroups();
     if ($retie_hash) { &tiehash(); }                  if (keys(%curr_groups) > 0) {
 }                      $noremove=1;
                   }
 sub is_hash_old {                  $nocut=1;
     my $untie_hash=0;                  $nocopy=1;
     if (!$hashtied) {              }
  $untie_hash=1;          } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
  &tiehash();              my $group = $1;
     }              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
     my $return=$hash{'old'};                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     if ($untie_hash) { &untiehash(); }                  if (keys(%curr_group) > 0) {
     return $return;                      $noremove=1;
 }                  }
               }
 sub changewarning {              $nocut=1;
     my ($r,$postexec,$message,$url)=@_;              $nocopy=1;
     if (!&is_hash_old()) { return; }          } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
     my $pathvar='folderpath';              my $group = $1;
     my $path=&escape($env{'form.folderpath'});              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
     if (!defined($url)) {                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
  if (defined($env{'form.pagepath'})) {                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
     $pathvar='pagepath';                  if (keys(%groupsettings) > 0) {
     $path=&escape($env{'form.pagepath'});                      $noremove=1;
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                  }
  }                  $nocut=1;
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                  $nocopy=1;
     }              }
     my $course_type = &Apache::loncommon::course_type();          } elsif ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
     if (!defined($message)) {              my $group = $1;
  $message='Changes will become active for your current session after [_1], or the next time you log in.';              my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     }              if ($url =~ /group_boards_\Q$group\E/) {
     $r->print("\n\n".                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.                  if (keys(%groupsettings) > 0) {
 '<input type="hidden" name="orgurl" value="'.$url.                      if (ref($groupsettings{'functions'}) eq 'HASH') {
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
 &mt($message,' <input type="hidden" name="'.                              $noremove=1;
     $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");                  }
 }                  $nocut=1;
                   $nocopy=1;
               }
 sub init_breadcrumbs {          }
     my ($form,$text)=@_;          my ($copylink,$cutlink,$removelink);
     &Apache::lonhtmlcommon::clear_breadcrumbs();   my $skip_confirm = 0;
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",   if ( $folder =~ /^supplemental/
     text=>"Edit ".&Apache::loncommon::course_type(),       || ($url =~ m{( /smppg$
     faq=>273,      |/syllabus$
     bug=>'Instructor Interface',      |/aboutme$
                                             help => 'Docs_Adding_Course_Doc'});      |/navmaps$
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',      |/bulletinboard$
     text=>$text,      |\.html$)}x)
     faq=>273,               || $isexternal) {
     bug=>'Instructor Interface'});      $skip_confirm = 1;
 }   }
   
    if ($nocopy) {
               $copylink=(<<ENDCOPY);
   <span style="visibility: hidden;">$lt{'cp'}</span>
 sub handler {  ENDCOPY
     my $r = shift;          } else {
     &Apache::loncommon::content_type($r,'text/html');      $copylink=(<<ENDCOPY);
     $r->send_http_header;  <a href="javascript:markcopy('$esc_path','$index','$renametitle','$container','$folder');" class="LC_docs_copy">$lt{'cp'}</a>
     return OK if $r->header_only;  ENDCOPY
     my $type = &Apache::loncommon::course_type();          }
    if ($nocut) {
               $cutlink=(<<ENDCUT);
 # --------------------------------------------- Initialize help topics for this  <span style="visibility: hidden;">$lt{'ct'}</span>
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',  ENDCUT
                'Adding_External_Resource','Navigate_Content',          } else {
                'Adding_Folders','Docs_Overview', 'Load_Map',      $cutlink=(<<ENDCUT);
                'Supplemental','Score_Upload_Form','Adding_Pages',  <a href="javascript:cutres('$esc_path','$index','$renametitle','$container','$folder',$skip_confirm);" class="LC_docs_cut">$lt{'ct'}</a>
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',  ENDCUT
                'Check_Resource_Versions','Verify_Content') {          }
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);          if ($noremove) {
     }              $removelink=(<<ENDREM);
     # Composite help files  <span style="visibility: hidden;">$lt{'rm'}</a>
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(  ENDREM
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');          } else {
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(              $removelink=(<<ENDREM);
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');  <a href='javascript:removeres("$esc_path","$index","$renametitle",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(  ENDREM
     'Option_Response_Simple');          }
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(          unless ($isexternal) {
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');              $renamelink=(<<ENDREN);
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(  <a href='javascript:changename("$esc_path","$index","$renametitle");' class="LC_docs_rename">$lt{'rn'}</a>
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');  ENDREN
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');          }
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');   $form_start = '
      <form action="/adm/coursedocs" method="post">
 # does this user have privileges to modify docs  ';
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});          $form_common=(<<END);
   if ($allowed && $env{'form.verify'}) {     <input type="hidden" name="${type}path" value="$path" />
       &init_breadcrumbs('verify','Verify Content');     <input type="hidden" name="${type}symb" value="$symb" />
       &verifycontent($r);     <input type="hidden" name="setparms" value="$orderidx" />
   } elsif ($allowed && $env{'form.listsymbs'}) {     <input type="hidden" name="changeparms" value="0" />
       &init_breadcrumbs('listsymbs','List Symbs');  END
       &list_symbs($r);          $form_end = '</form>';
   } elsif ($allowed && $env{'form.docslog'}) {   $line.=(<<END);
       &init_breadcrumbs('docslog','Show Log');  <td>
       &docs_change_log($r);  <div class="LC_docs_entry_move">
   } elsif ($allowed && $env{'form.versions'}) {    <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
       &init_breadcrumbs('versions','Check/Set Resource Versions');      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
       &checkversions($r);    </a>
   } elsif ($allowed && $env{'form.dumpcourse'}) {  </div>
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');  <div class="LC_docs_entry_move">
       &dumpcourse($r);    <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
   } elsif ($allowed && $env{'form.exportcourse'}) {      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');    </a>
       &exportcourse($r);  </div>
   } else {  </td>
 # is this a standard course?  <td>
      $form_start
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);     $form_common
     my $forcestandard = 0;     $selectbox
     my $forcesupplement;     $form_end
     my $script='';  </td>
     my $showdoc=0;  <td class="LC_docs_entry_commands"><span class="LC_nobreak">
     my $containertag;  $removelink
     my $uploadtag;  $cutlink
   $copylink
   </span>
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  </td>
     ['folderpath','pagepath',  END
      'pagesymb']);  
 # No folderpath, no pagepath, see if we have something stored      }
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {  # Figure out what kind of a resource this is
         &Apache::loncommon::restore_course_settings('docs_folderpath',      my ($extension)=($url=~/\.(\w+)$/);
                                               {'folderpath' => 'scalar'});      my $uploaded=($url=~/^\/*uploaded\//);
     }      my $icon=&Apache::loncommon::icon($url);
     if (!$env{'form.folderpath'}) {      my $isfolder;
         &Apache::loncommon::restore_course_settings('docs_folderpath',      my $ispage;
                                               {'pagepath' => 'scalar'});      my $containerarg;
     }      if ($uploaded) {
     if ($env{'form.pagepath'}) {          if (($extension eq 'sequence') || ($extension eq 'page')) {
        $env{'form.folderpath'}='';              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
     }              $containerarg = $1;
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {      if ($extension eq 'sequence') {
         $env{'form.folderpath'} = 'supplemental&'.          $icon=$iconpath.'navmap.folder.closed.gif';
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.                  $isfolder=1;
                                   $env{'form.folderpath'};              } else {
     }                  $icon=$iconpath.'page.gif';
     &Apache::loncommon::store_course_settings('docs_folderpath',                  $ispage=1;
                                                 {'pagepath' => 'scalar',              }
                                                  'folderpath' => 'scalar'});              if ($allowed) {
     if ($env{'form.folderpath'}) {                  $url='/adm/coursedocs?';
  my (@folderpath)=split('&',$env{'form.folderpath'});              } else {
  $env{'form.foldername'}=&unescape(pop(@folderpath));                  $url='/adm/supplemental?';
  $env{'form.folder'}=pop(@folderpath);              }
     }   } else {
     if ($env{'form.pagepath'}) {      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
         my (@pagepath)=split('&',$env{'form.pagepath'});   }
         $env{'form.pagename'}=&unescape(pop(@pagepath));      }
         $env{'form.folder'}=pop(@pagepath);  
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      my ($editlink,$extresform);
     '<input type="hidden" name="pagesymb" value="" />';      my $orig_url = $url;
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';      $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
     }      if (!$supplementalflag && $residx && $symb) {
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {          if ((!$isfolder) && (!$ispage)) {
        $showdoc='/'.$1;      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
     }      $url=&Apache::lonnet::clutter($url);
     unless ($showdoc) { # got called from remote      if ($url=~/^\/*uploaded\//) {
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||          $url=~/\.(\w+)$/;
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {          my $embstyle=&Apache::loncommon::fileembstyle($1);
            $forcestandard = 1;          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
        }      $url='/adm/wrapper'.$url;
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);          } elsif ($embstyle eq 'ssi') {
       #do nothing with these
        if ($allowed) {          } elsif ($url!~/\.(sequence|page)$/) {
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);      $url='/adm/coursedocs/showdoc'.$url;
          $script=&Apache::lonratedt::editscript('simple');          }
        }      } elsif ($url=~m|^/ext/|) {
     } else { # got called in sequence from course          $url='/adm/wrapper'.$url;
        $allowed=0;      }
     }              if (&Apache::lonnet::symbverify($symb,$url)) {
           $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
 # get course data              } else {
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};                  $url='';
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};              }
    }
 # get personal data      }
     my $uname=$env{'user.name'};      my ($rand_pick_text,$rand_order_text);
     my $udom=$env{'user.domain'};      if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));   my $foldername=&escape($foldertitle);
    my $folderpath=$env{'form.folderpath'};
 # graphics settings   if ($folderpath) { $folderpath.='&' };
           if (!$allowed && $supplementalflag) {
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");              $folderpath.=$containerarg.'&'.$foldername;
               $url.='folderpath='.&escape($folderpath);
     if ($allowed) {          } else {
  $script .= &editing_js($udom,$uname);  # Append randompick number, hidden, and encrypted with ":" to foldername,
     }  # so it gets transferred between levels
 # -------------------------------------------------------------------- Body tag      $folderpath.=$containerarg.'&'.$foldername.
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';                                                ':'.(&LONCAPA::map::getparameter($orderidx,
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];                                                'parameter_randompick'))[0]
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     {'force_register' => $showdoc,                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
                                      'bread_crumbs' => $brcrum}).                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
       &Apache::loncommon::help_open_menu('','',273,'RAT'));                                                'parameter_encrypturl'))[0]=~/^yes$/i)
                                                   .':'.((&LONCAPA::map::getparameter($orderidx,
   my %allfiles = ();                                                'parameter_randomorder'))[0]=~/^yes$/i)
   my %codebase = ();                                                 .':'.$ispage;
   my ($upload_result,$upload_output);      $url.='folderpath='.&escape($folderpath);
   if ($allowed) {              my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
       if (($env{'form.uploaddoc.filename'}) &&                                                          'parameter_randompick'))[0];
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {              my $rpckchk;
 # Process file upload - phase one - upload and parse primary file.                if ($rpicknum) {
   undef($hadchanges);                  $rpckchk = ' checked="checked"';
           $upload_result = &process_file_upload(\$upload_output,$coursenum,              }
  $coursedom,\%allfiles,              my $formname = 'edit_rpick_'.$orderidx;
  \%codebase,$1);      $rand_pick_text = 
   if ($hadchanges) {  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
       &mark_hash_old();  $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 ($upload_result eq 'phasetwo') {              if ($rpicknum ne '') {
               $r->print($upload_output);                  $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
           }              }
       } elsif ($env{'form.phasetwo'}) {              $rand_pick_text .= '</span></form>';
           my %newname = ();         my $ro_set=
           my %origname = ();          ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
           my %attribs = ();      $rand_order_text = 
           my $updateflag = 0;  $form_start.
           my $residx = $env{'form.newidx'};  $form_common.'
           my $primary_url = &unescape($env{'form.primaryurl'});  <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>';
 # Process file upload - phase two - gather secondary files.          }
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {      } elsif ($supplementalflag && !$allowed) {
               if ($env{'form.embedded_item_'.$i.'.filename'}) {          $url .= ($url =~ /\?/) ? '&amp;':'?';
                   my $javacodebase;          $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);          if ($title) {
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});              $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
                   if (exists($env{'form.embedded_codebase_'.$i})) {          }
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});            if ($isexternal && $orderidx) {
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;              $url .= '&amp;idx='.$orderidx;
                   }          }
                   my @attributes = ();      }
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {      my ($tdalign,$tdwidth);
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});      if ($allowed) {
                   } else {          my $fileloc = 
                       @attributes = ($env{'form.embedded_attrib_'.$i});              &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
                   }          if ($isexternal) {
                   foreach my $attr (@attributes) {              ($editlink,$extresform) = 
                       push(@{$attribs{$i}},&unescape($attr));                  &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
                   }          } elsif (!$isfolder && !$ispage) {
                   if ($javacodebase) {              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
                       $codebase{$i} = $javacodebase;                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
                       $codebase{$i} =~ s#/$##;              if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
                       $updateflag = 1;                  my $jscall = 
                   }                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
               }                                                              $switchserver,
               unless ($newname{$i} eq $origname{$i}) {                                                              $forceedit,
                   $updateflag = 1;                                                              undef,$symb,
               }                                                              &escape($env{'form.folderpath'}),
           }                                                              $renametitle,'','',1);
 # Process file upload - phase three - modify primary file                  if ($jscall) {
           if ($updateflag) {                      $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
               my ($content,$rtncode);                                  $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
               my $updateflag = 0;                  }
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);              }
               if ($getstatus eq 'ok') {          }
                   foreach my $item (keys(%newname)) {          $tdalign = ' align="right" valign="top"';
                       if ($newname{$item} ne $origname{$item}) {          $tdwidth = ' width="80%"';
                           my $attrib_regexp = '';      }
                           if (@{$attribs{$item}} > 1) {      my $reinit;
                               $attrib_regexp = join('|',@{$attribs{$item}});      if ($crstype eq 'Community') {
                           } else {          $reinit = &mt('(re-initialize community to access)');
                               $attrib_regexp = $attribs{$item}[0];      } else {
                           }          $reinit = &mt('(re-initialize course to access)');
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {      }
                           }      $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
                       }         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
                       if (exists($codebase{$item})) {      } elsif ($url) {
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
                       }                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
                   }      } else {
 # Save edited file.         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
                   my $saveresult;      }
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};      $line.='</span></td><td'.$tdwidth.'>';
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);         $line.='<a href="'.$url.'">'.$title.'</a>';
               } else {      } elsif ($url) {
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
               }                                               $title,600,500);
           }      } else {
       }         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
   }      }
       $line.="$extresform</td>";
   unless ($showdoc ||  $upload_result eq 'phasetwo') {      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
 # -----------------------------------------------------------------------------      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
        my %lt=&Apache::lonlocal::texthash(      if (($allowed) && ($folder!~/^supplemental/)) {
                 'uplm' => 'Upload a new main '.lc($type).' document',    my %lt=&Apache::lonlocal::texthash(
                 'upls' => 'Upload a new supplemental '.lc($type).' document',         'hd' => 'Hidden',
                 'impp' => 'Import a document',         'ec' => 'URL hidden');
                 'pubd' => 'Published Documents',   my $enctext=
  'copm' => 'All documents out of a published map into this folder',      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
                 'upld' => 'Upload Document',   my $hidtext=
                 'srch' => 'Search',      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
                 'impo' => 'Import',   $line.=(<<ENDPARMS);
  'book' => 'Import Bookmarks',    <td class="LC_docs_entry_parameter">
                 'selm' => 'Select Map',      $form_start
                 'load' => 'Load Map',      $form_common
                 'reco' => 'Recover Deleted Resources',      <label><input type="checkbox" name="hiddenresource_$orderidx" onclick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
                 'newf' => 'New Folder',      $form_end
                 'newp' => 'New Composite Page',      <br />
                 'extr' => 'External Resource',      $form_start
                 'syll' => 'Syllabus',      $form_common
                 'navc' => 'Navigate Contents',      <label><input type="checkbox" name="encrypturl_$orderidx" onclick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
                 'sipa' => 'Simple Page',      $form_end
                 'sipr' => 'Simple Problem',    </td>
                 'drbx' => 'Drop Box',    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
                 'scuf' => 'Score Upload Form',                                        $rand_order_text</td>
                 'bull' => 'Bulletin Board',  ENDPARMS
                 'mypi' => 'My Personal Info',      }
                 'grpo' => 'Group Files',      $line.=&Apache::loncommon::end_data_table_row();
                 'rost' => 'Course Roster',      return $line;
  'abou' => 'About User',  }
                 'imsf' => 'Import IMS package',  
                 'file' =>  'File',  sub new_timebased_suffix {
                 'title' => 'Title',      my ($coursedom,$coursenum,$type,$area,$container) = @_;
                 'comment' => 'Comment',      my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',      if ($type eq 'map') {
  'nd' => 'New Document',          $prefix = 'docs';
  'pm' => 'Published Map',          if ($area eq 'supplemental') {
  'sd' => 'Special Document',              $prefix = 'supp';
  'mo' => 'More Options',          }
  'hao' => 'Hide all Options'          $prefix .= $container;
   );          $namespace = 'uploadedmaps';
 # -----------------------------------------------------------------------------      } else {
  my $fileupload=(<<FIUP);          $prefix = $type;
  $lt{'file'}:<br />          $namespace = 'templated';
  <input type="file" name="uploaddoc" size="40" />      }
 FIUP      $idtype = 'concat';
       my ($suffix,$freedlock,$error) =
  my $checkbox=(<<CHBO);          &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,
  <!-- <label>$lt{'parse'}?                                            $coursedom,$coursenum);
  <input type="checkbox" name="parserflag" />      if (!$suffix) {
  </label> -->          if ($type eq 'map') {
  <label>              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}          } elsif ($type eq 'smppg') {
  </label>              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
 CHBO          } else {
               $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new bulletin board.');
  my $fileuploadform=(<<FUFORM);          }
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">          if ($error) {
  $fileupload              $errtext .= '<br />'.$error;
  <br />          }
  $lt{'title'}:<br />      }
  <input type="text" size="50" name="comment" />      if ($freedlock ne 'ok') {
  $uploadtag          $locknotfreed =
  <input type="hidden" name="cmd" value="upload_default" />              '<div class="LC_error">'.
  <br />              &mt('There was a problem removing a lockfile.').' ';
  <span class="LC_nobreak">          if ($type eq 'map') {
  $checkbox              &mt('This will prevent creation of additional folders or composite pages in this course.');
  </span>          } elsif ($type eq 'smppg') {
  <br />              $locknotfreed .=
  <br />                  &mt('This will prevent creation of additional simple pages in this course.');
  <span class="LC_nobreak">          } else {
  <input type="submit" value="$lt{'upld'}" />              $locknotfreed .=
  $help{'Uploading_From_Harddrive'}                  &mt('This will prevent creation of additional bulletin boards in this course.');
  </span>          }
  </form>          $locknotfreed .=
 FUFORM              ' '.&mt('Please contact the domain coordinator for your LON-CAPA domain.').
               '</div>';
  my $simpleeditdefaultform=(<<SEDFFORM);      }
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">      return ($suffix,$errtext,$locknotfreed);
  $lt{'pubd'}<br />  }
  $uploadtag  
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />  =pod
  <br />  
  <span class="LC_nobreak">  =item tiehash()
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />  
  $help{'Importing_LON-CAPA_Resource'}  tie the hash
  </span>  
  <br />  =cut
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />  
  <hr />  sub tiehash {
  <p>      my ($mode)=@_;
  $lt{'copm'}<br />      $hashtied=0;
  <input type="text" size="40" name="importmap" /><br />      if ($env{'request.course.fn'}) {
  <span class="LC_nobreak"><input type="button"   if ($mode eq 'write') {
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />      &GDBM_WRCREAT(),0640)) {
  $help{'Load_Map'}</span>                  $hashtied=2;
  </p>      }
  </form>   } else {
 SEDFFORM      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
       &GDBM_READER(),0640)) {
  my $extresourcesform=(<<ERFORM);                  $hashtied=1;
  <form action="/adm/coursedocs" method="post" name="newext">      }
  $uploadtag   }
  <input type="hidden" name="importdetail" value="" />      }
  <span class="LC_nobreak">  }
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"  
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}  sub untiehash {
  </span>      if ($hashtied) { untie %hash; }
  </form>      $hashtied=0;
 ERFORM      return OK;
   }
     if ($allowed) {  
  &update_paste_buffer($coursenum,$coursedom);  
        my $dumpbut=&dumpbutton();  
        my $exportbut=&exportbutton();  
        my %lt=&Apache::lonlocal::texthash(  sub checkonthis {
  'vc' => 'Verify Content',      my ($r,$url,$level,$title)=@_;
  'cv' => 'Check/Set Resource Versions',      $url=&unescape($url);
  'ls' => 'List Symbs',      $alreadyseen{$url}=1;
                                          'sl' => 'Show Log'      $r->rflush();
   );      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
          $r->print("\n<br />");
        my $folderpath=$env{'form.folderpath'};         if ($level==0) {
        if (!$folderpath) {             $r->print("<br />");
    if ($env{'form.folder'} eq '' ||         }
        $env{'form.folder'} eq 'supplemental') {         for (my $i=0;$i<=$level*5;$i++) {
        $folderpath='default&'.             $r->print('&nbsp;');
    &escape(&mt('Main '.$type.' Documents'));         }
    }         $r->print('<a href="'.$url.'" target="cat">'.
        }   ($title?$title:$url).'</a> ');
        unless ($env{'form.pagepath'}) {         if ($url=~/^\/res\//) {
            $containertag = '<input type="hidden" name="folderpath" value="" />';    my $result=&Apache::lonnet::repcopy(
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';                                &Apache::lonnet::filelocation('',$url));
        }            if ($result eq 'ok') {
                $r->print('<span class="LC_success">'.&mt('ok').'</span>');
        $r->print(<<ENDCOURSEVERIFY);               $r->rflush();
 <form name="renameform" method="post" action="/adm/coursedocs">               &Apache::lonnet::countacc($url);
   <input type="hidden" name="title" />               $url=~/\.(\w+)$/;
   <input type="hidden" name="cmd" />               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
   <input type="hidden" name="markcopy" />   $r->print('<br />');
   <input type="hidden" name="copyfolder" />                   $r->rflush();
   $containertag                   for (my $i=0;$i<=$level*5;$i++) {
 </form>                       $r->print('&nbsp;');
 <form name="simpleedit" method="post" action="/adm/coursedocs">                   }
   <input type="hidden" name="importdetail" value="" />                   $r->print('- '.&mt('Rendering:').' ');
   $uploadtag   my ($errorcount,$warningcount)=split(/:/,
 </form>         &Apache::lonnet::ssi_body($url,
 <form action="/adm/coursedocs" method="post" name="courseverify">         ('grade_target'=>'web',
   <div class="LC_docs_course_commands">   'return_only_error_and_warning_counts' => 1)));
                    if (($errorcount) ||
       <div>                       ($warningcount)) {
         <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}       if ($errorcount) {
       </div>                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
       <div>                            &mt('[quant,_1,error]',$errorcount).'</span>');
         <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}                       }
       </div>       if ($warningcount) {
         $dumpbut                          $r->print('<span class="LC_warning">'.
         $exportbut                            &mt('[quant,_1,warning]',$warningcount).'</span>');
       <div>                       }
         <input type="submit" name="listsymbs" value="$lt{'ls'}" />                   } else {
       </div>                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
       <div>                   }
         <input type="hidden" name="folder" value="$env{'form.folder'}" />                   $r->rflush();
         <input type="submit" name="docslog" value="$lt{'sl'}" />               }
       </div>       my $dependencies=
   </div>                  &Apache::lonnet::metadata($url,'dependencies');
 </form>               foreach my $dep (split(/\,/,$dependencies)) {
 <div style="clear: both; height: 0px;">&nbsp;</div>   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 ENDCOURSEVERIFY                      &checkonthis($r,$dep,$level+1);
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',                   }
      &mt('Editing the Table of Contents for your '.$type)));               }
     }            } elsif ($result eq 'unavailable') {
 # --------------------------------------------------------- Standard documents               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
     $r->print('<table class="LC_docs_documents">');            } elsif ($result eq 'not_found') {
         unless ($url=~/\$/) {
     if (($standard) && ($allowed) && (!$forcesupplement)) {    $r->print('<span class="LC_error">'.&mt('not found').'</span>');
  $r->print('<tr><td class="LC_docs_document">');        } else {
 #  '<h2>'.&mt('Main Course Documents').    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');        }
        my $folder=$env{'form.folder'};            } else {
        if ($folder eq '' || $folder eq 'supplemental') {               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
            $folder='default';            }
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));         }
            $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">this.window.name="loncapaclient";</script>');  =pod
        } else {  
            #$postexec='self.close();';  =item list_symbs()
        }  
        $hadchanges=0;  List Content Identifiers
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,  
    $upload_output,$type);  =cut
        if ($error) {  
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');  sub list_symbs {
        }      my ($r) = @_;
        if ($hadchanges) {  
    &mark_hash_old();      my $crstype = &Apache::loncommon::course_type();
        }      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
        &changewarning($r,$postexec);      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      $r->print(&startContentScreen('tools'));
                      '.sequence';      my $navmap = Apache::lonnavmaps::navmap->new();
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      if (!defined($navmap)) {
                      '.page';          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
  my $container='sequence';                    '<div class="LC_error">'.
  if ($env{'form.pagepath'}) {                    &mt('Unable to retrieve information about course contents').
     $container='page';                    '</div>');
  }          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;      } else {
           $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
                     &Apache::loncommon::start_data_table().
                     &Apache::loncommon::start_data_table_header_row().
  my $recoverform=(<<RFORM);                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
  <form action="/adm/groupsort" method="post" name="recover">                    &Apache::loncommon::end_data_table_header_row()."\n");
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />          my $count;
  </form>          foreach my $res ($navmap->retrieveResources()) {
 RFORM              $r->print(&Apache::loncommon::start_data_table_row().
                         '<td>'.$res->compTitle().'</td>'.
  my $imspform=(<<IMSPFORM);                        '<td>'.$res->symb().'</td>'.
  <form action="/adm/imsimportdocs" method="post" name="ims">                        &Apache::loncommon::end_data_table_row());
  <input type="hidden" name="folder" value="$folder" />              $count ++;
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />          }
  </form>          if (!$count) {
 IMSPFORM              $r->print(&Apache::loncommon::start_data_table_row().
                         '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
  my $newnavform=(<<NNFORM);                        &Apache::loncommon::end_data_table_row()); 
  <form action="/adm/coursedocs" method="post" name="newnav">          }
  $uploadtag          $r->print(&Apache::loncommon::end_data_table());
  <input type="hidden" name="importdetail"      }
  value="$lt{'navc'}=/adm/navmaps" />      $r->print(&endContentScreen());
  <span class="LC_nobreak">  }
  <input name="newnav" type="submit" value="$lt{'navc'}" />  
  $help{'Navigate_Content'}  
  </span>  sub verifycontent {
  </form>      my ($r) = @_;
 NNFORM      my $crstype = &Apache::loncommon::course_type();
  my $newsmppageform=(<<NSPFORM);      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
  <form action="/adm/coursedocs" method="post" name="newsmppg">      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
  $uploadtag      $r->print(&startContentScreen('tools'));
  <input type="hidden" name="importdetail" value="" />      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
  <span class="LC_nobreak">     $hashtied=0;
  <input name="newsmppg" type="button" value="$lt{'sipa'}"     undef %alreadyseen;
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}     %alreadyseen=();
  </span>     &tiehash();
  </form>     
 NSPFORM     foreach my $key (keys(%hash)) {
          if ($hash{$key}=~/\.(page|sequence)$/) {
  my $newsmpproblemform=(<<NSPROBFORM);     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">         $r->print('<hr /><span class="LC_error">'.
  $uploadtag   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
  <input type="hidden" name="importdetail" value="" />   &unescape($hash{$key}).'</span><br />'.
  <span class="LC_nobreak">   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"     }
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}         }
  </span>         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
  </form>             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
          }
 NSPROBFORM     }
      &untiehash();
  my $newdropboxform=(<<NDBFORM);     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
  <form action="/adm/coursedocs" method="post" name="newdropbox">      $r->print(&endContentScreen());
  $uploadtag        }
  <input type="hidden" name="importdetail" value="" />  
  <span class="LC_nobreak">            
  <input name="newdropbox" type="button" value="$lt{'drbx'}"  sub devalidateversioncache {
  onClick="javascript:makedropbox();" />      my $src=shift;
  </span>              &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
  </form>    &Apache::lonnet::clutter($src));
 NDBFORM  }
   
  my $newexuploadform=(<<NEXUFORM);  sub checkversions {
  <form action="/adm/coursedocs" method="post" name="newexamupload">      my ($r) = @_;
  $uploadtag      my $crstype = &Apache::loncommon::course_type();
  <input type="hidden" name="importdetail" value="" />      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
  <span class="LC_nobreak">      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
  <input name="newexamupload" type="button" value="$lt{'scuf'}"      $r->print(&startContentScreen('tools'));
  onClick="javascript:makeexamupload();" />  
  $help{'Score_Upload_Form'}      my $header='';
  </span>      my $startsel='';
  </form>      my $monthsel='';
 NEXUFORM      my $weeksel='';
       my $daysel='';
  my $newbulform=(<<NBFORM);      my $allsel='';
  <form action="/adm/coursedocs" method="post" name="newbul">      my %changes=();
  $uploadtag      my $starttime=0;
  <input type="hidden" name="importdetail" value="" />      my $haschanged=0;
  <span class="LC_nobreak">      my %setversions=&Apache::lonnet::dump('resourceversions',
  <input name="newbulletin" type="button" value="$lt{'bull'}"    $env{'course.'.$env{'request.course.id'}.'.domain'},
  onClick="javascript:makebulboard();" />    $env{'course.'.$env{'request.course.id'}.'.num'});
  $help{'Bulletin Board'}  
  </span>      $hashtied=0;
  </form>      &tiehash();
 NBFORM      my %newsetversions=();
       if ($env{'form.setmostrecent'}) {
  my $newaboutmeform=(<<NAMFORM);   $haschanged=1;
  <form action="/adm/coursedocs" method="post" name="newaboutme">   foreach my $key (keys(%hash)) {
  $uploadtag      if ($key=~/^ids\_(\/res\/.+)$/) {
  <input type="hidden" name="importdetail"   $newsetversions{$1}='mostrecent';
  value="$plainname=/adm/$udom/$uname/aboutme" />                  &devalidateversioncache($1);
  <span class="LC_nobreak">      }
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />   }
  $help{'My Personal Info'}      } elsif ($env{'form.setcurrent'}) {
  </span>   $haschanged=1;
  </form>   foreach my $key (keys(%hash)) {
 NAMFORM      if ($key=~/^ids\_(\/res\/.+)$/) {
    my $getvers=&Apache::lonnet::getversion($1);
  my $newaboutsomeoneform=(<<NASOFORM);   if ($getvers>0) {
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">      $newsetversions{$1}=$getvers;
  $uploadtag      &devalidateversioncache($1);
  <input type="hidden" name="importdetail" value="" />   }
  <span class="LC_nobreak">      }
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"   }
  onClick="javascript:makeabout();" />      } elsif ($env{'form.setversions'}) {
  </span>   $haschanged=1;
  </form>   foreach my $key (keys(%env)) {
 NASOFORM      if ($key=~/^form\.set_version_(.+)$/) {
    my $src=$1;
    if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
  my $newrosterform=(<<NROSTFORM);      $newsetversions{$src}=$env{$key};
  <form action="/adm/coursedocs" method="post" name="newroster">      &devalidateversioncache($src);
  $uploadtag   }
  <input type="hidden" name="importdetail"      }
  value="$lt{'rost'}=/adm/viewclasslist" />   }
  <span class="LC_nobreak">      }
  <input name="newroster" type="submit" value="$lt{'rost'}" />      if ($haschanged) {
  $help{'Course Roster'}          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
  </span>    $env{'course.'.$env{'request.course.id'}.'.domain'},
  </form>    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 NROSTFORM      $r->print(&Apache::loncommon::confirmwrapper(
                   &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
        $r->print(<<ENDFORM);   } else {
       $r->print(&Apache::loncommon::confirmwrapper(
 <ul class="LC_TabContent">                  &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
 <li>$lt{'nd'}</li>   }
 <li>$lt{'pm'}</li>   &mark_hash_old();
 <li>$lt{'pubd'}</li>      }
 <li>$lt{'sd'}</li>      &changewarning($r,'');
 <li>$lt{'mo'}</li>      if ($env{'form.timerange'} eq 'all') {
 <li>$lt{'hao'}</li>  # show all documents
 </ul>   $header=&mt('All Documents in '.$crstype);
    $allsel=' selected="selected"';
 <table class="LC_docs_adddocs">   foreach my $key (keys(%hash)) {
 <!-- <tr>      if ($key=~/^ids\_(\/res\/.+)$/) {
 <th>$lt{'uplm'}</th>   my $src=$1;
 <th>$lt{'impp'}</th>   $changes{$src}=1;
 <th>$lt{'spec'}</th>      }
 </tr> -->   }
 <tr>      } else {
 <td>  # show documents which changed
 $fileuploadform   %changes=&Apache::lonnet::dump
 </td>   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
 <td>                       $env{'course.'.$env{'request.course.id'}.'.num'});
 $simpleeditdefaultform   my $firstkey=(keys(%changes))[0];
 <hr />   unless ($firstkey=~/^error\:/) {
 $recoverform      unless ($env{'form.timerange'}) {
 ENDFORM   $env{'form.timerange'}=604800;
        unless ($env{'form.pagepath'}) {      }
    $r->print(<<ENDFORM);      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 <hr />   .&mt('seconds');
 $extresourcesform      if ($env{'form.timerange'}==-1) {
  <br />   $seltext='since start of course';
 $imspform   $startsel=' selected="selected"';
 ENDFORM   $env{'form.timerange'}=time;
        }      }
        $r->print('</td><td>');      $starttime=time-$env{'form.timerange'};
        unless ($env{'form.pagepath'}) {      if ($env{'form.timerange'}==2592000) {
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $monthsel=' selected="selected"';
       } elsif ($env{'form.timerange'}==604800) {
    $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  my $newpageform=(<<NPFORM);   $weeksel=' selected="selected"';
  <form action="/adm/coursedocs" method="post" name="newpage">      } elsif ($env{'form.timerange'}==86400) {
  <input type="hidden" name="folderpath" value="$path" />   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  <input type="hidden" name="importdetail" value="" />   $daysel=' selected="selected"';
  <span class="LC_nobreak">      }
  <input name="newpage" type="button"      $header=&mt('Content changed').' '.$seltext;
  onClick="javascript:makenewpage(this.form,'$pageseq');"   } else {
  value="$lt{'newp'}" />$help{'Adding_Pages'}      $header=&mt('No content modifications yet.');
  </span>   }
  </form>      }
 NPFORM      %setversions=&Apache::lonnet::dump('resourceversions',
     $env{'course.'.$env{'request.course.id'}.'.domain'},
  my $newfolderform=(<<NFFORM);    $env{'course.'.$env{'request.course.id'}.'.num'});
  <form action="/adm/coursedocs" method="post" name="newfolder">      my %lt=&Apache::lonlocal::texthash
  <input type="hidden" name="folderpath" value="$path" />        ('st' => 'Version changes since start of '.$crstype,
  <input type="hidden" name="importdetail" value="" />         'lm' => 'Version changes since last Month',
  <span class="LC_nobreak">         'lw' => 'Version changes since last Week',
  <input name="newfolder" type="button"         'sy' => 'Version changes since Yesterday',
  onClick="javascript:makenewfolder(this.form,'$folderseq');"                 'al' => 'All Resources (possibly large output)',
  value="$lt{'newf'}" />$help{'Adding_Folders'}                 'cd' => 'Change display', 
  </span>         'sd' => 'Display',
  </form>         'fi' => 'File',
 NFFORM         'md' => 'Modification Date',
                  'mr' => 'Most recently published Version',
  my $newsylform=(<<NSYLFORM);         've' => 'Version used in '.$crstype,
  <form action="/adm/coursedocs" method="post" name="newsyl">                 'vu' => 'Set Version to be used in '.$crstype,
  $uploadtag  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
  <input type="hidden" name="importdetail"  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
  <span class="LC_nobreak">         'di' => 'Differences',
  <input name="newsyl" type="submit" value="$lt{'syll'}" />         'save' => 'Save changes',
  $help{'Syllabus'}                 'vers' => 'Version choice(s) for specific resources', 
  </span>         'act' => 'Actions');
  </form>      $r->print(<<ENDHEADERS);
 NSYLFORM  <h4 class="LC_info">$header</h4>
   <form action="/adm/coursedocs" method="post">
  my $newgroupfileform=(<<NGFFORM);  <input type="hidden" name="versions" value="1" />
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">  <div class="LC_left_float">
  $uploadtag  <fieldset>
  <input type="hidden" name="importdetail"  <legend>$lt{'cd'}</legend>
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />  <select name="timerange">
  <span class="LC_nobreak">  <option value='all'$allsel>$lt{'al'}</option>
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />  <option value="-1"$startsel>$lt{'st'}</option>
  $help{'Group Files'}  <option value="2592000"$monthsel>$lt{'lm'}</option>
  </span>  <option value="604800"$weeksel>$lt{'lw'}</option>
  </form>  <option value="86400"$daysel>$lt{'sy'}</option>
 NGFFORM  </select>
   <input type="submit" name="display" value="$lt{'sd'}" />
   </fieldset>
            $r->print(<<ENDFORM);  </div>
 <br />  <div class="LC_left_float">
 $newfolderform  <fieldset>
 <br />  <legend>$lt{'act'}</legend>
 $newpageform  $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
 <br />  $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
 $newsylform  </fieldset>
 <br />  </div>
 $newnavform  <br clear="all" />
 <br />  <hr />
 $newsmppageform  <h4>$lt{'vers'}</h4>
 <br />  <input type="submit" name="setversions" value="$lt{'save'}" />
 $newsmpproblemform  ENDHEADERS
 <br />      #number of columns for version history
 $newdropboxform      $r->print(
 <br />          &Apache::loncommon::start_data_table().
 $newexuploadform          &Apache::loncommon::start_data_table_header_row().
 <br />          '<th>'.&mt('Resources').'</th>'.
 $newbulform          "<th>$lt{'mr'}</th>".
 <br />          "<th>$lt{'ve'}</th>".
 $newaboutmeform          "<th>$lt{'vu'}</th>".
 <br />          '<th>'.&mt('History').'</th>'.
 $newaboutsomeoneform          &Apache::loncommon::end_data_table_header_row()
 <br />      );
 $newgroupfileform      foreach my $key (sort(keys(%changes))) {
 <br />          #excludes not versionable problems from resource version history:
 $newrosterform          next unless ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/);
 ENDFORM          my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
        }          my $currentversion=&Apache::lonnet::getversion($key);
        if ($env{'form.pagepath'}) {          if ($currentversion<0) {
            $r->print(<<ENDBLOCK);              $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
 $newsmpproblemform          }
 <br />          my $linkurl=&Apache::lonnet::clutter($key);
 $newexuploadform          $r->print(
 ENDBLOCK              &Apache::loncommon::start_data_table_row().
        }              '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
        $r->print('</td></tr>'."\n".              '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
 '</table>');              '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
        $r->print('</td></tr>');              &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
     }              '<td align="right">'
 # ----------------------------------------------------- Supplemental documents          );
     if (!$forcestandard) {          # Used in course
        $r->print('<tr><td class="LC_docs_document">');          my $usedversion=$hash{'version_'.$linkurl};
 # '<h2>'.&mt('Supplemental Course Documents').          if (($usedversion) && ($usedversion ne 'mostrecent')) {
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');                  if ($usedversion != $currentversion) {
        my $folder=$env{'form.folder'};                      $r->print('<span class="LC_warning">'.$usedversion.'</span>');
        unless ($folder=~/^supplemental/) {                  } else {
    $folder='supplemental';                      $r->print($usedversion);
        }                  }
        if ($folder =~ /^supplemental$/ &&              } else {
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {                  $r->print($currentversion);
           $env{'form.folderpath'} = 'supplemental&'.              }
                                     &escape(&mt('Supplemental '.$type.' Documents'));          $r->print('</td><td title="'.$lt{'vu'}.'">');
        }          # Set version
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);          $r->print(&Apache::loncommon::select_form(
        if ($error) {              $setversions{$linkurl},
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');              'set_version_'.$linkurl,
        }              {'select_form_order' => ['',1..$currentversion,'mostrecent'],
        if ($allowed) {               '' => '',
    my $folderseq=               'mostrecent' => &mt('most recent'),
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.               map {$_,$_} (1..$currentversion)}));
        '.sequence';          my $lastold=1;
           for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');              my $url=$root.'.'.$prevvers.'.'.$extension;
               if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
  my $supupdocform=(<<SUPDOCFORM);                  $lastold=$prevvers;
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">              }
  $fileupload          }
  <br />          $r->print('</td>');
  <br />          # List all available versions
  <span class="LC_nobreak">          $r->print('<td valign="top"><span class="LC_fontsize_medium">');
  $checkbox          for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
  </span>              my $url=$root.'.'.$prevvers.'.'.$extension;
  <br /><br />              $r->print(
  $lt{'comment'}:<br />                  '<span class="LC_nobreak">'
  <textarea cols=50 rows=4 name='comment'>                 .'<a href="'.&Apache::lonnet::clutter($url).'">'
  </textarea>                 .&mt('Version [_1]',$prevvers).'</a>'
  <br />                 .' ('.&Apache::lonlocal::locallocaltime(
  <input type="hidden" name="folderpath" value="$path" />                           &Apache::lonnet::metadata($url,'lastrevisiondate'))
  <input type="hidden" name="cmd" value="upload_supplemental" />                 .')');
  <span class="LC_nobreak">              if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
  <input type="submit" value="$lt{'upld'}" />                  $r->print(
  $help{'Uploading_From_Harddrive'}                      ' <a href="/adm/diff?filename='.
  </span>                      &Apache::lonnet::clutter($root.'.'.$extension).
  </form>                      &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
 SUPDOCFORM                      '" target="diffs">'.&mt('Diffs').'</a>');
               }
  my $supnewfolderform=(<<SNFFORM);              $r->print('</span><br />');
  <form action="/adm/coursedocs" method="post" name="supnewfolder">          }
  <input type="hidden" name="folderpath" value="$path" />          $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
  <input type="hidden" name="importdetail" value="" />      }
  <span class="LC_nobreak">      $r->print(
  <input name="newfolder" type="button"          &Apache::loncommon::end_data_table().
  onClick="javascript:makenewfolder(this.form,'$folderseq');"          '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
  value="$lt{'newf'}" /> $help{'Adding_Folders'}          '</form>'
  </span>      );
  </form>  
 SNFFORM      &untiehash();
       $r->print(&endContentScreen());
   }
  my $supnewextform=(<<SNEFORM);  
  <form action="/adm/coursedocs" method="post" name="supnewext">  sub mark_hash_old {
  <input type="hidden" name="folderpath" value="$path" />      my $retie_hash=0;
  <input type="hidden" name="importdetail" value="" />      if ($hashtied) {
  <span class="LC_nobreak">   $retie_hash=1;
  <input name="newext" type="button"   &untiehash();
  onClick="javascript:makenewext('supnewext');"      }
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      &tiehash('write');
  </span>      $hash{'old'}=1;
  </form>      &untiehash();
 SNEFORM      if ($retie_hash) { &tiehash(); }
   }
  my $supnewsylform=(<<SNSFORM);  
  <form action="/adm/coursedocs" method="post" name="supnewsyl">  sub is_hash_old {
  <input type="hidden" name="folderpath" value="$path" />      my $untie_hash=0;
  <input type="hidden" name="importdetail"      if (!$hashtied) {
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />   $untie_hash=1;
  <span class="LC_nobreak">   &tiehash();
  <input name="newsyl" type="submit" value="$lt{'syll'}" />      }
  $help{'Syllabus'}      my $return=$hash{'old'};
  </span>      if ($untie_hash) { &untiehash(); }
  </form>      return $return;
 SNSFORM  }
   
  my $supnewaboutmeform=(<<SNAMFORM);  sub changewarning {
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">      my ($r,$postexec,$message,$url)=@_;
  <input type="hidden" name="folderpath" value="$path" />      if (!&is_hash_old()) { return; }
  <input type="hidden" name="importdetail"      my $pathvar='folderpath';
  value="$plainname=/adm/$udom/$uname/aboutme" />      my $path=&escape($env{'form.folderpath'});
  <span class="LC_nobreak">      if (!defined($url)) {
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />   $url='/adm/coursedocs?'.$pathvar.'='.$path;
  $help{'My Personal Info'}      }
  </span>      my $course_type = &Apache::loncommon::course_type();
  </form>      if (!defined($message)) {
 SNAMFORM   $message='Changes will become active for your current session after [_1], or the next time you log in.';
       }
    $r->print(<<ENDSUPFORM);      $r->print("\n\n".
 <ul class="LC_TabContent">  '<script type="text/javascript">'."\n".
 <li>$lt{'nd'}</li>  '// <![CDATA['."\n".
 <li>$lt{'sd'}</li>  'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
 <li>$lt{'hao'}</li>  '// ]]>'."\n".
 </ul>  '</script>'."\n".
 <table class="LC_docs_adddocs">  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 <tr><td>  '<input type="hidden" name="orgurl" value="'.$url.
 $supupdocform  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
 </td>  &mt($message,' <input type="hidden" name="'.
 <td>      $env{'request.role'}.'" value="1" /><input type="button" value="'.
 $supnewfolderform      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
 <br />  $help{'Caching'}.'</p></form>'."\n\n");
 $supnewextform  }
 <br />  
 $supnewsylform  
 <br />  sub init_breadcrumbs {
 $supnewaboutmeform      my ($form,$text)=@_;
 </td></tr>      &Apache::lonhtmlcommon::clear_breadcrumbs();
 </table></td></tr>      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
 ENDSUPFORM      text=>&Apache::loncommon::course_type().' Editor',
        }      faq=>273,
     }      bug=>'Instructor Interface',
     $r->print('</table>');                                              help => 'Docs_Adding_Course_Doc'});
     if ($allowed) {      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
  $r->print('      text=>$text,
 <form method="post" name="extimport" action="/adm/coursedocs">      faq=>273,
   <input type="hidden" name="title" />      bug=>'Instructor Interface'});
   <input type="hidden" name="url" />  }
   <input type="hidden" name="useform" />  
   <input type="hidden" name="residx" />  # subroutine to list form elements
 </form>');  sub create_list_elements {
     }     my @formarr = @_;
   } else {     my $list = '';
       unless ($upload_result eq 'phasetwo') {     foreach my $button (@formarr){
 # -------------------------------------------------------- This is showdoc mode          foreach my $picture (keys(%{$button})) {
           $r->print("<h1>".&mt('Uploaded Document').' - '.              $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.          }
 &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>');     return $list;
       }  }
   }  
  }  # subroutine to create ul from list elements
  $r->print(&Apache::loncommon::end_page());  sub create_form_ul {
  return OK;     my $list = shift;
 }     my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
      return $ul;
   }
 sub editing_js {  
     my ($udom,$uname) = @_;  #
     my $now = time();  # Start tabs
     my %lt = &Apache::lonlocal::texthash(  #
                                           p_mnf => 'Name of New Folder',  
                                           t_mnf => 'New Folder',  sub startContentScreen {
                                           p_mnp => 'Name of New Page',      my ($mode) = @_;
                                           t_mnp => 'New Page',      my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
                                           p_mxu => 'Title for the Uploaded Score',      if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
                                           p_msp => 'Title for the Page',          $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";
                                           p_msb => 'Title for the Problem',          $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";
                                           p_mdb => 'Title for the Drop Box',          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
                                           p_mbb => 'Title for the Bulletin Board',      } else {
                                           p_mab => "Enter user:domain for User's 'About Me' Page",          $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";
                                           p_mab2 => "About [_99]",          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
                                           p_mab_alrt1 => 'Not a valid user:domain',          $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";
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',                     '><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>';
                                           p_chn => 'New Title',      }
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',      $output .= "\n".'</ul>'."\n";
                                           p_rmr2a => 'Remove[_99]',      $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
                                           p_rmr2b => '?[_99]',                 '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',                 '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',      return $output;
                                           p_ctr2a => 'Cut[_98]',  }
                                           p_ctr2b => '?[_98]'  
                                         );  #
   # End tabs
     return <<ENDNEWSCRIPT;  #
 function makenewfolder(targetform,folderseq) {  
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');  sub endContentScreen {
     if (foldername) {      return '</div></div></div>';
        targetform.importdetail.value=escape(foldername)+"="+folderseq;  }
         targetform.submit();  
     }  sub supplemental_base {
 }      return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
   }
 function makenewpage(targetform,folderseq) {  
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');  sub handler {
     if (pagename) {      my $r = shift;
         targetform.importdetail.value=escape(pagename)+"="+folderseq;      &Apache::loncommon::content_type($r,'text/html');
         targetform.submit();      $r->send_http_header;
     }      return OK if $r->header_only;
 }  
   # get course data
 function makenewext(targetname) {      my $crstype = &Apache::loncommon::course_type();
     this.document.forms.extimport.useform.value=targetname;      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
     this.document.forms.extimport.title.value='';      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
     this.document.forms.extimport.url.value='';  
     this.document.forms.extimport.residx.value='';  # graphics settings
     window.open('/adm/rat/extpickframe.html');      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
 }  
   #
 function edittext(targetname,residx,title,url) {  # --------------------------------------------- Initialize help topics for this
     this.document.forms.extimport.useform.value=targetname;      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
     this.document.forms.extimport.residx.value=residx;                 'Adding_External_Resource','Navigate_Content',
     this.document.forms.extimport.url.value=url;                 'Adding_Folders','Docs_Overview', 'Load_Map',
     this.document.forms.extimport.title.value=title;                 'Supplemental','Score_Upload_Form','Adding_Pages',
     window.open('/adm/rat/extpickframe.html');                 'Importing_LON-CAPA_Resource','Importing_IMS_Course',
 }                         'Uploading_From_Harddrive',
                  'Check_Resource_Versions','Verify_Content') {
 function makeexamupload() {   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
    var title=prompt('$lt{"p_mxu"}');      }
    if (title) {      # Composite help files
     this.document.forms.newexamupload.importdetail.value=      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
  escape(title)+'=/res/lib/templates/examupload.problem';      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
     this.document.forms.newexamupload.submit();      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
    }      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 }      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
       'Option_Response_Simple');
 function makesmppage() {      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
    var title=prompt('$lt{"p_msp"}');      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
    if (title) {      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
     this.document.forms.newsmppg.importdetail.value=    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
  escape(title)+'=/adm/$udom/$uname/$now/smppg';      $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
     this.document.forms.newsmppg.submit();      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
    }  
 }      
       my $allowed;
 function makesmpproblem() {  # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
    var title=prompt('$lt{"p_msb"}');      unless ($r->uri eq '/adm/supplemental') {
    if (title) {          # does this user have privileges to modify content.  
     this.document.forms.newsmpproblem.importdetail.value=          $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
  escape(title)+'=/res/lib/templates/simpleproblem.problem';      }
     this.document.forms.newsmpproblem.submit();  
    }      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
 }                                              'inhibitmenu']);
     if ($allowed && $env{'form.chooseserver'}) {
 function makedropbox() {        &choose_dump_server($r);
    var title=prompt('$lt{"p_mdb"}');        return OK;
    if (title) {    } elsif ($allowed && $env{'form.verify'}) {
     this.document.forms.newdropbox.importdetail.value=        &init_breadcrumbs('verify','Verify Content');
         escape(title)+'=/res/lib/templates/DropBox.problem';        &verifycontent($r);
     this.document.forms.newdropbox.submit();    } elsif ($allowed && $env{'form.listsymbs'}) {
    }        &init_breadcrumbs('listsymbs','List Content IDs');
 }        &list_symbs($r);
     } elsif ($allowed && $env{'form.docslog'}) {
 function makebulboard() {        &init_breadcrumbs('docslog','Show Log');
    var title=prompt('$lt{"p_mbb"}');        my $folder = $env{'form.folder'};
    if (title) {        if ($folder eq '') {
     this.document.forms.newbul.importdetail.value=            $folder='default';
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';        }
     this.document.forms.newbul.submit();        &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
    }    } elsif ($allowed && $env{'form.versions'}) {
 }        &init_breadcrumbs('versions','Check/Set Resource Versions');
         &checkversions($r);
 function makeabout() {    } elsif ($allowed && $env{'form.dumpcourse'}) {
    var user=prompt("$lt{'p_mab'}");        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
    if (user) {        &dumpcourse($r);
        var comp=new Array();    } elsif ($allowed && $env{'form.exportcourse'}) {
        comp=user.split(':');        &init_breadcrumbs('exportcourse','IMS Export');
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {        &Apache::imsexport::exportcourse($r);
    if ((comp[0]) && (comp[1])) {    } else {
        this.document.forms.newaboutsomeone.importdetail.value=  #
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';  # Done catching special calls
        this.document.forms.newaboutsomeone.submit();  # The whole rest is for course and supplemental documents and utilities menu
    } else {  # Get the parameters that may be needed
                alert("$lt{'p_mab_alrt1'}");  #
            }      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
        } else {                                              ['folderpath',
            alert("$lt{'p_mab_alrt2'}");                                               'forcesupplement','forcestandard',
        }                                               'tools','symb','command','supppath']);
    }  
 }  # standard=1: this is a "new-style" course with an uploaded map as top level
   # standard=2: this is a "old-style" course, and there is nothing we can do
 function makeims() {  
     var caller = document.forms.ims.folder.value;      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";  
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");  # Decide whether this should display supplemental or main content or utilities
     newWindow.location.href = newlocation;  # supplementalflag=1: show supplemental documents
 }  # supplementalflag=0: show standard documents
   # toolsflag=1: show utilities
   
 function finishpick() {  
     var title=this.document.forms.extimport.title.value;      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
     var url=this.document.forms.extimport.url.value;      if (($env{'form.folderpath'}=~/^default/) || ($env{'form.folderpath'} eq "")) {
     var form=this.document.forms.extimport.useform.value;         $supplementalflag=0;
     var residx=this.document.forms.extimport.residx.value;      }
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');      if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 }      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
       unless ($allowed) { $supplementalflag=1; }
 function changename(folderpath,index,oldtitle,container,pagesymb) {      unless ($standard) { $supplementalflag=1; }
     var title=prompt('$lt{"p_chn"}',oldtitle);      my $toolsflag=0;
     if (title) {      if ($env{'form.tools'}) { $toolsflag=1; }
  this.document.forms.renameform.markcopy.value=-1;  
  this.document.forms.renameform.title.value=title;      my $script='';
  this.document.forms.renameform.cmd.value='rename_'+index;      my $showdoc=0;
         if (container == 'sequence') {      my $addentries = {};
     this.document.forms.renameform.folderpath.value=folderpath;      my $container;
         }      my $containertag;
         if (container == 'page') {      my $pathitem;
             this.document.forms.renameform.pagepath.value=folderpath;  
             this.document.forms.renameform.pagesymb.value=pagesymb;  # Do we directly jump somewhere?
         }  
         this.document.forms.renameform.submit();     if (($env{'form.command'} eq 'direct') || ($env{'form.command'} eq 'directnav')) {
     }         if ($env{'form.symb'} ne '') {
 }             $env{'form.folderpath'}=
                  &Apache::loncommon::symb_to_docspath($env{'form.symb'});
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {             &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {                 $env{'form.command'}.'_'.$env{'form.symb'}});
  this.document.forms.renameform.markcopy.value=-1;         } elsif ($env{'form.supppath'} ne '') {
  this.document.forms.renameform.cmd.value='del_'+index;             $env{'form.folderpath'}=$env{'form.supppath'};
         if (container == 'sequence') {             &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
             this.document.forms.renameform.folderpath.value=folderpath;                 $env{'form.command'}.'_'.$env{'form.supppath'}});
         }         }
         if (container == 'page') {     } elsif ($env{'form.command'} eq 'editdocs') {
             this.document.forms.renameform.pagepath.value=folderpath;         $env{'form.folderpath'} = 'default&'.
             this.document.forms.renameform.pagesymb.value=pagesymb;                                   &Apache::lonhtmlcommon::entity_encode('Main Course Content').
         }                                   ':::::';
         this.document.forms.renameform.submit();         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => $env{'form.command'}});
     }     } elsif ($env{'form.command'} eq 'editsupp') {
 }         $env{'form.folderpath'} = 'supplemental&'.
                                     &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/supplemental'});
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {     } elsif ($env{'form.command'} eq 'contents') {
  this.document.forms.renameform.cmd.value='cut_'+index;         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/navmaps'});
  this.document.forms.renameform.markcopy.value=index;     } elsif ($env{'form.command'} eq 'home') {
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/menu'});
         if (container == 'sequence') {     }
             this.document.forms.renameform.folderpath.value=folderpath;  
         }  
         if (container == 'page') {  # Where do we store these for when we come back?
             this.document.forms.renameform.pagepath.value=folderpath;      my $stored_folderpath='docs_folderpath';
             this.document.forms.renameform.pagesymb.value=pagesymb;      if ($supplementalflag) {
         }         $stored_folderpath='docs_sup_folderpath';
         this.document.forms.renameform.submit();      }
     }  
 }  # No folderpath, and in edit mode, see if we have something stored
       if ((!$env{'form.folderpath'}) && $allowed) {
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {          &Apache::loncommon::restore_course_settings($stored_folderpath,
     this.document.forms.renameform.markcopy.value=index;                                            {'folderpath' => 'scalar'});
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;          unless (&unescape($env{'form.folderpath'}) =~ m{^(default|supplemental)&}) {
     if (container == 'sequence') {              undef($env{'form.folderpath'});
  this.document.forms.renameform.folderpath.value=folderpath;          }
     }      }
     if (container == 'page') {     
  this.document.forms.renameform.pagepath.value=folderpath;  # If we are not allowed to make changes, all we can see are supplemental docs
  this.document.forms.renameform.pagesymb.value=pagesymb;      if (!$allowed) {
     }          unless ($env{'form.folderpath'} =~ /^supplemental/) {
     this.document.forms.renameform.submit();              $env{'form.folderpath'} = &supplemental_base();
 }          }
       }
   # Make the zeroth entry in supplemental docs page paths, so we can get to top level
 ENDNEWSCRIPT      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 }          $env{'form.folderpath'} = &supplemental_base()
 1;                                    .'&'.
 __END__                                    $env{'form.folderpath'};
       }
   # If after all of this, we still don't have any paths, make them
 =head1 NAME      unless ($env{'form.folderpath'}) {
          if ($supplementalflag) {
 Apache::londocs.pm            $env{'form.folderpath'}=&supplemental_base();
          } else {
 =head1 SYNOPSIS            $env{'form.folderpath'}='default'.&escape(&mt('Main '.$crstype.' Documents')).
                                     ':::::';
 This is part of the LearningOnline Network with CAPA project         }
 described at http://www.lon-capa.org.      }
   
 =head1 SUBROUTINES  # Store this
       unless ($toolsflag) {
 =over          if ($allowed) {
               &Apache::loncommon::store_course_settings($stored_folderpath,
 =item %help=()                                                        {'folderpath' => 'scalar'});
           }
 Available help topics          my $folderpath;
           if ($env{'form.folderpath'}) {
 =item mapread()              $folderpath = $env{'form.folderpath'};
       my (@folders)=split('&',$env{'form.folderpath'});
 Mapread read maps into LONCAPA::map:: global arrays      $env{'form.foldername'}=&unescape(pop(@folders));
 @order and @resources, determines status              if ($env{'form.foldername'} =~ /\:1$/) {
 sets @order - pointer to resources in right order                  $container = 'page';
 sets @resources - array with the resources with correct idx              } else {
                   $container = 'sequence';
 =item authorhosts()              }
       $env{'form.folder'}=pop(@folders);
 Return hash with valid author names          } else {
               if ($env{'form.folder'} eq '' ||
 =item dumpbutton()                  $env{'form.folder'} eq 'supplemental') {
                   $folderpath='default&'.
 Generate "dump" button                              &escape(&mt('Main '.$crstype.' Documents')).
                               ':::::';
 =item clean()              }
           }
 =item dumpcourse()          $containertag = '<input type="hidden" name="folderpath" value="" />';
           $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
     Actually dump course          if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
              $showdoc='/'.$1;
           }
 =item exportbutton()          if ($showdoc) { # got called in sequence from course
       $allowed=0; 
     Generate "export" button          } else {
               if ($allowed) {
 =item exportcourse()                  &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                   $script=&Apache::lonratedt::editscript('simple');
 =item create_ims_store()              }
           }
 =item build_package()      }
   
 =item get_dependencies()  # get personal data
       my $uname=$env{'user.name'};
 =item process_content()      my $udom=$env{'user.domain'};
       my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 =item replicate_content()  
       if ($allowed) {
 =item extract_media()          if ($toolsflag) {
               $script .= &inject_data_js();
 =item store_template()              my ($home,$other,%outhash)=&authorhosts();
               if (!$home && $other) {
 =item group_import()                  my @hosts;
                   foreach my $aurole (keys(%outhash)) {
     Imports the given (name, url) resources into the course                      unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
     coursenum, coursedom, and folder must precede the list                          push(@hosts,$outhash{$aurole});
                       }
 =item breadcrumbs()                  }
                   $script .= &dump_switchserver_js(@hosts); 
 =item log_docs()              }
           } else {
 =item docs_change_log()              my @tabids;
               if ($supplementalflag) {
 =item update_paste_buffer()                  @tabids = ('002','ee2','ff2');
               } else {
 =item print_paste_buffer()                  @tabids = ('aa1','bb1','cc1','ff1');
                   unless ($env{'form.folderpath'} =~ /\:1$/) {
 =item do_paste_from_buffer()                      unshift(@tabids,'001');
                       push(@tabids,('dd1','ee1'));
 =item update_parameter()                  }
               }
 =item handle_edit_cmd()              my $tabidstr = join("','",@tabids);
       $script .= &editing_js($udom,$uname,$supplementalflag).
 =item editor()                         &history_tab_js().
                          &inject_data_js().
 =item process_file_upload()                         &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr).
                          &Apache::lonextresedit::extedit_javascript();
 =item process_secondary_uploads()              $addentries = {
                               onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
 =item is_supplemental_title()                            };
           }
 =item parse_supplemental_title()          if ($env{'docs.markedcopy_url'}) {
               $script .= &paste_popup_js(); 
 =item entryline()          }
           my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
 =item tiehash()                               &mt('Switch server?');
           
 =item untiehash()  
       }
 =item checkonthis()  # -------------------------------------------------------------------- Body tag
       $script = '<script type="text/javascript">'."\n"
 check on this                .'// <![CDATA['."\n"
                 .$script."\n"
 =item verifycontent()                .'// ]]>'."\n"
                 .'</script>'."\n";
 Verify Content  
       # Breadcrumbs
 =item devalidateversioncache() & checkversions()      &Apache::lonhtmlcommon::clear_breadcrumbs();
   
 Check Versions      if ($showdoc) {
           $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
 =item mark_hash_old()                                                  {'force_register' => $showdoc,}));
       } elsif ($r->uri eq '/adm/supplemental') {
 =item is_hash_old()          my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype);
           $r->print(&Apache::loncommon::start_page("Supplemental $crstype Content",undef,
 =item changewarning()                                                  {'bread_crumbs' => $brcrum,}));
       } else {
 =item init_breadcrumbs()          &Apache::lonhtmlcommon::add_breadcrumb({
               href=>"/adm/coursedocs",text=>"$crstype Contents"});
 Breadcrumbs for special functions  
           $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
 =back                                                   {'add_entries'    => $addentries}
                                                   )
 =cut                   .&Apache::loncommon::help_open_menu('','',273,'RAT')
                    .&Apache::lonhtmlcommon::breadcrumbs(
                        'Editing '.$crstype.' Contents',
                        'Docs_Adding_Course_Doc')
           );
       }
   
     my %allfiles = ();
     my %codebase = ();
     my ($upload_result,$upload_output,$uploadphase);
     if ($allowed) {
         if (($env{'form.uploaddoc.filename'}) &&
     ($env{'form.cmd'}=~/^upload_(\w+)/)) {
             my $context = $1; 
             # Process file upload - phase one - upload and parse primary file.
     undef($hadchanges);
             $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
                                                 \%allfiles,\%codebase,$context);
     if ($hadchanges) {
         &mark_hash_old();
     }
             $r->print($upload_output);
         } elsif ($env{'form.phase'} eq 'upload_embedded') {
             # Process file upload - phase two - upload embedded objects 
             $uploadphase = 'check_embedded';
             my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
             my $state = &embedded_form_elems($uploadphase,$primaryurl,
                                              $env{'form.newidx'});
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
             my $actionurl = '/adm/coursedocs';
             my ($result,$flag) = 
                 &Apache::loncommon::upload_embedded('coursedoc',$destination,
                     $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
                     $actionurl);
             $r->print($result.&return_to_editor());
         } elsif ($env{'form.phase'} eq 'check_embedded') {
             # Process file upload - phase three - modify references in HTML file
             $uploadphase = 'modified_orightml';
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $result = 
                 &Apache::loncommon::modify_html_refs('coursedoc',$destination,
                                                      $docuname,$docudom,undef,
                                                      $dir_root);
             $r->print($result.&return_to_editor());   
         } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
             $uploadphase = 'decompress_phase_one';
             $r->print(&decompression_phase_one().
                       &return_to_editor());
         } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
             $uploadphase = 'decompress_phase_two';
             $r->print(&decompression_phase_two().
                       &return_to_editor());
         }
     }
   
     if ($allowed && $toolsflag) {
         $r->print(&startContentScreen('tools'));
         $r->print(&generate_admin_menu($crstype));
         $r->print(&endContentScreen());
     } elsif ((!$showdoc) && (!$uploadphase)) {
   # -----------------------------------------------------------------------------
          my %lt=&Apache::lonlocal::texthash(
    'copm' => 'All documents out of a published map into this folder',
                   'upfi' => 'Upload File',
                   'upld' => 'Import Content',
                   'srch' => 'Search',
                   'impo' => 'Import',
    'lnks' => 'Import from Stored Links',
                   'impm' => 'Import from Assembled Map',
                   'selm' => 'Select Map',
                   'load' => 'Load Map',
                   'newf' => 'New Folder',
                   'newp' => 'New Composite Page',
                   'syll' => 'Syllabus',
                   'navc' => 'Table of Contents',
                   'sipa' => 'Simple Course Page',
                   'sipr' => 'Simple Problem',
                   'drbx' => 'Drop Box',
                   'scuf' => 'External Scores (handgrade, upload, clicker)',
                   'bull' => 'Discussion Board',
                   'mypi' => 'My Personal Information Page',
                   'grpo' => 'Group Portfolio',
                   'rost' => 'Course Roster',
                   'abou' => 'Personal Information Page for a User',
                   'imsf' => 'IMS Import',
                   'imsl' => 'Import IMS package',
                   'cms'  => 'Origin of IMS package',
                   'se'   => 'Select',
                   'file' =>  'File',
                   'title' => 'Title',
                   'comment' => 'Comment',
                   'parse' => 'Upload embedded images/multimedia files if HTML file',
     );
   # -----------------------------------------------------------------------------
    my $fileupload=(<<FIUP);
    $lt{'file'}:<br />
    <input type="file" name="uploaddoc" size="40" />
   FIUP
   
    my $checkbox=(<<CHBO);
    <!-- <label>$lt{'parse'}?
    <input type="checkbox" name="parserflag" />
    </label> -->
    <label>
    <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
    </label>
   CHBO
           my $imsfolder = $env{'form.folder'};
           if ($imsfolder eq '') {
               $imsfolder = 'default';  
           }
           my $imspform=(<<IMSFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
           $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
           <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
           <fieldset id="uploadimsform" style="display: none;">
           <legend>$lt{'imsf'}</legend>
           $fileupload
           <br />
           <p>
           $lt{'cms'}:&nbsp; 
           <select name="source">
           <option value="-1" selected="selected">$lt{'se'}</option>
           <option value="bb5">Blackboard 5</option>
           <option value="bb6">Blackboard 6</option>
           <option value="angel5">ANGEL 5.5</option>
           <option value="webctce4">WebCT 4 Campus Edition</option>
           </select>
           <input type="hidden" name="folder" value="$imsfolder" />
           </p>
           <input type="hidden" name="phase" value="one" />
           <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" />
           </fieldset>
           </form>
   IMSFORM
   
    my $fileuploadform=(<<FUFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
           <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
           <fieldset id="uploaddocform" style="display: none;">
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="aa" />
    $fileupload
    <br />
    $lt{'title'}:<br />
    <input type="text" size="60" name="comment" />
    $pathitem
    <input type="hidden" name="cmd" value="upload_default" />
    <br />
    <span class="LC_nobreak" style="float:left">
    $checkbox
    </span>
           <br clear="all" />
           <input type="submit" value="$lt{'upld'}" />
           </fieldset>
           </form>
   FUFORM
   
    my $importpubform=(<<SEDFFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleMap('map');">
           $lt{'impm'}</a>$help{'Load_Map'}
    <form action="/adm/coursedocs" method="post" name="mapimportform">
           <fieldset id="importmapform" style="display: none;">
           <legend>$lt{'impm'}</legend>
    <input type="hidden" name="active" value="bb" />
           $lt{'copm'}<br />
           <span class="LC_nobreak">
           <input type="text" name="importmap" size="40" value="" 
           onfocus="this.blur();openbrowser('mapimportform','importmap','sequence,page','');" />
           &nbsp;<a href="javascript:openbrowser('mapimportform','importmap','sequence,page','');">$lt{'selm'}</a></span><br />
           <input type="submit" name="loadmap" value="$lt{'load'}" />
           </fieldset>
           </form>
   
   SEDFFORM
    my @importpubforma = (
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => $pathitem."<a class='LC_menubuttons_link' href='javascript:groupsearch()'>$lt{'srch'}</a>" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{impo}.'"  onclick="javascript:groupimport();"/>' => "<a class='LC_menubuttons_link' href='javascript:groupimport();'>$lt{'impo'}</a>$help{'Importing_LON-CAPA_Resource'}" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{lnks}.'" onclick="javascript:open_StoredLinks_Import();" />' => "<a class='LC_menubuttons_link' href='javascript:open_StoredLinks_Import();'>$lt{'lnks'}</a>" },
           { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/sequence.png" alt="'.$lt{impm}.'" onclick="javascript:toggleMap(\'map\');" />' => $importpubform }
    );
    $importpubform = &create_form_ul(&create_list_elements(@importpubforma));
           my $extresourcesform =
               &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
       if ($allowed) {
           my $folder = $env{'form.folder'};
           if ($folder eq '') {
               $folder='default';
           }
    &update_paste_buffer($coursenum,$coursedom,$folder);
    $r->print(<<HIDDENFORM);
    <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
      <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
      <input type="hidden" name="copyfolder" />
      $containertag
    </form>
   
   HIDDENFORM
           $r->print(&makesimpleeditform($pathitem)."\n".
                     &makedocslogform($pathitem."\n".
                                      '<input type="hidden" name="folder" value="'.
                                      $env{'form.folder'}.'" />'."\n"));
       }
   
   # Generate the tabs
       my ($mode,$needs_end);
       if (($supplementalflag) && (!$allowed)) {
           my @folders = split('&',$env{'form.folderpath'});
           unless (@folders > 2) {
               &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
               $needs_end = 1;
           }
       } else {
           $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
           $needs_end = 1;
       }
   
   #
   
       my $savefolderpath;
   
       if ($allowed) {
          my $folder=$env{'form.folder'};
          if ($folder eq '' || $supplementalflag) {
              $folder='default';
      $savefolderpath = $env{'form.folderpath'};
      $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
              $pathitem = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
          my $postexec='';
          if ($folder eq 'default') {
              $r->print('<script type="text/javascript">'."\n"
                       .'// <![CDATA['."\n"
                       .'this.window.name="loncapaclient";'."\n"
                       .'// ]]>'."\n"
                       .'</script>'."\n"
          );
          } else {
              #$postexec='self.close();';
          }
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.page';
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
   
    my $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'navc'}=/adm/navmaps" />
    <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
    $help{'Navigate_Content'}
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
    $help{'Simple Page'}
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
    $help{'Simple Problem'}
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
    $help{'Score_Upload_Form'}
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
    $help{'Bulletin Board'}
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
    </form>
   NASOFORM
   
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'rost'}=/adm/viewclasslist" />
    <a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
    $help{'Course Roster'}
    </form>
   NROSTFORM
   
   my $specialdocumentsform;
   my @specialdocumentsforma;
   my $gradingform;
   my @gradingforma;
   my $communityform;
   my @communityforma;
   my $newfolderform;
   my $newfolderb;
   
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $newpageform=(<<NPFORM);
    <form action="/adm/coursedocs" method="post" name="newpage">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="cc" />
    <a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
    $help{'Adding_Pages'}
    </form>
   NPFORM
   
   
    $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="aa" />
    <a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
   
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
    $help{'Group Portfolio'}
    </form>
   NGFFORM
    @specialdocumentsforma=(
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
           );
           $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
   
   
           my @importdoc = (
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform}
           );
           unless ($container eq 'page') {
               push(@importdoc,
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform}
               );
           }
           push(@importdoc,
               {'<img class="LC_noBorder_LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'doc\');" />'=>$fileuploadform}
           );
           $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc));
   
           @gradingforma=(
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
   
           );
           $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
   
           @communityforma=(
          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
           );
           $communityform = &create_form_ul(&create_list_elements(@communityforma));
   
   my %orderhash = (
                   'aa' => ['Import Content',$fileuploadform],
                   'bb' => ['Published Content',$importpubform],
                   'cc' => ['Grading Resources',$gradingform],
                   );
   unless ($container eq 'page') {
       $orderhash{'00'} = ['Newfolder',$newfolderform];
       $orderhash{'dd'} = ['Collaboration',$communityform];
       $orderhash{'ee'} = ['Special Pages',$specialdocumentsform];
   }
   
    $hadchanges=0;
          unless (($supplementalflag || $toolsflag)) {
             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                 $supplementalflag,\%orderhash,$iconpath,$pathitem);
             if ($error) {
                $r->print('<p><span class="LC_error">'.$error.'</span></p>');
             }
             if ($hadchanges) {
                &mark_hash_old();
             }
   
             &changewarning($r,'');
           }
       }
   
   # Supplemental documents start here
   
          my $folder=$env{'form.folder'};
          unless ($supplementalflag) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = &supplemental_base();
          } elsif ($allowed) {
     $env{'form.folderpath'} = $savefolderpath;
          }
          $pathitem = '<input type="hidden" name="folderpath" value="'.
                       &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_new.sequence';
   
    my $supupdocform=(<<SUPDOCFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppdoc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
    <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
           <fieldset id="uploadsuppdocform" style="display: none;">
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="ee" />
    $fileupload
    <br />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br /><br />
    $lt{'comment'}:<br />
    <textarea cols="50" rows="4" name="comment"></textarea>
    <br />
    $pathitem
    <input type="hidden" name="cmd" value="upload_supplemental" />
           <input type='submit' value="$lt{'upld'}" />
           </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="active" value="ee" />
           $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
    $help{'Adding_Folders'}
    </form>
   SNFFORM
   
           my $supextform =
               &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="active" value="ff" />
           $pathitem
    <input type="hidden" name="importdetail" 
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="supnewaboutme">
    <input type="hidden" name="active" value="ff" />
           $pathitem
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   SNAMFORM
   
   
   my @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:toggleUpload(\'suppext\')" />'
               =>$supextform},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
               =>$supupdocform},
                      );
   
   $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
   my %suporderhash = (
    '00' => ['Supnewfolder', $supnewfolderform],
                   'ee' => ['Import Content',$supupdocform],
                   'ff' => ['Special Pages',&create_form_ul(&create_list_elements(@specialdocs))]
                   );
           if ($supplementalflag) {
              my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                  $supplementalflag,\%suporderhash,$iconpath,$pathitem);
              if ($error) {
                 $r->print('<p><span class="LC_error">'.$error.'</span></p>');
              }
           }
       } elsif ($supplementalflag) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,'',$iconpath,$pathitem);
           if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
       }
   
       if ($needs_end) {
           $r->print(&endContentScreen());
       }
   
       if ($allowed) {
    $r->print('
   <form method="post" name="extimport" action="/adm/coursedocs">
     <input type="hidden" name="title" />
     <input type="hidden" name="url" />
     <input type="hidden" name="useform" />
     <input type="hidden" name="residx" />
   </form>');
       }
     } elsif ($showdoc) {
   # -------------------------------------------------------- This is showdoc mode
         $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p class="LC_warning">'.
   &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
                   &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
     }
    }
    $r->print(&Apache::loncommon::end_page());
    return OK;
   }
   
   sub embedded_form_elems {
       my ($phase,$primaryurl,$newidx) = @_;
       my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
       return <<STATE;
       <input type="hidden" name="folderpath" value="$folderpath" />
       <input type="hidden" name="cmd" value="upload_embedded" />
       <input type="hidden" name="newidx" value="$newidx" />
       <input type="hidden" name="phase" value="$phase" />
       <input type="hidden" name="primaryurl" value="$primaryurl" />
   STATE
   }
   
   sub embedded_destination {
       my $folder=$env{'form.folder'};
       my $destination = 'docs/';
       if ($folder =~ /^supplemental/) {
           $destination = 'supplemental/';
       }
       if (($folder eq 'default') || ($folder eq 'supplemental')) {
           $destination .= 'default/';
       } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
           $destination .=  $2.'/';
       }
       $destination .= $env{'form.newidx'};
       my $dir_root = '/userfiles';
       return ($destination,$dir_root);
   }
   
   sub return_to_editor {
       my $actionurl = '/adm/coursedocs';
       return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
              '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
              '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
              '</a></p>';
   }
   
   sub decompression_info {
       my ($destination,$dir_root) = &embedded_destination();
       my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
       my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
       my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $container='sequence';
       my ($pathitem,$hiddenelem);
       my @hiddens = ('newidx','comment','position','folderpath');
       if ($env{'form.folderpath'} =~ /\:1$/) {
           $container='page';
       }
       unshift(@hiddens,$pathitem);
       foreach my $item (@hiddens) {
           if ($env{'form.'.$item}) {
               $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
                              $env{'form.'.$item}.'" />'."\n";
           }
       }
       return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
               $hiddenelem);
   }
   
   sub decompression_phase_one {
       my ($dir,$file,$warning,$error,$output);
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/\E(?:docs|supplemental)/(?:default|\d+).*/([^/]+)$}) {
           $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
       } else {
           my $file = $1;
           $output = 
               &Apache::loncommon::process_decompression($docudom,$docuname,$file,
                                                         $destination,$dir_root,
                                                         $hiddenelem);
           if ($env{'form.autoextract_camtasia'}) {
               $output .= &remove_archive($docudom,$docuname,$container);
           }
       }
       if ($error) {
           $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                      $error.'</p>'."\n";
       }
       if ($warning) {
           $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
       }
       return $output;
   }
   
   sub decompression_phase_two {
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       my $output;
       if ($env{'form.archivedelete'}) {
           $output = &remove_archive($docudom,$docuname,$container);
       }
       $output .= 
           &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
                                                       $destination,$dir_root,$hiddenelem);
       return $output;
   }
   
   sub remove_archive {
       my ($docudom,$docuname,$container) = @_;
       my $map = $env{'form.folder'}.'.'.$container;
       my ($output,$delwarning,$delresult,$url);
       my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
       if ($fatal) {
           if ($container eq 'page') {
               $delwarning = &mt('An error occurred retrieving the contents of the current page.');
           } else {
               $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
           }
           $delwarning .= &mt('As a result the archive file has not been removed.');
       } else {
           my $currcmd = $env{'form.cmd'};
           my $position = $env{'form.position'};
           if ($position > 0) { 
               $env{'form.cmd'} = 'del_'.$position;
               my ($title,$url,@rrest) = 
                   split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$position]]);
               if (&handle_edit_cmd($docuname,$docudom)) {
                   ($errtext,$fatal) = &storemap($docuname,$docudom,$map,1);
                   if ($fatal) {
                       if ($container eq 'page') {
                           $delwarning = &mt('An error occurred updating the contents of the current page.');
                       } else {
                           $delwarning = &mt('An error occurred updating the contents of the current folder.');
                       }
                   } else {
                       $delresult = &mt('Archive file removed.');
                   }
               }
           }
           $env{'form.cmd'} = $currcmd;
       }
       if ($delwarning) {
           $output = '<p class="LC_warning">'.
                      $delwarning.
                      '</p>';
       }
       if ($delresult) {
           $output .= '<p class="LC_info">'.
                      $delresult.
                      '</p>';
       }
       return $output;
   }
   
   sub generate_admin_menu {
       my ($crstype) = @_;
       my $lc_crstype = lc($crstype);
       my ($home,$other,%outhash)=&authorhosts();
       my %lt=&Apache::lonlocal::texthash (
                                            'vc'   => 'Verify Content',
                                            'cv'   => 'Check/Set Resource Versions',
                                            'ls'   => 'List Resource Identifiers',
                                            'imse' => 'Export contents to IMS Archive',
                                            'dcd'  => "Dump $crstype Content to Authoring Space",
                                          );
       my ($candump,$dumpurl);
       if ($home + $other > 0) {
           $candump = 'F';
           if ($home) {
               $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
           } else {
               my @hosts;
               foreach my $aurole (keys(%outhash)) {
                   unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                       push(@hosts,$outhash{$aurole});
                   }  
               }
               if (@hosts == 1) {
                   my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
                                  '&amp;role='.
                                  &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
                                  &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
                   $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
               } else {
                   $dumpurl = "javascript:choose_switchserver_window()";
               }
           }
       }
       my @menu=
           ({  categorytitle=>'Administration',
               items =>[
                   {   linktext   => $lt{'vc'},
                       url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
                       permission => 'F',
                       help       => 'Verify_Content',
                       icon       => 'verify.png',
                       linktitle  => 'Verify contents can be retrieved/rendered',
                   },
                   {   linktext => $lt{'cv'},
                       url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
                       permission => 'F',
                       help       => 'Check_Resource_Versions',
                       icon       => 'resversion.png',
                       linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
                   },
                   {   linktext   => $lt{'ls'},
                       url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
                       permission => 'F',
                       #help => '',
                       icon       => 'symbs.png',
                       linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
                   },
                   ]
           },
           {   categorytitle=>'Export',
               items =>[
                   {   linktext   => $lt{'imse'},
                       url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
                       permission => 'F',
                       help       => 'Docs_Export_Course_Docs',
                       icon       => 'imsexport.png',
                       linktitle  => $lt{'imse'},
                   },
                   {   linktext   => $lt{'dcd'},
                       url        => $dumpurl,
                       permission => $candump,
                       #help => '',
                       icon       => 'dump.png',
                       linktitle  => $lt{'dcd'},
                   },
                   ]
           });
       return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
              '<input type="hidden" id="dummy" />'."\n".
              &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
              '</form>';
   }
   
   sub generate_edit_table {
       my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile) = @_;
       return unless(ref($orderhash_ref) eq 'HASH');
       my %orderhash = %{$orderhash_ref};
       my $form;
       my $activetab;
       my $active;
       if (($env{'form.active'} ne '') && ($env{'form.active'} ne 'aa')) {
           $activetab = $env{'form.active'};
       }
       my $backicon = $iconpath.'clickhere.gif';
       my $backtext = &mt('Exit Editor');
       $form = '<div class="LC_Box" style="margin:0;">'.
               '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
               '<li class="goback">'.
               '<a href="javascript:toContents('.$jumpto.');">'.
               '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
               '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n".
               '<li>'.
               '<a href="javascript:groupopen('."'$readfile'".',1);">'.
               &mt('Undo Delete').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li class="active">';
       } else {
           $form .= '<li>';
       }
       $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
                &mt('History').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
                    &mt('Edit').'</a></li>'."\n";
       }
       foreach my $name (reverse(sort(keys(%orderhash)))) {
           if($name ne '00'){
               if($activetab eq '' || $activetab ne $name){
                  $active = '';
               }elsif($activetab eq $name){
                  $active = 'class="active"';
               }
               $form .= '<li style="float:right" '.$active
                   .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
           } else {
       $form .= '<li '.$active.' style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
   
    }
       }
       $form .= '</ul>'."\n";
       $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
   
       if ($to_show ne '') {
           $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'."\n";
       }
       foreach my $field (keys(%orderhash)){
    if($field ne '00'){
               if($activetab eq '' || $activetab ne $field){
                   $active = 'style="display: none;float:left"';
               }elsif($activetab eq $field){
                   $active = 'style="display:block;float:left"';
               }
               $form .= '<div id="'.$field.$tid.'"'
                       .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
                       .'</div>'."\n";
           }
       }
       unless ($env{'form.docslog'}) {
           $form .= '</div></div>'."\n";
       }
       return $form;
   }
   
   sub editing_js {
       my ($udom,$uname,$supplementalflag) = @_;
       my %lt = &Apache::lonlocal::texthash(
                                             p_mnf => 'Name of New Folder',
                                             t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
                                             t_mnp => 'New Page',
                                             p_mxu => 'Title for the External Score',
                                             p_msp => 'Name of Simple Course Page',
                                             p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Discussion Board',
                                             p_mab => "Enter user:domain for User's Personal Information Page",
                                             p_mab2 => 'Personal Information Page of ',
                                             p_mab_alrt1 => 'Not a valid user:domain',
                                             p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                             p_chn => 'New Title',
                                             p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
                                             p_rmr2a => 'Remove[_99]',
                                             p_rmr2b => '?[_99]',
                                             p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                             p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                             p_ctr2a => 'Cut[_98]',
                                             p_ctr2b => '?[_98]',
                                             rpck    => 'Enter number to pick (e.g., 3)',
                                             imsfile => 'You must choose an IMS package for import',
                                             imscms  => 'You must select which Course Management System was the source of the IMS package',
                                             invurl  => 'Invalid URL',
                                             titbl   => 'Title is blank',
                                           );
   
       my $crstype = &Apache::loncommon::course_type();
       my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
       my $main_container_page;
       if (&HTML::Entities::decode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'}) =~ /\:1$/) {
           $main_container_page = 1;
       }
       my $toplevelmain = 'default&Main%20'.$crstype.'%20Documents%3A%3A%3A%3A%3A';
       my $toplevelsupp = &supplemental_base();
   
       my $backtourl;
       if ($env{'docs.exit.'.$env{'request.course.id'}} =~ /^direct_(.+)$/) {
           my $caller = $1;
           if ($caller =~ /^supplemental/) {
               $backtourl = '/adm/supplemental?folderpath='.&escape($caller);
           } else {
               my ($map,$id,$res)=&Apache::lonnet::decode_symb($caller);
               $res = &Apache::lonnet::clutter($res);
               if (&Apache::lonnet::is_on_map($res)) {
                   $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($res),'<>&"').'?symb='.
                                &HTML::Entities::encode($caller,'<>&"');
               }
           }
       } elsif ($env{'docs.exit.'.$env{'request.course.id'}} eq '/adm/menu') {
           $backtourl = '/adm/menu';
       } elsif ($supplementalflag) {
           $backtourl = '/adm/supplemental';
       } else {
           $backtourl = '/adm/navmaps';
       }
   
       my $fieldsets = "'ext','doc'";
       unless ($main_container_page) {
           $fieldsets .=",'ims'";
       }
       if ($supplementalflag) {
           $fieldsets = "'suppext','suppdoc'";
       }
   
       return <<ENDNEWSCRIPT;
   function makenewfolder(targetform,folderseq) {
       var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
       if (foldername) {
          targetform.importdetail.value=escape(foldername)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makenewpage(targetform,folderseq) {
       var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
       if (pagename) {
           targetform.importdetail.value=escape(pagename)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makeexamupload() {
      var title=prompt('$lt{"p_mxu"}');
      if (title) {
       this.document.forms.newexamupload.importdetail.value=
    escape(title)+'=/res/lib/templates/examupload.problem';
       this.document.forms.newexamupload.submit();
      }
   }
   
   function makesmppage() {
      var title=prompt('$lt{"p_msp"}');
      if (title) {
       this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/new/smppg';
       this.document.forms.newsmppg.submit();
      }
   }
   
   function makesmpproblem() {
      var title=prompt('$lt{"p_msb"}');
      if (title) {
       this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
       this.document.forms.newsmpproblem.submit();
      }
   }
   
   function makedropbox() {
      var title=prompt('$lt{"p_mdb"}');
      if (title) {
       this.document.forms.newdropbox.importdetail.value=
           escape(title)+'=/res/lib/templates/DropBox.problem';
       this.document.forms.newdropbox.submit();
      }
   }
   
   function makebulboard() {
      var title=prompt('$lt{"p_mbb"}');
      if (title) {
       this.document.forms.newbul.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/new/bulletinboard';
       this.document.forms.newbul.submit();
      }
   }
   
   function makeabout() {
      var user=prompt("$lt{'p_mab'}");
      if (user) {
          var comp=new Array();
          comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
      if ((comp[0]) && (comp[1])) {
          this.document.forms.newaboutsomeone.importdetail.value=
      '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
          this.document.forms.newaboutsomeone.submit();
      } else {
          alert("$lt{'p_mab_alrt1'}");
      }
   } else {
      alert("$lt{'p_mab_alrt2'}");
   }
   }
   }
   
   function toggleUpload(caller) {
       var blocks = Array($fieldsets);
       for (var i=0; i<blocks.length; i++) {
           var disp = 'none';
           if (caller == blocks[i]) {
               var curr = document.getElementById('upload'+caller+'form').style.display;
               if (curr == 'none') {
                   disp='block';
               }
           }
           document.getElementById('upload'+blocks[i]+'form').style.display=disp;
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   function toggleMap(caller) {
       var disp = 'none';
       if (document.getElementById('importmapform')) {
           if (caller == 'map') {
               var curr = document.getElementById('importmapform').style.display;
               if (curr == 'none') {
                   disp='block';
               }
           }
           document.getElementById('importmapform').style.display=disp;
           resize_scrollbox('contentscroll','1','1');
       }
       return;
   }
   
   function makeims(imsform) {
       if ((imsform.uploaddoc.value == '')  || (!imsform.uploaddoc.value)) {
           alert("$lt{'imsfile'}");
           return;
       }
       if (imsform.source.selectedIndex == 0) {
           alert("$lt{'imscms'}");
           return;
       }
       newWindow = window.open('', 'IMSimport',"HEIGHT=700,WIDTH=750,scrollbars=yes");
       imsform.submit();
   }
   
   function changename(folderpath,index,oldtitle) {
   var title=prompt('$lt{"p_chn"}',oldtitle);
   if (title) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.title.value=title;
   this.document.forms.renameform.cmd.value='rename_'+index;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   }
   
   function removeres(folderpath,index,oldtitle,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.cmd.value='del_'+index;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   }
   
   function cutres(folderpath,index,oldtitle,container,folder,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
   this.document.forms.renameform.cmd.value='cut_'+index;
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   }
   
   function markcopy(folderpath,index,oldtitle,container,folder) {
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   
   function updatePick(targetform,index,caller) {
       var pickitem = document.getElementById('rpick_'+index);
       var picknumitem = document.getElementById('rpicknum_'+index);
       if (pickitem.checked) {
           var picknum=prompt('$lt{"rpck"}',picknumitem.value);
           if (picknum == '' || picknum == null) {
               if (caller == 'check') {
                   pickitem.checked=false;
                   return;
               }
           } else {
               picknum.toString();
               var regexdigit=/^\\d+\$/;
               if (regexdigit.test(picknum)) {
                   picknumitem.value = picknum;
                   targetform.changeparms.value='randompick';
                   targetform.submit();
               } else {
                   if (caller == 'check') {
                       pickitem.checked=false;
                   }
                   return;
               }
           }
       } else {
           picknumitem.value = 0;
           targetform.changeparms.value='randompick';
           targetform.submit();
       }
   }
   
   function unselectInactive(nav) {
   currentNav = document.getElementById(nav);
   currentLis = currentNav.getElementsByTagName('LI');
   for (i = 0; i < currentLis.length; i++) {
           if (currentLis[i].className == 'goback') {
               currentLis[i].className = 'goback';
           } else {
       if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
    currentLis[i].className = 'right';
       } else {
    currentLis[i].className = 'i';
       }
           }
   }
   }
   
   function hideAll(current, nav, data) {
   unselectInactive(nav);
   if(current.className == 'right'){
    current.className = 'right active'
    }else{
    current.className = 'active';
   }
   currentData = document.getElementById(data);
   currentDivs = currentData.getElementsByTagName('DIV');
   for (i = 0; i < currentDivs.length; i++) {
    if(currentDivs[i].className == 'LC_ContentBox'){
    currentDivs[i].style.display = 'none';
    }
   }
   }
   
   function openTabs(pageId) {
    tabnav = document.getElementById(pageId).getElementsByTagName('UL');
    if(tabnav.length > 2 ){
    currentNav = document.getElementById(tabnav[1].id);
    currentLis = currentNav.getElementsByTagName('LI');
    for(i = 0; i< currentLis.length; i++){
    if(currentLis[i].className == 'active') {
    funcString = currentLis[i].onclick.toString();
    tab = funcString.split('"');
                                   if(tab.length < 2) {
                                      tab = funcString.split("'");
                                   }
    currentData = document.getElementById(tab[1]);
           currentData.style.display = 'block';
    }
    }
    }
   }
   
   function showPage(current, pageId, nav, data) {
    hideAll(current, nav, data);
    openTabs(pageId);
    unselectInactive(nav);
    current.className = 'active';
    currentData = document.getElementById(pageId);
    currentData.style.display = 'block';
           activeTab = pageId;
           toggleUpload();
           toggleMap();
           if (nav == 'mainnav') {
               var storedpath = "$docs_folderpath";
               var storedpage = "$main_container_page";
               var reg = new RegExp("^supplemental");
               if (pageId == 'mainCourseDocuments') {
                   if (storedpage == 1) {
                       document.simpleedit.folderpath.value = '';
                       document.uploaddocument.folderpath.value = '';
                   } else {
                       if (reg.test(storedpath)) {
                           document.simpleedit.folderpath.value = '$toplevelmain';
                           document.uploaddocument.folderpath.value = '$toplevelmain';
                           document.newext.folderpath.value = '$toplevelmain';
                       } else {
                           document.simpleedit.folderpath.value = storedpath;
                           document.uploaddocument.folderpath.value = storedpath;
                           document.newext.folderpath.value = storedpath;
                       }
                   }
               } else {
                   if (reg.test(storedpath)) {
                       document.simpleedit.folderpath.value = storedpath;
                       document.supuploaddocument.folderpath.value = storedpath;
                       document.supnewext.folderpath.value = storedpath;
                   } else {
                       document.simpleedit.folderpath.value = '$toplevelsupp';
                       document.supuploaddocument.folderpath.value = '$toplevelsupp';
                       document.supnewext.folderpath.value = '$toplevelsupp';
                   }
               }
           }
           resize_scrollbox('contentscroll','1','0');
    return false;
   }
   
   function toContents(jumpto) {
       var newurl = '$backtourl';
       if ((newurl == '/adm/navmaps') && (jumpto != '')) {
           newurl = newurl+'?postdata='+jumpto;
       }
       location.href=newurl;
   }
   
   ENDNEWSCRIPT
   }
   
   sub history_tab_js {
       return <<"ENDHIST";
   function toggleHistoryDisp(choice) {
       document.docslogform.docslog.value = choice;
       document.docslogform.submit();
       return;
   }
   
   ENDHIST
   }
   
   sub inject_data_js {
       return <<ENDINJECT;
   
   function injectData(current, hiddenField, name, value) {
           currentElement = document.getElementById(hiddenField);
           currentElement.name = name;
           currentElement.value = value;
           current.submit();
   }
   
   ENDINJECT
   }
   
   sub dump_switchserver_js {
       my @hosts = @_;
       my %lt = &Apache::lonlocal::texthash(
           dump => 'Dumping to Authoring Space requires switching server.',
           swit => 'Switch server?',
           duco => 'Dump content to Authoring Space',
           yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
           chos => 'Choose server',
       );
       my $role = $env{'request.role'};
       my $js = <<"ENDSWJS";
   <script type="text/javascript">
   function write_switchserver() {
       var server;
       if (document.setserver.posshosts.length > 0) {
           for (var i=0; i<document.setserver.posshosts.length; i++) {
               if (document.setserver.posshosts[i].checked) {
                   server = document.setserver.posshosts[i].value;
               }
          }
          opener.document.location.href="/adm/switchserver?otherserver="+server+"&role=$role&origurl=/adm/coursedocs";
       }
       window.close();
   }
   </script>
   
   ENDSWJS
   
       my $startpage = &Apache::loncommon::start_page('Choose server',$js,
                                                      {'only_body' => 1,
                                                       'js_ready'  => 1,});
       my $endpage = &Apache::loncommon::end_page({'js_ready'  => 1});
   
       my $hostpicker;
       my $count = 0;
       foreach my $host (sort(@hosts)) {
           my $checked;
           if ($count == 0) {
               $checked = ' checked="checked"';
           }
           $hostpicker .= '<label><input type="radio" name="posshosts" value="'.
                          $host.'"'.$checked.' />'.$host.'</label>&nbsp;&nbsp;';
           $count++;
       }
       
       return <<"ENDSWITCHJS";
   
   function dump_needs_switchserver(url) {
       if (url!='' && url!= null) {
           if (confirm("$lt{'dump'}\\n$lt{'swit'}")) {
               go(url);
           }
       }
       return;
   }
   
   function choose_switchserver_window() {
       newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
       newWindow.document.open();
       newWindow.document.writeln('$startpage');
       newWindow.document.write('<h3>$lt{'duco'}<\\/h3>\\n'+
          '<p>$lt{'yone'}<\\/p>\\n'+
          '<div class="LC_left_float"><fieldset><legend>$lt{'chos'}<\\/legend>\\n'+
          '<form name="setserver" method="post" action="" \\/>\\n'+
          '$hostpicker\\n'+
          '<br \\/><br \\/>\\n'+
          '<input type="button" name="makeswitch" value="$lt{'swit'}" '+
          'onclick="write_switchserver();" \\/>\\n'+
          '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
       newWindow.document.writeln('$endpage');
       newWindow.document.close();
       newWindow.focus();
   }
   
   ENDSWITCHJS
   }
   
   sub makedocslogform {
       my ($formelems,$docslog) = @_;
       return <<"LOGSFORM";
    <form action="/adm/coursedocs" method="post" name="docslogform">
      <input type="hidden" name="docslog" value="$docslog" />
      $formelems
    </form>
   LOGSFORM
   }
   
   sub makesimpleeditform {
       my ($formelems) = @_;
       return <<"SIMPFORM";
    <form name="simpleedit" method="post" action="/adm/coursedocs">
      <input type="hidden" name="importdetail" value="" />
      $formelems
    </form>
   SIMPFORM
   }
   
   1;
   __END__
   
   
   =head1 NAME
   
   Apache::londocs.pm
   
   =head1 SYNOPSIS
   
   This is part of the LearningOnline Network with CAPA project
   described at http://www.lon-capa.org.
   
   =head1 SUBROUTINES
   
   =over
   
   =item %help=()
   
   Available help topics
   
   =item mapread()
   
   Mapread read maps into LONCAPA::map:: global arrays
   @order and @resources, determines status
   sets @order - pointer to resources in right order
   sets @resources - array with the resources with correct idx
   
   =item authorhosts()
   
   Return hash with valid author names
   
   =item clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   =item group_import()
   
       Imports the given (name, url) resources into the course
       coursenum, coursedom, and folder must precede the list
   
   =item breadcrumbs()
   
   =item log_docs()
   
   =item docs_change_log()
   
   =item update_paste_buffer()
   
   =item print_paste_buffer()
   
   =item do_paste_from_buffer()
   
   =item get_newmap_url()
   
   =item dbcopy()
   
   =item uniqueness_check()
   
   =item contained_map_check()
   
   =item url_paste_fixups()
   
   =item apply_fixups()
   
   =item copy_dependencies()
   
   =item update_parameter()
   
   =item handle_edit_cmd()
   
   =item editor()
   
   =item process_file_upload()
   
   =item process_secondary_uploads()
   
   =item is_supplemental_title()
   
   =item entryline()
   
   =item tiehash()
   
   =item untiehash()
   
   =item checkonthis()
   
   check on this
   
   =item verifycontent()
   
   Verify Content
   
   =item devalidateversioncache() & checkversions()
   
   Check Versions
   
   =item mark_hash_old()
   
   =item is_hash_old()
   
   =item changewarning()
   
   =item init_breadcrumbs()
   
   Breadcrumbs for special functions
   
   =item create_list_elements()
   
   =item create_form_ul()
   
   =item startContentScreen() 
   
   =item endContentScreen()
   
   =item supplemental_base()
   
   =item embedded_form_elems()
   
   =item embedded_destination()
   
   =item return_to_editor()
   
   =item decompression_info()
   
   =item decompression_phase_one()
   
   =item decompression_phase_two()
   
   =item remove_archive()
   
   =item generate_admin_menu()
   
   =item generate_edit_table()
   
   =item editing_js()
   
   =item history_tab_js()
   
   =item inject_data_js()
   
   =item dump_switchserver_js()
   
   =item resize_scrollbox_js()
   
   =item makedocslogform()
   
   =item makesimpleeditform()
   
   =back
   
   =cut

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


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