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

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

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


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