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

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

Removed from v.1.328  
changed lines
  Added in v.1.499


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