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

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

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


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