Diff for /loncom/interface/londocs.pm between versions 1.326 and 1.500

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

Removed from v.1.326  
changed lines
  Added in v.1.500


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