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

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

Removed from v.1.327  
changed lines
  Added in v.1.486


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