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

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

Removed from v.1.326  
changed lines
  Added in v.1.484.2.13


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