Diff for /loncom/interface/londocs.pm between versions 1.327 and 1.520

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


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