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

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


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