Diff for /loncom/interface/londocs.pm between versions 1.327 and 1.484.2.17

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


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