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

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


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