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

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

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


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