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

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

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


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