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

version 1.328, 2009/01/28 13:24:54 version 1.505, 2012/11/13 22:49:15
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
   package Apache::londocs;
   
 package Apache::londocs;  use strict;
   use Apache::Constants qw(:common :http);
 use strict;  use Apache::imsexport;
 use Apache::Constants qw(:common :http);  use Apache::lonnet;
 use Apache::imsexport;  use Apache::loncommon;
 use Apache::lonnet;  use Apache::lonhtmlcommon;
 use Apache::loncommon;  use LONCAPA::map();
 use LONCAPA::map();  use Apache::lonratedt();
 use Apache::lonratedt();  use Apache::lonxml;
 use Apache::lonxml;  use Apache::lonclonecourse;
 use Apache::lonclonecourse;  use Apache::lonnavmaps;
 use Apache::lonnavmaps;  use Apache::lonnavdisplay();
 use HTML::Entities;  use Apache::lonuserstate();
 use GDBM_File;  use HTML::Entities;
 use Apache::lonlocal;  use HTML::TokeParser;
 use Cwd;  use GDBM_File;
 use LONCAPA qw(:DEFAULT :match);  use Apache::lonlocal;
   use Cwd;
 my $iconpath;  use LONCAPA qw(:DEFAULT :match);
   
 my %hash;  my $iconpath;
   
 my $hashtied;  my %hash;
 my %alreadyseen=();  
   my $hashtied;
 my $hadchanges;  my %alreadyseen=();
   
   my $hadchanges;
 my %help=();  
   
   my %help=();
 sub mapread {  
     my ($coursenum,$coursedom,$map)=@_;  
     return  sub mapread {
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map)=@_;
      $map);      return
 }        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
        $map);
 sub storemap {  }
     my ($coursenum,$coursedom,$map)=@_;  
     my ($outtext,$errtext)=  sub storemap {
       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map,$contentchg)=@_;
       $map,1);      my $report;
     if ($errtext) { return ($errtext,2); }      if (($contentchg) && ($map =~ /^default/)) {
             $report = 1;
     $hadchanges=1;      }
     return ($errtext,0);      my ($outtext,$errtext)=
 }        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1,$report);
       if ($errtext) { return ($errtext,2); }
   
 sub authorhosts {      $hadchanges=1;
     my %outhash=();      return ($errtext,0);
     my $home=0;  }
     my $other=0;  
     foreach my $key (keys(%env)) {  
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {  
     my $role=$1;  sub authorhosts {
     my $realm=$2;      my %outhash=();
     my ($start,$end)=split(/\./,$env{$key});      my $home=0;
     if (($start) && ($start>time)) { next; }      my $other=0;
     if (($end) && (time>$end)) { next; }      foreach my $key (keys(%env)) {
     my ($ca,$cd);   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     if ($1 eq 'au') {      my $role=$1;
  $ca=$env{'user.name'};      my $realm=$2;
  $cd=$env{'user.domain'};      my ($start,$end)=split(/\./,$env{$key});
     } else {      if (($start) && ($start>time)) { next; }
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);      if (($end) && (time>$end)) { next; }
     }      my ($ca,$cd);
     my $allowed=0;      if ($1 eq 'au') {
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);   $ca=$env{'user.name'};
     my @ids=&Apache::lonnet::current_machine_ids();   $cd=$env{'user.domain'};
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      } else {
     if ($allowed) {   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  $home++;      }
  $outhash{'home_'.$ca.'@'.$cd}=1;      my $allowed=0;
     } else {      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      my @ids=&Apache::lonnet::current_machine_ids();
  $other++;      foreach my $id (@ids) {
     }                  if ($id eq $myhome) {
  }                      $allowed=1;
     }                      last;
     return ($home,$other,%outhash);                  }
 }              }
       if ($allowed) {
    $home++;
 sub dumpbutton {   $outhash{'home_'.$ca.':'.$cd}=1;
     my ($home,$other,%outhash)=&authorhosts();      } else {
     my $type = &Apache::loncommon::course_type();   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
     if ($home+$other==0) { return ''; }   $other++;
     if ($home) {      }
  return '<input type="submit" name="dumpcourse" value="'.   }
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      }
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');      return ($home,$other,%outhash);
     } else {  }
  return '<div>'.  
      &mt('Dump '.$type.  
  ' DOCS to Construction Space: available on other servers').  sub clean {
  '</div>';      my ($title)=@_;
     }      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
 }      return $title;
   }
 sub clean {  
     my ($title)=@_;  
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;  
     return $title;  sub dumpcourse {
 }      my ($r) = @_;
       my $crstype = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
                 &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
 sub dumpcourse {      $r->print(&startContentScreen('tools'));
     my ($r) = @_;      my ($home,$other,%outhash)=&authorhosts();
     my $type = &Apache::loncommon::course_type();      unless ($home) {
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').          $r->print(&endContentScreen());
       '<form name="dumpdoc" method="post">');          return '';
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      }
     my ($home,$other,%outhash)=&authorhosts();      my $origcrsid=$env{'request.course.id'};
     unless ($home) { return ''; }      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my $origcrsid=$env{'request.course.id'};      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);  # Do the dumping
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
 # Do the dumping              $r->print(&endContentScreen());
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }              return '';
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});          }
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
  my $title=$env{'form.authorfolder'};   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  $title=&clean($title);   my $title=$env{'form.authorfolder'};
  my %replacehash=();   $title=&clean($title);
  foreach my $key (keys(%env)) {   my %replacehash=();
     if ($key=~/^form\.namefor\_(.+)/) {   foreach my $key (keys(%env)) {
  $replacehash{$1}=$env{$key};      if ($key=~/^form\.namefor\_(.+)/) {
     }   $replacehash{$1}=$env{$key};
  }      }
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   }
  $crs=~s/\_/\//g;   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  foreach my $item (keys(%replacehash)) {   $crs=~s/\_/\//g;
     my $newfilename=$title.'/'.$replacehash{$item};   foreach my $item (keys(%replacehash)) {
     $newfilename=~s/\.(\w+)$//;      my $newfilename=$title.'/'.$replacehash{$item};
     my $ext=$1;      $newfilename=~s/\.(\w+)$//;
     $newfilename=&clean($newfilename);      my $ext=$1;
     $newfilename.='.'.$ext;      $newfilename=&clean($newfilename);
     my @dirs=split(/\//,$newfilename);      $newfilename.='.'.$ext;
     my $path='/home/'.$ca.'/public_html';      my @dirs=split(/\//,$newfilename);
     my $makepath=$path;      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
     my $fail=0;      my $makepath=$path;
     for (my $i=0;$i<$#dirs;$i++) {      my $fail=0;
  $makepath.='/'.$dirs[$i];      for (my $i=0;$i<$#dirs;$i++) {
  unless (-e $makepath) {   $makepath.='/'.$dirs[$i];
     unless(mkdir($makepath,0777)) { $fail=1; }   unless (-e $makepath) {
  }      unless(mkdir($makepath,0777)) { $fail=1; }
     }   }
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      }
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     print $fh &Apache::lonclonecourse::rewritefile(   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),      print $fh &Apache::lonclonecourse::rewritefile(
      (%replacehash,$crs => '')           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
     );       (%replacehash,$crs => '')
  } else {      );
     print $fh   } else {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);      print $fh
        }           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  $fh->close();         }
     } else {   $fh->close();
  $fail=1;      } else {
     }   $fail=1;
     if ($fail) {      }
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');      if ($fail) {
     } else {   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      } else {
     }   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  }      }
     } else {   }
 # Input form      } else {
  unless ($home==1) {          $r->print(&mt('Searching ...').'<br />');
     $r->print(          $r->rflush();
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');  # Input form
  }          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
  foreach my $key (sort(keys(%outhash))) {   unless ($home==1) {
     if ($key=~/^home_(.+)$/) {      $r->print('<div class="LC_left_float">'.
  if ($home==1) {        '<fieldset><legend>'.
     $r->print(                        &mt('Select the Authoring Space').
   '<input type="hidden" name="authorspace" value="'.$1.'" />');                        '</legend><select name="authorspace">');
  } else {   }
     $r->print('<option value="'.$1.'">'.$1.' - '.   foreach my $key (sort(keys(%outhash))) {
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');      if ($key=~/^home_(.+)$/) {
  }   if ($home==1) {
     }      $r->print(
  }    '<input type="hidden" name="authorspace" value="'.$1.'" />');
  unless ($home==1) {   } else {
     $r->print('</select>');      $r->print('<option value="'.$1.'">'.$1.' - '.
  }        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
  my $title=$origcrsdata{'description'};   }
  $title=~s/[\/\s]+/\_/gs;      }
  $title=&clean($title);   }
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'   unless ($home==1) {
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');      $r->print('</select></fieldset></div>'."\n");
  &tiehash();   }
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'   my $title=$origcrsdata{'description'};
                  .&Apache::loncommon::start_data_table()   $title=~s/[\/\s]+/\_/gs;
                  .&Apache::loncommon::start_data_table_header_row()   $title=&clean($title);
                  .'<th>'.&mt('Internal Filename').'</th>'   $r->print('<div class="LC_left_float">'.
                  .'<th>'.&mt('Title').'</th>'                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
                  .'<th>'.&mt('Save as ...').'</th>'                    '<input type="text" size="50" name="authorfolder" value="'.
                  .&Apache::loncommon::end_data_table_header_row());                    $title.'" />'.
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {                    '</fieldset></div><br clear="all" />'."\n");
     $r->print(&Apache::loncommon::start_data_table_row()   &tiehash();
                      .'<td>'.$file.'</td>');   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
     my ($ext)=($file=~/\.(\w+)$/);                   .&Apache::loncommon::start_data_table()
     my $title=$hash{'title_'.$hash{                   .&Apache::loncommon::start_data_table_header_row()
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                   .'<th>'.&mt('Internal Filename').'</th>'
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');                   .'<th>'.&mt('Title').'</th>'
     if (!$title) {                   .'<th>'.&mt('Save as ...').'</th>'
  $title=$file;                   .&Apache::loncommon::end_data_table_header_row());
     } else {   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  $title=~s|/|_|g;      $r->print(&Apache::loncommon::start_data_table_row()
     }                       .'<td>'.$file.'</td>');
     $title=~s/\.(\w+)$//;      my ($ext)=($file=~/\.(\w+)$/);
     $title=&clean($title);      my $title=$hash{'title_'.$hash{
     $title.='.'.$ext;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
                      .&Apache::loncommon::end_data_table_row());      if (!$title) {
  }   $title=$file;
  $r->print(&Apache::loncommon::end_data_table());      } else {
  &untiehash();   $title=~s|/|_|g;
  $r->print(      }
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      $title=~s/\.(\w+)$//;
     }      $title=&clean($title);
 }      $title.='.'.$ext;
       $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
                        .&Apache::loncommon::end_data_table_row());
    }
 sub exportbutton {   $r->print(&Apache::loncommon::end_data_table());
     my $type = &Apache::loncommon::course_type();   &untiehash();
     return '<input type="submit" name="exportcourse" value="'.   $r->print(
             &mt('Export '.$type.' to IMS').'" />'.    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');      }
 }      $r->print(&endContentScreen());
   }
   
   sub group_import {
 sub exportcourse {      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
     my $r=shift;  
     my $type = &Apache::loncommon::course_type();      while (@files) {
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',   my ($name, $url, $residx) = @{ shift(@files) };
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
     my $numdisc = keys(%discussiontime);       && ($caller eq 'londocs')
     my $navmap = Apache::lonnavmaps::navmap->new();       && (!&Apache::lonnet::stat_file($url))) {
     if (!defined($navmap)) {  
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').              my $errtext = '';
                   '<h2>IMS Export Failed</h2>'.              my $fatal = 0;
                   '<div class="LC_error">'.              my $newmapstr = '<map>'."\n".
                   &mt('Unable to retrieve information about course contents').                              '<resource id="1" src="" type="start"></resource>'."\n".
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');                              '<link from="1" to="2" index="1"></link>'."\n".
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                              '<resource id="2" src="" type="finish"></resource>'."\n".
         return;                              '</map>';
     }              $env{'form.output'}=$newmapstr;
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
     my $curRes;                                                  'output',$1.$2);
     my $outcome;              if ($result != m|^/uploaded/|) {
                   $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                  $fatal = 2;
                                             ['finishexport']);              }
     if ($env{'form.finishexport'}) {              if ($fatal) {
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                  return ($errtext,$fatal);
                                             ['archive','discussion']);              }
           }
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');   if ($url) {
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');      if (!$residx
         if (@exportitems == 0 && @discussions == 0) {   || defined($LONCAPA::map::zombies[$residx])) {
             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';   $residx = &LONCAPA::map::getresidx($url,$residx);
         } else {   push(@LONCAPA::map::order, $residx);
             my $now = time;      }
             my %symbs;      my $ext = 'false';
             my $manifestok = 0;      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
             my $imsresources;      $url  = &LONCAPA::map::qtunescape($url);
             my $tempexport;      $name = &LONCAPA::map::qtunescape($name);
             my $copyresult;      $LONCAPA::map::resources[$residx] =
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);   join(':', ($name, $url, $ext, 'normal', 'res'));
             if ($manifestok) {   }
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);      }
                 close($ims_manifest);      return &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
   }
 #Create zip file in prtspool  
                 my $imszipfile = '/prtspool/'.  sub breadcrumbs {
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.      my ($allowed,$crstype)=@_;
                    time.'_'.rand(1000000000).'.zip';      &Apache::lonhtmlcommon::clear_breadcrumbs();
                 my $cwd = &Cwd::getcwd();      my (@folders);
                 my $imszip = '/home/httpd/'.$imszipfile;      if ($env{'form.pagepath'}) {
                 chdir $tempexport;          @folders = split('&',$env{'form.pagepath'});
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");      } else {
                 close(OUTPUT);          @folders=split('&',$env{'form.folderpath'});
                 chdir $cwd;      }
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      my $folderpath;
                 if ($copyresult) {      my $plain='';
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);      my $randompick=-1;
                 }      my $isencrypted=0;
             } else {      my $ishidden=0;
                 $outcome = '<br />'.&mt('Unfortunately you will not be able to retrieve an IMS archive of this posts at this time, because there was a problem creating a manifest file.').'<br />';      my $is_random_order=0;
             }      while (@folders) {
         }   my $folder=shift(@folders);
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));      my $foldername=shift(@folders);
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));   if ($folderpath) {$folderpath.='&';}
         $r->print($outcome);   $folderpath.=$folder.'&'.$foldername;
         $r->print(&Apache::loncommon::end_page());          my $url;
     } else {          if ($allowed) {
         my $display;              $url = '/adm/coursedocs?folderpath=';
         $display = '<form name="exportdoc" method="post">'."\n";          } else {
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');              $url = '/adm/supplemental?folderpath=';
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.          }
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.   $url .= &escape($folderpath);
                     '<input type="button" value="check all" '.   my $name=&unescape($foldername);
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.  # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.    $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.   if ($1 ne '') {
                     '<td>&nbsp;</td><td>&nbsp;</td>'.             $randompick=$1;
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.          } else {
                     '</b></legend><input type="button" value="check all"'.             $randompick=-1;
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.          }
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.          if ($2) { $ishidden=1; }
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.          if ($3) { $isencrypted=1; }
                     '</tr></table>';   if ($4 ne '') { $is_random_order = 1; }
         my $curRes;          if ($folder eq 'supplemental') {
         my $depth = 0;              $name = &mt('Supplemental '.$crstype.' Content');
         my $count = 0;          }
         my $boards = 0;   &Apache::lonhtmlcommon::add_breadcrumb(
         my $startcount = 5;        {'href'=>$url,
         my %parent = ();         'title'=>$name,
         my %children = ();         'text'=>$name,
         my $lastcontainer = $startcount;         'no_mt'=>1,
         my @bgcolors = ('#F6F6F6','#FFFFFF');         });
         $display .= '<table cellspacing="0"><tr>'.   $plain.=$name.' &gt; ';
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";      }
         if ($numdisc > 0) {      $plain=~s/\&gt\;\s*$//;
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";      return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
         }         undef, undef, 1 ),$randompick,$ishidden,
         $display.='&nbsp;</td></tr>';                                                 $isencrypted,$plain,$is_random_order);
         while ($curRes = $it->next()) {  }
             if (ref($curRes)) {  
                 $count ++;  sub log_docs {
             }      return &Apache::lonnet::write_log('course','docslog',@_);
             if ($curRes == $it->BEGIN_MAP()) {  }
                 $depth++;  
                 $parent{$depth} = $lastcontainer;  {
             }      my @oldresources=();
             if ($curRes == $it->END_MAP()) {      my @oldorder=();
                 $depth--;      my $parmidx;
                 $lastcontainer = $parent{$depth};      my %parmaction=();
             }      my %parmvalue=();
             if (ref($curRes)) {      my $changedflag;
                 my $symb = $curRes->symb();  
                 my $ressymb = $symb;      sub snapshotbefore {
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {          @oldresources=@LONCAPA::map::resources;
                     unless ($ressymb =~ m|adm/wrapper/adm|) {          @oldorder=@LONCAPA::map::order;
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';          $parmidx=undef;
                     }          %parmaction=();
                 }          %parmvalue=();
                 my $color = $count%2;          $changedflag=0;
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".      }
                     '<input type="checkbox" name="archive" value="'.$count.'" ';  
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {      sub remember_parms {
                     my $checkitem = $count + $boards + $startcount;          my ($idx,$parameter,$action,$value)=@_;
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';          $parmidx=$idx;
                 }          $parmaction{$parameter}=$action;
                 $display .= ' />'."\n";          $parmvalue{$parameter}=$value;
                 for (my $i=0; $i<$depth; $i++) {          $changedflag=1;
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";      }
                 }  
                 if ($curRes->is_sequence()) {      sub log_differences {
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";          my ($plain)=@_;
                     $lastcontainer = $count + $startcount + $boards;          my %storehash=('folder' => $plain,
                 } elsif ($curRes->is_page()) {                         'currentfolder' => $env{'form.folder'});
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";          if ($parmidx) {
                     $lastcontainer = $count + $startcount + $boards;             $storehash{'parameter_res'}=$oldresources[$parmidx];
                 }             foreach my $parm (keys(%parmaction)) {
                 my $currelem = $count+$boards+$startcount;                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
                 $children{$parent{$depth}} .= $currelem.':';                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
                 $display .= '&nbsp;'.$curRes->title().'</td>';             }
                 if ($discussiontime{$ressymb} > 0) {          }
                     $boards ++;          my $maxidx=$#oldresources;
                     $currelem = $count+$boards+$startcount;          if ($#LONCAPA::map::resources>$#oldresources) {
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";             $maxidx=$#LONCAPA::map::resources;
                 } else {          }
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";          for (my $idx=0; $idx<=$maxidx; $idx++) {
                 }             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
             }                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
         }                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
         my $scripttag = qq|                $changedflag=1;
 <script>             }
              if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
 function checkAll(field) {                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
     if (field.length > 0) {                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
         for (i = 0; i < field.length; i++) {                $changedflag=1;
             field[i].checked = true ;             }
         }          }
     } else {   $storehash{'maxidx'}=$maxidx;
         field.checked = true          if ($changedflag) { &log_docs(\%storehash); }
     }      }
 }  }
                                                                                  
 function uncheckAll(field) {  sub docs_change_log {
     if (field.length > 0) {      my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
         for (i = 0; i < field.length; i++) {      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
             field[i].checked = false ;      my $js = '<script type="text/javascript">'."\n".
         }               '// <![CDATA['."\n".
     } else {               &Apache::loncommon::display_filter_js('docslog')."\n".
         field.checked = false ;               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
     }               &history_tab_js()."\n".
 }               &Apache::lonratedt::editscript('simple')."\n".
                '// ]]>'."\n".
 function propagateCheck(item) {               '</script>'."\n";
     if (document.exportdoc.elements[item].checked == true) {      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
         containerCheck(item)      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
     }      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
 }      my %orderhash;
       my $container='sequence';
 function containerCheck(item) {      my $pathitem;
     document.exportdoc.elements[item].checked = true      if ($env{'form.pagepath'}) {
     var numitems = $count + $boards + $startcount          $container='page';
     var parents = new Array(numitems)          $pathitem = '<input type="hidden" name="pagepath" value="'.
     for (var i=$startcount; i<numitems; i++) {                      &HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />';
         parents[i] = new Array      } else {
     }          my $folderpath=$env{'form.folderpath'};
         |;          if ($folderpath eq '') {
               $folderpath = 'default&'.&escape(&mt('Main '.$crstype.' Documents'));
         foreach my $container (sort { $a <=> $b } (keys(%children))) {          }
             my @contents = split(/:/,$children{$container});          $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
             for (my $i=0; $i<@contents; $i ++) {      }
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
             }      my $jumpto = $readfile;
         }      $jumpto =~ s{^/}{};
       my $tid = 1;
         $scripttag .= qq|      if ($supplementalflag) {
     if (parents[item].length > 0) {          $tid = 2;
         for (var j=0; j<parents[item].length; j++) {      }
             containerCheck(parents[item][j])      my ($breadcrumbtrail) = &breadcrumbs($allowed,$crstype);
         }      $r->print($breadcrumbtrail.
      }                  &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
 }                $readfile));
       my %docslog=&Apache::lonnet::dump('nohist_docslog',
 </script>                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
         |;                                        $env{'course.'.$env{'request.course.id'}.'.num'});
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',  
  $scripttag));      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));  
  $r->print($display.'</table>'.      my %saveable_parameters = ('show' => 'scalar',);
                   '<p><input type="hidden" name="finishexport" value="1">'.      &Apache::loncommon::store_course_settings('docs_log',
                   '<input type="submit" name="exportcourse" value="'.                                                \%saveable_parameters);
                   &mt('Export '.$type.' DOCS').'" /></p></form>');      &Apache::loncommon::restore_course_settings('docs_log',
     }                                                  \%saveable_parameters);
 }      if (!$env{'form.show'}) { $env{'form.show'}=10; }
   # FIXME: internationalization seems wrong here
 sub create_ims_store {      my %lt=('hiddenresource' => 'Resources hidden',
     my ($now,$manifestok,$outcome,$tempexport) = @_;      'encrypturl'     => 'URL hidden',
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';      'randompick'     => 'Randomly pick',
     my $ims_manifest;      'randomorder'    => 'Randomly ordered',
     if (!-e $$tempexport) {      'set'            => 'set to',
         mkdir($$tempexport,0700);      'del'            => 'deleted');
     }      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
     $$tempexport .= '/'.$now;                   $pathitem."\n".
     if (!-e $$tempexport) {                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
         mkdir($$tempexport,0700);                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
     }      $r->print('<div class="LC_left_float">'.
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
     if (!-e $$tempexport) {                &makedocslogform($filter,1).
         mkdir($$tempexport,0700);                '</fieldset></div><br clear="all" />');
     }      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     if (!-e "$$tempexport/resources") {                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
         mkdir("$$tempexport/resources",0700);                &mt('After').'</th>'.
     }                &Apache::loncommon::end_data_table_header_row());
 # open manifest file      my $shown=0;
     my $manifest = '/imsmanifest.xml';      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     my $manifestfilename = $$tempexport.$manifest;   if ($env{'form.displayfilter'} eq 'currentfolder') {
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
         $$manifestok=1;   }
         print $ims_manifest          my @changes=keys(%{$docslog{$id}{'logentry'}});
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".          if ($env{'form.displayfilter'} eq 'containing') {
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.      foreach my $key (@changes) {
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.      }
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
 '  <metadata>   }
     <schema></schema>          my $count = 0;
     <imsmd:lom>          my $time =
       <imsmd:general>              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>          my $plainname =
         <imsmd:title>              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>                                            $docslog{$id}{'exe_udom'});
         </imsmd:title>          my $about_me_link =
       </imsmd:general>              &Apache::loncommon::aboutmewrapper($plainname,
     </imsmd:lom>                                                 $docslog{$id}{'exe_uname'},
   </metadata>'."\n".                                                 $docslog{$id}{'exe_udom'});
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".          my $send_msg_link='';
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
 ' structure="hierarchical">'."\n".               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'              $send_msg_link ='<br />'.
     } else {                  &Apache::loncommon::messagewrapper(&mt('Send message'),
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'                                                     $docslog{$id}{'exe_uname'},
 ;                                                     $docslog{$id}{'exe_udom'});
     }          }
     return $ims_manifest;          $r->print(&Apache::loncommon::start_data_table_row());
 }          $r->print('<td>'.$time.'</td>
                          <td>'.$about_me_link.
 sub build_package {                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
 # first iterator to look for dependencies                    $send_msg_link.'</td><td>'.
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
     my $curRes;          my $is_supp = 0; 
     my $count = 0;          if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
     my $depth = 0;              $is_supp = 1;
     my $lastcontainer = 0;          }
     my %parent = ();  # Before
     my @dependencies = ();   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
     while ($curRes = $it->next()) {      if ($oldname ne $newname) {
         if (ref($curRes)) {                  my $shown = &LONCAPA::map::qtescape($oldname);
             $count ++;                  if ($is_supp) {
         }                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
         if ($curRes == $it->BEGIN_MAP()) {                  }
             $depth++;                  $r->print($shown);
             $parent{$depth} = $lastcontainer;      }
         }   }
         if ($curRes == $it->END_MAP()) {   $r->print('<ul>');
             $depth--;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
             $lastcontainer = $parent{$depth};              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
         }                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
         if (ref($curRes)) {                  if ($is_supp) {
             if ($curRes->is_sequence() || $curRes->is_page()) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                 $lastcontainer = $count;                  }
             }   $r->print('<li>'.$shown.'</li>');
             if (grep(/^$count$/,@$exportitems)) {      }
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);   }
             }   $r->print('</ul>');
         }  # After
     }          $r->print('</td><td>');
 # second iterator to build manifest and store resources  
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     $depth = 0;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     my $prevdepth;      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
     $count = 0;      if ($oldname ne '' && $oldname ne $newname) {
     my $imsresources;                  my $shown = &LONCAPA::map::qtescape($newname);
     my $pkgdepth;                  if ($is_supp) {
     while ($curRes = $it->next()) {                      $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
         if ($curRes == $it->BEGIN_MAP()) {                  }
             $prevdepth = $depth;                  $r->print($shown);
             $depth++;      }
         }   }
         if ($curRes == $it->END_MAP()) {   $r->print('<ul>');
             $prevdepth = $depth;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
             $depth--;              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
         }                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
                   if ($is_supp) {
         if (ref($curRes)) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
             $count ++;                  }
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {                  $r->print('<li>'.$shown.'</li>');
                 my $symb = $curRes->symb();      }
                 my $isvisible = 'true';   }
                 my $resourceref;   $r->print('</ul>');
                 if ($curRes->randomout()) {   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                     $isvisible = 'false';      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
                 }      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
                 unless ($curRes->is_sequence()) {   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';  # FIXME: internationalization seems wrong here
                 }      $r->print('<li>'.
                 my $step = $prevdepth - $depth;        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
                 if (($step >= 0) && ($count > 1)) {    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
                     while ($step >= 0) {        .'</li>');
                         print $ims_manifest "\n".'  </item>'."\n";   }
                         $step --;      }
                     }      $r->print('</ul>');
                 }   }
                 $prevdepth = $depth;  # End
           $r->print('</td>'.&Apache::loncommon::end_data_table_row());
                 my $itementry =          $shown++;
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.          if (!($env{'form.show'} eq &mt('all')
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.                || $shown<=$env{'form.show'})) { last; }
               '<title>'.$curRes->title().'</title>';      }
                 print $ims_manifest "\n".$itementry;      $r->print(&Apache::loncommon::end_data_table()."\n".
                 &makesimpleeditform($pathitem)."\n".
                 unless ($curRes->is_sequence()) {                '</div></div>');
                     my $content_file;      $r->print(&endContentScreen());
                     my @hrefs = ();  }
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);  
                     if ($content_file) {  sub update_paste_buffer {
                         $imsresources .= "\n".      my ($coursenum,$coursedom,$folder) = @_;
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.  
                      '" type="webcontent" href="'.$content_file.'">'."\n".      return if (!defined($env{'form.markcopy'}));
                      '       <file href="'.$content_file.'" />'."\n";      return if (!defined($env{'form.copyfolder'}));
                         foreach my $item (@hrefs) {      return if ($env{'form.markcopy'} < 0);
                             $imsresources .=  
                      '        <file href="'.$item.'" />'."\n";      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                         }      $env{'form.copyfolder'});
                         if (grep(/^$count$/,@$discussions)) {  
                             my $ressymb = $symb;      return if ($fatal);
                             my $mode;  
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {  # Mark for copying
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';      if (&is_supplemental_title($title)) {
                                 }          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
                                 $mode = 'board';   ($title) = &Apache::loncommon::parse_supplemental_title($title);
                             }      } elsif ($env{'docs.markedcopy_supplemental'}) {
                             my %extras = (          &Apache::lonnet::delenv('docs.markedcopy_supplemental');
                                           caller => 'imsexport',      }
                                           tempexport => $tempexport.'/resources',      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
                                           count => $count  
                                          );      (my $cmd,undef)=split('_',$env{'form.cmd'});
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);  
                         }      my %addtoenv = (
                         $imsresources .= '    </resource>'."\n";                      'docs.markedcopy_title' => $title,
                     }                      'docs.markedcopy_url'   => $url,
                 }                      'docs.markedcopy_cmd'   => $cmd,
                 $pkgdepth = $depth;                     );
             }      &Apache::lonnet::delenv('docs.markedcopy_nested');
         }      &Apache::lonnet::delenv('docs.markedcopy_nestednames');
     }      if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
     while ($pkgdepth > 0) {          my $prefix = $1;
         print $ims_manifest "    </item>\n";          my $subdir =$2;
         $pkgdepth --;          if ($subdir eq '') {
     }              $subdir = $prefix;
     my $resource_text = qq|          }
     </organization>          my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
   </organizations>          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
   <resources>                               \%hierarchy,\%titles,\%allmaps);
     $imsresources          if (ref($hierarchy{$url}) eq 'HASH') {
   </resources>              my ($nested,$nestednames);
 </manifest>              &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
     |;              $nested =~ s/\&$//;
     print $ims_manifest $resource_text;              $nestednames =~ s/\Q___&&&___\E$//;
 }              if ($nested ne '') {
                   $addtoenv{'docs.markedcopy_nested'} = $nested;
 sub get_dependencies {              }
     my ($exportitems,$parent,$depth,$dependencies) = @_;              if ($nestednames ne '') {
     if ($depth > 1) {                  $addtoenv{'docs.markedcopy_nestednames'} = $nestednames;
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {              }
             push(@{$dependencies},$$parent{$depth});          }
             if ($depth > 2) {      }
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);      &Apache::lonnet::appenv(\%addtoenv);
             }      delete($env{'form.markcopy'});
         }  }
     }  
 }  sub recurse_uploaded_maps {
       my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
 sub process_content {      if (ref($hierarchy->{$url}) eq 'HASH') {
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;          my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
     my $content_type;          my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
     my $message;          my (@uploaded,@names,%shorter);
     my @uploads = ();          for (my $i=0; $i<@maps; $i++) {
     if ($curRes->is_sequence()) {              my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
         $content_type = 'sequence';              if ($inner ne '') {
     } elsif ($curRes->is_page()) {                  push(@uploaded,$inner);
         $content_type = 'page'; # need to handle individual items in pages.                  push(@names,&escape($titles[$i]));
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {                  $shorter{$maps[$i]} = $inner;
         $content_type = 'syllabus';              }
         my $contents = &Apache::imsexport::templatedpage($content_type);          }
         if ($contents) {          $$nestref .= "$dir:".join(',',@uploaded).'&';
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
         }          foreach my $map (@maps) {
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {              if ($shorter{$map} ne '') {
         $content_type = 'external';                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
         my $title = $curRes->title;              }
         my $contents =  &Apache::imsexport::external($symb,$title);          }
         if ($contents) {      }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      return;
         }  }
     } elsif ($symb =~ m-adm/navmaps$-) {  
         $content_type =  'navmap';  sub print_paste_buffer {
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
         $content_type = 'simplepage';      return if (!defined($env{'docs.markedcopy_url'}));
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);  
         if ($contents) {      my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
         }      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {          $is_external = 1;
         $content_type = 'simpleproblem';      }
         my $contents =  &Apache::imsexport::simpleproblem($symb);  
         if ($contents) {      my ($canpaste,$nopaste,$othercrs,$areachange,$is_uploaded_map);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      if ($folder =~ /^supplemental/) {
         }          $canpaste = &supp_pasteable($env{'docs.markedcopy_url'});
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {          unless ($canpaste) {
         $content_type = 'examupload';              $nopaste = &mt('Paste into Supplemental Content unavailable for this type of content.');
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {          } 
         $content_type = 'bulletinboard';      } else {
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);          $canpaste = 1;
         if ($contents) {      }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);  
         }      if ($canpaste) {
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {          if ($env{'docs.markedcopy_url'} =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
         $content_type = 'aboutme';              my $srcdom = $1;
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);              my $srcnum = $2;
         if ($contents) {              my $rem = $3;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
         }                  $othercourse = 1;
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {                  if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                      if ($canpaste) {
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {                          $othercrs = '<br />'.&mt('(from another course).');  
         my $canedit = 0;                      }
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {                  } else {
             $canedit= 1;                      $canpaste = 0;
         }                      $nopaste = &mt('Paste from another course unavailable.') 
 # only include problem code where current user is author                  }
         if ($canedit) {              }
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');              if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
         } else {                  my $prefix = $1;
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');                  $parent = $2;
         }                  if ($folder !~ /^\Q$prefix\E/) {
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {                      $areachange = 1;
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                  }
     }                  $is_uploaded_map = 1;
     if (@uploads > 0) {              }
         foreach my $item (@uploads) {          }
             my $uploadmsg = '';      }
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');  
             if ($uploadmsg) {      $r->print('<fieldset>'
                 $$copyresult .= $uploadmsg."\n";               .'<legend>'.&mt('Clipboard').'</legend>');
             }      my ($type,$buffer);
         }      if ($is_external) {
     }          $type = &mt('External Resource');
     if ($message) {          $buffer = $type.': '.
         $$copyresult .= $message."\n";                    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
     }                    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')';
 }      }  else {
           my $icon = &Apache::loncommon::icon($extension);
 sub replicate_content {          if ($extension eq 'sequence' &&
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;              $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
     my ($map,$ind,$url);              $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     if ($caller eq 'templateupload') {              $icon .= '/navmap.folder.closed.gif';
         $url = $symb;          }
         $url =~ s#//#/#g;          $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
     } else {          $buffer = $icon.$type.': '.  &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'}));
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);      }
     }      if ($canpaste) {
     my $content;          $r->print('<form name="pasteform" action="/adm/coursedocs" method="post">'.$buffer);
     my $filename;          if (($is_uploaded_map) && (!$areachange)) {
     my $repstatus;              if ((!$othercourse) && ($env{'docs.markedcopy_cmd'} eq 'cut')) {
     my $content_name;                  $r->print(('&nbsp;'x 4).'<span id="pasteoptionstext">'.
     if ($url =~ m-/([^/]+)$-) {                            '<a href="javascript:showPasteOptions();" class="LC_menubuttons_link">'.
         $filename = $1;                            &mt('Show Paste Options').'</a></span><br />'.
         if (!-e $tempexport.'/resources') {                            '<div id="pasteoptions" class="LC_dccid">'.('&nbsp;'x 4).
             mkdir($tempexport.'/resources',0700);                            '<label>'.
         }                            '<input type="radio" name="docs.markedcopy_options" value="new" checked="checked" />'.
         if (!-e $tempexport.'/resources/'.$count) {                            &mt('Copy to new folder').'</label>'.('&nbsp;' x2).
             mkdir($tempexport.'/resources/'.$count,0700);                            '<label>'.   
         }                            '<input type="radio" name="docs.markedcopy_options" value="move" />'.
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;                            &mt('Move old folder').'</label><br />');
         my $copiedfile;                  if ($env{'docs.markedcopy_nested'}) {
         if ($copiedfile = Apache::File->new('>'.$destination)) {                      $r->print('<br />'.&mt('Folder to paste contains sub-folders').
             my $content;                                '<br /><table border="0">');
             if ($caller eq 'resource') {                      my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested'});
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                      my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames'});
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);                      my $lastdir = $parent;
                 $content = &Apache::lonnet::getfile($filepath);                      my %depths = (
                 if ($content eq -1) {                                     $lastdir => 0,
                     $$message = 'Could not copy file '.$filename;                                   );
                 } else {                      my (%display,%deps); 
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');                      for (my $i=0; $i<@pastemaps; $i++) {
                     $repstatus = 'ok';                          ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
                 }                          my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {                          my @subfolders = split(/,/,$subfolderstr);
                 my $rtncode;                          $deps{$lastdir} = \@subfolders;
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);                          my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
                 if ($repstatus eq 'ok') {                          my $depth = $depths{$lastdir} + 1;
                     if ($url =~ /\.html?$/i) {                          my $offset = int($depth * 4);
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');                          my $indent = ('&nbsp;' x $offset);
                     }                          for (my $j=0; $j<@subfolders; $j++) {
                 } else {                              $depths{$subfolders[$j]} = $depth;
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";                              $display{$subfolders[$j]} = 
                 }                                    '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
             } elsif ($caller eq 'noedit') {                                    '<td><label>'.
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
                 $repstatus = 'ok';                                    '<label>'.
                 $content = 'Not the owner of this resource';                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="move" />'.
             }                                    &mt('Move old').'</label>'.
             if ($repstatus eq 'ok') {                                    '</td></tr>';
                 print $copiedfile $content;                          }
             }                      }
             close($copiedfile);                      &recurse_print($r,$parent,\%deps,\%display);
         } else {                      $r->print('</table>');
             $$message = 'Could not open destination file for '.$filename."<br />\n";                  }
         }                  $r->print('</div>');
     } else {              }
         $$message = 'Could not determine name of file for '.$symb."<br />\n";          }
     }          $r->print('<br /><input type="submit" name="pastemarked" value="'.&mt('Paste').'" />'.$othercrs);
     if ($repstatus eq 'ok') {          if ($container eq 'page') {
         $content_name = 'resources/'.$count.'/'.$filename;              $r->print('
     }          <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
     return $content_name;          <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
 }  ');
           } else {
 sub extract_media {              $r->print('
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
     my ($dirpath,$container);  ');
     my %allfiles = ();          }
     my %codebase = ();          $r->print('</form>');
     if ($url =~ m-(.*/)([^/]+)$-) {      } else {
         $dirpath = $1;          $r->print(&mt('Paste buffer contains:').' '.$buffer.
         $container = $2;                    '<br /><p class="LC_info">'.$nopaste.'</p>');
     } else {      }
         $dirpath = $url;      $r->print('</fieldset>');
         $container = '';  }
     }  
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);  sub recurse_print {
     foreach my $embed_file (keys(%allfiles)) {      my ($r,$dir,$deps,$display) = @_;
         my $filename;      $r->print($display->{$dir}."\n");
         if ($embed_file =~ m#([^/]+)$#) {      if (ref($deps->{$dir}) eq 'ARRAY') {
             $filename = $1;          foreach my $subdir (@{$deps->{$dir}}) {
         } else {              &recurse_print($r,$subdir,$deps,$display);
             $filename = $embed_file;          }
         }      }
         my $newname = 'res/'.$filename;  }
         my ($rtncode,$embed_content,$repstatus);  
         my $embed_url;  sub supp_pasteable {
         if ($embed_file =~ m-^/-) {      my ($url) = @_;
             $embed_url = $embed_file;           # points to absolute path      if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
         } else {          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
             if ($embed_file =~ m-https?://-) {          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
                 next;                           # points to url          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
             } else {          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
                 $embed_url = $dirpath.$embed_file;  # points to relative path          return 1;
             }      }
         }      return;
         if ($caller eq 'resource') {  }
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';    
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);  sub paste_popup_js {
             $embed_content = &Apache::lonnet::getfile($embed_path);      my %lt = &Apache::lonlocal::texthash(
             unless ($embed_content eq -1) {                                            show => 'Show Paste Options',
                 $repstatus = 'ok';                                            hide => 'Hide Paste Options',
             }                                          );
         } elsif ($caller eq 'uploaded') {      return <<"END";
              
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);  function showPasteOptions() {
         }      document.getElementById('pasteoptions').style.display='block';
         if ($repstatus eq 'ok') {      document.getElementById('pasteoptions').style.textAlign='left';
             my $destination = $tempexport.'/resources/'.$count.'/res';      document.getElementById('pasteoptions').style.textFace='normal';
             if (!-e "$destination") {      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:hidePasteOptions();" class="LC_menubuttons_link">$lt{'hide'}</a><br />';
                 mkdir($destination,0755);      return;
             }  }
             $destination .= '/'.$filename;  
             my $copiedfile;  function hidePasteOptions() {
             if ($copiedfile = Apache::File->new('>'.$destination)) {      document.getElementById('pasteoptions').style.display='none';
                 print $copiedfile $embed_content;      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:showPasteOptions()" class="LC_menubuttons_link">$lt{'show'}</a>';
                 push(@{$href},'resources/'.$count.'/res/'.$filename);      return;
                 my $attrib_regexp = '';  }
                 if (@{$allfiles{$embed_file}} > 1) {  
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});  END
                 } else {  
                     $attrib_regexp = $allfiles{$embed_file}[0];  }
                 }  
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;  
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {  sub do_paste_from_buffer {
                     $$content =~ s#\Q$embed_file\E#$newname#gi;      my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
                 }  
             }  # Early out if paste buffer is empty
         } else {      if (!$env{'form.pastemarked'}) {
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";          return ();
         }      }
     }  
     return;  # Supplemental content may only include certain types of content
 }  # Early out if pasted content is not supported in Supplemental area
       if ($folder =~ /^supplemental/) {
 sub store_template {          unless (&supp_pasteable($env{'docs.markedcopy_url'})) {
     my ($contents,$tempexport,$count,$content_type) = @_;              return (&mt('Paste failed: content type is not supported within Supplemental Content'));
     if ($contents) {          }
         if ($tempexport) {      }
             if (!-e $tempexport.'/resources') {  
                 mkdir($tempexport.'/resources',0700);  # Prepare to paste resource at end of list
             }      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
             if (!-e $tempexport.'/resources/'.$count) {      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
                 mkdir($tempexport.'/resources/'.$count,0700);  
             }      my ($is_map,$srcdom,$srcnum,$prefixchg,%before,%after,%mapchanges,%tomove);
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';      if ($url=~/\.(page|sequence)$/) {
             my $storetemplate;          $is_map = 1; 
             if ($storetemplate = Apache::File->new('>'.$destination)) {      }
                 print $storetemplate $contents;      if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/([^/]+)}) {
                 close($storetemplate);          $srcdom = $1;
             }          $srcnum = $2;
             if ($content_type eq 'external') {          my $oldprefix = $3;
                 return 'resources/'.$count.'/'.$content_type.'.html';  # When paste buffer was populated using an active role in a different course
             } else {  # check for mdc privilege in the course from which the resource was pasted 
                 return 'resources/'.$count.'/'.$content_type.'.xml';          if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
             }              unless ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         }                  return (&mt('Paste failed: Item is from a different course which you do not have rights to edit.'));
     }              }
 }          }
   # When pasting content from Main Content to Supplemental Content and vice versa 
   # URLs will contain different paths (which depend on whether pasted item is
 sub group_import {  # a folder/page or a document.   
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;          if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
               $prefixchg = 1;
     while (@files) {              %before = ( map => 'default',
  my ($name, $url, $residx) = @{ shift(@files) };                          doc => 'docs');
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})              %after =  ( map => 'supplemental',
      && ($caller eq 'londocs')                          doc => 'supplemental' );
      && (!&Apache::lonnet::stat_file($url))) {          } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
                   $prefixchg = 1;
             my $errtext = '';              %before = ( map => 'supplemental',
             my $fatal = 0;                          doc => 'supplemental');
             my $newmapstr = '<map>'."\n".              %after  = ( map => 'default',
                             '<resource id="1" src="" type="start"></resource>'."\n".                          doc => 'docs');
                             '<link from="1" to="2" index="1"></link>'."\n".          }
                             '<resource id="2" src="" type="finish"></resource>'."\n".  
                             '</map>';  # If pasting an uploaded map, get list of contained uploaded maps.
             $env{'form.output'}=$newmapstr;          my @nested;
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,          if ($env{'docs.markedcopy_nested'}) {
                                                 'output',$1.$2);              my ($type) = ($oldprefix =~ /^(default|supplemental)/);
             if ($result != m|^/uploaded/|) {              my @items = split(/\&/,$env{'docs.markedcopy_nested'});
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';              my @deps = map { /\d+:([\d,]+$)/ } @items;
                 $fatal = 2;              foreach my $dep (@deps) {
             }                  if ($dep =~ /,/) {
             if ($fatal) {                      push(@nested,split(/,/,$dep));
                 return ($errtext,$fatal);                  } else {
             }                      push(@nested,$dep);
         }                  }
  if ($url) {              }
     if (!$residx              foreach my $item (@nested) {
  || defined($LONCAPA::map::zombies[$residx])) {                  if ($env{'form.docs.markedcopy_'.$item} eq 'move') {
  $residx = &LONCAPA::map::getresidx($url,$residx);                      $tomove{$type.'_'.$item} = 1;
  push(@LONCAPA::map::order, $residx);                  }
     }              }
     my $ext = 'false';          }
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }      }
     $url  = &LONCAPA::map::qtunescape($url);  
     $name = &LONCAPA::map::qtunescape($name);  # Maps need to be copied first
     $LONCAPA::map::resources[$residx] =      my ($oldurl,%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
  join(':', ($name, $url, $ext, 'normal', 'res'));          %dbcopies,%zombies,%params,%docmoves,%mapmoves,%newsubdir,%newurls);
  }      $oldurl = $url;
     }      if ($is_map) {
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);          if ($folder =~ /^default/) {
 }              my $lastchange = &Apache::lonnet::get_coursechange($coursedom,$coursenum);
               if ($lastchange > $env{'request.course.tied'}) {
 sub breadcrumbs {                  &reinit_role($coursedom,$coursenum,$env{"course.$env{'request.course.id'}.home"}); 
     my ($where,$allowed,$type)=@_;              }
     &Apache::lonhtmlcommon::clear_breadcrumbs();          }
     my (@folders);  # If pasting a map, check if map contains other maps
     if ($env{'form.pagepath'}) {          my (%allmaps,%hierarchy,%titles);
         @folders = split('&',$env{'form.pagepath'});          if ($folder =~ /^default/) {
     } else {              my $navmap = Apache::lonnavmaps::navmap->new();
         @folders=split('&',$env{'form.folderpath'});              if (defined($navmap)) {
     }                  foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
     my $folderpath;                      $allmaps{$res->src()} = 1;
     my $cpinfo='';                  }
     my $plain='';              }
     my $randompick=-1;          }
     my $isencrypted=0;          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
     my $ishidden=0;                               \%addedmaps,\%hierarchy,\%titles,\%allmaps);
     my $is_random_order=0;          if ($url=~ m{^/uploaded/}) {
     while (@folders) {              my $newurl;
  my $folder=shift(@folders);              unless ($env{'form.docs.markedcopy_options'} eq 'move') {
     my $foldername=shift(@folders);                  ($newurl,my $error) = 
  if ($folderpath) {$folderpath.='&';}                      &get_newmap_url($url,$folder,$prefixchg,$coursedom,$coursenum,
  $folderpath.=$folder.'&'.$foldername;                                      $srcdom,$srcnum,\$title,\%allmaps,\%newurls);
  my $url='/adm/coursedocs?folderpath='.                  if ($error) {
     &escape($folderpath);                      return ($error);
     my $name=&unescape($foldername);                  }
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername                  if ($newurl ne '') {
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;                      if ($newurl ne $url) {
     if ($1 ne '') {                          if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
                $randompick=$1;                              $newsubdir{$url} = $1;
             } else {                          }
                $randompick=-1;                          $mapchanges{$url} = 1;
             }                      }
             if ($2) { $ishidden=1; }                  }
             if ($3) { $isencrypted=1; }              }
     if ($4 ne '') { $is_random_order = 1; }              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum) || ($prefixchg) ||
             if ($folder eq 'supplemental') {                  (($newurl ne '') && ($newurl ne $url))) {
                 if ($allowed) {                  unless (&url_paste_fixups($url,$folder,$prefixchg,$coursedom,$coursenum,
                     $name = &mt('Supplemental '.$type.' Documents');                                            \%allmaps,\%rewrites,\%retitles,\%copies,\%dbcopies,
                 } else {                                            \%zombies,\%params,\%mapmoves,\%mapchanges,\%tomove,
                     $name = &mt($type.' Documents');                                            \%newsubdir,\%newurls)) {
                 }                      $mapmoves{$url} = 1;
             }                  }
     &Apache::lonhtmlcommon::add_breadcrumb(                  $url = $newurl;
       {'href'=>$url.$cpinfo,              } elsif ($env{'docs.markedcopy_nested'}) {
        'title'=>$name,                  &url_paste_fixups($url,$folder,$prefixchg,$coursedom,$coursenum,\%allmaps,\%rewrites,
        'text'=>'<font size="+1">'.                                    \%retitles,\%copies,\%dbcopies,\%zombies,\%params,\%mapmoves,
    $name.'</font>',                                    \%mapchanges,\%tomove,\%newsubdir,\%newurls); 
        'no_mt'=>1,              }
        });          } elsif ($url=~m {^/res/}) {
  $plain.=$name.' &gt; ';  # published maps can only exists once, so remove it from paste buffer when done
     }              &Apache::lonnet::delenv('docs.markedcopy');
     $plain=~s/\&gt\;\s*$//;  # if pasting published map (main content are only) check map is not already in course
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',              if ($folder =~ /^default/) {
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);                  if ($allmaps{$url}) {
 }                      return (&mt('Paste failed: only one instance of a particular published sequence or page is allowed within each course.'));
                   }
 sub log_docs {              }
     return &Apache::lonnet::instructor_log('docslog',@_);          }
 }      }
       if ($url=~ m{/smppg$}) {
 {   my $db_name = &Apache::lonsimplepage::get_db_name($url);
     my @oldresources=();   if ($db_name =~ /^smppage_/) {
     my @oldorder=();      #simple pages, need to copy the db contents to a new one.
     my $parmidx;      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
     my %parmaction=();      my $now = time();
     my %parmvalue=();      $db_name =~ s{_\d*$ }{_$now}x;
     my $changedflag;      my $dbresult=&Apache::lonnet::put($db_name,\%contents,
       $coursedom,$coursenum);
     sub snapshotbefore {              if ($dbresult eq 'ok') {
         @oldresources=@LONCAPA::map::resources;                  $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
         @oldorder=@LONCAPA::map::order;                  $title=&mt('Copy of').' '.$title;
         $parmidx=undef;              } else {
         %parmaction=();                  return (&mt('Paste failed: An error occurred when copying the simple page.'));
         %parmvalue=();              }
         $changedflag=0;   }
     }      }
       $title = &LONCAPA::map::qtunescape($title);
     sub remember_parms {      my $ext='false';
         my ($idx,$parameter,$action,$value)=@_;      if ($url=~m{^http(|s)://}) { $ext='true'; }
         $parmidx=$idx;      $url       = &LONCAPA::map::qtunescape($url);
         $parmaction{$parameter}=$action;  
         $parmvalue{$parameter}=$value;  # For uploaded files (excluding pages/sequences) path in copied file is changed
         $changedflag=1;  # if paste is from Main to Supplemental (or vice versa), or if pasting between
     }  # courses.
   
     sub log_differences {      my $newidx;
         my ($plain)=@_;      unless ($is_map) {
         my %storehash=('folder' => $plain,  # Now insert the URL at the bottom
                        'currentfolder' => $env{'form.folder'});          $newidx = &LONCAPA::map::getresidx($url);
         if ($parmidx) {          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
            $storehash{'parameter_res'}=$oldresources[$parmidx];              my $relpath = $1;
            foreach my $parm (keys(%parmaction)) {              if ($relpath ne '') {
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};                  my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};                  my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
            }                  my $newprefix = $newloc;
         }                  if ($newloc eq 'default') {
         my $maxidx=$#oldresources;                      $newprefix = 'docs';
         if ($#LONCAPA::map::resources>$#oldresources) {                  }
            $maxidx=$#LONCAPA::map::resources;                  if ($newdocsdir eq '') {
         }                      $newdocsdir = 'default';
         for (my $idx=0; $idx<=$maxidx; $idx++) {                  }
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {                  if (($prefixchg) || ($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];                      my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];                      $url =
               $changedflag=1;                          &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
            }                                                             &Apache::lonnet::getfile($oldurl));
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {                      if ($url eq '/adm/notfound.html') {
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];                          return (&mt('Paste failed: an error occurred saving the file.'));
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];                      } else {
               $changedflag=1;                          my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
            }                          $newsubpath =~ s{/+$}{/};
         }                          $docmoves{$oldurl} = $newsubpath;
  $storehash{'maxidx'}=$maxidx;                      }
         if ($changedflag) { &log_docs(\%storehash); }                  }
     }              }
 }          }
       }
   # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
       my ($result,$save_err);
       $result =
           &apply_fixups($folder,$is_map,$prefixchg,$coursedom,$coursenum,$oldurl,
 sub docs_change_log {                        $url,\%removefrommap,\%removeparam,\%rewrites,\%retitles,
     my ($r)=@_;                        \%copies,\%dbcopies,\%zombies,\%params,\%docmoves,
     my $folder=$env{'form.folder'};                        \%mapmoves,\%newsubdir,$errors,\%before,\%after);
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));      if ($result eq 'ok') {
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));          if ($is_map) { 
     my %docslog=&Apache::lonnet::dump('nohist_docslog',              my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},                                              $folder.'.'.$container);
                                       $env{'course.'.$env{'request.course.id'}.'.num'});              return $errtext if ($fatal);
   
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }              if ($#LONCAPA::map::order<1) {
                   my $idx=&LONCAPA::map::getresidx();
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.                  if ($idx<=0) { $idx=1; }
               '<input type="hidden" name="docslog" value="1" />');                  $LONCAPA::map::order[0]=$idx;
                   $LONCAPA::map::resources[$idx]='';
     my %saveable_parameters = ('show' => 'scalar',);              }
     &Apache::loncommon::store_course_settings('docs_log',              $newidx = &LONCAPA::map::getresidx($url);
                                               \%saveable_parameters);          }
     &Apache::loncommon::restore_course_settings('docs_log',          if ($env{'docs.markedcopy_supplemental'}) {
                                                 \%saveable_parameters);              if ($folder !~ /^supplemental/) {
     if (!$env{'form.show'}) { $env{'form.show'}=10; }                  (undef,undef,$title) =
     my %lt=('hiddenresource' => 'Resources hidden',                      &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental'});
     'encrypturl'     => 'URL hidden',              }
     'randompick'     => 'Randomly pick',          } else {
     'randomorder'    => 'Randomly ordered',              if ($folder=~/^supplemental/) {
     'set'            => 'set to',                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     'del'            => 'deleted');                         $env{'user.domain'}.'___&&&___'.$title;
     $r->print(&Apache::loncommon::display_filter().              }
               '<input type="hidden" name="folder" value="'.$folder.'" />'.          }
               '<input type="submit" value="'.&mt('Display').'" /></form>');          $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().          push(@LONCAPA::map::order, $newidx);
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.  
               &mt('After').'</th>'.  # Store the result
               &Apache::loncommon::end_data_table_header_row());          my ($errtext,$fatal) = 
     my $shown=0;              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {          if ($fatal) {
  if ($env{'form.displayfilter'} eq 'currentfolder') {              $save_err = $errtext;
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }          }
  }      }
         my @changes=keys(%{$docslog{$id}{'logentry'}});     
         if ($env{'form.displayfilter'} eq 'containing') {      if ($env{'form.docs.markedcopy_options'} eq 'move') {
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.          &Apache::lonnet::delenv('docs.markedcopy');
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});          &Apache::lonnet::delenv('docs.markedcopy_nested');
     foreach my $key (@changes) {          &Apache::lonnet::delenv('docs.markedcopy_nestednames');
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};      }
     }      return ($result,$save_err);
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }          }
  }  
         my $count = 0;  sub get_newmap_url {
         my $time =      my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});          $titleref,$allmaps,$newurls) = @_;
         my $plainname =      my $newurl;
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},      if ($url=~ m{^/uploaded/}) {
                                           $docslog{$id}{'exe_udom'});          $$titleref=&mt('Copy of').' '.$$titleref;
         my $about_me_link =      }
             &Apache::loncommon::aboutmewrapper($plainname,      my $now = time;
                                                $docslog{$id}{'exe_uname'},      my $suffix=$$.int(rand(100)).$now;
                                                $docslog{$id}{'exe_udom'});      my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
         my $send_msg_link='';      if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})          my $path = $1;
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {          my $prefix = $2;
             $send_msg_link ='<br />'.          my $ancestor = $3;
                 &Apache::loncommon::messagewrapper(&mt('Send message'),          if (length($ancestor) > 10) {
                                                    $docslog{$id}{'exe_uname'},              $ancestor = substr($ancestor,-10,10);
                                                    $docslog{$id}{'exe_udom'});          }
         }          my $newid;
         $r->print(&Apache::loncommon::start_data_table_row());          if ($prefixchg) {
         $r->print('<td>'.$time.'</td>              if ($folder =~ /^supplemental/) {
                        <td>'.$about_me_link.                  $prefix =~ s/^default/supplemental/;
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.              } else {
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.                  $prefix =~ s/^supplemental/default/;
                   $send_msg_link.'</td><td>'.              }
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');          }
 # Before          if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];          } else {
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];              $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
     if ($oldname ne $newname) {          }
  $r->print(&LONCAPA::map::qtescape($oldname));          my $counter = 0;
     }          my $is_unique = &uniqueness_check($newurl);
  }          if ($folder =~ /^default/) {
  $r->print('<ul>');              if ($allmaps->{$newurl}) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  $is_unique = 0;
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {              }
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');          }
     }          while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
  }              $counter ++;
  $r->print('</ul>');              $suffix ++;
 # After              if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
         $r->print('</td><td>');                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
               } else {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];              }
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];              $is_unique = &uniqueness_check($newurl);
     if ($oldname ne '' && $oldname ne $newname) {          }
  $r->print(&LONCAPA::map::qtescape($newname));          if ($is_unique) {
     }              $newurls->{$newurl} = 1;
  }                  } else {
  $r->print('<ul>');              if ($url=~/\.page$/) {
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {              } else {
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
     }              }
  }          }
  $r->print('</ul>');      }
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {      return ($newurl);
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');  }
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {  
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {  sub dbcopy {
     $r->print('<li>'.      my ($url,$coursedom,$coursenum) = @_;
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',      if ($url=~ m{/smppg$}) {
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})          my $db_name = &Apache::lonsimplepage::get_db_name($url);
       .'</li>');          if ($db_name =~ /^smppage_/) {
  }              #simple pages, need to copy the db contents to a new one.
     }              my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
     $r->print('</ul>');              my $now = time();
  }              $db_name =~ s{_\d*$ }{_$now}x;
 # End              my $result=&Apache::lonnet::put($db_name,\%contents,
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());                                              $coursedom,$coursenum);
         $shown++;              $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
         if (!($env{'form.show'} eq &mt('all')          }
               || $shown<=$env{'form.show'})) { last; }      }
     }      return $url;
     $r->print(&Apache::loncommon::end_data_table());  }
 }  
   sub uniqueness_check {
 sub update_paste_buffer {      my ($newurl) = @_;
     my ($coursenum,$coursedom) = @_;      my $unique = 1;
       foreach my $res (@LONCAPA::map::order) {
     return if (!defined($env{'form.markcopy'}));          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     return if (!defined($env{'form.copyfolder'}));          $url=&LONCAPA::map::qtescape($url);
     return if ($env{'form.markcopy'} < 0);          if ($newurl eq $url) {
               $unique = 0;
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,              last;
     $env{'form.copyfolder'});          }
          }
     return if ($fatal);      return $unique;
   }
 # Mark for copying  
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);  sub contained_map_check {
     if (&is_supplemental_title($title)) {      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});          $allmaps) = @_;
  ($title) = &parse_supplemental_title($title);      my $content = &Apache::lonnet::getfile($url);
     } elsif ($env{'docs.markedcopy_supplemental'}) {      unless ($content eq '-1') {
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');          my $parser = HTML::TokeParser->new(\$content);
     }          $parser->attr_encoded(1);
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};          while (my $token = $parser->get_token) {
               next if ($token->[0] ne 'S');
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,              if ($token->[1] eq 'resource') {
     'docs.markedcopy_url'   => $url});                  next if ($token->[2]->{'type'} eq 'zombie');
     delete($env{'form.markcopy'});                  my $ressrc = $token->[2]->{'src'};
 }                  if ($folder =~ /^supplemental/) {
                       unless (&supp_pasteable($ressrc)) {
 sub print_paste_buffer {                          $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     my ($r,$container) = @_;                          next;
     return if (!defined($env{'docs.markedcopy_url'}));                      }
                   }
     $r->print(<<ENDPASTE);                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>                      if ($1 eq 'uploaded') {
 ENDPASTE                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');                          $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
                       } else {
     my $type;                          if ($allmaps->{$ressrc}) {
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc; 
  $type = &mt('External Resource');                          } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
  $r->print($type.': '.                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.                          } else {
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');                              $addedmaps->{$ressrc} = [$url];
     }  else {                          }
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];                      }
  my $icon = &Apache::loncommon::icon($extension);                      &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
  if ($extension eq 'sequence' &&                                           $addedmaps,$hierarchy,$titles,$allmaps);
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {                  }
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));              } elsif ($token->[1] eq 'param') {
     $icon .= '/folder_closed.gif';                  if ($folder =~ /^supplemental/) {
  }                      if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';                          push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));                      } else {
     }                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
     if ($container eq 'page') {                      }
  $r->print('                  }
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />              }
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />          }
 ');      }
     } else {      return;
  $r->print('  }
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />  
 ');  sub reinit_role {
     }      my ($cdom,$cnum,$chome) = @_;
     $r->print('</p></form>');      my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
 }      unless ($ferr) {
           &Apache::loncommon::update_content_constraints($cdom,$cnum,$chome,$cdom.'_'.$cnum);
 sub do_paste_from_buffer {      }
     my ($coursenum,$coursedom,$folder) = @_;      return;
   }
     if (!$env{'form.pastemarked'}) {  
         return;  sub url_paste_fixups {
     }      my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$allmaps,$rewrites,$retitles,$copies,
           $dbcopies,$zombies,$params,$mapmoves,$mapchanges,$tomove,$newsubdir,$newurls) = @_;
 # paste resource to end of list      my $checktitle;
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});      if (($prefixchg) &&
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});          ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
 # Maps need to be copied first          $checktitle = 1;
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {      }
  $title=&mt('Copy of').' '.$title;      my $skip;
  my $newid=$$.int(rand(100)).time;      if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);          my $mapid = $1.$2;
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {          if ($tomove->{$mapid}) {
             my $path = $1;              $skip = 1;
             my $prefix = $2;          }
             my $ancestor = $3;      }
             if (length($ancestor) > 10) {      my $file = &Apache::lonnet::getfile($oldurl);
                 $ancestor = substr($ancestor,-10,10);      return if ($file eq '-1');
             }      my $parser = HTML::TokeParser->new(\$file);
             $oldid = $path.$prefix.$ancestor;      $parser->attr_encoded(1);
         }      my $changed = 0;
         my $counter = 0;      while (my $token = $parser->get_token) {
         my $newurl=$oldid.$newid.'.'.$ext;          next if ($token->[0] ne 'S');
         my $is_unique = &uniqueness_check($newurl);          if ($token->[1] eq 'resource') {
         while (!$is_unique && $counter < 100) {              my $ressrc = $token->[2]->{'src'};
             $counter ++;              next if ($ressrc eq '');
             $newid ++;              my $id = $token->[2]->{'id'};
             $newurl = $oldid.$newid;              my $title = $token->[2]->{'title'};
             $is_unique = &uniqueness_check($newurl);              if ($checktitle) {
         }                  if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
         if (!$is_unique) {                      $retitles->{$oldurl}{$ressrc} = $id;
             if ($url=~/\.page$/) {                  }
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');              }
             } else {              next if ($token->[2]->{'type'} eq 'external');
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');              if ($token->[2]->{'type'} eq 'zombie') {
             }                  next if ($skip);  
         }                  $zombies->{$oldurl}{$ressrc} = $id;
  my $storefn=$newurl;                  $changed = 1;
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};              } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
  my $paste_map_result =                  my $srcdom = $1;
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,                  my $srcnum = $2;
        &Apache::lonnet::getfile($url));                  my $rem = $3;
         if ($paste_map_result eq '/adm/notfound.html') {                  my $newurl;
             if ($url=~/\.page$/) {                  my $mapname;
                 return &mt('Paste failed: an error occurred saving the composite page');                  if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
             } else {                      my $prefix = $1;
                 return &mt('Paste failed: an error occurred saving the folder');                      $mapname = $prefix.$2;
             }                      if ($tomove->{$mapname}) {
         }                          &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,$allmaps,
  $url = $newurl;                                            $rewrites,$retitles,$copies,$dbcopies,$zombies,
     }                                            $params,$mapmoves,$mapchanges,$tomove,$newsubdir,
 # published maps can only exists once, so remove it from paste buffer when done                                            $newurls);
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {                          next;
  &Apache::lonnet::delenv('docs\\.markedcopy');                      } else {
     }                          ($newurl,my $error) =
     if ($url=~ m{/smppg$}) {                              &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
  my $db_name = &Apache::lonsimplepage::get_db_name($url);                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
  if ($db_name =~ /^smppage_/) {                          if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
     #simple pages, need to copy the db contents to a new one.                              $newsubdir->{$ressrc} = $1;
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);                          }
     my $now = time();                          if ($error) {
     $db_name =~ s{_\d*$ }{_$now}x;                              next;
     my $result=&Apache::lonnet::put($db_name,\%contents,                          }
     $coursedom,$coursenum);                      }
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;                  }
     $title=&mt('Copy of').' '.$title;                  if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
  }                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
     }                     
     $title = &LONCAPA::map::qtunescape($title);                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
     my $ext='false';                          $rewrites->{$oldurl}{$ressrc} = $id;
     if ($url=~m{^http(|s)://}) { $ext='true'; }                          $mapchanges->{$ressrc} = 1;
     $url       = &LONCAPA::map::qtunescape($url);                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,$allmaps,
 # Now insert the URL at the bottom                                                    $rewrites,$retitles,$copies,$dbcopies,$zombies,
     my $newidx = &LONCAPA::map::getresidx($url);                                                    $params,$mapmoves,$mapchanges,$tomove,$newsubdir,
     if ($env{'docs.markedcopy_supplemental'}) {                                                    $newurls)) {
         if ($folder =~ /^supplemental/) {                              $mapmoves->{$ressrc} = 1;
             $title = $env{'docs.markedcopy_supplemental'};                          }
         } else {                          $changed = 1;
             (undef,undef,$title) =                      } else {
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});                          $rewrites->{$oldurl}{$ressrc} = $id;
         }                          $copies->{$oldurl}{$ressrc} = $id;
     } else {                          $changed = 1;
         if ($folder=~/^supplemental/) {                      }
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                  }
                   $env{'user.domain'}.'___&&&___'.$title;              } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/(.+)$}) {
         }                  next if ($skip);  
     }                  my $srcdom = $1;
                   my $srcnum = $2;
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
     push(@LONCAPA::map::order, $newidx);                      $rewrites->{$oldurl}{$ressrc} = $id;
     return 'ok';                      $dbcopies->{$oldurl}{$ressrc} = $id;
 # Store the result                      $changed = 1;
 }                  }
               } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
 sub uniqueness_check {                  next if ($skip);
     my ($newurl) = @_;                  my $srcdom = $1;
     my $unique = 1;                  my $srcnum = $2;
     foreach my $res (@LONCAPA::map::order) {                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                      $rewrites->{$oldurl}{$ressrc} = $id;
         $url=&LONCAPA::map::qtescape($url);                      $dbcopies->{$oldurl}{$ressrc} = $id;
         if ($newurl eq $url) {                      $changed = 1;
             $unique = 0;                  }
             last;                  }
         }          } elsif ($token->[1] eq 'param') {
     }              next if ($skip);
     return $unique;              my $to = $token->[2]->{'to'}; 
 }              if ($to ne '') {
                   if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
 my %parameter_type = ( 'randompick'     => 'int_pos',                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
        'hiddenresource' => 'string_yesno',                  } else {
        'encrypturl'     => 'string_yesno',                      @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
        'randomorder'    => 'string_yesno',);                  }
 my $valid_parameters_re = join('|',keys(%parameter_type));              }
 # set parameters          }
 sub update_parameter {      }
       return $changed;
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);  }
   
     my $which = $env{'form.changeparms'};  sub apply_fixups {
     my $idx = $env{'form.setparms'};      my ($folder,$is_map,$prefixchg,$cdom,$cnum,$oldurl,$url,$removefrommap,
     if ($env{'form.'.$which.'_'.$idx}) {          $removeparam,$rewrites,$retitles,$copies,$dbcopies,$zombies,$params,
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}          $docmoves,$mapmoves,$newsubdir,$errors,$before,$after) = @_;
                                      : 'yes';      foreach my $key (keys(%{$copies}),keys(%{$docmoves})) {
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,          my @allcopies;
       $parameter_type{$which});          if (ref($copies->{$key}) eq 'HASH') {
  &remember_parms($idx,$which,'set',$value);              my %added;
     } else {              foreach my $innerkey (keys(%{$copies->{$key}})) {
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);                  if (($innerkey ne '') && (!$added{$innerkey})) {
                       push(@allcopies,$innerkey);
  &remember_parms($idx,$which,'del');                      $added{$innerkey} = 1;
     }                  }
     return 1;              }
 }              undef(%added);
           }
           if ($key eq $oldurl) {
 sub handle_edit_cmd {              if ((exists($docmoves->{$key}))) {
     my ($coursenum,$coursedom) =@_;                  unless (grep(/^\Q$oldurl\E/,@allcopies)) {
                       push(@allcopies,$oldurl);
     my ($cmd,$idx)=split('_',$env{'form.cmd'});                  }
               }
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];          }
     my ($title, $url, @rrest) = split(':', $ratstr);          if (@allcopies > 0) {
               foreach my $item (@allcopies) {
     if ($cmd eq 'del') {                  my ($relpath,$oldsubdir,$fname) = 
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {                  if ($fname ne '') {
     &Apache::lonnet::removeuploadedurl($url);                      my $content = &Apache::lonnet::getfile($item);
  } else {                      unless ($content eq '-1') {
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                          my $storefn;
  }                          if (($key eq $oldurl) && (ref($docmoves) eq 'HASH') && (exists($docmoves->{$key}))) {
  splice(@LONCAPA::map::order, $idx, 1);                              $storefn = $docmoves->{$key};
                           } else {
     } elsif ($cmd eq 'cut') {                              $storefn = $relpath;
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
  splice(@LONCAPA::map::order, $idx, 1);                              if ($prefixchg) {
                                   $storefn =~ s/^\Q$before->{'doc'}\E/$after->{'doc'}/;
     } elsif ($cmd eq 'up'                              }
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {                              if ($newsubdir->{$key}) {
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];                                  $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir->{$key}#;
                               }
     } elsif ($cmd eq 'down'                          }
      && defined($LONCAPA::map::order[$idx+1])) {                          &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];                          my $copyurl = 
                               &Apache::lonclonecourse::writefile($env{'request.course.id'},
     } elsif ($cmd eq 'rename') {                                                                 $storefn.$fname,$content);
                           if ($copyurl eq '/adm/notfound.html') {
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});                              if ((ref($docmoves) eq 'HASH') && (exists($docmoves->{$oldurl}))) {
  if ($comment=~/\S/) {                                  return &mt('Paste failed: an error occurred copying the file.');
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=                              } elsif (ref($errors) eq 'HASH') {
  $comment.':'.join(':', $url, @rrest);                                  $errors->{$item} = 1;
  }                              }
 # Devalidate title cache                          }
  my $renamed_url=&LONCAPA::map::qtescape($url);                      }
  &Apache::lonnet::devalidate_title_cache($renamed_url);                  }
     } else {              }
  return 0;          }
     }      }
     return 1;      foreach my $key (keys(%{$mapmoves})) {
 }          my $storefn=$key;
           $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
 sub editor {          if ($prefixchg) {
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;              $storefn =~ s/^\Q$before->{'map'}\E/$after->{'map'}/;
           }
     my $container= ($env{'form.pagepath'}) ? 'page'          if ($newsubdir->{$key}) {
                            : 'sequence';              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir->{$key}/;
           }
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,          my $mapcontent = &Apache::lonnet::getfile($key);
     $folder.'.'.$container);          if ($mapcontent eq '-1') {
     return $errtext if ($fatal);              if (ref($errors) eq 'HASH') {
                   $errors->{$key} = 1;
     if ($#LONCAPA::map::order<1) {              }
  my $idx=&LONCAPA::map::getresidx();          } else {
  if ($idx<=0) { $idx=1; }              my $newmap =
         $LONCAPA::map::order[0]=$idx;                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
         $LONCAPA::map::resources[$idx]='';                                                     $mapcontent);
     }              if ($newmap eq '/adm/notfound.html') {
                      if (ref($errors) eq 'HASH') {
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=                      $errors->{$key} = 1;
  &breadcrumbs($folder,$allowed,$type);                  }
     $r->print($breadcrumbtrail);              }
              }
 # ------------------------------------------------------------ Process commands      }
       my %updates;
 # ---------------- if they are for this folder and user allowed to make changes      if ($is_map) {
     if (($allowed) && ($env{'form.folder'} eq $folder)) {          foreach my $key (keys(%{$rewrites})) {
 # set parameters and change order              $updates{$key} = 1;
  &snapshotbefore();          }
           foreach my $key (keys(%{$zombies})) {
  if (&update_parameter()) {              $updates{$key} = 1;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          }
     return $errtext if ($fatal);          foreach my $key (keys(%{$removefrommap})) {
  }              $updates{$key} = 1;
           }
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {          foreach my $key (keys(%{$removeparam})) {
 # change order              $updates{$key} = 1;
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);          }
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);          foreach my $key (keys(%{$dbcopies})) {
               $updates{$key} = 1;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          }
     return $errtext if ($fatal);          foreach my $key (keys(%{$retitles})) {
  }              $updates{$key} = 1;
               }
  if ($env{'form.pastemarked'}) {          foreach my $key (keys(%updates)) {
             my $paste_res =              my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);              if (ref($rewrites->{$key}) eq 'HASH') {
             if ($paste_res eq 'ok') {                  %torewrite = %{$rewrites->{$key}};
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);              }
                 return $errtext if ($fatal);              if (ref($retitles->{$key}) eq 'HASH') {
             } elsif ($paste_res ne '') {                  %toretitle = %{$retitles->{$key}};
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');              }
             }              if (ref($removefrommap->{$key}) eq 'HASH') {
  }                  %toremove = %{$removefrommap->{$key}};
               }
  $r->print($upload_output);              if (ref($removeparam->{$key}) eq 'HASH') {
                   %remparam = %{$removeparam->{$key}};
  if (&handle_edit_cmd()) {              }
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);              if (ref($zombies->{$key}) eq 'HASH') {
     return $errtext if ($fatal);                  %zombie = %{$zombies->{$key}};
  }              }
 # Group import/search              if (ref($dbcopies->{$key}) eq 'HASH') {
  if ($env{'form.importdetail'}) {                  foreach my $item (keys(%{$dbcopies->{$key}})) {
     my @imports;                      $newdb{$item} = &dbcopy($item);
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {                  }
  if (defined($item)) {              }
     my ($name,$url,$residx)=              if (ref($params->{$key}) eq 'HASH') {
  map {&unescape($_)} split(/\=/,$item);                  %currparam = %{$params->{$key}};
     push(@imports, [$name, $url, $residx]);              }
  }              my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
     }              if ($fatal) {
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,                  return $errtext;
     $container,'londocs',@imports);              }
     return $errtext if ($fatal);              for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
  }                  if (defined($LONCAPA::map::zombies[$i])) {
 # Loading a complete map                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
  if ($env{'form.loadmap'}) {                      if ($zombie{$src} eq $i) {
     if ($env{'form.importmap'}=~/\w/) {                          undef($LONCAPA::map::zombies[$i]);
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {                      }
     my ($title,$url,$ext,$type)=split(/\:/,$res);                  }
     my $idx=&LONCAPA::map::getresidx($url);              }
     $LONCAPA::map::resources[$idx]=$res;              for (my $i=0; $i<@LONCAPA::map::resources; $i++) {
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;                  if (defined($LONCAPA::map::resources[$i])) {
  }                      my $changed;
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$i]);
     $folder.'.'.$container);                      if ($toremove{$src} eq $i) {
  return $errtext if ($fatal);                          splice(@LONCAPA::map::order,$i,1);
     } else {                          if (ref($currparam{$i}) eq 'ARRAY') {
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');                              foreach my $name (@{$currparam{$i}}) {
                                   &LONCAPA::map::delparameter($i,'parameter_'.$name);
     }                              }
  }                          }
  &log_differences($plain);                          next;
     }                      }
 # ---------------------------------------------------------------- End commands                      my $origsrc = $src;
 # ---------------------------------------------------------------- Print screen                      if ((exists($toretitle{$src})) && ($toretitle{$src} eq $i)) {
     my $idx=0;                          if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
     my $shown=0;                              $changed = 1;
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {                          }
  $r->print('<p>'.&mt('Parameters').':<ul>'.                      }
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').                      if ((exists($torewrite{$src})) && ($torewrite{$src} eq $i)) {
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').                          if ($origsrc =~ m{^/uploaded/}) {
   '</ul></p>');                              if ($prefixchg) {
     }                                                                                                                                      if ($src =~ /\.(page|sequence)$/) {
     if ($randompick>=0) {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before->{'map'}\E#$1$after->{'map'}#;
  $r->print('<p>'.&mt('Caution: this folder is set to randomly pick a subset of resources. Adding or removing resources from this folder will change the set of resources that the students see, resulting in spurious or missing credit for completed problems, not limited to ones you modify. Do not modify the contents of this folder if it is in active student use.').'</p>');                                  } else {
     }                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before->{'doc'}\E#$1$after->{'doc'}#;
     if ($is_random_order) {                                  }
  $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');                              }
     }                              if ($newsubdir->{$origsrc}) {
     $r->print('<table class="LC_docs_editor">');                                  if ($src =~ /\.(page|sequence)$/) {
     foreach my $res (@LONCAPA::map::order) {                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir->{$origsrc}#;
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);                                  } else {
  $name=&LONCAPA::map::qtescape($name);                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir->{$origsrc}#;
  $url=&LONCAPA::map::qtescape($url);                                  }
  unless ($name) {  $name=(split(/\//,$url))[-1]; }                              }
  unless ($name) { $idx++; next; }                          }
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,                          $changed = 1;
      $coursenum));                      } elsif ($newdb{$src} ne '') {
  $idx++;                          $src = $newdb{$src};
  $shown++;                          $changed = 1;
     }                      }
     unless ($shown) {                      if ($changed) {
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');                          $LONCAPA::map::resources[$i] = join(':',($title,$src,$ext,$type));
     }                      }
     $r->print("\n</table>\n");                  }
     if ($allowed) {              }
         &print_paste_buffer($r,$container);              foreach my $idx (keys(%remparam)) {
     }                  if (ref($remparam{$idx}) eq 'ARRAY') {
     return;                      foreach my $name (@{$remparam{$idx}}) {   
 }                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
                       }
 sub process_file_upload {                  }
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;              }
 # upload a file, if present              my $storefn;
     my $parseaction;              if ($key eq $oldurl) {
    if ($env{'form.parserflag'}) {                  $storefn = $url;
         $parseaction = 'parse';                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     }              } else {
     my $phase_status;                  $storefn = $key;
     my $folder=$env{'form.folder'};                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     if ($folder eq '') {                  if ($prefixchg) {
         $folder='default';                      $storefn =~ s/^\Q$before->{'map'}\E/$after->{'map'}/;
     }                  }
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {                  if ($newsubdir->{$key}) {
         my $errtext='';                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir->{$key}/;
         my $fatal=0;                  }
         my $container='sequence';              }
         if ($env{'form.pagepath'}) {              my $report;
             $container='page';              if ($folder !~ /^supplemental/) {
         }                  $report = 1;
         ($errtext,$fatal)=              }
               &mapread($coursenum,$coursedom,$folder.'.'.$container);              my ($outtext,$errtext) =
         if ($#LONCAPA::map::order<1) {                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
             $LONCAPA::map::order[0]=1;              if ($errtext) {
             $LONCAPA::map::resources[1]='';                  return &mt('Paste failed: an error occurred saving the folder or page.');
         }              }
         if ($fatal) {          }
             return 'failed';      }
         }      return 'ok';
         my $destination = 'docs/';  }
         if ($folder =~ /^supplemental/) {  
             $destination = 'supplemental/';  sub copy_dependencies {
         }      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
         if (($folder eq 'default') || ($folder eq 'supplemental')) {      my $content;
             $destination .= 'default/';      if (ref($contentref)) {
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {          $content = $$contentref;
             $destination .=  $2.'/';      } else {
         }          $content = &Apache::lonnet::getfile($item);
 # this is for a course, not a user, so set coursedoc flag      }
 # probably the only place in the system where this should be "1"      unless ($content eq '-1') {
         my $newidx=&LONCAPA::map::getresidx();          my $mm = new File::MMagic;
         $destination .= $newidx;          my $mimetype = $mm->checktype_contents($content);
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,          if ($mimetype eq 'text/html') {
  $parseaction,$allfiles,              my (%allfiles,%codebase,$state);
  $codebase);              my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
         my $ext='false';              if ($res eq 'ok') {
         if ($url=~m{^http://}) { $ext='true'; }                  my ($numexisting,$numpathchanges,$existing);
  $url     = &LONCAPA::map::qtunescape($url);                  (undef,$numexisting,$numpathchanges,$existing) =
         my $comment=$env{'form.comment'};                      &Apache::loncommon::ask_for_embedded_content(
  $comment = &LONCAPA::map::qtunescape($comment);                          '/adm/coursedocs',$state,\%allfiles,\%codebase,
         if ($folder=~/^supplemental/) {                          {'error_on_invalid_names'   => 1,
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                           'ignore_remote_references' => 1,
                   $env{'user.domain'}.'___&&&___'.$comment;                           'docs_url'                 => $item,
         }                           'context'                  => 'paste'});
                   if ($numexisting > 0) {
         $LONCAPA::map::resources[$newidx]=                      if (ref($existing) eq 'HASH') {
     $comment.':'.$url.':'.$ext.':normal:res';                          foreach my $dep (keys(%{$existing})) {
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;                              my $depfile = $dep;
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,                              unless ($depfile =~ m{^\Q$relpath\E}) {
     $folder.'.'.$container);                                  $depfile = $relpath.$dep;
         if ($fatal) {                              }
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';                              my $depcontent = &Apache::lonnet::getfile($depfile);
             return 'failed';                              unless ($depcontent eq '-1') {
         } else {                                  my $storedep = $dep;
             if ($parseaction eq 'parse') {                                  $storedep =~ s{^\Q$relpath\E}{};
                 my $total_embedded = keys(%{$allfiles});                                  my $dep_url =
                 if ($total_embedded > 0) {                                      &Apache::lonclonecourse::writefile(
                     my $num = 0;                                          $env{'request.course.id'},
     my $state = '                                          $storefn.$storedep,$depcontent);
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />                                  if ($dep_url eq '/adm/notfound.html') {
    <input type="hidden" name="cmd" value="upload_embedded" />                                      if (ref($errors) eq 'HASH') {
    <input type="hidden" name="newidx" value="'.$newidx.'" />                                          $errors->{$depfile} = 1;
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />                                      }
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';                                  } else {
     $phase_status = 'phasetwo';                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
                                   }
                     $$upload_output .=                              }
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.                          }
  &Apache::loncommon::ask_for_embedded_content(                      }
                             '/adm/coursedocs',$state,$allfiles,$codebase);                  }
                 } else {              }
                     $$upload_output .= 'No embedded items identified<br />';          }
                 }      }
             }      return;
         }  }
     }  
     return $phase_status;  my %parameter_type = ( 'randompick'     => 'int_pos',
 }         'hiddenresource' => 'string_yesno',
          'encrypturl'     => 'string_yesno',
 sub process_secondary_uploads {         'randomorder'    => 'string_yesno',);
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;  my $valid_parameters_re = join('|',keys(%parameter_type));
     my $folder=$env{'form.folder'};  # set parameters
     my $destination = 'docs/';  sub update_parameter {
     if ($folder =~ /^supplemental/) {  
         $destination = 'supplemental/';      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     }  
     if (($folder eq 'default') || ($folder eq 'supplemental')) {      my $which = $env{'form.changeparms'};
         $destination .= 'default/';      my $idx = $env{'form.setparms'};
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {      if ($env{'form.'.$which.'_'.$idx}) {
         $destination .=  $2.'/';   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
     }                                       : 'yes';
     $destination .= $newidx;   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
     my ($url,$filename);        $parameter_type{$which});
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);   &remember_parms($idx,$which,'set',$value);
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});      } else {
     return $filename;   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
 }  
    &remember_parms($idx,$which,'del');
 sub is_supplemental_title {      }
     my ($title) = @_;      return 1;
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);  }
 }  
   
 sub parse_supplemental_title {  sub handle_edit_cmd {
     my ($title) = @_;      my ($coursenum,$coursedom) =@_;
       my ($cmd,$idx)=split('_',$env{'form.cmd'});
     my ($foldertitle,$renametitle);  
     if ($title =~ /&amp;&amp;&amp;/) {      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  $title = &HTML::Entites::decode($title);      my ($title, $url, @rrest) = split(':', $ratstr);
     }  
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {      if ($cmd eq 'del') {
  $renametitle=$4;   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  my ($time,$uname,$udom) = ($1,$2,$3);      ($url!~/$LONCAPA::assess_page_seq_re/)) {
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);      &Apache::lonnet::removeuploadedurl($url);
  my $name =  &Apache::loncommon::plainname($uname,$udom);   } else {
  $name = &HTML::Entities::encode($name,'"<>&\'');      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.   }
     $name.': <br />'.$foldertitle;   splice(@LONCAPA::map::order, $idx, 1);
     }  
     if (wantarray) {      } elsif ($cmd eq 'cut') {
  return ($title,$foldertitle,$renametitle);   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     }   splice(@LONCAPA::map::order, $idx, 1);
     return $title;  
 }      } elsif ($cmd eq 'up'
        && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
 # --------------------------------------------------------------- An entry line   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
   
 sub entryline {      } elsif ($cmd eq 'down'
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;       && defined($LONCAPA::map::order[$idx+1])) {
    @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
     my ($foldertitle,$pagetitle,$renametitle);  
     if (&is_supplemental_title($title)) {      } elsif ($cmd eq 'rename') {
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);  
  $pagetitle = $foldertitle;   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
     } else {   if ($comment=~/\S/) {
  $title=&HTML::Entities::encode($title,'"<>&\'');      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
  $renametitle=$title;   $comment.':'.join(':', $url, @rrest);
  $foldertitle=$title;   }
  $pagetitle=$title;  # Devalidate title cache
     }   my $renamed_url=&LONCAPA::map::qtescape($url);
    &Apache::lonnet::devalidate_title_cache($renamed_url);
     my $orderidx=$LONCAPA::map::order[$index];      } else {
       return 0;
       }
     $renametitle=~s/\\/\\\\/g;      return 1;
     $renametitle=~s/\&quot\;/\\\"/g;  }
     $renametitle=~s/ /%20/g;  
     my $line='<tr>';  sub editor {
     my ($form_start,$form_end);      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 # Edit commands          $supplementalflag,$orderhash,$iconpath,$uploadtag)=@_;
     my ($container, $type, $esc_path, $path, $symb);      my $container= ($env{'form.pagepath'}) ? 'page'
     if ($env{'form.folderpath'}) {                             : 'sequence';
  $type = 'folder';  
         $container = 'sequence';      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order) =
  $esc_path=&escape($env{'form.folderpath'});          &breadcrumbs($allowed,$crstype);
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      $r->print($breadcrumbtrail);
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');  
     }      my $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
     if ($env{'form.pagepath'}) {  
         $type = $container = 'page';      unless ($allowed) {
         $esc_path=&escape($path = $env{'form.pagepath'});          $randompick = -1;
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');      }
         $symb=&escape($env{'form.pagesymb'});  
     }      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
     my $cpinfo='';      $folder.'.'.$container);
     if ($allowed) {      return $errtext if ($fatal);
  my $incindex=$index+1;  
  my $selectbox='';      if ($#LONCAPA::map::order<1) {
  if (($folder!~/^supplemental/) &&   my $idx=&LONCAPA::map::getresidx();
     ($#LONCAPA::map::order>0) &&   if ($idx<=0) { $idx=1; }
     ((split(/\:/,          $LONCAPA::map::order[0]=$idx;
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]          $LONCAPA::map::resources[$idx]='';
      ne '') &&      }
     ((split(/\:/,  
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]  # ------------------------------------------------------------ Process commands
      ne '')) {  
     $selectbox=  # ---------------- if they are for this folder and user allowed to make changes
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.      if (($allowed) && ($env{'form.folder'} eq $folder)) {
  '<select name="newpos" onChange="this.form.submit()">';  # set parameters and change order
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {   &snapshotbefore();
  if ($i==$incindex) {  
     $selectbox.='<option value="" selected="1">('.$i.')</option>';   if (&update_parameter()) {
  } else {      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';      return $errtext if ($fatal);
  }   }
     }  
     $selectbox.='</select>';   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
  }  # change order
  my %lt=&Apache::lonlocal::texthash(      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
                 'up' => 'Move Up',      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
  'dw' => 'Move Down',  
  'rm' => 'Remove',      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                 'ct' => 'Cut',      return $errtext if ($fatal);
  'rn' => 'Rename',   }
  'cp' => 'Copy');  
  my $nocopy=0;   if ($env{'form.pastemarked'}) {
         my $nocut=0;              my %paste_errors;
         if ($url=~/\.(page|sequence)$/) {              my ($paste_res,$save_error) =
     if ($url =~ m{/res/}) {                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
  # no copy for published maps                                        \%paste_errors);
  $nocopy = 1;                  if ($save_error ne '') {
     } else {                      return $save_error; 
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {                  }
     my ($title,$url,$ext,$type)=split(/\:/,$item);              if ($paste_res ne 'ok') {
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
  $nocopy=1;              }
  last;              if (keys(%paste_errors) > 0) {
     }                  $r->print('<p span class="LC_warning">'."\n".
  }                            &mt('The following files are either dependencies of a web page or references within a folder and/or composite page which could not be copied during the paste operation:')."\n".
     }                            '<ul>'."\n");
  }                  foreach my $key (sort(keys(%paste_errors))) {
         if ($url=~/^\/res\/lib\/templates\//) {                      $r->print('<li>'.$key.'</li>'."\n");
            $nocopy=1;                  }
            $nocut=1;                  $r->print('</ul></p>'."\n");
         }              }
         my $copylink='&nbsp;';   }
         my $cutlink='&nbsp;';  
    $r->print($upload_output);
  my $skip_confirm = 0;  
  if ( $folder =~ /^supplemental/   if (&handle_edit_cmd()) {
      || ($url =~ m{( /smppg$              my $contentchg;
     |/syllabus$              if ($env{'form.cmd'} =~ /^(del|cut)_/) {
     |/aboutme$                  $contentchg = 1;
     |/navmaps$              }
     |/bulletinboard$      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
     |\.html$      return $errtext if ($fatal);
     |^/adm/wrapper/ext)}x)) {   }
     $skip_confirm = 1;  # Group import/search
  }   if ($env{'form.importdetail'}) {
       my @imports;
  if (!$nocopy) {      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
     $copylink=(<<ENDCOPY);   if (defined($item)) {
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>      my ($name,$url,$residx)=
 ENDCOPY   map {&unescape($_)} split(/\=/,$item);
         }                      if ($url=~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
  if (!$nocut) {                          my ($suffix,$errortxt,$locknotfreed) = 
     $cutlink=(<<ENDCUT);                              &newmap_suffix($1,$2,$coursedom,$coursenum);
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>                          if ($locknotfreed) {
 ENDCUT                              $r->print($locknotfreed);
         }                          }
  $form_start = (<<END);                          if ($suffix) {
    <form  action="/adm/coursedocs" method="post">                              $url =~ s/_new\./_$suffix./; 
    <input type="hidden" name="${type}path" value="$path" />                          } else {
    <input type="hidden" name="${type}symb" value="$symb" />                              return $errortxt;
    <input type="hidden" name="setparms" value="$orderidx" />                          }
    <input type="hidden" name="changeparms" value="0" />                      }
 END      push(@imports, [$name, $url, $residx]);
         $form_end = '</form>';   }
  $line.=(<<END);      }
 <td>      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
    <table class="LC_docs_entry_move">      $container,'londocs',@imports);
       <tr>      return $errtext if ($fatal);
          <td>   }
             <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" /></a>  # Loading a complete map
          </td>   if ($env{'form.loadmap'}) {
       </tr>      if ($env{'form.importmap'}=~/\w/) {
       <tr>   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
         <td>      my ($title,$url,$ext,$type)=split(/\:/,$res);
            <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" /></a>      my $idx=&LONCAPA::map::getresidx($url);
         </td>      $LONCAPA::map::resources[$idx]=$res;
       </tr>      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
     </table>   }
 </td>   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 <td>      $folder.'.'.$container,1);
    $form_start   return $errtext if ($fatal);
    $selectbox      } else {
    $form_end   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
 </td>  
 <td class="LC_docs_entry_commands">      }
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>   }
 $cutlink   &log_differences($plain);
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>      }
 $copylink  # ---------------------------------------------------------------- End commands
 </td>  # ---------------------------------------------------------------- Print screen
 END      my $idx=0;
       my $shown=0;
     }      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
 # Figure out what kind of a resource this is   $r->print('<div class="LC_Box">'.
     my ($extension)=($url=~/\.(\w+)$/);            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
     my $uploaded=($url=~/^\/*uploaded\//);    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
     my $icon=&Apache::loncommon::icon($url);    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
     my $isfolder=0;    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
     my $ispage=0;    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
     my $folderarg;    '</ol>');
     my $pagearg;          if ($randompick>=0) {
     my $pagefile;              $r->print('<p class="LC_warning">'
     if ($uploaded) {                   .&mt('Caution: this folder is set to randomly pick a subset'
  if ($extension eq 'sequence') {                       .' of resources. Adding or removing resources from this'
     $icon=$iconpath.'/folder_closed.gif';                       .' folder will change the set of resources that the'
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;                       .' students see, resulting in spurious or missing credit'
     $url='/adm/coursedocs?';                       .' for completed problems, not limited to ones you'
     $folderarg=$1;                       .' modify. Do not modify the contents of this folder if'
     $isfolder=1;                       .' it is in active student use.')
         } elsif ($extension eq 'page') {                   .'</p>'
             $icon=$iconpath.'/page.gif';              );
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;          }
             $pagearg=$1;          if ($is_random_order) {
             $url='/adm/coursedocs?';              $r->print('<p class="LC_warning">'
             $ispage=1;                   .&mt('Caution: this folder is set to randomly order its'
  } else {                       .' contents. Adding or removing resources from this folder'
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);                       .' will change the order of resources shown.')
  }                   .'</p>'
     }              );
              }
     my $orig_url = $url;          $r->print('</div>');
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});      }
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {  
  my $symb=&Apache::lonnet::symbclean(      my ($to_show,$output);
           &Apache::lonnet::declutter('uploaded/'.  
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.      &Apache::loncommon::start_data_table_count(); #setup a row counter 
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.      foreach my $res (@LONCAPA::map::order) {
            '.sequence').          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
            '___'.$residx.'___'.          $name=&LONCAPA::map::qtescape($name);
    &Apache::lonnet::declutter($url));          $url=&LONCAPA::map::qtescape($url);
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);          unless ($name) {  $name=(split(/\//,$url))[-1]; }
  $url=&Apache::lonnet::clutter($url);          unless ($name) { $idx++; next; }
  if ($url=~/^\/*uploaded\//) {          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
     $url=~/\.(\w+)$/;                                $coursenum,$coursedom,$crstype,
     my $embstyle=&Apache::loncommon::fileembstyle($1);                                $uploadtag,$supplementalflag);
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {          $idx++;
  $url='/adm/wrapper'.$url;          $shown++;
     } elsif ($embstyle eq 'ssi') {      }
  #do nothing with these      &Apache::loncommon::end_data_table_count();
     } elsif ($url!~/\.(sequence|page)$/) {      
  $url='/adm/coursedocs/showdoc'.$url;      if ($shown) {
     }          $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
  } elsif ($url=~m|^/ext/|) {                    .&Apache::loncommon::start_data_table(undef,'contentlist');
     $url='/adm/wrapper'.$url;          if ($allowed) {
     $external = 1;              $to_show .= &Apache::loncommon::start_data_table_header_row()
  }                       .'<th colspan="2">'.&mt('Move').'</th>'
         if (&Apache::lonnet::symbverify($symb,$url)) {                       .'<th>'.&mt('Actions').'</th>'
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                       .'<th colspan="2">'.&mt('Document').'</th>';
         } else {              if ($folder !~ /^supplemental/) {
             $url='';                  $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
         }              }
  if ($container eq 'page') {              $to_show .= &Apache::loncommon::end_data_table_header_row();
     my $symb=$env{'form.pagesymb'};          }
                   $to_show .= $output.' '
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);                   .&Apache::loncommon::end_data_table()
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                   .'<br style="line-height:2px;" />'
  }                   .&Apache::loncommon::end_scrollbox();
     }      } else {
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');          $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
     if ($isfolder || $extension eq 'sequence') {                   .'<div class="LC_info" id="contentlist">'
  my $foldername=&escape($foldertitle);                   .&mt('Currently no documents.')
  my $folderpath=$env{'form.folderpath'};                   .'</div>'
  if ($folderpath) { $folderpath.='&' };                   .&Apache::loncommon::end_scrollbox();
 # Append randompick number, hidden, and encrypted with ":" to foldername,      }
 # so it gets transferred between levels      my $tid = 1;
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,      if ($supplementalflag) {
                                               'parameter_randompick'))[0]          $tid = 2;
                                                .':'.((&LONCAPA::map::getparameter($orderidx,      }
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)      if ($allowed) {
                                                .':'.((&LONCAPA::map::getparameter($orderidx,          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
                                               'parameter_encrypturl'))[0]=~/^yes$/i)          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,$jumpto,
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                                         $readfile));
                                               'parameter_randomorder'))[0]=~/^yes$/i);          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
  $url.='folderpath='.&escape($folderpath).$cpinfo;      } else {
  $parameterset='<label>'.&mt('Randomly Pick: ').          if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.              #Function Box for Supplemental Content for users with mdc priv.
     (&LONCAPA::map::getparameter($orderidx,              my $funcname = &mt('Folder Editor');
                                               'parameter_randompick'))[0].              $r->print(
                                               '" />'.                  &Apache::loncommon::head_subbox(
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';                      &Apache::lonhtmlcommon::start_funclist().
     my $ro_set=                      &Apache::lonhtmlcommon::add_item_funclist(
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');                          '<a href="/adm/coursedocs?command=direct&forcesupplement=1&'.
  $rand_order_text ='                          'supppath='.&HTML::Entities::encode($env{'form.folderpath'}).'">'.
 <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>';                            '<img src="/res/adm/pages/docs.png" alt="'.$funcname.'" class="LC_icon" />'.
     }                          '<span class="LC_menubuttons_inline_text">'.$funcname.'</span></a>').
     if ($ispage) {                            &Apache::lonhtmlcommon::end_funclist()));
         my $pagename=&escape($pagetitle);          }
         my $pagepath;          $r->print($to_show);
         my $folderpath=$env{'form.folderpath'};      }
         if ($folderpath) { $pagepath = $folderpath.'&' };      return;
         $pagepath.=$pagearg.'&'.$pagename;  }
  my $symb=$env{'form.pagesymb'};  
  if (!$symb) {  sub process_file_upload {
     my $path='uploaded/'.      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.  # upload a file, if present
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';      my ($parseaction,$showupload,$nextphase,$mimetype);
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',      if ($env{'form.parserflag'}) {
        $residx,          $parseaction = 'parse';
        $path.$pagearg.'.page');      }
  }      my $folder=$env{'form.folder'};
  $url.='pagepath='.&escape($pagepath).      if ($folder eq '') {
     '&amp;pagesymb='.&escape($symb).$cpinfo;          $folder='default';
     }      }
     if ($external) {      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';          my $errtext='';
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';          my $fatal=0;
     } else {          my $container='sequence';
  undef($external);          if ($env{'form.pagepath'}) {
     }              $container='page';
     $line.='          }
   <td class="LC_docs_entry_icon">          ($errtext,$fatal)=
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'                &mapread($coursenum,$coursedom,$folder.'.'.$container);
   </td>          if ($#LONCAPA::map::order<1) {
   <td class="LC_docs_entry_title">              $LONCAPA::map::order[0]=1;
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."              $LONCAPA::map::resources[1]='';
   </td>";          }
     if (($allowed) && ($folder!~/^supplemental/)) {          if ($fatal) {
   my %lt=&Apache::lonlocal::texthash(              $$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>';
        'hd' => 'Hidden',              return;
        'ec' => 'URL hidden');          }
  my $enctext=          my $destination = 'docs/';
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');          if ($folder =~ /^supplemental/) {
  my $hidtext=              $destination = 'supplemental/';
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');          }
  $line.=(<<ENDPARMS);          if (($folder eq 'default') || ($folder eq 'supplemental')) {
   <td class="LC_docs_entry_parameter">              $destination .= 'default/';
     $form_start          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>              $destination .=  $2.'/';
     $form_end          }
   </td>  # this is for a course, not a user, so set context to coursedoc.
   <td class="LC_docs_entry_parameter">          my $newidx=&LONCAPA::map::getresidx();
     $form_start          $destination .= $newidx;
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
     $form_end   $parseaction,$allfiles,
   </td>   $codebase,undef,undef,undef,undef,
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>                                                  undef,undef,\$mimetype);
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
 ENDPARMS              my $stored = $1;
     }              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
     $line.="</tr>";                            $stored.'</span>').'</p>';
     return $line;          } else {
 }              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
               
 =pod              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
               return;
 =item tiehash()          }
           my $ext='false';
 tie the hash          if ($url=~m{^http://}) { $ext='true'; }
    $url     = &LONCAPA::map::qtunescape($url);
 =cut          my $comment=$env{'form.comment'};
    $comment = &LONCAPA::map::qtunescape($comment);
 sub tiehash {          if ($folder=~/^supplemental/) {
     my ($mode)=@_;                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     $hashtied=0;                    $env{'user.domain'}.'___&&&___'.$comment;
     if ($env{'request.course.fn'}) {          }
  if ($mode eq 'write') {  
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",          $LONCAPA::map::resources[$newidx]=
     &GDBM_WRCREAT(),0640)) {      $comment.':'.$url.':'.$ext.':normal:res';
                 $hashtied=2;          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     }          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
  } else {      $folder.'.'.$container,1);
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",          if ($fatal) {
     &GDBM_READER(),0640)) {              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
                 $hashtied=1;              return;
     }          } else {
  }              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
     }                      $$upload_output = $showupload;
 }                  my $total_embedded = scalar(keys(%{$allfiles}));
                   if ($total_embedded > 0) {
 sub untiehash {                      my $uploadphase = 'upload_embedded';
     if ($hashtied) { untie %hash; }                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
     $hashtied=0;      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
     return OK;                      my ($embedded,$num) = 
 }                          &Apache::loncommon::ask_for_embedded_content(
                               '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
                       if ($embedded) {
                           if ($num) {
                               $$upload_output .=
 sub checkonthis {           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
     my ($r,$url,$level,$title)=@_;                              $nextphase = $uploadphase;
     $url=&unescape($url);                          } else {
     $alreadyseen{$url}=1;                              $$upload_output .= $embedded;
     $r->rflush();                          }
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {                      } else {
        $r->print("\n<br />");                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
        if ($level==0) {                      }
            $r->print("<br />");                  } else {
        }                      $$upload_output .= &mt('No embedded items identified').'<br />';
        for (my $i=0;$i<=$level*5;$i++) {                  }
            $r->print('&nbsp;');                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
        }              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
        $r->print('<a href="'.$url.'" target="cat">'.                  $nextphase = 'decompress_uploaded';
  ($title?$title:$url).'</a> ');                  my $position = scalar(@LONCAPA::map::order)-1;
        if ($url=~/^\/res\//) {                  my $noextract = &return_to_editor();
   my $result=&Apache::lonnet::repcopy(                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
                               &Apache::lonnet::filelocation('',$url));                  my %archiveitems = (
           if ($result eq 'ok') {                      folderpath => $env{'form.folderpath'},
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');                      pagepath   => $env{'form.pagepath'},
              $r->rflush();                      cmd        => $nextphase,
              &Apache::lonnet::countacc($url);                      newidx     => $newidx,
              $url=~/\.(\w+)$/;                      position   => $position,
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {                      phase      => $nextphase,
  $r->print('<br />');                      comment    => $comment,
                  $r->rflush();                  );
                  for (my $i=0;$i<=$level*5;$i++) {                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
                      $r->print('&nbsp;');                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
                  }                  $$upload_output = $showupload.
                  $r->print('- '.&mt('Rendering:').' ');                                    &Apache::loncommon::decompress_form($mimetype,
  my ($errorcount,$warningcount)=split(/:/,                                        $archiveurl,'/adm/coursedocs',$noextract,
        &Apache::lonnet::ssi_body($url,                                        \%archiveitems,\@current);
        ('grade_target'=>'web',              }
  'return_only_error_and_warning_counts' => 1)));          }
                  if (($errorcount) ||      }
                      ($warningcount)) {      return $nextphase;
      if ($errorcount) {  }
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.  
                           &mt('[quant,_1,error]',$errorcount).'</span>');  sub get_dir_list {
                      }      my ($url,$coursenum,$coursedom,$newidx) = @_;
      if ($warningcount) {      my ($destination,$dir_root) = &embedded_destination();
                         $r->print('<span class="LC_warning">'.      my ($dirlistref,$listerror) =  
                           &mt('[quant,_1,warning]',$warningcount).'</span>');          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
                      }      my @dir_lines;
                  } else {      my $dirptr=16384;
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');      if (ref($dirlistref) eq 'ARRAY') {
                  }          foreach my $dir_line (sort
                  $r->rflush();                            {
              }                                my ($afile)=split('&',$a,2);
      my $dependencies=                                my ($bfile)=split('&',$b,2);
                 &Apache::lonnet::metadata($url,'dependencies');                                return (lc($afile) cmp lc($bfile));
              foreach my $dep (split(/\,/,$dependencies)) {                            } (@{$dirlistref})) {
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
                     &checkonthis($r,$dep,$level+1);              $filename =~ s/\s+$//;
                  }              next if ($filename =~ /^\.\.?$/); 
              }              my $isdir = 0;
           } elsif ($result eq 'unavailable') {              if ($dirptr&$testdir) {
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');                  $isdir = 1;
           } elsif ($result eq 'not_found') {              }
       unless ($url=~/\$/) {              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');          }
       } else {      }
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');      return @dir_lines;
       }  }
           } else {  
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');  sub is_supplemental_title {
           }      my ($title) = @_;
        }      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
     }  }
 }  
   # --------------------------------------------------------------- An entry line
   
   sub entryline {
 =pod      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
           $crstype,$uploadtag,$supplementalflag)=@_;
 =item list_symbs()      my ($foldertitle,$pagetitle,$renametitle);
       if (&is_supplemental_title($title)) {
 List Symbs   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
    $pagetitle = $foldertitle;
 =cut      } else {
    $title=&HTML::Entities::encode($title,'"<>&\'');
 sub list_symbs {   $renametitle=$title;
     my ($r) = @_;   $foldertitle=$title;
    $pagetitle=$title;
     my $type = &Apache::loncommon::course_type();      }
     $r->print(&Apache::loncommon::start_page('Symb List'));  
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));      my $orderidx=$LONCAPA::map::order[$index];
     my $navmap = Apache::lonnavmaps::navmap->new();  
     if (!defined($navmap)) {      $renametitle=~s/\\/\\\\/g;
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.      $renametitle=~s/\&quot\;/\\\"/g;
                   '<div class="LC_error">'.      $renametitle=~s/ /%20/g;
                   &mt('Unable to retrieve information about course contents').      my $line=&Apache::loncommon::start_data_table_row();
                   '</div>');      my ($form_start,$form_end,$form_common);
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});  # Edit commands
     } else {      my ($container, $type, $esc_path, $path, $symb);
         $r->print("<pre>\n");      if ($env{'form.folderpath'}) {
         foreach my $res ($navmap->retrieveResources()) {   $type = 'folder';
     $r->print($res->compTitle()."\t".$res->symb()."\n");          $container = 'sequence';
         }   $esc_path=&escape($env{'form.folderpath'});
         $r->print("\n</pre>\n");   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
     }   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');      }
 }      if ($env{'form.pagepath'}) {
           $type = $container = 'page';
           $esc_path=&escape($env{'form.pagepath'});
 sub verifycontent {   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
     my ($r) = @_;      }
     my $type = &Apache::loncommon::course_type();      my $isexternal;
    my $loaderror=&Apache::lonnet::overloaderror($r);      if (!$supplementalflag && $residx) {
    if ($loaderror) { return $loaderror; }          my $currurl = $url;
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));          if ($currurl =~ m{^/adm/wrapper/ext/}) {
    $hashtied=0;              $isexternal = 1;
    undef %alreadyseen;          }
    %alreadyseen=();          my $path = 'uploaded/'.
    &tiehash();                     $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
    foreach my $key (keys(%hash)) {                     $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
        if ($hash{$key}=~/\.(page|sequence)$/) {          $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {                                               $residx,
        $r->print('<hr /><span class="LC_error">'.                                               &Apache::lonnet::declutter($currurl));
  &mt('The following sequence or page is included more than once in your '.$type.': ').      }
  &unescape($hash{$key}).'</span><br />'.      my %lt;
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));      if ($allowed) {
    }   my $incindex=$index+1;
        }   my $selectbox='';
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {   if (($#LONCAPA::map::order>0) &&
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});      ((split(/\:/,
        }       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
    }       ne '') &&
    &untiehash();      ((split(/\:/,
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
      &mt('Return to DOCS').'</a>');       ne '')) {
 }      $selectbox=
    '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
    '<select name="newpos" onchange="this.form.submit()">';
 sub devalidateversioncache {      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
     my $src=shift;   if ($i==$incindex) {
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
   &Apache::lonnet::clutter($src));   } else {
 }      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
    }
 sub checkversions {      }
     my ($r) = @_;      $selectbox.='</select>';
     my $type = &Apache::loncommon::course_type();   }
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));   %lt=&Apache::lonlocal::texthash(
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));                  'up' => 'Move Up',
     my $header='';   'dw' => 'Move Down',
     my $startsel='';   'rm' => 'Remove',
     my $monthsel='';                  'ct' => 'Cut',
     my $weeksel='';   'rn' => 'Rename',
     my $daysel='';   'cp' => 'Copy',
     my $allsel='';                  'ex' => 'External Resource',
     my %changes=();                  'ed' => 'Edit',
     my $starttime=0;                  'pr' => 'Preview',
     my $haschanged=0;                  'sv' => 'Save',
     my %setversions=&Apache::lonnet::dump('resourceversions',                  'ul' => 'URL',
   $env{'course.'.$env{'request.course.id'}.'.domain'},                  'ti' => 'Title', 
   $env{'course.'.$env{'request.course.id'}.'.num'});                  );
    my $nocopy=0;
     $hashtied=0;          my $nocut=0;
     &tiehash();          my $noremove=0;
     my %newsetversions=();          if ($url=~ m{^/res/.+\.(page|sequence)$}) {
     if ($env{'form.setmostrecent'}) {      # no copy for published maps
  $haschanged=1;      $nocopy=1;
  foreach my $key (keys(%hash)) {   }
     if ($key=~/^ids\_(\/res\/.+)$/) {          if ($url=~/^\/res\/lib\/templates\//) {
  $newsetversions{$1}='mostrecent';             $nocopy=1;
                 &devalidateversioncache($1);             $nocut=1;
     }          }
  }          my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
     } elsif ($env{'form.setcurrent'}) {          my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  $haschanged=1;          if ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
  foreach my $key (keys(%hash)) {              if ($env{'form.folderpath'} =~ /^default&[^\&]+$/) {
     if ($key=~/^ids\_(\/res\/.+)$/) {                  my %curr_groups = &Apache::longroup::coursegroups();
  my $getvers=&Apache::lonnet::getversion($1);                  if (keys(%curr_groups) > 0) {
  if ($getvers>0) {                      $noremove=1;
     $newsetversions{$1}=$getvers;                  }
     &devalidateversioncache($1);                  $nocut=1;
  }                  $nocopy=1;
     }              }
  }          } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
     } elsif ($env{'form.setversions'}) {              my $group = $1;
  $haschanged=1;              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
  foreach my $key (keys(%env)) {                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     if ($key=~/^form\.set_version_(.+)$/) {                  if (keys(%curr_group) > 0) {
  my $src=$1;                      $noremove=1;
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {                  }
     $newsetversions{$src}=$env{$key};              }
     &devalidateversioncache($src);              $nocut=1;
  }              $nocopy=1;
     }          } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
  }              my $group = $1;
     }              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
     if ($haschanged) {                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
   $env{'course.'.$env{'request.course.id'}.'.domain'},                  if (keys(%groupsettings) > 0) {
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {                      $noremove=1;
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');                  }
  } else {                  $nocut=1;
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');                  $nocopy=1;
  }              }
  &mark_hash_old();          } elsif ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
     }              my $group = $1;
     &changewarning($r,'');              my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     if ($env{'form.timerange'} eq 'all') {              if ($url =~ /group_boards_\Q$group\E/) {
 # show all documents                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
  $header=&mt('All Documents in '.$type);                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
  $allsel=1;                  if (keys(%groupsettings) > 0) {
  foreach my $key (keys(%hash)) {                      if (ref($groupsettings{'functions'}) eq 'HASH') {
     if ($key=~/^ids\_(\/res\/.+)$/) {                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
  my $src=$1;                              $noremove=1;
  $changes{$src}=1;                          }
     }                      }
  }                  }
     } else {                  $nocut=1;
 # show documents which changed                  $nocopy=1;
  %changes=&Apache::lonnet::dump              }
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},          }
                      $env{'course.'.$env{'request.course.id'}.'.num'});          my $copylink='&nbsp;';
  my $firstkey=(keys(%changes))[0];          my $cutlink='&nbsp;';
  unless ($firstkey=~/^error\:/) {          my $removelink='&nbsp;';
     unless ($env{'form.timerange'}) {  
  $env{'form.timerange'}=604800;   my $skip_confirm = 0;
     }   if ( $folder =~ /^supplemental/
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '       || ($url =~ m{( /smppg$
  .&mt('seconds');      |/syllabus$
     if ($env{'form.timerange'}==-1) {      |/aboutme$
  $seltext='since start of course';      |/navmaps$
  $startsel='selected';      |/bulletinboard$
  $env{'form.timerange'}=time;      |\.html$)}x)
     }               || $isexternal) {
     $starttime=time-$env{'form.timerange'};      $skip_confirm = 1;
     if ($env{'form.timerange'}==2592000) {   }
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  
  $monthsel='selected';   if (!$nocopy) {
     } elsif ($env{'form.timerange'}==604800) {      $copylink=(<<ENDCOPY);
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  <a href="javascript:markcopy('$esc_path','$index','$renametitle','$container','$symb','$folder');" class="LC_docs_copy">$lt{'cp'}</a>
  $weeksel='selected';  ENDCOPY
     } elsif ($env{'form.timerange'}==86400) {          }
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   if (!$nocut) {
  $daysel='selected';      $cutlink=(<<ENDCUT);
     }  <a href="javascript:cutres('$esc_path','$index','$renametitle','$container','$symb','$folder',$skip_confirm);" class="LC_docs_cut">$lt{'ct'}</a>
     $header=&mt('Content changed').' '.$seltext;  ENDCUT
  } else {          }
     $header=&mt('No content modifications yet.');          if (!$noremove) {
  }              $removelink=(<<ENDREM);
     }  <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     %setversions=&Apache::lonnet::dump('resourceversions',  ENDREM
   $env{'course.'.$env{'request.course.id'}.'.domain'},          }
   $env{'course.'.$env{'request.course.id'}.'.num'});   $form_start = '
     my %lt=&Apache::lonlocal::texthash     <form action="/adm/coursedocs" method="post">
       ('st' => 'Version changes since start of '.$type,  ';
        'lm' => 'Version changes since last Month',          $form_common=(<<END);
        'lw' => 'Version changes since last Week',     <input type="hidden" name="${type}path" value="$path" />
        'sy' => 'Version changes since Yesterday',     <input type="hidden" name="${type}symb" value="$symb" />
                'al' => 'All Resources (possibly large output)',     <input type="hidden" name="setparms" value="$orderidx" />
        'sd' => 'Display',     <input type="hidden" name="changeparms" value="0" />
        'fi' => 'File',  END
        'md' => 'Modification Date',          $form_end = '</form>';
                'mr' => 'Most recently published Version',   $line.=(<<END);
        've' => 'Version used in '.$type,  <td>
                'vu' => 'Set Version to be used in '.$type,  <div class="LC_docs_entry_move">
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',    <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',    </a>
        'di' => 'Differences');  </div>
     $r->print(<<ENDHEADERS);  <div class="LC_docs_entry_move">
 <form action="/adm/coursedocs" method="post">    <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
 <input type="hidden" name="versions" value="1" />      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />    </a>
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />  </div>
 <select name="timerange">  </td>
 <option value='all' $allsel>$lt{'al'}</option>  <td>
 <option value="-1" $startsel>$lt{'st'}</option>     $form_start
 <option value="2592000" $monthsel>$lt{'lm'}</option>     $form_common
 <option value="604800" $weeksel>$lt{'lw'}</option>     $selectbox
 <option value="86400" $daysel>$lt{'sy'}</option>     $form_end
 </select>  </td>
 <input type="submit" name="display" value="$lt{'sd'}" />  <td class="LC_docs_entry_commands">
 <h3>$header</h3>  $removelink
 <input type="submit" name="setversions" value="$lt{'sv'}" />  $cutlink
 <table border="0">     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
 ENDHEADERS  $copylink
     foreach my $key (sort(keys(%changes))) {  </td>
  if ($changes{$key}>$starttime) {  END
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);  
     my $currentversion=&Apache::lonnet::getversion($key);      }
     if ($currentversion<0) {  # Figure out what kind of a resource this is
  $currentversion=&mt('Could not be determined.');      my ($extension)=($url=~/\.(\w+)$/);
     }      my $uploaded=($url=~/^\/*uploaded\//);
     my $linkurl=&Apache::lonnet::clutter($key);      my $icon=&Apache::loncommon::icon($url);
     $r->print(      my $isfolder=0;
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.      my $ispage=0;
       &Apache::lonnet::gettitle($linkurl).      my $folderarg;
                       '</b></font></td></tr>'.      my $pagearg;
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      my $pagefile;
                       '<td colspan="4">'.      if ($uploaded) {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.          if (($extension eq 'sequence') || ($extension eq 'page')) {
       '</a></td></tr>'.              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
                       '<tr><td></td>'.              my $containerarg = $1;
                       '<td title="'.$lt{'md'}.'">'.      if ($extension eq 'sequence') {
       &Apache::lonlocal::locallocaltime(          $icon=$iconpath.'navmap.folder.closed.gif';
                            &Apache::lonnet::metadata($root.'.'.$extension,                  $folderarg=$containerarg;
                                                      'lastrevisiondate')                  $isfolder=1;
                                                         ).              } else {
                       '</td>'.                  $icon=$iconpath.'page.gif';
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.                  $pagearg=$containerarg;
                       '<font size="+1">'.$currentversion.'</font>'.                  $ispage=1;
                       '</span></td>'.              }
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.              if ($allowed) {
                       '<font size="+1">');                  $url='/adm/coursedocs?';
 # Used in course              } else {
     my $usedversion=$hash{'version_'.$linkurl};                  $url='/adm/supplemental?';
     if (($usedversion) && ($usedversion ne 'mostrecent')) {              }
  $r->print($usedversion);   } else {
     } else {      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
  $r->print($currentversion);   }
     }      }
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.  
                       '<span class="LC_nobreak">Use: ');      my $editlink;
 # Set version      my $orig_url = $url;
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
       'set_version_'.$linkurl,      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
       ('select_form_order' =>      if (!$supplementalflag && $residx && $symb) {
        ['',1..$currentversion,'mostrecent'],          if ($container eq 'page') {
        '' => '',              $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
        'mostrecent' => 'most recent',              $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
        map {$_,$_} (1..$currentversion))));          } 
     $r->print('</span></td></tr><tr><td></td>');          if ((!$isfolder) && (!$ispage)) {
     my $lastold=1;      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {      $url=&Apache::lonnet::clutter($url);
  my $url=$root.'.'.$prevvers.'.'.$extension;      if ($url=~/^\/*uploaded\//) {
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<          $url=~/\.(\w+)$/;
     $starttime) {          my $embstyle=&Apache::loncommon::fileembstyle($1);
     $lastold=$prevvers;          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
  }      $url='/adm/wrapper'.$url;
     }          } elsif ($embstyle eq 'ssi') {
             #      #do nothing with these
             # Code to figure out how many version entries should go in          } elsif ($url!~/\.(sequence|page)$/) {
             # each of the four columns      $url='/adm/coursedocs/showdoc'.$url;
             my $entries_per_col = 0;          }
             my $num_entries = ($currentversion-$lastold);      } elsif ($url=~m|^/ext/|) {
             if ($num_entries % 4 == 0) {          $url='/adm/wrapper'.$url;
                 $entries_per_col = $num_entries/4;          $external = 1;
             } else {      }
                 $entries_per_col = $num_entries/4 + 1;              if (&Apache::lonnet::symbverify($symb,$url)) {
             }          $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
             my $entries_count = 0;              } else {
             $r->print('<td valign="top"><font size="-2">');                  $url='';
             my $cols_output = 1;              }
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {   }
  my $url=$root.'.'.$prevvers.'.'.$extension;      }
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).      my ($rand_pick_text,$rand_order_text);
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      if ($isfolder || $extension eq 'sequence') {
   &Apache::lonlocal::locallocaltime(   my $foldername=&escape($foldertitle);
                                 &Apache::lonnet::metadata($url,   my $folderpath=$env{'form.folderpath'};
                                                           'lastrevisiondate')   if ($folderpath) { $folderpath.='&' };
                                                             ).  # Append randompick number, hidden, and encrypted with ":" to foldername,
   ')');  # so it gets transferred between levels
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
                     $r->print(' <a href="/adm/diff?filename='.                                                'parameter_randompick'))[0]
       &Apache::lonnet::clutter($root.'.'.$extension).                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
       '&versionone='.$prevvers.                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
       '">'.&mt('Diffs').'</a>');                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  }                                                'parameter_encrypturl'))[0]=~/^yes$/i)
  $r->print('</span><br />');                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                 if (++$entries_count % $entries_per_col == 0) {                                                'parameter_randomorder'))[0]=~/^yes$/i);
                     $r->print('</font></td>');   $url.='folderpath='.&escape($folderpath);
                     if ($cols_output != 4) {          my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
                         $r->print('<td valign="top"><font size="-2">');                                                     'parameter_randompick'))[0];
                         $cols_output++;          my $rpckchk;
                     }          if ($rpicknum) {
                 }              $rpckchk = ' checked="checked"';
     }          }
             while($cols_output++ < 4) {          my $formname = 'edit_rpick_'.$orderidx;
                 $r->print('</font></td><td><font>')   $rand_pick_text = 
             }  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
     $r->print('</font></td></tr>'."\n");  $form_common."\n".
  }  '<span class="LC_nobreak"><label><input type="checkbox" name="randpickon_'.$orderidx.'" id="rpick_'.$orderidx.'" onclick="'."updatePick(this.form,'$orderidx','check');".'"'.$rpckchk.' /> '.&mt('Randomly Pick').'</label><input type="hidden" name="randompick_'.$orderidx.'" id="rpicknum_'.$orderidx.'" value="'.$rpicknum.'" />';
     }          if ($rpicknum ne '') {
     $r->print('</table></form>');              $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
     $r->print('<h1>'.&mt('Done').'.</h1>');          }
           $rand_pick_text .= '</span></form>';
     &untiehash();      my $ro_set=
 }      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
    $rand_order_text = 
 sub mark_hash_old {  $form_start.
     my $retie_hash=0;  $form_common.'
     if ($hashtied) {  <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>';
  $retie_hash=1;      }
  &untiehash();      if ($ispage) {
     }          my $pagename=&escape($pagetitle);
     &tiehash('write');          my $pagepath;
     $hash{'old'}=1;          my $folderpath=$env{'form.folderpath'};
     &untiehash();          if ($folderpath) { $pagepath = $folderpath.'&' };
     if ($retie_hash) { &tiehash(); }          $pagepath.=$pagearg.'&'.$pagename;
 }   $url.='pagepath='.&escape($pagepath).
       '&amp;pagesymb='.&escape($symb);
 sub is_hash_old {      }
     my $untie_hash=0;      if ($allowed) {
     if (!$hashtied) {          my $fileloc = 
  $untie_hash=1;              &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
  &tiehash();  
     }          if ($external) {
     my $return=$hash{'old'};      $editlink = <<"EXTLNK";
     if ($untie_hash) { &untiehash(); }              &nbsp;
     return $return;              <a class="LC_docs_ext_edit" href="javascript:editext('$residx');">
 }              $lt{'ed'}</a>
               <form action="/adm/coursedocs" method="post" name="editext_$residx">
 sub changewarning {              <fieldset id="uploadext$residx" style="display: none;" />
     my ($r,$postexec,$message,$url)=@_;              <input type="hidden" name="active" value="aa" />
     if (!&is_hash_old()) { return; }              <span class="LC_nobreak">
     my $pathvar='folderpath';              <span class="LC_docs_ext_edit">$lt{'ul'}&nbsp;</span>
     my $path=&escape($env{'form.folderpath'});              <input type="text" size="40" name="exturl" id="exturl_$residx" value="$orig_url" />&nbsp;
     if (!defined($url)) {              <a class="LC_docs_ext_edit" href="javascript:extUrlPreview('exturl_$residx');">$lt{'pr'}</a></span>
  if (defined($env{'form.pagepath'})) {              </span><br />
     $pathvar='pagepath';              <span class="LC_nobreak">
     $path=&escape($env{'form.pagepath'});              <span class="LC_docs_ext_edit">$lt{'ti'}&nbsp;</span>
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});              <input type="text" size="40" name="exttitle" value="$title" />
  }              $uploadtag
  $url='/adm/coursedocs?'.$pathvar.'='.$path;              <input type="hidden" name="importdetail" value="" />
     }              <input type="button" value="$lt{'sv'}" onclick="javascript:setExternal(this.form,'$residx')" />
     my $course_type = &Apache::loncommon::course_type();              </span>
     if (!defined($message)) {              </fieldset>
  $message='Changes will become active for your current session after [_1], or the next time you log in.';              </form>
     }  EXTLNK
     $r->print("\n\n".          } else { 
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
 '<input type="hidden" name="orgurl" value="'.$url.              if (($cfile ne '') && ($symb ne '')) {
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.                  my $jscall = 
 &mt($message,' <input type="hidden" name="'.                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
     $env{'request.role'}.'" value="1" /><input type="button" value="'.                                                              $switchserver,
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').                                                              $forceedit,
 $help{'Caching'}.'</span></h3></form>'."\n\n");                                                              undef,$symb);
 }                  if ($jscall) {
                       $editlink = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:'.
                                   $jscall.'" >'.&mt('Edit').'</a>';
 sub init_breadcrumbs {                  }
     my ($form,$text)=@_;              }
     &Apache::lonhtmlcommon::clear_breadcrumbs();          }
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",      }
     text=>"Edit ".&Apache::loncommon::course_type(),      my $reinit;
     faq=>273,      if ($crstype eq 'Community') {
     bug=>'Instructor Interface',          $reinit = &mt('(re-initialize community to access)');
                                             help => 'Docs_Adding_Course_Doc'});      } else {
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',          $reinit = &mt('(re-initialize course to access)');
     text=>$text,      }  
     faq=>273,      $line.='<td>';
     bug=>'Instructor Interface'});      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 }         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
       } elsif ($url) {
          $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
                                                '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
       } else {
 sub handler {         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
     my $r = shift;      }
     &Apache::loncommon::content_type($r,'text/html');      $line.='</td><td>';
     $r->send_http_header;      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
     return OK if $r->header_only;         $line.='<a href="'.$url.'">'.$title.'</a>';
     my $type = &Apache::loncommon::course_type();      } elsif ($url) {
          $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
                                                $title,600,500);
 # --------------------------------------------- Initialize help topics for this      } else {
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
                'Adding_External_Resource','Navigate_Content',      }
                'Adding_Folders','Docs_Overview', 'Load_Map',      $line.=$editlink."</td>";
                'Supplemental','Score_Upload_Form','Adding_Pages',      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
                'Check_Resource_Versions','Verify_Content') {      if (($allowed) && ($folder!~/^supplemental/)) {
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);    my %lt=&Apache::lonlocal::texthash(
     }         'hd' => 'Hidden',
     # Composite help files         'ec' => 'URL hidden');
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(   my $enctext=
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(   my $hidtext=
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(   $line.=(<<ENDPARMS);
     'Option_Response_Simple');    <td class="LC_docs_entry_parameter">
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(      $form_start
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');      $form_common
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(      <label><input type="checkbox" name="hiddenresource_$orderidx" onclick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');      $form_end
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');      <br />
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');      $form_start
       $form_common
 # does this user have privileges to modify docs      <label><input type="checkbox" name="encrypturl_$orderidx" onclick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});      $form_end
   if ($allowed && $env{'form.verify'}) {    </td>
       &init_breadcrumbs('verify','Verify Content');    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
       &verifycontent($r);                                        $rand_order_text</td>
   } elsif ($allowed && $env{'form.listsymbs'}) {  ENDPARMS
       &init_breadcrumbs('listsymbs','List Symbs');      }
       &list_symbs($r);      $line.=&Apache::loncommon::end_data_table_row();
   } elsif ($allowed && $env{'form.docslog'}) {      return $line;
       &init_breadcrumbs('docslog','Show Log');  }
       &docs_change_log($r);  
   } elsif ($allowed && $env{'form.versions'}) {  sub newmap_suffix {
       &init_breadcrumbs('versions','Check/Set Resource Versions');      my ($area,$container,$coursedom,$coursenum) = @_;
       &checkversions($r);      my ($prefix,$idtype,$errtext,$locknotfreed);
   } elsif ($allowed && $env{'form.dumpcourse'}) {      $prefix = 'docs';
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');      if ($area eq 'supplemental') {
       &dumpcourse($r);          $prefix = 'supp';
   } elsif ($allowed && $env{'form.exportcourse'}) {      }
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');      $prefix .= $container;
       &exportcourse($r);      $idtype = 'concat';
   } else {      my ($suffix,$freedlock,$error) =
 # is this a standard course?          &Apache::lonnet::get_timebased_id($prefix,'num','uploadedmaps',
                                             $coursedom,$coursenum);
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);      if (!$suffix) {
     my $forcestandard = 0;          $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
     my $forcesupplement;          if ($error) {
     my $script='';              $errtext .= '<br />'.$error;
     my $showdoc=0;          }
     my $containertag;      }
     my $uploadtag;      if ($freedlock ne 'ok') {
           $locknotfreed = '<div class="LC_error">'.&mt('There was a problem removing a lockfile. This will prevent creation of additional folders or composite pages in this course.  Please contact the domain coordinator for your LON-CAPA domain.').'</div>';
       }
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      return ($suffix,$errtext,$locknotfreed);
     ['folderpath','pagepath',  }
      'pagesymb']);  
 # No folderpath, no pagepath, see if we have something stored  =pod
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {  
         &Apache::loncommon::restore_course_settings('docs_folderpath',  =item tiehash()
                                               {'folderpath' => 'scalar'});  
     }  tie the hash
     if (!$env{'form.folderpath'}) {  
         &Apache::loncommon::restore_course_settings('docs_folderpath',  =cut
                                               {'pagepath' => 'scalar'});  
     }  sub tiehash {
     if ($env{'form.pagepath'}) {      my ($mode)=@_;
        $env{'form.folderpath'}='';      $hashtied=0;
     }      if ($env{'request.course.fn'}) {
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {   if ($mode eq 'write') {
         $env{'form.folderpath'} = 'supplemental&'.      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.      &GDBM_WRCREAT(),0640)) {
                                   $env{'form.folderpath'};                  $hashtied=2;
     }      }
     &Apache::loncommon::store_course_settings('docs_folderpath',   } else {
                                                 {'pagepath' => 'scalar',      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
                                                  'folderpath' => 'scalar'});      &GDBM_READER(),0640)) {
     if ($env{'form.folderpath'}) {                  $hashtied=1;
  my (@folderpath)=split('&',$env{'form.folderpath'});      }
  $env{'form.foldername'}=&unescape(pop(@folderpath));   }
  $env{'form.folder'}=pop(@folderpath);      }
     }  }
     if ($env{'form.pagepath'}) {  
         my (@pagepath)=split('&',$env{'form.pagepath'});  sub untiehash {
         $env{'form.pagename'}=&unescape(pop(@pagepath));      if ($hashtied) { untie %hash; }
         $env{'form.folder'}=pop(@pagepath);      $hashtied=0;
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      return OK;
     '<input type="hidden" name="pagesymb" value="" />';  }
         $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'},'<>&"').'" />';  
     }  
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {  
        $showdoc='/'.$1;  sub checkonthis {
     }      my ($r,$url,$level,$title)=@_;
     unless ($showdoc) { # got called from remote      $url=&unescape($url);
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||      $alreadyseen{$url}=1;
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {      $r->rflush();
            $forcestandard = 1;      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
        }         $r->print("\n<br />");
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);         if ($level==0) {
              $r->print("<br />");
        if ($allowed) {         }
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);         for (my $i=0;$i<=$level*5;$i++) {
          $script=&Apache::lonratedt::editscript('simple');             $r->print('&nbsp;');
        }         }
     } else { # got called in sequence from course         $r->print('<a href="'.$url.'" target="cat">'.
        $allowed=0;   ($title?$title:$url).'</a> ');
     }         if ($url=~/^\/res\//) {
     my $result=&Apache::lonnet::repcopy(
 # get course data                                &Apache::lonnet::filelocation('',$url));
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};            if ($result eq 'ok') {
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                $r->rflush();
 # get personal data               &Apache::lonnet::countacc($url);
     my $uname=$env{'user.name'};               $url=~/\.(\w+)$/;
     my $udom=$env{'user.domain'};               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));   $r->print('<br />');
                    $r->rflush();
 # graphics settings                   for (my $i=0;$i<=$level*5;$i++) {
                        $r->print('&nbsp;');
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");                   }
                    $r->print('- '.&mt('Rendering:').' ');
     if ($allowed) {   my ($errorcount,$warningcount)=split(/:/,
  $script .= &editing_js($udom,$uname);         &Apache::lonnet::ssi_body($url,
     }         ('grade_target'=>'web',
 # -------------------------------------------------------------------- Body tag   'return_only_error_and_warning_counts' => 1)));
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';                   if (($errorcount) ||
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];                       ($warningcount)) {
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,       if ($errorcount) {
     {'force_register' => $showdoc,                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
                                      'bread_crumbs' => $brcrum}).                            &mt('[quant,_1,error]',$errorcount).'</span>');
       &Apache::loncommon::help_open_menu('','',273,'RAT'));                       }
         if ($warningcount) {
   my %allfiles = ();                          $r->print('<span class="LC_warning">'.
   my %codebase = ();                            &mt('[quant,_1,warning]',$warningcount).'</span>');
   my ($upload_result,$upload_output);                       }
   if ($allowed) {                   } else {
       if (($env{'form.uploaddoc.filename'}) &&                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {                   }
 # Process file upload - phase one - upload and parse primary file.                     $r->rflush();
   undef($hadchanges);               }
           $upload_result = &process_file_upload(\$upload_output,$coursenum,       my $dependencies=
  $coursedom,\%allfiles,                  &Apache::lonnet::metadata($url,'dependencies');
  \%codebase,$1);               foreach my $dep (split(/\,/,$dependencies)) {
   if ($hadchanges) {   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
       &mark_hash_old();                      &checkonthis($r,$dep,$level+1);
   }                   }
           if ($upload_result eq 'phasetwo') {               }
               $r->print($upload_output);            } elsif ($result eq 'unavailable') {
           }               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
       } elsif ($env{'form.phasetwo'}) {            } elsif ($result eq 'not_found') {
           my %newname = ();        unless ($url=~/\$/) {
           my %origname = ();    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
           my %attribs = ();        } else {
           my $updateflag = 0;    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
           my $residx = $env{'form.newidx'};        }
           my $primary_url = &unescape($env{'form.primaryurl'});            } else {
 # Process file upload - phase two - gather secondary files.               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {            }
               if ($env{'form.embedded_item_'.$i.'.filename'}) {         }
                   my $javacodebase;      }
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);  }
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});  
                   if (exists($env{'form.embedded_codebase_'.$i})) {  
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});    
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;  =pod
                   }  
                   my @attributes = ();  =item list_symbs()
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {  
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});  List Content Identifiers
                   } else {  
                       @attributes = ($env{'form.embedded_attrib_'.$i});  =cut
                   }  
                   foreach my $attr (@attributes) {  sub list_symbs {
                       push(@{$attribs{$i}},&unescape($attr));      my ($r) = @_;
                   }  
                   if ($javacodebase) {      my $crstype = &Apache::loncommon::course_type();
                       $codebase{$i} = $javacodebase;      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
                       $codebase{$i} =~ s#/$##;      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
                       $updateflag = 1;      $r->print(&startContentScreen('tools'));
                   }      my $navmap = Apache::lonnavmaps::navmap->new();
               }      if (!defined($navmap)) {
               unless ($newname{$i} eq $origname{$i}) {          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
                   $updateflag = 1;                    '<div class="LC_error">'.
               }                    &mt('Unable to retrieve information about course contents').
           }                    '</div>');
 # Process file upload - phase three - modify primary file          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
           if ($updateflag) {      } else {
               my ($content,$rtncode);          $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
               my $updateflag = 0;                    &Apache::loncommon::start_data_table().
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);                    &Apache::loncommon::start_data_table_header_row().
               if ($getstatus eq 'ok') {                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
                   foreach my $item (keys(%newname)) {                    &Apache::loncommon::end_data_table_header_row()."\n");
                       if ($newname{$item} ne $origname{$item}) {          my $count;
                           my $attrib_regexp = '';          foreach my $res ($navmap->retrieveResources()) {
                           if (@{$attribs{$item}} > 1) {              $r->print(&Apache::loncommon::start_data_table_row().
                               $attrib_regexp = join('|',@{$attribs{$item}});                        '<td>'.$res->compTitle().'</td>'.
                           } else {                        '<td>'.$res->symb().'</td>'.
                               $attrib_regexp = $attribs{$item}[0];                        &Apache::loncommon::start_data_table_row());
                           }              $count ++;
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {          }
                           }          if (!$count) {
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;              $r->print(&Apache::loncommon::start_data_table_row().
                       }                        '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
                       if (exists($codebase{$item})) {                        &Apache::loncommon::end_data_table_row()); 
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs          }
                       }          $r->print(&Apache::loncommon::end_data_table());
                   }      }
 # Save edited file.  }
                   my $saveresult;  
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};  
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};  sub verifycontent {
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);      my ($r) = @_;
               } else {      my $crstype = &Apache::loncommon::course_type();
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
               }      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
           }      $r->print(&startContentScreen('tools'));
       }      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
   }     $hashtied=0;
      undef %alreadyseen;
   unless ($showdoc ||  $upload_result eq 'phasetwo') {     %alreadyseen=();
 # -----------------------------------------------------------------------------     &tiehash();
        my %lt=&Apache::lonlocal::texthash(     
                 'uplm' => 'Upload a new main '.lc($type).' document',     foreach my $key (keys(%hash)) {
                 'upls' => 'Upload a new supplemental '.lc($type).' document',         if ($hash{$key}=~/\.(page|sequence)$/) {
                 'impp' => 'Import a document',     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
                 'pubd' => 'Published Documents',         $r->print('<hr /><span class="LC_error">'.
  'copm' => 'All documents out of a published map into this folder',   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
                 'upld' => 'Upload Document',   &unescape($hash{$key}).'</span><br />'.
                 'srch' => 'Search',   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
                 'impo' => 'Import',     }
  'book' => 'Import Bookmarks',         }
                 'selm' => 'Select Map',         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
                 'load' => 'Load Map',             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
                 'reco' => 'Recover Deleted Resources',         }
                 'newf' => 'New Folder',     }
                 'newp' => 'New Composite Page',     &untiehash();
                 'extr' => 'External Resource',     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
                 'syll' => 'Syllabus',  }
                 'navc' => 'Navigate Contents',  
                 'sipa' => 'Simple Page',  
                 'sipr' => 'Simple Problem',  sub devalidateversioncache {
                 'drbx' => 'Drop Box',      my $src=shift;
                 'scuf' => 'Score Upload Form',      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
                 'bull' => 'Bulletin Board',    &Apache::lonnet::clutter($src));
                 'mypi' => 'My Personal Info',  }
                 'grpo' => 'Group Files',  
                 'rost' => 'Course Roster',  sub checkversions {
  'abou' => 'About User',      my ($r) = @_;
                 'imsf' => 'Import IMS package',      my $crstype = &Apache::loncommon::course_type();
                 'file' =>  'File',      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
                 'title' => 'Title',      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
                 'comment' => 'Comment',      $r->print(&startContentScreen('tools'));
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',  
  'nd' => 'New Document',      my $header='';
  'pm' => 'Published Map',      my $startsel='';
  'sd' => 'Special Document',      my $monthsel='';
  'mo' => 'More Options',      my $weeksel='';
  'hao' => 'Hide all Options'      my $daysel='';
   );      my $allsel='';
 # -----------------------------------------------------------------------------      my %changes=();
  my $fileupload=(<<FIUP);      my $starttime=0;
  $lt{'file'}:<br />      my $haschanged=0;
  <input type="file" name="uploaddoc" size="40" />      my %setversions=&Apache::lonnet::dump('resourceversions',
 FIUP    $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
  my $checkbox=(<<CHBO);  
  <!-- <label>$lt{'parse'}?      $hashtied=0;
  <input type="checkbox" name="parserflag" />      &tiehash();
  </label> -->      my %newsetversions=();
  <label>      if ($env{'form.setmostrecent'}) {
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}   $haschanged=1;
  </label>   foreach my $key (keys(%hash)) {
 CHBO      if ($key=~/^ids\_(\/res\/.+)$/) {
    $newsetversions{$1}='mostrecent';
  my $fileuploadform=(<<FUFORM);                  &devalidateversioncache($1);
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">      }
  $fileupload   }
  <br />      } elsif ($env{'form.setcurrent'}) {
  $lt{'title'}:<br />   $haschanged=1;
  <input type="text" size="50" name="comment" />   foreach my $key (keys(%hash)) {
  $uploadtag      if ($key=~/^ids\_(\/res\/.+)$/) {
  <input type="hidden" name="cmd" value="upload_default" />   my $getvers=&Apache::lonnet::getversion($1);
  <br />   if ($getvers>0) {
  <span class="LC_nobreak">      $newsetversions{$1}=$getvers;
  $checkbox      &devalidateversioncache($1);
  </span>   }
  <br />      }
  <br />   }
  <span class="LC_nobreak">      } elsif ($env{'form.setversions'}) {
  <input type="submit" value="$lt{'upld'}" />   $haschanged=1;
  $help{'Uploading_From_Harddrive'}   foreach my $key (keys(%env)) {
  </span>      if ($key=~/^form\.set_version_(.+)$/) {
  </form>   my $src=$1;
 FUFORM   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
       $newsetversions{$src}=$env{$key};
  my $simpleeditdefaultform=(<<SEDFFORM);      &devalidateversioncache($src);
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">   }
  $lt{'pubd'}<br />      }
  $uploadtag   }
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />      }
  <br />      if ($haschanged) {
  <span class="LC_nobreak">          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />    $env{'course.'.$env{'request.course.id'}.'.domain'},
  $help{'Importing_LON-CAPA_Resource'}    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
  </span>      $r->print(&Apache::loncommon::confirmwrapper(
  <br />                  &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />   } else {
  <hr />      $r->print(&Apache::loncommon::confirmwrapper(
  <p>                  &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
  $lt{'copm'}<br />   }
  <input type="text" size="40" name="importmap" /><br />   &mark_hash_old();
  <span class="LC_nobreak"><input type="button"      }
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      &changewarning($r,'');
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />      if ($env{'form.timerange'} eq 'all') {
  $help{'Load_Map'}</span>  # show all documents
  </p>   $header=&mt('All Documents in '.$crstype);
  </form>   $allsel=1;
 SEDFFORM   foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
  my $extresourcesform=(<<ERFORM);   my $src=$1;
  <form action="/adm/coursedocs" method="post" name="newext">   $changes{$src}=1;
  $uploadtag      }
  <input type="hidden" name="importdetail" value="" />   }
  <span class="LC_nobreak">      } else {
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"  # show documents which changed
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   %changes=&Apache::lonnet::dump
  </span>   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
  </form>                       $env{'course.'.$env{'request.course.id'}.'.num'});
 ERFORM   my $firstkey=(keys(%changes))[0];
    unless ($firstkey=~/^error\:/) {
     if ($allowed) {      unless ($env{'form.timerange'}) {
  &update_paste_buffer($coursenum,$coursedom);   $env{'form.timerange'}=604800;
        my %lt=&Apache::lonlocal::texthash(      }
  'vc' => 'Verify Content',      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
  'cv' => 'Check/Set Resource Versions',   .&mt('seconds');
  'ls' => 'List Symbs',      if ($env{'form.timerange'}==-1) {
                                          'sl' => 'Show Log'   $seltext='since start of course';
   );   $startsel='selected';
    $env{'form.timerange'}=time;
        my $folderpath=$env{'form.folderpath'};      }
        if (!$folderpath) {      $starttime=time-$env{'form.timerange'};
    if ($env{'form.folder'} eq '' ||      if ($env{'form.timerange'}==2592000) {
        $env{'form.folder'} eq 'supplemental') {   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
        $folderpath='default&'.   $monthsel='selected';
    &escape(&mt('Main '.$type.' Documents'));      } elsif ($env{'form.timerange'}==604800) {
    }   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
        }   $weeksel='selected';
        unless ($env{'form.pagepath'}) {      } elsif ($env{'form.timerange'}==86400) {
            $containertag = '<input type="hidden" name="folderpath" value="" />';   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';   $daysel='selected';
        }      }
        $r->print(&generate_admin_options($containertag,$uploadtag,\%lt,\%help,\%env));      $header=&mt('Content changed').' '.$seltext;
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',   } else {
      &mt('Editing the Table of Contents for your '.$type)));      $header=&mt('No content modifications yet.');
     }   }
 # --------------------------------------------------------- Standard documents      }
     $r->print('<table class="LC_docs_documents">');      %setversions=&Apache::lonnet::dump('resourceversions',
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     if (($standard) && ($allowed) && (!$forcesupplement)) {    $env{'course.'.$env{'request.course.id'}.'.num'});
  $r->print('<tr><td class="LC_docs_document">');      my %lt=&Apache::lonlocal::texthash
 #  '<h2>'.&mt('Main Course Documents').        ('st' => 'Version changes since start of '.$crstype,
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');         'lm' => 'Version changes since last Month',
        my $folder=$env{'form.folder'};         'lw' => 'Version changes since last Week',
        if ($folder eq '' || $folder eq 'supplemental') {         'sy' => 'Version changes since Yesterday',
            $folder='default';                 'al' => 'All Resources (possibly large output)',
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));                 'cd' => 'Change display', 
            $uploadtag = '<input type="hidden" name="folderpath" value="'.         'sd' => 'Display',
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';         'fi' => 'File',
        }         'md' => 'Modification Date',
        my $postexec='';                 'mr' => 'Most recently published Version',
        if ($folder eq 'default') {         've' => 'Version used in '.$crstype,
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');                 'vu' => 'Set Version to be used in '.$crstype,
        } else {  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
            #$postexec='self.close();';  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
        }  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
        $hadchanges=0;         'di' => 'Differences',
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,         'save' => 'Save changes',
    $upload_output,$type);                 'vers' => 'Version choice(s) for specific resources', 
        if ($error) {         'act' => 'Actions');
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');      $r->print(<<ENDHEADERS);
        }  <h4 class="LC_info">$header</h4>
        if ($hadchanges) {  <form action="/adm/coursedocs" method="post">
    &mark_hash_old();  <input type="hidden" name="versions" value="1" />
        }  <div class="LC_left_float">
        &changewarning($r,$postexec);  <fieldset>
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  <legend>$lt{'cd'}</legend>
                      '.sequence';  <select name="timerange">
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  <option value='all' $allsel>$lt{'al'}</option>
                      '.page';  <option value="-1" $startsel>$lt{'st'}</option>
  my $container='sequence';  <option value="2592000" $monthsel>$lt{'lm'}</option>
  if ($env{'form.pagepath'}) {  <option value="604800" $weeksel>$lt{'lw'}</option>
     $container='page';  <option value="86400" $daysel>$lt{'sy'}</option>
  }  </select>
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;  <input type="submit" name="display" value="$lt{'sd'}" />
   </fieldset>
   </div>
   <div class="LC_left_float">
  my $recoverform=(<<RFORM);  <fieldset>
  <form action="/adm/groupsort" method="post" name="recover">  <legend>$lt{'act'}</legend>
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />  $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
  </form>  $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
 RFORM  </fieldset>
   </div>
  my $imspform=(<<IMSPFORM);  <br clear="all" />
  <form action="/adm/imsimportdocs" method="post" name="ims">  <hr />
  <input type="hidden" name="folder" value="$folder" />  <h4>$lt{'vers'}</h4>
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />  <input type="submit" name="setversions" value="$lt{'save'}" />
  </form>  <table border="0">
 IMSPFORM  ENDHEADERS
       #number of columns for version history
  my $newnavform=(<<NNFORM);      my $num_ver_col = 1;
  <form action="/adm/coursedocs" method="post" name="newnav">      $r->print(
  $uploadtag      &Apache::loncommon::start_data_table().
  <input type="hidden" name="importdetail"      &Apache::loncommon::start_data_table_header_row().
  value="$lt{'navc'}=/adm/navmaps" />      '<th>'.&mt('Resources').'</th>'.
  <span class="LC_nobreak">      "<th>$lt{'mr'}</th>".
  <input name="newnav" type="submit" value="$lt{'navc'}" />      "<th>$lt{'ve'}</th>".
  $help{'Navigate_Content'}      "<th>$lt{'vu'}</th>".
  </span>      '<th colspan="'.$num_ver_col.'">'.&mt('History').'</th>'.
  </form>      '</b>');
 NNFORM      foreach my $key (sort(keys(%changes))) {
  my $newsmppageform=(<<NSPFORM);          #excludes not versionable problems from resource version history:
  <form action="/adm/coursedocs" method="post" name="newsmppg">          if ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/) {
  $uploadtag      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
  <input type="hidden" name="importdetail" value="" />      my $currentversion=&Apache::lonnet::getversion($key);
  <span class="LC_nobreak">      if ($currentversion<0) {
  <input name="newsmppg" type="button" value="$lt{'sipa'}"                  $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}      }
  </span>      my $linkurl=&Apache::lonnet::clutter($key);
  </form>          $r->print(
 NSPFORM              &Apache::loncommon::end_data_table_header_row().
               &Apache::loncommon::start_data_table_row().
  my $newsmpproblemform=(<<NSPROBFORM);              '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br>'.
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">              '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
  $uploadtag              '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br>('.
  <input type="hidden" name="importdetail" value="" />              &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
  <span class="LC_nobreak">              '<td align="right">');
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"  # Used in course
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}      my $usedversion=$hash{'version_'.$linkurl};
  </span>      if (($usedversion) && ($usedversion ne 'mostrecent')) {
  </form>                  if($usedversion != $currentversion){
                       $r->print('<span class="LC_warning">'.$usedversion.'</span>');
 NSPROBFORM                  }else{
                       $r->print($usedversion);
  my $newdropboxform=(<<NDBFORM);                  }
  <form action="/adm/coursedocs" method="post" name="newdropbox">      } else {
  $uploadtag         $r->print($currentversion);
  <input type="hidden" name="importdetail" value="" />      }
  <span class="LC_nobreak">                $r->print('</td><td title="'.$lt{'vu'}.'">');
  <input name="newdropbox" type="button" value="$lt{'drbx'}"  # Set version
  onClick="javascript:makedropbox();" />      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
  </span>                'set_version_'.$linkurl,
  </form>        {'select_form_order' =>
 NDBFORM         ['',1..$currentversion,'mostrecent'],
          '' => '',
  my $newexuploadform=(<<NEXUFORM);         'mostrecent' => &mt('most recent'),
  <form action="/adm/coursedocs" method="post" name="newexamupload">         map {$_,$_} (1..$currentversion)}));
  $uploadtag      my $lastold=1;
  <input type="hidden" name="importdetail" value="" />      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
  <span class="LC_nobreak">   my $url=$root.'.'.$prevvers.'.'.$extension;
  <input name="newexamupload" type="button" value="$lt{'scuf'}"   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
  onClick="javascript:makeexamupload();" />      $starttime) {
  $help{'Score_Upload_Form'}      $lastold=$prevvers;
  </span>   }
  </form>      }
 NEXUFORM              #
               # Code to figure out how many version entries should go in
  my $newbulform=(<<NBFORM);              # each of the four columns
  <form action="/adm/coursedocs" method="post" name="newbul">              my $entries_per_col = 0;
  $uploadtag              my $num_entries = ($currentversion-$lastold);
  <input type="hidden" name="importdetail" value="" />              if ($num_entries % $num_ver_col == 0) {
  <span class="LC_nobreak">                  $entries_per_col = $num_entries/$num_ver_col;
  <input name="newbulletin" type="button" value="$lt{'bull'}"              } else {
  onClick="javascript:makebulboard();" />                  $entries_per_col = $num_entries/$num_ver_col + 1;
  $help{'Bulletin Board'}              }
  </span>              my $entries_count = 0;
  </form>              $r->print('<td valign="top"><span class="LC_fontsize_medium">');
 NBFORM              my $cols_output = 1;
               for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
  my $newaboutmeform=(<<NAMFORM);   my $url=$root.'.'.$prevvers.'.'.$extension;
  <form action="/adm/coursedocs" method="post" name="newaboutme">   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
  $uploadtag    '">'.&mt('Version').' '.$prevvers.'</a> ('.
  <input type="hidden" name="importdetail"    &Apache::lonlocal::locallocaltime(
  value="$plainname=/adm/$udom/$uname/aboutme" />                                  &Apache::lonnet::metadata($url,
  <span class="LC_nobreak">                                                            'lastrevisiondate')
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />                                                              ).
  $help{'My Personal Info'}    ')');
  </span>   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
  </form>                      $r->print(' <a href="/adm/diff?filename='.
 NAMFORM        &Apache::lonnet::clutter($root.'.'.$extension).
         '&versionone='.$prevvers.
  my $newaboutsomeoneform=(<<NASOFORM);        '" target="diffs">'.&mt('Diffs').'</a>');
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">   }
  $uploadtag   $r->print('</span><br />');
  <input type="hidden" name="importdetail" value="" />                  if (++$entries_count % $entries_per_col == 0) {
  <span class="LC_nobreak">                      $r->print('</span></td>');
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"                      if ($cols_output != $num_ver_col) {
  onClick="javascript:makeabout();" />                          $r->print('<td valign="top"><span class="LC_fontsize_medium">');
  </span>                          $cols_output++;
  </form>                      }
 NASOFORM                  }
       }
               while($cols_output++ < $num_ver_col) {
  my $newrosterform=(<<NROSTFORM);                  $r->print('</span></td><td>');
  <form action="/adm/coursedocs" method="post" name="newroster">              }
  $uploadtag   }
  <input type="hidden" name="importdetail"      }
  value="$lt{'rost'}=/adm/viewclasslist" />      $r->print('</td>'.&Apache::loncommon::end_data_table_row().
  <span class="LC_nobreak">              &Apache::loncommon::end_data_table().
  <input name="newroster" type="submit" value="$lt{'rost'}" />              '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />');
  $help{'Course Roster'}  
  </span>      &untiehash();
  </form>  }
 NROSTFORM  
   sub mark_hash_old {
        $r->print(<<ENDFORM);      my $retie_hash=0;
       if ($hashtied) {
 <ul class="LC_TabContent">   $retie_hash=1;
 <li>$lt{'nd'}</li>   &untiehash();
 <li>$lt{'pm'}</li>      }
 <li>$lt{'pubd'}</li>      &tiehash('write');
 <li>$lt{'sd'}</li>      $hash{'old'}=1;
 <li>$lt{'mo'}</li>      &untiehash();
 <li>$lt{'hao'}</li>      if ($retie_hash) { &tiehash(); }
 </ul>  }
   
 <table class="LC_docs_adddocs">  sub is_hash_old {
 <!-- <tr>      my $untie_hash=0;
 <th>$lt{'uplm'}</th>      if (!$hashtied) {
 <th>$lt{'impp'}</th>   $untie_hash=1;
 <th>$lt{'spec'}</th>   &tiehash();
 </tr> -->      }
 <tr>      my $return=$hash{'old'};
 <td>      if ($untie_hash) { &untiehash(); }
 $fileuploadform      return $return;
 </td>  }
 <td>  
 $simpleeditdefaultform  sub changewarning {
 <hr />      my ($r,$postexec,$message,$url)=@_;
 $recoverform      if (!&is_hash_old()) { return; }
 ENDFORM      my $pathvar='folderpath';
        unless ($env{'form.pagepath'}) {      my $path=&escape($env{'form.folderpath'});
    $r->print(<<ENDFORM);      if (!defined($url)) {
 <hr />   if (defined($env{'form.pagepath'})) {
 $extresourcesform      $pathvar='pagepath';
  <br />      $path=&escape($env{'form.pagepath'});
 $imspform      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
 ENDFORM   }
        }   $url='/adm/coursedocs?'.$pathvar.'='.$path;
        $r->print('</td><td>');      }
        unless ($env{'form.pagepath'}) {      my $course_type = &Apache::loncommon::course_type();
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      if (!defined($message)) {
    $message='Changes will become active for your current session after [_1], or the next time you log in.';
       }
       $r->print("\n\n".
  my $newpageform=(<<NPFORM);  '<script type="text/javascript">'."\n".
  <form action="/adm/coursedocs" method="post" name="newpage">  '// <![CDATA['."\n".
  <input type="hidden" name="folderpath" value="$path" />  'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
  <input type="hidden" name="importdetail" value="" />  '// ]]>'."\n".
  <span class="LC_nobreak">  '</script>'."\n".
  <input name="newpage" type="button"  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
  onClick="javascript:makenewpage(this.form,'$pageseq');"  '<input type="hidden" name="orgurl" value="'.$url.
  value="$lt{'newp'}" />$help{'Adding_Pages'}  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
  </span>  &mt($message,' <input type="hidden" name="'.
  </form>      $env{'request.role'}.'" value="1" /><input type="button" value="'.
 NPFORM      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
   $help{'Caching'}.'</p></form>'."\n\n");
  my $newfolderform=(<<NFFORM);  }
  <form action="/adm/coursedocs" method="post" name="newfolder">  
  <input type="hidden" name="folderpath" value="$path" />  
  <input type="hidden" name="importdetail" value="" />  sub init_breadcrumbs {
  <span class="LC_nobreak">      my ($form,$text)=@_;
  <input name="newfolder" type="button"      &Apache::lonhtmlcommon::clear_breadcrumbs();
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
  value="$lt{'newf'}" />$help{'Adding_Folders'}      text=>&Apache::loncommon::course_type().' Editor',
  </span>      faq=>273,
  </form>      bug=>'Instructor Interface',
 NFFORM                                              help => 'Docs_Adding_Course_Doc'});
       &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
  my $newsylform=(<<NSYLFORM);      text=>$text,
  <form action="/adm/coursedocs" method="post" name="newsyl">      faq=>273,
  $uploadtag      bug=>'Instructor Interface'});
  <input type="hidden" name="importdetail"  }
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />  
  <span class="LC_nobreak">  # subroutine to list form elements
  <input name="newsyl" type="submit" value="$lt{'syll'}" />  sub create_list_elements {
  $help{'Syllabus'}     my @formarr = @_;
  </span>     my $list = '';
  </form>     foreach my $button (@formarr){
 NSYLFORM          foreach my $picture (keys(%{$button})) {
               $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
  my $newgroupfileform=(<<NGFFORM);          }
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">     }
  $uploadtag     return $list;
  <input type="hidden" name="importdetail"  }
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />  
  <span class="LC_nobreak">  # subroutine to create ul from list elements
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />  sub create_form_ul {
  $help{'Group Files'}     my $list = shift;
  </span>     my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
  </form>     return $ul;
 NGFFORM  }
   
   #
            $r->print(<<ENDFORM);  # Start tabs
 <br />  #
 $newfolderform  
 <br />  sub startContentScreen {
 $newpageform      my ($mode) = @_;
 <br />      my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
 $newsylform      if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
 <br />          $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";
 $newnavform          $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";
 <br />          $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";
 $newsmppageform          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
 <br />      } else {
 $newsmpproblemform          $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";
 <br />          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
 $newdropboxform          $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";
 <br />                     '><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>';
 $newexuploadform      }
 <br />      $output .= "\n".'</ul>'."\n";
 $newbulform      $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
 <br />                 '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
 $newaboutmeform                 '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
 <br />      return $output;
 $newaboutsomeoneform  }
 <br />  
 $newgroupfileform  #
 <br />  # End tabs
 $newrosterform  #
 ENDFORM  
        }  sub endContentScreen {
        if ($env{'form.pagepath'}) {      return '</div></div></div>';
            $r->print(<<ENDBLOCK);  }
 $newsmpproblemform  
 <br />  sub supplemental_base {
 $newexuploadform      return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
 ENDBLOCK  }
        }  
        $r->print('</td></tr>'."\n".  sub handler {
 '</table>');      my $r = shift;
        $r->print('</td></tr>');      &Apache::loncommon::content_type($r,'text/html');
     }      $r->send_http_header;
 # ----------------------------------------------------- Supplemental documents      return OK if $r->header_only;
     if (!$forcestandard) {  
        $r->print('<tr><td class="LC_docs_document">');  # get course data
 # '<h2>'.&mt('Supplemental Course Documents').      my $crstype = &Apache::loncommon::course_type();
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
        my $folder=$env{'form.folder'};      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
        unless ($folder=~/^supplemental/) {  
    $folder='supplemental';  # graphics settings
        }      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
        if ($folder =~ /^supplemental$/ &&  
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {  #
           $env{'form.folderpath'} = 'supplemental&'.  # --------------------------------------------- Initialize help topics for this
                                     &escape(&mt('Supplemental '.$type.' Documents'));      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
        }                 'Adding_External_Resource','Navigate_Content',
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);                 'Adding_Folders','Docs_Overview', 'Load_Map',
        if ($error) {                 'Supplemental','Score_Upload_Form','Adding_Pages',
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');                 'Importing_LON-CAPA_Resource','Importing_IMS_Course',
        }                         'Uploading_From_Harddrive',
        if ($allowed) {                 'Check_Resource_Versions','Verify_Content') {
    my $folderseq=   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.      }
        '.sequence';      # Composite help files
       $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
       $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
  my $supupdocform=(<<SUPDOCFORM);      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
  $fileupload      'Option_Response_Simple');
  <br />      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
  <br />      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
  <span class="LC_nobreak">      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
  $checkbox    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
  </span>      $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
  <br /><br />      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
  $lt{'comment'}:<br />  
  <textarea cols=50 rows=4 name='comment'>      
  </textarea>      my $allowed;
  <br />  # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
  <input type="hidden" name="folderpath" value="$path" />      unless ($r->uri eq '/adm/supplemental') {
  <input type="hidden" name="cmd" value="upload_supplemental" />          # does this user have privileges to modify content.  
  <span class="LC_nobreak">          $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
  <input type="submit" value="$lt{'upld'}" />      }
  $help{'Uploading_From_Harddrive'}  
  </span>      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
  </form>                                              'inhibitmenu']);
 SUPDOCFORM    if ($allowed && $env{'form.chooseserver'}) {
         &choose_dump_server($r);
  my $supnewfolderform=(<<SNFFORM);        return OK;
  <form action="/adm/coursedocs" method="post" name="supnewfolder">    } elsif ($allowed && $env{'form.verify'}) {
  <input type="hidden" name="folderpath" value="$path" />        &init_breadcrumbs('verify','Verify Content');
  <input type="hidden" name="importdetail" value="" />        &verifycontent($r);
  <span class="LC_nobreak">    } elsif ($allowed && $env{'form.listsymbs'}) {
  <input name="newfolder" type="button"        &init_breadcrumbs('listsymbs','List Content IDs');
  onClick="javascript:makenewfolder(this.form,'$folderseq');"        &list_symbs($r);
  value="$lt{'newf'}" /> $help{'Adding_Folders'}    } elsif ($allowed && $env{'form.docslog'}) {
  </span>        &init_breadcrumbs('docslog','Show Log');
  </form>        my $folder = $env{'form.folder'};
 SNFFORM        if ($folder eq '') {
             $folder='default';
         }
  my $supnewextform=(<<SNEFORM);        &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
  <form action="/adm/coursedocs" method="post" name="supnewext">    } elsif ($allowed && $env{'form.versions'}) {
  <input type="hidden" name="folderpath" value="$path" />        &init_breadcrumbs('versions','Check/Set Resource Versions');
  <input type="hidden" name="importdetail" value="" />        &checkversions($r);
  <span class="LC_nobreak">    } elsif ($allowed && $env{'form.dumpcourse'}) {
  <input name="newext" type="button"        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
  onClick="javascript:makenewext('supnewext');"        &dumpcourse($r);
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}    } elsif ($allowed && $env{'form.exportcourse'}) {
  </span>        &init_breadcrumbs('exportcourse','IMS Export');
  </form>        &Apache::imsexport::exportcourse($r);
 SNEFORM    } else {
   #
  my $supnewsylform=(<<SNSFORM);  # Done catching special calls
  <form action="/adm/coursedocs" method="post" name="supnewsyl">  # The whole rest is for course and supplemental documents and utilities menu
  <input type="hidden" name="folderpath" value="$path" />  # Get the parameters that may be needed
  <input type="hidden" name="importdetail"  #
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  <span class="LC_nobreak">                                              ['folderpath','pagepath',
  <input name="newsyl" type="submit" value="$lt{'syll'}" />                                               'pagesymb','forcesupplement','forcestandard',
  $help{'Syllabus'}                                               'tools','symb','command']);
  </span>  
  </form>  # standard=1: this is a "new-style" course with an uploaded map as top level
 SNSFORM  # standard=2: this is a "old-style" course, and there is nothing we can do
   
  my $supnewaboutmeform=(<<SNAMFORM);      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">  
  <input type="hidden" name="folderpath" value="$path" />  # Decide whether this should display supplemental or main content or utilities
  <input type="hidden" name="importdetail"  # supplementalflag=1: show supplemental documents
  value="$plainname=/adm/$udom/$uname/aboutme" />  # supplementalflag=0: show standard documents
  <span class="LC_nobreak">  # toolsflag=1: show utilities
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />  
  $help{'My Personal Info'}  
  </span>      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
  </form>      if (($env{'form.folderpath'}=~/^default/) || $env{'form.folderpath'} eq "" || ($env{'form.pagepath'})) {
 SNAMFORM         $supplementalflag=0;
       }
    $r->print(<<ENDSUPFORM);      if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 <ul class="LC_TabContent">      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
 <li>$lt{'nd'}</li>      unless ($allowed) { $supplementalflag=1; }
 <li>$lt{'sd'}</li>      unless ($standard) { $supplementalflag=1; }
 <li>$lt{'hao'}</li>      my $toolsflag=0;
 </ul>      if ($env{'form.tools'}) { $toolsflag=1; }
 <table class="LC_docs_adddocs">  
 <tr><td>      my $script='';
 $supupdocform      my $showdoc=0;
 </td>      my $addentries = {};
 <td>      my $container;
 $supnewfolderform      my $containertag;
 <br />      my $uploadtag;
 $supnewextform  
 <br />  # Do we directly jump somewhere?
 $supnewsylform  
 <br />     if ($env{'form.command'} eq 'direct') {
 $supnewaboutmeform         my ($mapurl,$id,$resurl);
 </td></tr>         if ($env{'form.symb'} ne '') {
 </table></td></tr>             ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
 ENDSUPFORM             if ($resurl=~/\.(sequence|page)$/) {
        }                 $mapurl=$resurl;
     }             } elsif ($resurl eq 'adm/navmaps') {
     $r->print('</table>');                 $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
     if ($allowed) {             }
  $r->print('             my $mapresobj;
 <form method="post" name="extimport" action="/adm/coursedocs">             my $navmap = Apache::lonnavmaps::navmap->new();
   <input type="hidden" name="title" />             if (ref($navmap)) {
   <input type="hidden" name="url" />                 $mapresobj = $navmap->getResourceByUrl($mapurl);
   <input type="hidden" name="useform" />             }
   <input type="hidden" name="residx" />             $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
 </form>');             my $type=$2;
     }             my $path;
   } else {             if (ref($mapresobj)) {
       unless ($upload_result eq 'phasetwo') {                 my $pcslist = $mapresobj->map_hierarchy();
 # -------------------------------------------------------- This is showdoc mode                 if ($pcslist ne '') {
           $r->print("<h1>".&mt('Uploaded Document').' - '.                     foreach my $pc (split(/,/,$pcslist)) {
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.                         next if ($pc <= 1);
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".                         my $res = $navmap->getByMapPc($pc);
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');                         if (ref($res)) {
       }                             my $thisurl = $res->src();
   }                             $thisurl=~s{^.*/([^/]+)\.\w+$}{$1}; 
  }                             my $thistitle = $res->title();
  $r->print(&Apache::loncommon::end_page());                             $path .= '&'.
  return OK;                                      &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
 }                                      &Apache::lonhtmlcommon::entity_encode($thistitle).
                                       ':'.$res->randompick().
 sub generate_admin_options {                                      ':'.$res->randomout().
   my ($containertag,$uploadtag,$lt_ref,$help_ref,$env_ref) = @_;                                      ':'.$res->encrypted().
   my %lt = %{$lt_ref};                                      ':'.$res->randomorder();
   my %help = %{$help_ref};                         }
   my %env = %{$env_ref};                     }
   my $dumpbut=&dumpbutton();                 }
   my $exportbut=&exportbutton();                 $path .= '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
   return (<<ENDOPTIONFORM);                      &Apache::lonhtmlcommon::entity_encode($mapresobj->title()).
  <form name="renameform" method="post" action="/adm/coursedocs">                      ':'.$mapresobj->randompick().
    <input type="hidden" name="title" />                      ':'.$mapresobj->randomout().
    <input type="hidden" name="cmd" />                      ':'.$mapresobj->encrypted().
    <input type="hidden" name="markcopy" />                      ':'.$mapresobj->randomorder();
    <input type="hidden" name="copyfolder" />             } else {
    $containertag                 my $maptitle = &Apache::lonnet::gettitle($mapurl);
  </form>                 $path = '&default&...::::'.
  <form name="simpleedit" method="post" action="/adm/coursedocs">                     '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
    <input type="hidden" name="importdetail" value="" />                     &Apache::lonhtmlcommon::entity_encode($maptitle).'::::';
    $uploadtag             }
  </form>             $path = 'default&'.
  <form action="/adm/coursedocs" method="post" name="courseverify">                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
    <ul style="list-style-type:none">                     $path;
        <li>             if ($type eq 'sequence') {
            <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}                 $env{'form.folderpath'}=$path;
        </li>                 $env{'form.pagepath'}='';
        <li>             } else {
            <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}                 $env{'form.pagepath'}=$path;
        </li>                 $env{'form.folderpath'}='';
        <li>             }
            $dumpbut         } elsif ($env{'form.supppath'} ne '') {
        </li>             $env{'form.folderpath'}=$env{'form.supppath'};
        <li>         }
            $exportbut     } elsif ($env{'form.command'} eq 'editdocs') {
        </li>          $env{'form.folderpath'} = 'default&'.
        <li>                                    &Apache::lonhtmlcommon::entity_encode('Main Course Content');
           <input type="submit" name="listsymbs" value="$lt{'ls'}" />          $env{'form.pagepath'}='';
         </li>     } elsif ($env{'form.command'} eq 'editsupp') {
         <li>          $env{'form.folderpath'} = 'default&'.
           <input type="hidden" name="folder" value="$env{'form.folder'}" />                                    &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
           <input type="submit" name="docslog" value="$lt{'sl'}" />          $env{'form.pagepath'}='';
         </li>     }
    </ul>  
  </form>  # Where do we store these for when we come back?
  <div style="clear: both; height: 0px;">&nbsp;</div>      my $stored_folderpath='docs_folderpath';
 ENDOPTIONFORM      if ($supplementalflag) {
 }         $stored_folderpath='docs_sup_folderpath';
       }
 sub generate_edit_table {  
     my ($optionhash_ref,$namehash_ref,$orderhash_ref) = @_;  # No folderpath, no pagepath, see if we have something stored
     my %optionhash = %{$optionhash_ref};         #id verlinkt mit inhalt      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
     my %namehash = %{$namehash_ref};             #name verlinkt mit id          &Apache::loncommon::restore_course_settings($stored_folderpath,
     my %orderhash = %{$orderhash_ref};           #name mit kürzel verlinkt mit name                                                {'folderpath' => 'scalar'});
     my $form;      }
     $form = '<div class="LC_ContentBoxSpecial"><h4 class="LC_hcell">'.&mt('Upload Course Documents').'<h4>';     
     $form .= '<ul class="LC_TabContent">';  # If we are not allowed to make changes, all we can see are supplemental docs
     foreach my $name (sort(keys(%orderhash))){      if (!$allowed) {
         if($name eq 'zz_hide'){          $env{'form.pagepath'}='';
             $form .= '<li><a onclick="hideAllSection();" href="#">'.&mt($orderhash{$name}).'</a></li>';          unless ($env{'form.folderpath'} =~ /^supplemental/) {
         }else{              $env{'form.folderpath'} = &supplemental_base();
             $form .= '<li><a onclick="popUpSection(\''.$namehash{$orderhash{$name}}.'\');" href="#">'.&mt($orderhash{$name}).'</a></li>';          }
         }      }
     }  # If we still not have a folderpath, see if we can resurrect at pagepath
     foreach my $field (keys(%optionhash)){      if (!$env{'form.folderpath'} && $allowed) {
         $form .= '<div id="'.$field.'" class="LC_ContentBox LC_hideThis">'.$optionhash{$field}.'</div>';          &Apache::loncommon::restore_course_settings($stored_folderpath,
     }                                                {'pagepath' => 'scalar'});
     $form .= '</div>';      }
     return $form;  # Make the zeroth entry in supplemental docs page paths, so we can get to top level
 }      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
           $env{'form.folderpath'} = &supplemental_base()
 sub editing_js {                                    .'&'.
     my ($udom,$uname) = @_;                                    $env{'form.folderpath'};
     my $now = time();      }
     my %lt = &Apache::lonlocal::texthash(  # If after all of this, we still don't have any paths, make them
                                           p_mnf => 'Name of New Folder',      unless (($env{'form.pagepath'}) || ($env{'form.folderpath'})) {
                                           t_mnf => 'New Folder',         if ($supplementalflag) {
                                           p_mnp => 'Name of New Page',            $env{'form.folderpath'}=&supplemental_base();
                                           t_mnp => 'New Page',         } else {
                                           p_mxu => 'Title for the Uploaded Score',            $env{'form.folderpath'}='default';
                                           p_msp => 'Title for the Page',         }
                                           p_msb => 'Title for the Problem',      }
                                           p_mdb => 'Title for the Drop Box',  
                                           p_mbb => 'Title for the Bulletin Board',  # Store this
                                           p_mab => "Enter user:domain for User's 'About Me' Page",      unless ($toolsflag) {
                                           p_mab2 => "About [_99]",          &Apache::loncommon::store_course_settings($stored_folderpath,
                                           p_mab_alrt1 => 'Not a valid user:domain',                                                    {'pagepath' => 'scalar',
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',                                                     'folderpath' => 'scalar'});
                                           p_chn => 'New Title',          if ($env{'form.folderpath'}) {
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',      my (@folderpath)=split('&',$env{'form.folderpath'});
                                           p_rmr2a => 'Remove[_99]',      $env{'form.foldername'}=&unescape(pop(@folderpath));
                                           p_rmr2b => '?[_99]',      $env{'form.folder'}=pop(@folderpath);
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',              $container='sequence';
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',          }
                                           p_ctr2a => 'Cut[_98]',          if ($env{'form.pagepath'}) {
                                           p_ctr2b => '?[_98]'              my (@pagepath)=split('&',$env{'form.pagepath'});
                                         );              $env{'form.pagename'}=&unescape(pop(@pagepath));
               $env{'form.folder'}=pop(@pagepath);
     return <<ENDNEWSCRIPT;              $container='page';
 function makenewfolder(targetform,folderseq) {              $containertag = '<input type="hidden" name="pagepath" value="" />'.
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');                      '<input type="hidden" name="pagesymb" value="" />';
     if (foldername) {              $uploadtag = 
        targetform.importdetail.value=escape(foldername)+"="+folderseq;                  '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
         targetform.submit();          '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />'.
     }                  '<input type="hidden" name="folderpath" value="" />';
 }          } else {
               my $folderpath=$env{'form.folderpath'};
 function makenewpage(targetform,folderseq) {              if (!$folderpath) {
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');                  if ($env{'form.folder'} eq '' ||
     if (pagename) {                      $env{'form.folder'} eq 'supplemental') {
         targetform.importdetail.value=escape(pagename)+"="+folderseq;                      $folderpath='default&'.
         targetform.submit();                          &escape(&mt('Main '.$crstype.' Documents'));
     }                  }
 }              }
               $containertag = '<input type="hidden" name="folderpath" value="" />';
 function makenewext(targetname) {              $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
     this.document.forms.extimport.useform.value=targetname;          }
     this.document.forms.extimport.title.value='';          if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
     this.document.forms.extimport.url.value='';             $showdoc='/'.$1;
     this.document.forms.extimport.residx.value='';          }
     window.open('/adm/rat/extpickframe.html');          if ($showdoc) { # got called in sequence from course
 }      $allowed=0; 
           } else {
 function edittext(targetname,residx,title,url) {              if ($allowed) {
     this.document.forms.extimport.useform.value=targetname;                  &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
     this.document.forms.extimport.residx.value=residx;                  $script=&Apache::lonratedt::editscript('simple');
     this.document.forms.extimport.url.value=url;              }
     this.document.forms.extimport.title.value=title;          }
     window.open('/adm/rat/extpickframe.html');      }
 }  
   # get personal data
 function makeexamupload() {      my $uname=$env{'user.name'};
    var title=prompt('$lt{"p_mxu"}');      my $udom=$env{'user.domain'};
    if (title) {      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
     this.document.forms.newexamupload.importdetail.value=  
  escape(title)+'=/res/lib/templates/examupload.problem';      if ($allowed) {
     this.document.forms.newexamupload.submit();          if ($toolsflag) {
    }              $script .= &inject_data_js();
 }              my ($home,$other,%outhash)=&authorhosts();
               if (!$home && $other) {
 function makesmppage() {                  my @hosts;
    var title=prompt('$lt{"p_msp"}');                  foreach my $aurole (keys(%outhash)) {
    if (title) {                      unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
     this.document.forms.newsmppg.importdetail.value=                          push(@hosts,$outhash{$aurole});
  escape(title)+'=/adm/$udom/$uname/$now/smppg';                      }
     this.document.forms.newsmppg.submit();                  }
    }                  $script .= &dump_switchserver_js(@hosts); 
 }              }
           } else {
 function makesmpproblem() {              my @tabids;
    var title=prompt('$lt{"p_msb"}');              if ($supplementalflag) {
    if (title) {                  @tabids = ('002','ee2','ff2');
     this.document.forms.newsmpproblem.importdetail.value=              } else {
  escape(title)+'=/res/lib/templates/simpleproblem.problem';                  @tabids = ('aa1','bb1','cc1','ff1');
     this.document.forms.newsmpproblem.submit();                  unless ($env{'form.pagepath'}) {
    }                      unshift(@tabids,'001');
 }                      push(@tabids,('dd1','ee1'));
                   }
 function makedropbox() {              }
    var title=prompt('$lt{"p_mdb"}');              my $tabidstr = join("','",@tabids);
    if (title) {      $script .= &editing_js($udom,$uname,$supplementalflag).
     this.document.forms.newdropbox.importdetail.value=                         &history_tab_js().
         escape(title)+'=/res/lib/templates/DropBox.problem';                         &inject_data_js().
     this.document.forms.newdropbox.submit();                         &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr);
    }              $addentries = {
 }                              onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
                             };
 function makebulboard() {          }
    var title=prompt('$lt{"p_mbb"}');          if ($env{'docs.markedcopy_url'}) {
    if (title) {              $script .= &paste_popup_js(); 
     this.document.forms.newbul.importdetail.value=          }
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';          my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
     this.document.forms.newbul.submit();                               &mt('Switch server?');
    }          
 }  
       }
 function makeabout() {  # -------------------------------------------------------------------- Body tag
    var user=prompt("$lt{'p_mab'}");      $script = '<script type="text/javascript">'."\n"
    if (user) {                .'// <![CDATA['."\n"
        var comp=new Array();                .$script."\n"
        comp=user.split(':');                .'// ]]>'."\n"
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {                .'</script>'."\n";
    if ((comp[0]) && (comp[1])) {  
        this.document.forms.newaboutsomeone.importdetail.value=      # Breadcrumbs
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';      &Apache::lonhtmlcommon::clear_breadcrumbs();
        this.document.forms.newaboutsomeone.submit();      unless ($showdoc) {
    } else {          &Apache::lonhtmlcommon::add_breadcrumb({
                alert("$lt{'p_mab_alrt1'}");              href=>"/adm/coursedocs",text=>"$crstype Contents"});
            }  
        } else {          $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
            alert("$lt{'p_mab_alrt2'}");                                                   {'force_register' => $showdoc,
        }                                                    'add_entries'    => $addentries,
    }                                                   })
 }                   .&Apache::loncommon::help_open_menu('','',273,'RAT')
                    .&Apache::lonhtmlcommon::breadcrumbs(
 function makeims() {                       'Editing '.$crstype.' Contents',
     var caller = document.forms.ims.folder.value;                       'Docs_Adding_Course_Doc')
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";          );
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");      } else {
     newWindow.location.href = newlocation;          $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
 }                                                  {'force_register' => $showdoc,}));
       }
   
 function finishpick() {    my %allfiles = ();
     var title=this.document.forms.extimport.title.value;    my %codebase = ();
     var url=this.document.forms.extimport.url.value;    my ($upload_result,$upload_output,$uploadphase);
     var form=this.document.forms.extimport.useform.value;    if ($allowed) {
     var residx=this.document.forms.extimport.residx.value;        if (($env{'form.uploaddoc.filename'}) &&
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 }            my $context = $1; 
             # Process file upload - phase one - upload and parse primary file.
 function changename(folderpath,index,oldtitle,container,pagesymb) {    undef($hadchanges);
     var title=prompt('$lt{"p_chn"}',oldtitle);            $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
     if (title) {                                                \%allfiles,\%codebase,$context);
  this.document.forms.renameform.markcopy.value=-1;    if ($hadchanges) {
  this.document.forms.renameform.title.value=title;        &mark_hash_old();
  this.document.forms.renameform.cmd.value='rename_'+index;    }
         if (container == 'sequence') {            $r->print($upload_output);
     this.document.forms.renameform.folderpath.value=folderpath;        } elsif ($env{'form.phase'} eq 'upload_embedded') {
         }            # Process file upload - phase two - upload embedded objects 
         if (container == 'page') {            $uploadphase = 'check_embedded';
             this.document.forms.renameform.pagepath.value=folderpath;            my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
             this.document.forms.renameform.pagesymb.value=pagesymb;            my $state = &embedded_form_elems($uploadphase,$primaryurl,
         }                                             $env{'form.newidx'});
         this.document.forms.renameform.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 $url_root = '/uploaded/'.$docudom.'/'.$docuname;
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {            my $actionurl = '/adm/coursedocs';
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {            my ($result,$flag) = 
  this.document.forms.renameform.markcopy.value=-1;                &Apache::loncommon::upload_embedded('coursedoc',$destination,
  this.document.forms.renameform.cmd.value='del_'+index;                    $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
         if (container == 'sequence') {                    $actionurl);
             this.document.forms.renameform.folderpath.value=folderpath;            $r->print($result.&return_to_editor());
         }        } elsif ($env{'form.phase'} eq 'check_embedded') {
         if (container == 'page') {            # Process file upload - phase three - modify references in HTML file
             this.document.forms.renameform.pagepath.value=folderpath;            $uploadphase = 'modified_orightml';
             this.document.forms.renameform.pagesymb.value=pagesymb;            my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
         }            my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
         this.document.forms.renameform.submit();            my ($destination,$dir_root) = &embedded_destination();
     }            my $result = 
 }                &Apache::loncommon::modify_html_refs('coursedoc',$destination,
                                                      $docuname,$docudom,undef,
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {                                                     $dir_root);
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {            $r->print($result.&return_to_editor());   
  this.document.forms.renameform.cmd.value='cut_'+index;        } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
  this.document.forms.renameform.markcopy.value=index;            $uploadphase = 'decompress_phase_one';
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;            $r->print(&decompression_phase_one().
         if (container == 'sequence') {                      &return_to_editor());
             this.document.forms.renameform.folderpath.value=folderpath;        } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
         }            $uploadphase = 'decompress_phase_two';
         if (container == 'page') {            $r->print(&decompression_phase_two().
             this.document.forms.renameform.pagepath.value=folderpath;                      &return_to_editor());
             this.document.forms.renameform.pagesymb.value=pagesymb;        }
         }    }
         this.document.forms.renameform.submit();  
     }    if ($allowed && $toolsflag) {
 }        $r->print(&startContentScreen('tools'));
         $r->print(&generate_admin_menu($crstype));
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {        $r->print(&endContentScreen());
     this.document.forms.renameform.markcopy.value=index;    } elsif ((!$showdoc) && (!$uploadphase)) {
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;  # -----------------------------------------------------------------------------
     if (container == 'sequence') {         my %lt=&Apache::lonlocal::texthash(
  this.document.forms.renameform.folderpath.value=folderpath;                  'uplm' => 'Upload a new main '.lc($crstype).' document',
     }                  'upls' => 'Upload a new supplemental '.lc($crstype).' document',
     if (container == 'page') {                  'impp' => 'Import a document',
  this.document.forms.renameform.pagepath.value=folderpath;   'copm' => 'All documents out of a published map into this folder',
  this.document.forms.renameform.pagesymb.value=pagesymb;                  'upfi' => 'Upload File',
     }                  'upld' => 'Import Content',
     this.document.forms.renameform.submit();                  'srch' => 'Search',
 }                  'impo' => 'Import',
    'lnks' => 'Import from Stored Links',
                   'impm' => 'Import from Assembled Map',
 ENDNEWSCRIPT                  'selm' => 'Select Map',
 }                  'load' => 'Load Map',
 1;                  'reco' => 'Recover Deleted Documents',
 __END__                  'newf' => 'New Folder',
                   'newp' => 'New Composite Page',
                   'extr' => 'External Resource',
 =head1 NAME                  'syll' => 'Syllabus',
                   'navc' => 'Table of Contents',
 Apache::londocs.pm                  'sipa' => 'Simple Course Page',
                   'sipr' => 'Simple Problem',
 =head1 SYNOPSIS                  'drbx' => 'Drop Box',
                   'scuf' => 'External Scores (handgrade, upload, clicker)',
 This is part of the LearningOnline Network with CAPA project                  'bull' => 'Discussion Board',
 described at http://www.lon-capa.org.                  'mypi' => 'My Personal Information Page',
                   'grpo' => 'Group Portfolio',
 =head1 SUBROUTINES                  'rost' => 'Course Roster',
    'abou' => 'Personal Information Page for a User',
 =over                  'imsf' => 'IMS Import',
                   'imsl' => 'Import IMS package',
 =item %help=()                  'cms'  => 'Origin of IMS package',
                   'se'   => 'Select',
 Available help topics                  'file' =>  'File',
                   'title' => 'Title',
 =item mapread()                  'comment' => 'Comment',
                   'url'  => 'URL',
 Mapread read maps into LONCAPA::map:: global arrays                  'prev' => 'Preview',
 @order and @resources, determines status                  'lnk'  => 'Add Link', 
 sets @order - pointer to resources in right order                  'parse' => 'Upload embedded images/multimedia files if HTML file',
 sets @resources - array with the resources with correct idx   'nd' => 'Upload Document',
    'pm' => 'Published Map',
 =item authorhosts()   'sd' => 'Special Document',
    'mo' => 'More Options',
 Return hash with valid author names    );
   # -----------------------------------------------------------------------------
 =item dumpbutton()   my $fileupload=(<<FIUP);
    $lt{'file'}:<br />
 Generate "dump" button   <input type="file" name="uploaddoc" size="40" />
   FIUP
 =item clean()  
    my $checkbox=(<<CHBO);
 =item dumpcourse()   <!-- <label>$lt{'parse'}?
    <input type="checkbox" name="parserflag" />
     Actually dump course   </label> -->
    <label>
    <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
 =item exportbutton()   </label>
   CHBO
     Generate "export" button          my $imsfolder = $env{'form.folder'};
           if ($imsfolder eq '') {
 =item exportcourse()              $imsfolder = 'default';  
           }
 =item create_ims_store()          my $imspform=(<<IMSFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
 =item build_package()          $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
           <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
 =item get_dependencies()          <fieldset id="uploadimsform" style="display: none;" />
           <legend>$lt{'imsf'}</legend>
 =item process_content()          $fileupload
           <br />
 =item replicate_content()          <p>
           $lt{'cms'}:&nbsp; 
 =item extract_media()          <select name="source">
           <option value="-1" selected="selected">$lt{'se'}</option>
 =item store_template()          <option value="bb5">Blackboard 5</option>
           <option value="bb6">Blackboard 6</option>
 =item group_import()          <option value="angel5">ANGEL 5.5</option>
           <option value="webctce4">WebCT 4 Campus Edition</option>
     Imports the given (name, url) resources into the course          </select>
     coursenum, coursedom, and folder must precede the list          <input type="hidden" name="folder" value="$imsfolder" />
           </p>
 =item breadcrumbs()          <input type="hidden" name="phase" value="one" />
           <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" />
 =item log_docs()          </fieldset>
           </form>
 =item docs_change_log()  IMSFORM
   
 =item update_paste_buffer()   my $fileuploadform=(<<FUFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
 =item print_paste_buffer()          $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
           <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 =item do_paste_from_buffer()          <fieldset id="uploaddocform" style="display: none;" />
           <legend>$lt{'upfi'}</legend>
 =item update_parameter()   <input type="hidden" name="active" value="aa" />
    $fileupload
 =item handle_edit_cmd()   <br />
    $lt{'title'}:<br />
 =item editor()   <input type="text" size="60" name="comment" />
    $uploadtag
 =item process_file_upload()   <input type="hidden" name="cmd" value="upload_default" />
    <br />
 =item process_secondary_uploads()   <span class="LC_nobreak" style="float:left">
    $checkbox
 =item is_supplemental_title()   </span>
           <br clear="all" />
 =item parse_supplemental_title()          <input type="submit" value="$lt{'upld'}" />
           </fieldset>
 =item entryline()          </form>
   FUFORM
 =item tiehash()  
    my $importpubform=(<<SEDFFORM);
 =item untiehash()          <a class="LC_menubuttons_link" href="javascript:toggleMap();">
           $lt{'impm'}</a>$help{'Load_Map'}
 =item checkonthis()   <form action="/adm/coursedocs" method="post" name="mapimportform">
           <fieldset id="importmapform" style="display: none;" />
 check on this          <legend>$lt{'impm'}</legend>
    <input type="hidden" name="active" value="bb" />
 =item verifycontent()          $lt{'copm'}<br />
           <span class="LC_nobreak">
 Verify Content          <input type="text" name="importmap" size="40" value="" 
           onfocus="this.blur();openbrowser('mapimportform','importmap','sequence,page','');" />
 =item devalidateversioncache() & checkversions()          &nbsp;<a href="javascript:openbrowser('mapimportform','importmap','sequence,page','');">$lt{'selm'}</a><br />
           <input type="submit" name="loadmap" value="$lt{'load'}" />
 Check Versions          </fieldset>
           </form>
 =item mark_hash_old()  
   SEDFFORM
 =item is_hash_old()   my @importpubforma = (
    { '<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>" },
 =item changewarning()   { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{impo}.'"  onclick="javascript:groupimport();"/>' => "<a class='LC_menubuttons_link' href='javascript:groupimport();'>$lt{'impo'}</a>$help{'Importing_LON-CAPA_Resource'}" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{lnks}.'" onclick="javascript:open_StoredLinks_Import();" />' => "<a class='LC_menubuttons_link' href='javascript:open_StoredLinks_Import();'>$lt{'lnks'}</a>" },
 =item init_breadcrumbs()          { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/sequence.png" alt="'.$lt{impm}.'" onclick="javascript:toggleMap();" />' => $importpubform }
    );
 Breadcrumbs for special functions   $importpubform = &create_form_ul(&create_list_elements(@importpubforma));
   
 =back        my $extresourcesform=(<<ERFORM);
         <a class="LC_menubuttons_link" href="javascript:toggleUpload('ext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
 =cut        <form action="/adm/coursedocs" method="post" name="newext">
         <fieldset id="uploadextform" style="display: none;" />
         <legend>$lt{'extr'}</legend>
         <input type="hidden" name="active" value="aa" />
         $lt{'url'}:<br />
         <input type="text" size="60" name="exturl" id="exturl" value="http://" />
         <input type="button" name="view" value="$lt{'prev'}" onclick="javascript:extUrlPreview('exturl');" /><br />
         $lt{'title'}:<br />
         <input type="text" size="60" name="exttitle" value="$lt{'extr'}" />
         $uploadtag
         <br />
         <input type="hidden" name="importdetail" value="" />
         <input type="button" value="$lt{'lnk'}" onclick="javascript:setExternal(this.form,0)" />
         </fieldset>
         </form>
   ERFORM
   
   
       if ($allowed) {
           my $folder = $env{'form.folder'};
           if ($folder eq '') {
               $folder='default';
           }
    &update_paste_buffer($coursenum,$coursedom,$folder);
    $r->print(<<HIDDENFORM);
    <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
      <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
      <input type="hidden" name="copyfolder" />
      $containertag
    </form>
   
   HIDDENFORM
           $r->print(&makesimpleeditform($uploadtag)."\n".
                     &makedocslogform($uploadtag."\n".
                                      '<input type="hidden" name="folder" value="'.
                                      $env{'form.folder'}.'" />'."\n"));
       }
   
   # Generate the tabs
       my $mode;
       if (($supplementalflag) && (!$allowed)) {
           &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
       } else {
           $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
       }
   
   #
   
       my $savefolderpath;
   
       if ($allowed) {
          my $folder=$env{'form.folder'};
          if ($folder eq '' || $supplementalflag) {
              $folder='default';
      $savefolderpath = $env{'form.folderpath'};
      $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
              $uploadtag = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
          my $postexec='';
          if ($folder eq 'default') {
              $r->print('<script type="text/javascript">'."\n"
                       .'// <![CDATA['."\n"
                       .'this.window.name="loncapaclient";'."\n"
                       .'// ]]>'."\n"
                       .'</script>'."\n"
          );
          } else {
              #$postexec='self.close();';
          }
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.page';
    my $container='sequence';
    if ($env{'form.pagepath'}) {
       $container='page';
    }
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
   
    my $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$lt{'navc'}=/adm/navmaps" />
    <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
    $help{'Navigate_Content'}
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
    $help{'Simple Page'}
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
    $help{'Simple Problem'}
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
    $help{'Score_Upload_Form'}
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
    $help{'Bulletin Board'}
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
    </form>
   NASOFORM
   
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$lt{'rost'}=/adm/viewclasslist" />
    <a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
    $help{'Course Roster'}
    </form>
   NROSTFORM
   
   my $specialdocumentsform;
   my @specialdocumentsforma;
   my $gradingform;
   my @gradingforma;
   my $communityform;
   my @communityforma;
   my $newfolderform;
   my $newfolderb;
   
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $newpageform=(<<NPFORM);
    <form action="/adm/coursedocs" method="post" name="newpage">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="cc" />
    <a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
    $help{'Adding_Pages'}
    </form>
   NPFORM
   
   
    $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="aa" />
    <a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail" 
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
   
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    <input type="hidden" name="active" value="cc" />
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
    $help{'Group Portfolio'}
    </form>
   NGFFORM
    @specialdocumentsforma=(
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
           );
           $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
   
   
           my @importdoc = (
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform},
           {'<img class="LC_noBorder_LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'doc\');" />'=>$fileuploadform,
           });
           $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc));
   
           @gradingforma=(
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
   
           );
           $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
   
           @communityforma=(
          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
           );
           $communityform = &create_form_ul(&create_list_elements(@communityforma));
   
   my %orderhash = (
                   'aa' => ['Import Content',$fileuploadform],
                   'bb' => ['Published Content',$importpubform],
                   'cc' => ['Grading Resources',$gradingform],
                   );
   unless ($env{'form.pagepath'}) {
       $orderhash{'00'} = ['Newfolder',$newfolderform];
       $orderhash{'dd'} = ['Collaboration',$communityform];
       $orderhash{'ee'} = ['Special Documents',$specialdocumentsform];
   }
   
    $hadchanges=0;
          unless (($supplementalflag || $toolsflag)) {
             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                 $supplementalflag,\%orderhash,$iconpath,$uploadtag);
             if ($error) {
                $r->print('<p><span class="LC_error">'.$error.'</span></p>');
             }
             if ($hadchanges) {
                &mark_hash_old();
             }
   
             &changewarning($r,'');
           }
       }
   
   # Supplemental documents start here
   
          my $folder=$env{'form.folder'};
          unless ($supplementalflag) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = &supplemental_base();
          } elsif ($allowed) {
     $env{'form.folderpath'} = $savefolderpath;
          }
          $env{'form.pagepath'} = '';
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_new.sequence';
   
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $supupdocform=(<<SUPDOCFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppdoc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
    <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
           <fieldset id="uploadsuppdocform" style="display: none;" />
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="ee" />
    $fileupload
    <br />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br /><br />
    $lt{'comment'}:<br />
    <textarea cols="50" rows="4" name="comment"></textarea>
    <br />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="cmd" value="upload_supplemental" />
           <input type='submit' value="$lt{'upld'}" />
           </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="active" value="ee" />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
    $help{'Adding_Folders'}
    </form>
   SNFFORM
   
           my $supextform=(<<ERFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
           <form action="/adm/coursedocs" method="post" name="newsuppext">
           <fieldset id="uploadsuppextform" style="display: none;" />
           <legend>$lt{'extr'}</legend>
           <input type="hidden" name="active" value="ee" />
           $lt{'url'}:<br />
           <input type="text" size="60" name="exturl" id="exturl" value="http://" />
           <input type="button" name="view" value="$lt{'prev'}" onclick="javascript:extUrlPreview('exturl');" /><br />
           $lt{'title'}:<br />
           <input type="text" size="60" name="exttitle" value="$lt{'extr'}" />
           $uploadtag
           <br />
           <input type="hidden" name="importdetail" value="" />
           <input type="button" value="$lt{'lnk'}" onclick="javascript:setExternal(this.form,0)" />
           </fieldset>
           </form>
   ERFORM
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="active" value="ff" />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" 
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="supnewaboutme">
    <input type="hidden" name="active" value="ff" />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   SNAMFORM
   
   
   my @specialdocs = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.supnewsyl.submit()" />'
               =>$supnewsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
               =>$supnewaboutmeform},
    );
   my @supimportdoc = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'suppext\')" />'
               =>$supextform},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
               =>$supupdocform},
                      );
   
   $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
   my %suporderhash = (
    '00' => ['Supnewfolder', $supnewfolderform],
                   'ee' => ['Import Content',$supupdocform],
                   'ff' => ['Special Documents',&create_form_ul(&create_list_elements(@specialdocs))]
                   );
           if ($supplementalflag) {
              my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                  $supplementalflag,\%suporderhash,$iconpath,$uploadtag);
              if ($error) {
                 $r->print('<p><span class="LC_error">'.$error.'</span></p>');
              }
           }
       } elsif ($supplementalflag) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,'',$iconpath,$uploadtag);
           if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
       }
   
       $r->print(&endContentScreen());
   
       if ($allowed) {
    $r->print('
   <form method="post" name="extimport" action="/adm/coursedocs">
     <input type="hidden" name="title" />
     <input type="hidden" name="url" />
     <input type="hidden" name="useform" />
     <input type="hidden" name="residx" />
   </form>');
       }
     } elsif ($showdoc) {
   # -------------------------------------------------------- This is showdoc mode
         $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p class="LC_warning">'.
   &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
                   &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
     }
    }
    $r->print(&Apache::loncommon::end_page());
    return OK;
   }
   
   sub embedded_form_elems {
       my ($phase,$primaryurl,$newidx) = @_;
       my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
       return <<STATE;
       <input type="hidden" name="folderpath" value="$folderpath" />
       <input type="hidden" name="cmd" value="upload_embedded" />
       <input type="hidden" name="newidx" value="$newidx" />
       <input type="hidden" name="phase" value="$phase" />
       <input type="hidden" name="primaryurl" value="$primaryurl" />
   STATE
   }
   
   sub embedded_destination {
       my $folder=$env{'form.folder'};
       my $destination = 'docs/';
       if ($folder =~ /^supplemental/) {
           $destination = 'supplemental/';
       }
       if (($folder eq 'default') || ($folder eq 'supplemental')) {
           $destination .= 'default/';
       } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
           $destination .=  $2.'/';
       }
       $destination .= $env{'form.newidx'};
       my $dir_root = '/userfiles';
       return ($destination,$dir_root);
   }
   
   sub return_to_editor {
       my $actionurl = '/adm/coursedocs';
       return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
              '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
              '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
              '</a></p>';
   }
   
   sub decompression_info {
       my ($destination,$dir_root) = &embedded_destination();
       my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
       my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
       my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $container='sequence';
       my ($pathitem,$hiddenelem);
       my @hiddens = ('newidx','comment','position');
       if ($env{'form.pagepath'}) {
           $container='page';
           $pathitem = 'pagepath';
       } else {
           $pathitem = 'folderpath';
       }
       unshift(@hiddens,$pathitem);
       foreach my $item (@hiddens) {
           if ($env{'form.'.$item}) {
               $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
                              $env{'form.'.$item}.'" />'."\n";
           }
       }
       return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
               $hiddenelem);
   }
   
   sub decompression_phase_one {
       my ($dir,$file,$warning,$error,$output);
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/\E(?:docs|supplemental)/(?:default|\d+).*/([^/]+)$}) {
           $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
       } else {
           my $file = $1;
           $output = 
               &Apache::loncommon::process_decompression($docudom,$docuname,$file,
                                                         $destination,$dir_root,
                                                         $hiddenelem);
           if ($env{'form.autoextract_camtasia'}) {
               $output .= &remove_archive($docudom,$docuname,$container);
           }
       }
       if ($error) {
           $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                      $error.'</p>'."\n";
       }
       if ($warning) {
           $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
       }
       return $output;
   }
   
   sub decompression_phase_two {
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       my $output;
       if ($env{'form.archivedelete'}) {
           $output = &remove_archive($docudom,$docuname,$container);
       }
       $output .= 
           &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
                                                       $destination,$dir_root,$hiddenelem);
       return $output;
   }
   
   sub remove_archive {
       my ($docudom,$docuname,$container) = @_;
       my $map = $env{'form.folder'}.'.'.$container;
       my ($output,$delwarning,$delresult,$url);
       my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
       if ($fatal) {
           if ($container eq 'page') {
               $delwarning = &mt('An error occurred retrieving the contents of the current page.');
           } else {
               $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
           }
           $delwarning .= &mt('As a result the archive file has not been removed.');
       } else {
           my $currcmd = $env{'form.cmd'};
           my $position = $env{'form.position'};
           if ($position > 0) { 
               $env{'form.cmd'} = 'del_'.$position;
               my ($title,$url,@rrest) = 
                   split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$position]]);
               if (&handle_edit_cmd($docuname,$docudom)) {
                   ($errtext,$fatal) = &storemap($docuname,$docudom,$map,1);
                   if ($fatal) {
                       if ($container eq 'page') {
                           $delwarning = &mt('An error occurred updating the contents of the current page.');
                       } else {
                           $delwarning = &mt('An error occurred updating the contents of the current folder.');
                       }
                   } else {
                       $delresult = &mt('Archive file removed.');
                   }
               }
           }
           $env{'form.cmd'} = $currcmd;
       }
       if ($delwarning) {
           $output = '<p class="LC_warning">'.
                      $delwarning.
                      '</p>';
       }
       if ($delresult) {
           $output .= '<p class="LC_info">'.
                      $delresult.
                      '</p>';
       }
       return $output;
   }
   
   sub generate_admin_menu {
       my ($crstype) = @_;
       my $lc_crstype = lc($crstype);
       my ($home,$other,%outhash)=&authorhosts();
       my %lt=&Apache::lonlocal::texthash (
                                            'vc'   => 'Verify Content',
                                            'cv'   => 'Check/Set Resource Versions',
                                            'ls'   => 'List Resource Identifiers',
                                            'imse' => 'Export contents to IMS Archive',
                                            'dcd'  => "Dump $crstype Content to Authoring Space",
                                          );
       my ($candump,$dumpurl);
       if ($home + $other > 0) {
           $candump = 'F';
           if ($home) {
               $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
           } else {
               my @hosts;
               foreach my $aurole (keys(%outhash)) {
                   unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                       push(@hosts,$outhash{$aurole});
                   }  
               }
               if (@hosts == 1) {
                   my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
                                  '&amp;role='.
                                  &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
                                  &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
                   $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
               } else {
                   $dumpurl = "javascript:choose_switchserver_window()";
               }
           }
       }
       my @menu=
           ({  categorytitle=>'Administration',
               items =>[
                   {   linktext   => $lt{'vc'},
                       url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
                       permission => 'F',
                       help       => 'Verify_Content',
                       icon       => 'verify.png',
                       linktitle  => 'Verify contents can be retrieved/rendered',
                   },
                   {   linktext => $lt{'cv'},
                       url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
                       permission => 'F',
                       help       => 'Check_Resource_Versions',
                       icon       => 'resversion.png',
                       linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
                   },
                   {   linktext   => $lt{'ls'},
                       url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
                       permission => 'F',
                       #help => '',
                       icon       => 'symbs.png',
                       linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
                   },
                   ]
           },
           {   categorytitle=>'Export',
               items =>[
                   {   linktext   => $lt{'imse'},
                       url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
                       permission => 'F',
                       help       => 'Docs_Export_Course_Docs',
                       icon       => 'imsexport.png',
                       linktitle  => $lt{'imse'},
                   },
                   {   linktext   => $lt{'dcd'},
                       url        => $dumpurl,
                       permission => $candump,
                       #help => '',
                       icon       => 'dump.png',
                       linktitle  => $lt{'dcd'},
                   },
                   ]
           });
       return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
              '<input type="hidden" id="dummy" />'."\n".
              &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
              '</form>';
   }
   
   sub generate_edit_table {
       my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile) = @_;
       return unless(ref($orderhash_ref) eq 'HASH');
       my %orderhash = %{$orderhash_ref};
       my $form;
       my $activetab;
       my $active;
       if($env{'form.active'} ne ''){
           $activetab = $env{'form.active'};
       }
       my $backicon = $iconpath.'clickhere.gif';
       my $backtext = &mt('To Overview');
       $form = '<div class="LC_Box" style="margin:0;">'.
               '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
               '<li class="goback">'.
               '<a href="javascript:toContents('."'$jumpto'".');">'.
               '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
               '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n".
               '<li>'.
               '<a href="javascript:groupopen('."'$readfile'".',1);">'.
               &mt('Undo Delete').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li class="active">';
       } else {
           $form .= '<li>';
       }
       $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
                &mt('History').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
                    &mt('Edit').'</a></li>'."\n";
       }
       foreach my $name (reverse(sort(keys(%orderhash)))) {
           if($name ne '00'){
               if($activetab eq '' || $activetab ne $name){
                  $active = '';
               }elsif($activetab eq $name){
                  $active = 'class="active"';
               }
               $form .= '<li style="float:right" '.$active
                   .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
           } else {
       $form .= '<li '.$active.' style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
   
    }
       }
       $form .= '</ul>'."\n";
       $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
   
       if ($to_show ne '') {
           $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'."\n";
       }
       foreach my $field (keys(%orderhash)){
    if($field ne '00'){
               if($activetab eq '' || $activetab ne $field){
                   $active = 'style="display: none;float:left"';
               }elsif($activetab eq $field){
                   $active = 'style="display:block;float:left"';
               }
               $form .= '<div id="'.$field.$tid.'"'
                       .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
                       .'</div>'."\n";
           }
       }
       unless ($env{'form.docslog'}) {
           $form .= '</div></div>'."\n";
       }
       return $form;
   }
   
   sub editing_js {
       my ($udom,$uname,$supplementalflag) = @_;
       my $now = time();
       my %lt = &Apache::lonlocal::texthash(
                                             p_mnf => 'Name of New Folder',
                                             t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
                                             t_mnp => 'New Page',
                                             p_mxu => 'Title for the External Score',
                                             p_msp => 'Name of Simple Course Page',
                                             p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Discussion Board',
                                             p_mab => "Enter user:domain for User's Personal Information Page",
                                             p_mab2 => 'Personal Information Page of ',
                                             p_mab_alrt1 => 'Not a valid user:domain',
                                             p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                             p_chn => 'New Title',
                                             p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
                                             p_rmr2a => 'Remove[_99]',
                                             p_rmr2b => '?[_99]',
                                             p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                             p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                             p_ctr2a => 'Cut[_98]',
                                             p_ctr2b => '?[_98]',
                                             rpck    => 'Enter number to pick (e.g., 3)',
                                             imsfile => 'You must choose an IMS package for import',
                                             imscms  => 'You must select which Course Management System was the source of the IMS package',
                                             invurl  => 'Invalid URL',
                                             titbl   => 'Title is blank',
                                           );
   
       my $crstype = &Apache::loncommon::course_type();
       my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
       my $docs_pagepath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.pagepath'},'<>&"');
       my $main_container_page;
       if ($docs_folderpath eq '') {
           if ($docs_pagepath ne '') {
               $main_container_page = 1;
           }
       }
       my $toplevelmain = 'default&Main%20'.$crstype.'%20Documents';
       my $toplevelsupp = &supplemental_base();
   
       my $backtourl = '/adm/navmaps';
       if ($supplementalflag) {
           $backtourl = '/adm/supplemental';
       }
   
       my $fieldsets = "'ext','doc','ims'";
       if ($supplementalflag) {
           $fieldsets = "'suppext','suppdoc'";
       }
   
       my $urlregexp = <<'ENDREGEXP';
   /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i
   ENDREGEXP
   
       return <<ENDNEWSCRIPT;
   function makenewfolder(targetform,folderseq) {
       var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
       if (foldername) {
          targetform.importdetail.value=escape(foldername)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makenewpage(targetform,folderseq) {
       var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
       if (pagename) {
           targetform.importdetail.value=escape(pagename)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function editext(residx) {
       if (document.getElementById('uploadext'+residx)) {
           var curr = document.getElementById('uploadext'+residx).style.display;
           if (curr == 'none') {
               disp = 'block';
           } else {
               disp = 'none';
           }
           document.getElementById('uploadext'+residx).style.display=disp;
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   function makeexamupload() {
      var title=prompt('$lt{"p_mxu"}');
      if (title) {
       this.document.forms.newexamupload.importdetail.value=
    escape(title)+'=/res/lib/templates/examupload.problem';
       this.document.forms.newexamupload.submit();
      }
   }
   
   function makesmppage() {
      var title=prompt('$lt{"p_msp"}');
      if (title) {
       this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/smppg';
       this.document.forms.newsmppg.submit();
      }
   }
   
   function makesmpproblem() {
      var title=prompt('$lt{"p_msb"}');
      if (title) {
       this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
       this.document.forms.newsmpproblem.submit();
      }
   }
   
   function makedropbox() {
      var title=prompt('$lt{"p_mdb"}');
      if (title) {
       this.document.forms.newdropbox.importdetail.value=
           escape(title)+'=/res/lib/templates/DropBox.problem';
       this.document.forms.newdropbox.submit();
      }
   }
   
   function makebulboard() {
      var title=prompt('$lt{"p_mbb"}');
      if (title) {
       this.document.forms.newbul.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
       this.document.forms.newbul.submit();
      }
   }
   
   function makeabout() {
      var user=prompt("$lt{'p_mab'}");
      if (user) {
          var comp=new Array();
          comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
      if ((comp[0]) && (comp[1])) {
          this.document.forms.newaboutsomeone.importdetail.value=
      '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
          this.document.forms.newaboutsomeone.submit();
      } else {
          alert("$lt{'p_mab_alrt1'}");
      }
   } else {
      alert("$lt{'p_mab_alrt2'}");
   }
   }
   }
   
   function toggleUpload(caller) {
       var blocks = Array($fieldsets);
       for (var i=0; i<blocks.length; i++) {
           var disp = 'none';
           if (caller == blocks[i]) {
               var curr = document.getElementById('upload'+caller+'form').style.display;
               if (curr == 'none') {
                   disp='block';
               }
           }
           document.getElementById('upload'+blocks[i]+'form').style.display=disp;
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   function toggleMap() {
       var disp = 'none';
       var curr = document.getElementById('importmapform').style.display;
       if (curr == 'none') {
           disp='block';
       }
       document.getElementById('importmapform').style.display=disp;
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   
   function extUrlPreview(caller) {
       if (document.getElementById(caller)) {
           var url = document.getElementById(caller).value;
           var regexp = $urlregexp;
           if (regexp.test(url)) {
               openMyModal(url,500,400,'yes');
           } else {
               alert("$lt{'invurl'}");
           }
       }
   }
   
   function makeims(imsform) {
       if ((imsform.uploaddoc.value == '')  || (!imsform.uploaddoc.value)) {
           alert("$lt{'imsfile'}");
           return;
       }
       if (imsform.source.selectedIndex == 0) {
           alert("$lt{'imscms'}");
           return;
       }
       newWindow = window.open('', 'IMSimport',"HEIGHT=700,WIDTH=750,scrollbars=yes");
       imsform.submit();
   }
   
   function setExternal(extform,residx) {
       var title=extform.exttitle.value;
       if (!String.trim) {
           String.prototype.trim = function() {return this.replace(\/^\\s+|\\s+$\/g, "");};    }
       var url=extform.exturl.value;
       var regexp = $urlregexp;
       if (title == null || title.trim()=="") {
           alert("$lt{'titbl'}");
           extform.exttitle.focus();
           return;
       }
       if (regexp.test(url)) {
           url = escape(url);
           if (residx > 0) {
               eval("extform.importdetail.value=title+'='+url+'='+residx;extform.submit();");
           } else {
               eval("extform.importdetail.value=title+'='+url;extform.submit();");
           }
       } else {
           alert("$lt{'invurl'}");
           extform.exturl.focus();
           return;
       }
   }
   
   function changename(folderpath,index,oldtitle,container,pagesymb) {
   var title=prompt('$lt{"p_chn"}',oldtitle);
   if (title) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.title.value=title;
   this.document.forms.renameform.cmd.value='rename_'+index;
   if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
       this.document.forms.renameform.pagepath.value=folderpath;
       this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   }
   
   function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.cmd.value='del_'+index;
   if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
       this.document.forms.renameform.pagepath.value=folderpath;
       this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   }
   
   function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
   this.document.forms.renameform.cmd.value='cut_'+index;
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
       this.document.forms.renameform.pagepath.value=folderpath;
       this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   }
   
   function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   if (container == 'sequence') {
   this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
   this.document.forms.renameform.pagepath.value=folderpath;
   this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   
   function updatePick(targetform,index,caller) {
       var pickitem = document.getElementById('rpick_'+index);
       var picknumitem = document.getElementById('rpicknum_'+index);
       if (pickitem.checked) {
           var picknum=prompt('$lt{"rpck"}',picknumitem.value);
           if (picknum == '' || picknum == null) {
               if (caller == 'check') {
                   pickitem.checked=false;
                   return;
               }
           } else {
               picknum.toString();
               var regexdigit=/^\\d+\$/;
               if (regexdigit.test(picknum)) {
                   picknumitem.value = picknum;
                   targetform.changeparms.value='randompick';
                   targetform.submit();
               } else {
                   if (caller == 'check') {
                       pickitem.checked=false;
                   }
                   return;
               }
           }
       } else {
           picknumitem.value = 0;
           targetform.changeparms.value='randompick';
           targetform.submit();
       }
   }
   
   function unselectInactive(nav) {
   currentNav = document.getElementById(nav);
   currentLis = currentNav.getElementsByTagName('LI');
   for (i = 0; i < currentLis.length; i++) {
           if (currentLis[i].className == 'goback') {
               currentLis[i].className = 'goback';
           } else {
       if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
    currentLis[i].className = 'right';
       } else {
    currentLis[i].className = 'i';
       }
           }
   }
   }
   
   function hideAll(current, nav, data) {
   unselectInactive(nav);
   if(current.className == 'right'){
    current.className = 'right active'
    }else{
    current.className = 'active';
   }
   currentData = document.getElementById(data);
   currentDivs = currentData.getElementsByTagName('DIV');
   for (i = 0; i < currentDivs.length; i++) {
    if(currentDivs[i].className == 'LC_ContentBox'){
    currentDivs[i].style.display = 'none';
    }
   }
   }
   
   function openTabs(pageId) {
    tabnav = document.getElementById(pageId).getElementsByTagName('UL');
    if(tabnav.length > 2 ){
    currentNav = document.getElementById(tabnav[1].id);
    currentLis = currentNav.getElementsByTagName('LI');
    for(i = 0; i< currentLis.length; i++){
    if(currentLis[i].className == 'active') {
    funcString = currentLis[i].onclick.toString();
    tab = funcString.split('"');
                                   if(tab.length < 2) {
                                      tab = funcString.split("'");
                                   }
    currentData = document.getElementById(tab[1]);
           currentData.style.display = 'block';
    }
    }
    }
   }
   
   function showPage(current, pageId, nav, data) {
    hideAll(current, nav, data);
    openTabs(pageId);
    unselectInactive(nav);
    current.className = 'active';
    currentData = document.getElementById(pageId);
    currentData.style.display = 'block';
           activeTab = pageId;
           toggleUpload();
           toggleMap();
           if (nav == 'mainnav') {
               var storedpath = "$docs_folderpath";
               if (storedpath == '') {
                   storedpath = "$docs_pagepath";
               }
               var storedpage = "$main_container_page";
               var reg = new RegExp("^supplemental");
               if (pageId == 'mainCourseDocuments') {
                   if (storedpage == 1) {
                       document.simpleedit.folderpath.value = '';
                       document.uploaddocument.folderpath.value = '';
                   } else {
                       if (reg.test(storedpath)) {
                           document.simpleedit.folderpath.value = '$toplevelmain';
                           document.uploaddocument.folderpath.value = '$toplevelmain';
                           document.newext.folderpath.value = '$toplevelmain';
                       } else {
                           document.simpleedit.folderpath.value = storedpath;
                           document.uploaddocument.folderpath.value = storedpath;
                           document.newext.folderpath.value = storedpath;
                       }
                   }
               } else {
                   if (reg.test(storedpath)) {
                       document.simpleedit.folderpath.value = storedpath;
                       document.supuploaddocument.folderpath.value = storedpath;
                       document.supnewext.folderpath.value = storedpath;
                   } else {
                       document.simpleedit.folderpath.value = '$toplevelsupp';
                       document.supuploaddocument.folderpath.value = '$toplevelsupp';
                       document.supnewext.folderpath.value = '$toplevelsupp';
                   }
               }
           }
           resize_scrollbox('contentscroll','1','0');
    return false;
   }
   
   function toContents(jumpto) {
       var newurl = '$backtourl';
       if (jumpto != '') {
           newurl = newurl+'?postdata='+jumpto;
   ;
       }
       location.href=newurl;
   }
   
   ENDNEWSCRIPT
   }
   
   sub history_tab_js {
       return <<"ENDHIST";
   function toggleHistoryDisp(choice) {
       document.docslogform.docslog.value = choice;
       document.docslogform.submit();
       return;
   }
   
   ENDHIST
   }
   
   sub inject_data_js {
       return <<ENDINJECT;
   
   function injectData(current, hiddenField, name, value) {
           currentElement = document.getElementById(hiddenField);
           currentElement.name = name;
           currentElement.value = value;
           current.submit();
   }
   
   ENDINJECT
   }
   
   sub dump_switchserver_js {
       my @hosts = @_;
       my %lt = &Apache::lonlocal::texthash(
           dump => 'Dumping to Authoring Space requires switching server.',
           swit => 'Switch server?',
           duco => 'Dump content to Authoring Space',
           yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
           chos => 'Choose server',
       );
       my $role = $env{'request.role'};
       my $js = <<"ENDSWJS";
   <script type="text/javascript">
   function write_switchserver() {
       var server;
       if (document.setserver.posshosts.length > 0) {
           for (var i=0; i<document.setserver.posshosts.length; i++) {
               if (document.setserver.posshosts[i].checked) {
                   server = document.setserver.posshosts[i].value;
               }
          }
          opener.document.location.href="/adm/switchserver?otherserver="+server+"&role=$role&origurl=/adm/coursedocs";
       }
       window.close();
   }
   </script>
   
   ENDSWJS
   
       my $startpage = &Apache::loncommon::start_page('Choose server',$js,
                                                      {'only_body' => 1,
                                                       'js_ready'  => 1,});
       my $endpage = &Apache::loncommon::end_page({'js_ready'  => 1});
   
       my $hostpicker;
       my $count = 0;
       foreach my $host (sort(@hosts)) {
           my $checked;
           if ($count == 0) {
               $checked = ' checked="checked"';
           }
           $hostpicker .= '<label><input type="radio" name="posshosts" value="'.
                          $host.'"'.$checked.' />'.$host.'</label>&nbsp;&nbsp;';
           $count++;
       }
       
       return <<"ENDSWITCHJS";
   
   function dump_needs_switchserver(url) {
       if (url!='' && url!= null) {
           if (confirm("$lt{'dump'}\\n$lt{'swit'}")) {
               go(url);
           }
       }
       return;
   }
   
   function choose_switchserver_window() {
       newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
       newWindow.document.open();
       newWindow.document.writeln('$startpage');
       newWindow.document.write('<h3>$lt{'duco'}<\\/h3>\\n'+
          '<p>$lt{'yone'}<\\/p>\\n'+
          '<div class="LC_left_float"><fieldset><legend>$lt{'chos'}<\\/legend>\\n'+
          '<form name="setserver" method="post" action="" \\/>\\n'+
          '$hostpicker\\n'+
          '<br \\/><br \\/>\\n'+
          '<input type="button" name="makeswitch" value="$lt{'swit'}" '+
          'onclick="write_switchserver();" \\/>\\n'+
          '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
       newWindow.document.writeln('$endpage');
       newWindow.document.close();
       newWindow.focus();
   }
   
   ENDSWITCHJS
   }
   
   sub makedocslogform {
       my ($formelems,$docslog) = @_;
       return <<"LOGSFORM";
    <form action="/adm/coursedocs" method="post" name="docslogform">
      <input type="hidden" name="docslog" value="$docslog" />
      $formelems
    </form>
   LOGSFORM
   }
   
   sub makesimpleeditform {
       my ($formelems) = @_;
       return <<"SIMPFORM";
    <form name="simpleedit" method="post" action="/adm/coursedocs">
      <input type="hidden" name="importdetail" value="" />
      $formelems
    </form>
   SIMPFORM
   }
   
   1;
   __END__
   
   
   =head1 NAME
   
   Apache::londocs.pm
   
   =head1 SYNOPSIS
   
   This is part of the LearningOnline Network with CAPA project
   described at http://www.lon-capa.org.
   
   =head1 SUBROUTINES
   
   =over
   
   =item %help=()
   
   Available help topics
   
   =item mapread()
   
   Mapread read maps into LONCAPA::map:: global arrays
   @order and @resources, determines status
   sets @order - pointer to resources in right order
   sets @resources - array with the resources with correct idx
   
   =item authorhosts()
   
   Return hash with valid author names
   
   =item clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   =item group_import()
   
       Imports the given (name, url) resources into the course
       coursenum, coursedom, and folder must precede the list
   
   =item breadcrumbs()
   
   =item log_docs()
   
   =item docs_change_log()
   
   =item update_paste_buffer()
   
   =item print_paste_buffer()
   
   =item do_paste_from_buffer()
   
   =item get_newmap_url()
   
   =item dbcopy()
   
   =item uniqueness_check()
   
   =item contained_map_check()
   
   =item reinit_role()
   
   =item url_paste_fixups()
   
   =item apply_fixups()
   
   =item copy_dependencies()
   
   =item update_parameter()
   
   =item handle_edit_cmd()
   
   =item editor()
   
   =item process_file_upload()
   
   =item process_secondary_uploads()
   
   =item is_supplemental_title()
   
   =item entryline()
   
   =item tiehash()
   
   =item untiehash()
   
   =item checkonthis()
   
   check on this
   
   =item verifycontent()
   
   Verify Content
   
   =item devalidateversioncache() & checkversions()
   
   Check Versions
   
   =item mark_hash_old()
   
   =item is_hash_old()
   
   =item changewarning()
   
   =item init_breadcrumbs()
   
   Breadcrumbs for special functions
   
   =item create_list_elements()
   
   =item create_form_ul()
   
   =item startContentScreen() 
   
   =item endContentScreen()
   
   =item supplemental_base()
   
   =item embedded_form_elems()
   
   =item embedded_destination()
   
   =item return_to_editor()
   
   =item decompression_info()
   
   =item decompression_phase_one()
   
   =item decompression_phase_two()
   
   =item remove_archive()
   
   =item generate_admin_menu()
   
   =item generate_edit_table()
   
   =item editing_js()
   
   =item history_tab_js()
   
   =item inject_data_js()
   
   =item dump_switchserver_js()
   
   =item resize_scrollbox_js()
   
   =item makedocslogform()
   
   =item makesimpleeditform()
   
   =back
   
   =cut

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


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