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

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


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