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

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


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