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

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


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