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

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


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