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

version 1.326, 2009/01/28 11:51:22 version 1.484.2.19, 2012/12/13 04:51:41
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          my $toolslink = '<table><tr><td>'
    $form_end                         .&Apache::loncommon::help_open_menu('Navigation Screen',
 </td>                                                             'Navigation_Screen',undef,'RAT')
 <td class="LC_docs_entry_commands">                         .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>                         .'<td align="left"><ul id="LC_toolbar">'
 $cutlink                         .'<li><a href="/adm/coursedocs?forcesupplement=1" '
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>                         .'id="LC_content_toolbar_edittoplevel" '
 $copylink                         .'class="LC_toolbarItem" '
 </td>                         .'title="'.&mt('Supplemental Content Editor').'">'
 END                         .'</a></li></ul></td></tr></table><br />';
           if ($shown) {
     }              if ($allowed) {
 # Figure out what kind of a resource this is                  $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
     my ($extension)=($url=~/\.(\w+)$/);                            .&Apache::loncommon::start_data_table(undef,'contentlist')
     my $uploaded=($url=~/^\/*uploaded\//);                            .&Apache::loncommon::start_data_table_header_row()
     my $icon=&Apache::loncommon::icon($url);                            .'<th colspan="2">'.&mt('Move').'</th>'
     my $isfolder=0;                            .'<th>'.&mt('Actions').'</th>'
     my $ispage=0;                            .'<th colspan="2">'.&mt('Document').'</th>';
     my $folderarg;                  if ($folder !~ /^supplemental/) {
     my $pagearg;                      $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
     my $pagefile;                  }
     if ($uploaded) {                  $to_show .= &Apache::loncommon::end_data_table_header_row()
  if ($extension eq 'sequence') {                             .$output.' '
     $icon=$iconpath.'/folder_closed.gif';                             .&Apache::loncommon::end_data_table()
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;                             .'<br style="line-height:2px;" />'
     $url='/adm/coursedocs?';                             .&Apache::loncommon::end_scrollbox();
     $folderarg=$1;              } else {
     $isfolder=1;                  $to_show .= $toolslink
         } elsif ($extension eq 'page') {                             .&Apache::loncommon::start_data_table('LC_tableOfContent')
             $icon=$iconpath.'/page.gif';                             .$output.' '
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;                             .&Apache::loncommon::end_data_table();
             $pagearg=$1;              }
             $url='/adm/coursedocs?';          } else {
             $ispage=1;              if (!$allowed) {
  } else {                  $to_show .= $toolslink;
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);              }
  }              $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
     }                         .'<div class="LC_info" id="contentlist">'
                             .&mt('Currently no documents.')
     my $orig_url = $url;                         .'</div>'
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});                         .&Apache::loncommon::end_scrollbox();
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {          }
  my $symb=&Apache::lonnet::symbclean(      } else {
           &Apache::lonnet::declutter('uploaded/'.          if ($shown) {
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.              $to_show = '<div>'
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.                        .&Apache::loncommon::start_data_table('LC_tableOfContent')
            '.sequence').                        .$output
            '___'.$residx.'___'.                        .&Apache::loncommon::end_data_table()
    &Apache::lonnet::declutter($url));                        .'</div>';
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);          } else {
  $url=&Apache::lonnet::clutter($url);              $to_show = '<div class="LC_info" id="contentlist">'
  if ($url=~/^\/*uploaded\//) {                        .&mt('Currently no documents.')
     $url=~/\.(\w+)$/;                        .'</div>'
     my $embstyle=&Apache::loncommon::fileembstyle($1);          }
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {      }
  $url='/adm/wrapper'.$url;      my $tid = 1;
     } elsif ($embstyle eq 'ssi') {      if ($supplementalflag) {
  #do nothing with these          $tid = 2;
     } elsif ($url!~/\.(sequence|page)$/) {      }
  $url='/adm/coursedocs/showdoc'.$url;      if ($allowed) {
     }          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
  } elsif ($url=~m|^/ext/|) {          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,$jumpto,
     $url='/adm/wrapper'.$url;                                         $readfile));
     $external = 1;          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
  }      } else {
         if (&Apache::lonnet::symbverify($symb,$url)) {          $r->print($to_show);
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);      }
         } else {      return;
             $url='';  }
         }  
  if ($container eq 'page') {  sub process_file_upload {
     my $symb=$env{'form.pagesymb'};      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
           # upload a file, if present
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);      my ($parseaction,$showupload,$nextphase,$mimetype);
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);      if ($env{'form.parserflag'}) {
  }          $parseaction = 'parse';
     }      }
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');      my $folder=$env{'form.folder'};
     if ($isfolder || $extension eq 'sequence') {      if ($folder eq '') {
  my $foldername=&escape($foldertitle);          $folder='default';
  my $folderpath=$env{'form.folderpath'};      }
  if ($folderpath) { $folderpath.='&' };      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
 # Append randompick number, hidden, and encrypted with ":" to foldername,          my $errtext='';
 # so it gets transferred between levels          my $fatal=0;
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,          my $container='sequence';
                                               'parameter_randompick'))[0]          if ($env{'form.folderpath'} =~ /:1$/) {
                                                .':'.((&LONCAPA::map::getparameter($orderidx,              $container='page';
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)          }
                                                .':'.((&LONCAPA::map::getparameter($orderidx,          ($errtext,$fatal)=
                                               'parameter_encrypturl'))[0]=~/^yes$/i)                &mapread($coursenum,$coursedom,$folder.'.'.$container);
                                                .':'.((&LONCAPA::map::getparameter($orderidx,          if ($#LONCAPA::map::order<1) {
                                               'parameter_randomorder'))[0]=~/^yes$/i);              $LONCAPA::map::order[0]=1;
  $url.='folderpath='.&escape($folderpath).$cpinfo;              $LONCAPA::map::resources[1]='';
  $parameterset='<label>'.&mt('Randomly Pick: ').          }
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.          if ($fatal) {
     (&LONCAPA::map::getparameter($orderidx,              $$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>';
                                               'parameter_randompick'))[0].              return;
                                               '" />'.          }
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';          my $destination = 'docs/';
     my $ro_set=          if ($folder =~ /^supplemental/) {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');              $destination = 'supplemental/';
  $rand_order_text ='          }
 <span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" onClick="this.form.changeparms.value=\'randomorder\';this.form.submit()" '.$ro_set.' /> '.&mt('Random Order').' </label></span>';            if (($folder eq 'default') || ($folder eq 'supplemental')) {
     }              $destination .= 'default/';
     if ($ispage) {          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
         my $pagename=&escape($pagetitle);              $destination .=  $2.'/';
         my $pagepath;          }
         my $folderpath=$env{'form.folderpath'};  # this is for a course, not a user, so set context to coursedoc.
         if ($folderpath) { $pagepath = $folderpath.'&' };          my $newidx=&LONCAPA::map::getresidx();
         $pagepath.=$pagearg.'&'.$pagename;          $destination .= $newidx;
  my $symb=$env{'form.pagesymb'};          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
  if (!$symb) {   $parseaction,$allfiles,
     my $path='uploaded/'.   $codebase,undef,undef,undef,undef,
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.                                                  undef,undef,\$mimetype);
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',              my $stored = $1;
        $residx,              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
        $path.$pagearg.'.page');                            $stored.'</span>').'</p>';
  }          } else {
  $url.='pagepath='.&escape($pagepath).              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
     '&amp;pagesymb='.&escape($symb).$cpinfo;              
     }              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
     if ($external) {              return;
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';          }
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';          my $ext='false';
     } else {          if ($url=~m{^http://}) { $ext='true'; }
  undef($external);   $url     = &LONCAPA::map::qtunescape($url);
     }          my $comment=$env{'form.comment'};
     $line.='   $comment = &LONCAPA::map::qtunescape($comment);
   <td class="LC_docs_entry_icon">          if ($folder=~/^supplemental/) {
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
   </td>                    $env{'user.domain'}.'___&&&___'.$comment;
   <td class="LC_docs_entry_title">          }
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."  
   </td>";          $LONCAPA::map::resources[$newidx]=
     if (($allowed) && ($folder!~/^supplemental/)) {      $comment.':'.$url.':'.$ext.':normal:res';
   my %lt=&Apache::lonlocal::texthash(          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
        'hd' => 'Hidden',          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
        'ec' => 'URL hidden');      $folder.'.'.$container,1);
  my $enctext=          if ($fatal) {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
  my $hidtext=              return;
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');          } else {
  $line.=(<<ENDPARMS);              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
   <td class="LC_docs_entry_parameter">                  $$upload_output = $showupload;
     $form_start                  my $total_embedded = scalar(keys(%{$allfiles}));
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>                  if ($total_embedded > 0) {
     $form_end                      my $uploadphase = 'upload_embedded';
   </td>                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
   <td class="LC_docs_entry_parameter">      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
     $form_start                      my ($embedded,$num) = 
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>                          &Apache::loncommon::ask_for_embedded_content(
     $form_end                              '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
   </td>                      if ($embedded) {
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>                          if ($num) {
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>                              $$upload_output .=
 ENDPARMS           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
     }                              $nextphase = $uploadphase;
     $line.="</tr>";                          } else {
     return $line;                              $$upload_output .= $embedded;
 }                          }
                       } else {
 =pod                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
                       }
 =item tiehash()                  } else {
                       $$upload_output .= &mt('No embedded items identified').'<br />';
 tie the hash                  }
                   $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
 =cut              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
                   $nextphase = 'decompress_uploaded';
 sub tiehash {                  my $position = scalar(@LONCAPA::map::order)-1;
     my ($mode)=@_;                  my $noextract = &return_to_editor();
     $hashtied=0;                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
     if ($env{'request.course.fn'}) {                  my %archiveitems = (
  if ($mode eq 'write') {                      folderpath => $env{'form.folderpath'},
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                      cmd        => $nextphase,
     &GDBM_WRCREAT(),0640)) {                      newidx     => $newidx,
                 $hashtied=2;                      position   => $position,
     }                      phase      => $nextphase,
  } else {                      comment    => $comment,
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",                  );
     &GDBM_READER(),0640)) {                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
                 $hashtied=1;                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
     }                  $$upload_output = $showupload.
  }                                    &Apache::loncommon::decompress_form($mimetype,
     }                                            $archiveurl,'/adm/coursedocs',$noextract,
 }                                        \%archiveitems,\@current);
               }
 sub untiehash {          }
     if ($hashtied) { untie %hash; }      }
     $hashtied=0;      return $nextphase;
     return OK;  }
 }  
   sub get_dir_list {
       my ($url,$coursenum,$coursedom,$newidx) = @_;
       my ($destination,$dir_root) = &embedded_destination();
       my ($dirlistref,$listerror) =  
 sub checkonthis {          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
     my ($r,$url,$level,$title)=@_;      my @dir_lines;
     $url=&unescape($url);      my $dirptr=16384;
     $alreadyseen{$url}=1;      if (ref($dirlistref) eq 'ARRAY') {
     $r->rflush();          foreach my $dir_line (sort
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {                            {
        $r->print("\n<br />");                                my ($afile)=split('&',$a,2);
        if ($level==0) {                                my ($bfile)=split('&',$b,2);
            $r->print("<br />");                                return (lc($afile) cmp lc($bfile));
        }                            } (@{$dirlistref})) {
        for (my $i=0;$i<=$level*5;$i++) {              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
            $r->print('&nbsp;');              $filename =~ s/\s+$//;
        }              next if ($filename =~ /^\.\.?$/); 
        $r->print('<a href="'.$url.'" target="cat">'.              my $isdir = 0;
  ($title?$title:$url).'</a> ');              if ($dirptr&$testdir) {
        if ($url=~/^\/res\//) {                  $isdir = 1;
   my $result=&Apache::lonnet::repcopy(              }
                               &Apache::lonnet::filelocation('',$url));              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
           if ($result eq 'ok') {          }
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');      }
              $r->rflush();      return @dir_lines;
              &Apache::lonnet::countacc($url);  }
              $url=~/\.(\w+)$/;  
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {  sub is_supplemental_title {
  $r->print('<br />');      my ($title) = @_;
                  $r->rflush();      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
                  for (my $i=0;$i<=$level*5;$i++) {  }
                      $r->print('&nbsp;');  
                  }  # --------------------------------------------------------------- An entry line
                  $r->print('- '.&mt('Rendering:').' ');  
  my ($errorcount,$warningcount)=split(/:/,  sub entryline {
        &Apache::lonnet::ssi_body($url,      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
        ('grade_target'=>'web',          $crstype,$pathitem,$supplementalflag,$container)=@_;
  'return_only_error_and_warning_counts' => 1)));      my ($foldertitle,$renametitle);
                  if (($errorcount) ||      if (&is_supplemental_title($title)) {
                      ($warningcount)) {   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
      if ($errorcount) {      } else {
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.   $title=&HTML::Entities::encode($title,'"<>&\'');
                           &mt('[quant,_1,error]',$errorcount).'</span>');   $renametitle=$title;
                      }   $foldertitle=$title;
      if ($warningcount) {      }
                         $r->print('<span class="LC_warning">'.  
                           &mt('[quant,_1,warning]',$warningcount).'</span>');      my $orderidx=$LONCAPA::map::order[$index];
                      }  
                  } else {      $renametitle=~s/\\/\\\\/g;
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');      $renametitle=~s/\&quot\;/\\\"/g;
                  }      $renametitle=~s/ /%20/g;
                  $r->rflush();      my $line=&Apache::loncommon::start_data_table_row();
              }      my ($form_start,$form_end,$form_common);
      my $dependencies=  # Edit commands
                 &Apache::lonnet::metadata($url,'dependencies');      my ($type, $esc_path, $path, $symb);
              foreach my $dep (split(/\,/,$dependencies)) {      if ($container eq 'page') {
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {          $type = 'page';
                     &checkonthis($r,$dep,$level+1);      } else {
                  }          $type = 'folder';
              }      }
           } elsif ($result eq 'unavailable') {      if ($env{'form.folderpath'}) {
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');   $esc_path=&escape($env{'form.folderpath'});
           } elsif ($result eq 'not_found') {   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
       unless ($url=~/\$/) {   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');      }
       } else {      my $isexternal;
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');      if ($residx) {
       }          my $currurl = $url;
           } else {          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');          if ($currurl =~ m{^/adm/wrapper/ext/}) {
           }              $isexternal = 1;
        }          }
     }          if (!$supplementalflag) {
 }              my $path = 'uploaded/'.
                          $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
                          $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
               $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
 =pod                                                   $residx,
                                                    &Apache::lonnet::declutter($currurl));
 =item list_symbs()          }
       }
 List Symbs      my ($renamelink,%lt);
       if ($allowed) {
 =cut   my $incindex=$index+1;
    my $selectbox='';
 sub list_symbs {   if (($#LONCAPA::map::order>0) &&
     my ($r) = @_;      ((split(/\:/,
        $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
     my $type = &Apache::loncommon::course_type();       ne '') &&
     $r->print(&Apache::loncommon::start_page('Symb List'));      ((split(/\:/,
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
     my $navmap = Apache::lonnavmaps::navmap->new();       ne '')) {
     if (!defined($navmap)) {      $selectbox=
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
                   '<div class="LC_error">'.   '<select name="newpos" onchange="this.form.submit()">';
                   &mt('Unable to retrieve information about course contents').      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
                   '</div>');   if ($i==$incindex) {
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
     } else {   } else {
         $r->print("<pre>\n");      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
         foreach my $res ($navmap->retrieveResources()) {   }
     $r->print($res->compTitle()."\t".$res->symb()."\n");      }
         }      $selectbox.='</select>';
         $r->print("\n</pre>\n");   }
     }   %lt=&Apache::lonlocal::texthash(
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');                  'up' => 'Move Up',
 }   'dw' => 'Move Down',
    'rm' => 'Remove',
                   'ct' => 'Cut',
 sub verifycontent {   'rn' => 'Rename',
     my ($r) = @_;   'cp' => 'Copy',
     my $type = &Apache::loncommon::course_type();                  'ex' => 'External Resource',
    my $loaderror=&Apache::lonnet::overloaderror($r);                  'ed' => 'Edit',
    if ($loaderror) { return $loaderror; }                  'pr' => 'Preview',
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));                  'sv' => 'Save',
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));                  'ul' => 'URL',
    $hashtied=0;                  'ti' => 'Title', 
    undef %alreadyseen;                  );
    %alreadyseen=();   my $nocopy=0;
    &tiehash();          my $nocut=0;
    foreach my $key (keys(%hash)) {          my $noremove=0;
        if ($hash{$key}=~/\.(page|sequence)$/) {          if ($url=~ m{^/res/.+\.(page|sequence)$}) {
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {      # no copy for published maps
        $r->print('<hr /><span class="LC_error">'.      $nocopy=1;
  &mt('The following sequence or page is included more than once in your '.$type.': ').   }
  &unescape($hash{$key}).'</span><br />'.          if ($url=~/^\/res\/lib\/templates\//) {
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));             $nocopy=1;
    }             $nocut=1;
        }          }
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {          my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});          my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        }          if ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
    }              if ($env{'form.folderpath'} =~ /^default&[^\&]+$/) {
    &untiehash();                  my %curr_groups = &Apache::longroup::coursegroups();
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.                  if (keys(%curr_groups) > 0) {
      &mt('Return to DOCS').'</a>');                      $noremove=1;
 }                  }
                   $nocut=1;
                   $nocopy=1;
 sub devalidateversioncache {              }
     my $src=shift;          } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.              my $group = $1;
   &Apache::lonnet::clutter($src));              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
 }                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
                   if (keys(%curr_group) > 0) {
 sub checkversions {                      $noremove=1;
     my ($r) = @_;                  }
     my $type = &Apache::loncommon::course_type();              }
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));              $nocut=1;
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));              $nocopy=1;
     my $header='';          } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
     my $startsel='';              my $group = $1;
     my $monthsel='';              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
     my $weeksel='';                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     my $daysel='';                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
     my $allsel='';                  if (keys(%groupsettings) > 0) {
     my %changes=();                      $noremove=1;
     my $starttime=0;                  }
     my $haschanged=0;                  $nocut=1;
     my %setversions=&Apache::lonnet::dump('resourceversions',                  $nocopy=1;
   $env{'course.'.$env{'request.course.id'}.'.domain'},              }
   $env{'course.'.$env{'request.course.id'}.'.num'});          } elsif ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
               my $group = $1;
     $hashtied=0;              my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     &tiehash();              if ($url =~ /group_boards_\Q$group\E/) {
     my %newsetversions=();                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     if ($env{'form.setmostrecent'}) {                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
  $haschanged=1;                  if (keys(%groupsettings) > 0) {
  foreach my $key (keys(%hash)) {                      if (ref($groupsettings{'functions'}) eq 'HASH') {
     if ($key=~/^ids\_(\/res\/.+)$/) {                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
  $newsetversions{$1}='mostrecent';                              $noremove=1;
                 &devalidateversioncache($1);                          }
     }                      }
  }                  }
     } elsif ($env{'form.setcurrent'}) {                  $nocut=1;
  $haschanged=1;                  $nocopy=1;
  foreach my $key (keys(%hash)) {              }
     if ($key=~/^ids\_(\/res\/.+)$/) {          }
  my $getvers=&Apache::lonnet::getversion($1);          my ($copylink,$cutlink,$removelink);
  if ($getvers>0) {   my $skip_confirm = 0;
     $newsetversions{$1}=$getvers;   if ( $folder =~ /^supplemental/
     &devalidateversioncache($1);       || ($url =~ m{( /smppg$
  }      |/syllabus$
     }      |/aboutme$
  }      |/navmaps$
     } elsif ($env{'form.setversions'}) {      |/bulletinboard$
  $haschanged=1;      |\.html$)}x)
  foreach my $key (keys(%env)) {               || $isexternal) {
     if ($key=~/^form\.set_version_(.+)$/) {      $skip_confirm = 1;
  my $src=$1;   }
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {  
     $newsetversions{$src}=$env{$key};   if ($nocopy) {
     &devalidateversioncache($src);              $copylink=(<<ENDCOPY);
  }  <span style="visibility: hidden;">$lt{'cp'}</span>
     }  ENDCOPY
  }          } else {
     }      $copylink=(<<ENDCOPY);
     if ($haschanged) {  <a href="javascript:markcopy('$esc_path','$index','$renametitle','$container','$folder');" class="LC_docs_copy">$lt{'cp'}</a>
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,  ENDCOPY
   $env{'course.'.$env{'request.course.id'}.'.domain'},          }
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {   if ($nocut) {
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');              $cutlink=(<<ENDCUT);
  } else {  <span style="visibility: hidden;">$lt{'ct'}</span>
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');  ENDCUT
  }          } else {
  &mark_hash_old();      $cutlink=(<<ENDCUT);
     }  <a href="javascript:cutres('$esc_path','$index','$renametitle','$container','$folder',$skip_confirm);" class="LC_docs_cut">$lt{'ct'}</a>
     &changewarning($r,'');  ENDCUT
     if ($env{'form.timerange'} eq 'all') {          }
 # show all documents          if ($noremove) {
  $header=&mt('All Documents in '.$type);              $removelink=(<<ENDREM);
  $allsel=1;  <span style="visibility: hidden;">$lt{'rm'}</a>
  foreach my $key (keys(%hash)) {  ENDREM
     if ($key=~/^ids\_(\/res\/.+)$/) {          } else {
  my $src=$1;              $removelink=(<<ENDREM);
  $changes{$src}=1;  <a href='javascript:removeres("$esc_path","$index","$renametitle",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     }  ENDREM
  }          }
     } else {          unless ($isexternal) {
 # show documents which changed              $renamelink=(<<ENDREN);
  %changes=&Apache::lonnet::dump  <a href='javascript:changename("$esc_path","$index","$renametitle");' class="LC_docs_rename">$lt{'rn'}</a>
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},  ENDREN
                      $env{'course.'.$env{'request.course.id'}.'.num'});          }
  my $firstkey=(keys(%changes))[0];   $form_start = '
  unless ($firstkey=~/^error\:/) {     <form action="/adm/coursedocs" method="post">
     unless ($env{'form.timerange'}) {  ';
  $env{'form.timerange'}=604800;          $form_common=(<<END);
     }     <input type="hidden" name="${type}path" value="$path" />
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '     <input type="hidden" name="${type}symb" value="$symb" />
  .&mt('seconds');     <input type="hidden" name="setparms" value="$orderidx" />
     if ($env{'form.timerange'}==-1) {     <input type="hidden" name="changeparms" value="0" />
  $seltext='since start of course';  END
  $startsel='selected';          $form_end = '</form>';
  $env{'form.timerange'}=time;   $line.=(<<END);
     }  <td>
     $starttime=time-$env{'form.timerange'};  <div class="LC_docs_entry_move">
     if ($env{'form.timerange'}==2592000) {    <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
  $monthsel='selected';    </a>
     } elsif ($env{'form.timerange'}==604800) {  </div>
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  <div class="LC_docs_entry_move">
  $weeksel='selected';    <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb'>
     } elsif ($env{'form.timerange'}==86400) {      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';    </a>
  $daysel='selected';  </div>
     }  </td>
     $header=&mt('Content changed').' '.$seltext;  <td>
  } else {     $form_start
     $header=&mt('No content modifications yet.');     $form_common
  }     $selectbox
     }     $form_end
     %setversions=&Apache::lonnet::dump('resourceversions',  </td>
   $env{'course.'.$env{'request.course.id'}.'.domain'},  <td class="LC_docs_entry_commands"><span class="LC_nobreak">
   $env{'course.'.$env{'request.course.id'}.'.num'});  $removelink
     my %lt=&Apache::lonlocal::texthash  $cutlink
       ('st' => 'Version changes since start of '.$type,  $copylink
        'lm' => 'Version changes since last Month',  </span>
        'lw' => 'Version changes since last Week',  </td>
        'sy' => 'Version changes since Yesterday',  END
                'al' => 'All Resources (possibly large output)',  
        'sd' => 'Display',      }
        'fi' => 'File',  # Figure out what kind of a resource this is
        'md' => 'Modification Date',      my ($extension)=($url=~/\.(\w+)$/);
                'mr' => 'Most recently published Version',      my $uploaded=($url=~/^\/*uploaded\//);
        've' => 'Version used in '.$type,      my $icon=&Apache::loncommon::icon($url);
                'vu' => 'Set Version to be used in '.$type,      my $isfolder;
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      my $ispage;
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      my $containerarg;
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      if ($uploaded) {
        'di' => 'Differences');          if (($extension eq 'sequence') || ($extension eq 'page')) {
     $r->print(<<ENDHEADERS);              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
 <form action="/adm/coursedocs" method="post">              $containerarg = $1;
 <input type="hidden" name="versions" value="1" />      if ($extension eq 'sequence') {
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />          $icon=$iconpath.'navmap.folder.closed.gif';
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />                  $isfolder=1;
 <select name="timerange">              } else {
 <option value='all' $allsel>$lt{'al'}</option>                  $icon=$iconpath.'page.gif';
 <option value="-1" $startsel>$lt{'st'}</option>                  $ispage=1;
 <option value="2592000" $monthsel>$lt{'lm'}</option>              }
 <option value="604800" $weeksel>$lt{'lw'}</option>              if ($allowed) {
 <option value="86400" $daysel>$lt{'sy'}</option>                  $url='/adm/coursedocs?';
 </select>              } else {
 <input type="submit" name="display" value="$lt{'sd'}" />                  $url='/adm/supplemental?';
 <h3>$header</h3>              }
 <input type="submit" name="setversions" value="$lt{'sv'}" />   } else {
 <table border="0">      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 ENDHEADERS   }
     foreach my $key (sort(keys(%changes))) {      }
  if ($changes{$key}>$starttime) {  
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);      my ($editlink,$extresform);
     my $currentversion=&Apache::lonnet::getversion($key);      my $orig_url = $url;
     if ($currentversion<0) {      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
  $currentversion=&mt('Could not be determined.');      $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
     }      if (!$supplementalflag && $residx && $symb) {
     my $linkurl=&Apache::lonnet::clutter($key);          if ((!$isfolder) && (!$ispage)) {
     $r->print(      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.      $url=&Apache::lonnet::clutter($url);
       &Apache::lonnet::gettitle($linkurl).      if ($url=~/^\/*uploaded\//) {
                       '</b></font></td></tr>'.          $url=~/\.(\w+)$/;
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.          my $embstyle=&Apache::loncommon::fileembstyle($1);
                       '<td colspan="4">'.          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.      $url='/adm/wrapper'.$url;
       '</a></td></tr>'.          } elsif ($embstyle eq 'ssi') {
                       '<tr><td></td>'.      #do nothing with these
                       '<td title="'.$lt{'md'}.'">'.          } elsif ($url!~/\.(sequence|page)$/) {
       &Apache::lonlocal::locallocaltime(      $url='/adm/coursedocs/showdoc'.$url;
                            &Apache::lonnet::metadata($root.'.'.$extension,          }
                                                      'lastrevisiondate')      } elsif ($url=~m|^/ext/|) {
                                                         ).          $url='/adm/wrapper'.$url;
                       '</td>'.      }
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.              if (&Apache::lonnet::symbverify($symb,$url)) {
                       '<font size="+1">'.$currentversion.'</font>'.          $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
                       '</span></td>'.              } else {
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.                  $url='';
                       '<font size="+1">');              }
 # Used in course   }
     my $usedversion=$hash{'version_'.$linkurl};      }
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      my ($rand_pick_text,$rand_order_text);
  $r->print($usedversion);      if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
     } else {   my $foldername=&escape($foldertitle);
  $r->print($currentversion);   my $folderpath=$env{'form.folderpath'};
     }   if ($folderpath) { $folderpath.='&' };
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.          if (!$allowed && $supplementalflag) {
                       '<span class="LC_nobreak">Use: ');              $folderpath.=$containerarg.'&'.$foldername;
 # Set version              $url.='folderpath='.&escape($folderpath);
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},          } else {
       'set_version_'.$linkurl,  # Append randompick number, hidden, and encrypted with ":" to foldername,
       ('select_form_order' =>  # so it gets transferred between levels
        ['',1..$currentversion,'mostrecent'],      $folderpath.=$containerarg.'&'.$foldername.
        '' => '',                                                ':'.(&LONCAPA::map::getparameter($orderidx,
        'mostrecent' => 'most recent',                                                'parameter_randompick'))[0]
        map {$_,$_} (1..$currentversion))));                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     $r->print('</span></td></tr><tr><td></td>');                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
     my $lastold=1;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {                                                'parameter_encrypturl'))[0]=~/^yes$/i)
  my $url=$root.'.'.$prevvers.'.'.$extension;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                                                'parameter_randomorder'))[0]=~/^yes$/i)
     $starttime) {                                                 .':'.$ispage;
     $lastold=$prevvers;      $url.='folderpath='.&escape($folderpath);
  }              my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
     }                                                          'parameter_randompick'))[0];
             #              my $rpckchk;
             # Code to figure out how many version entries should go in              if ($rpicknum) {
             # each of the four columns                  $rpckchk = ' checked="checked"';
             my $entries_per_col = 0;              }
             my $num_entries = ($currentversion-$lastold);              my $formname = 'edit_rpick_'.$orderidx;
             if ($num_entries % 4 == 0) {      $rand_pick_text = 
                 $entries_per_col = $num_entries/4;  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
             } else {  $form_common."\n".
                 $entries_per_col = $num_entries/4 + 1;  '<span class="LC_nobreak"><label><input type="checkbox" name="randpickon_'.$orderidx.'" id="rpick_'.$orderidx.'" onclick="'."updatePick(this.form,'$orderidx','check');".'"'.$rpckchk.' /> '.&mt('Randomly Pick').'</label><input type="hidden" name="randompick_'.$orderidx.'" id="rpicknum_'.$orderidx.'" value="'.$rpicknum.'" />';
             }              if ($rpicknum ne '') {
             my $entries_count = 0;                  $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
             $r->print('<td valign="top"><font size="-2">');              }
             my $cols_output = 1;              $rand_pick_text .= '</span></form>';
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {         my $ro_set=
  my $url=$root.'.'.$prevvers.'.'.$extension;          ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).      $rand_order_text = 
   '">'.&mt('Version').' '.$prevvers.'</a> ('.  $form_start.
   &Apache::lonlocal::locallocaltime(  $form_common.'
                                 &Apache::lonnet::metadata($url,  <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>';
                                                           'lastrevisiondate')          }
                                                             ).      } elsif ($supplementalflag && !$allowed) {
   ')');          $url .= ($url =~ /\?/) ? '&amp;':'?';
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {          $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
                     $r->print(' <a href="/adm/diff?filename='.          if ($title) {
       &Apache::lonnet::clutter($root.'.'.$extension).              $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
       '&versionone='.$prevvers.          }
       '">'.&mt('Diffs').'</a>');          if ($isexternal && $orderidx) {
  }              $url .= '&amp;idx='.$orderidx;
  $r->print('</span><br />');          }
                 if (++$entries_count % $entries_per_col == 0) {      }
                     $r->print('</font></td>');      my ($tdalign,$tdwidth);
                     if ($cols_output != 4) {      if ($allowed) {
                         $r->print('<td valign="top"><font size="-2">');          my $fileloc = 
                         $cols_output++;              &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
                     }          if ($isexternal) {
                 }              ($editlink,$extresform) = 
     }                  &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
             while($cols_output++ < 4) {          } elsif (!$isfolder && !$ispage) {
                 $r->print('</font></td><td><font>')              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
             }                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
     $r->print('</font></td></tr>'."\n");              if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
  }                  my $jscall = 
     }                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
     $r->print('</table></form>');                                                              $switchserver,
     $r->print('<h1>'.&mt('Done').'.</h1>');                                                              $forceedit,
                                                               undef,$symb,
     &untiehash();                                                              &escape($env{'form.folderpath'}),
 }                                                              $renametitle,'','',1);
                   if ($jscall) {
 sub mark_hash_old {                      $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
     my $retie_hash=0;                                  $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
     if ($hashtied) {                  }
  $retie_hash=1;              }
  &untiehash();          }
     }          $tdalign = ' align="right" valign="top"';
     &tiehash('write');          $tdwidth = ' width="80%"';
     $hash{'old'}=1;      }
     &untiehash();      my $reinit;
     if ($retie_hash) { &tiehash(); }      if ($crstype eq 'Community') {
 }          $reinit = &mt('(re-initialize community to access)');
       } else {
 sub is_hash_old {          $reinit = &mt('(re-initialize course to access)');
     my $untie_hash=0;      }
     if (!$hashtied) {      $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
  $untie_hash=1;      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
  &tiehash();         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
     }      } elsif ($url) {
     my $return=$hash{'old'};         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
     if ($untie_hash) { &untiehash(); }                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
     return $return;      } else {
 }         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
       }
 sub changewarning {      $line.='</span></td><td'.$tdwidth.'>';
     my ($r,$postexec,$message,$url)=@_;      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
     if (!&is_hash_old()) { return; }         $line.='<a href="'.$url.'">'.$title.'</a>';
     my $pathvar='folderpath';      } elsif ($url) {
     my $path=&escape($env{'form.folderpath'});         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
     if (!defined($url)) {                                               $title,600,500);
  if (defined($env{'form.pagepath'})) {      } else {
     $pathvar='pagepath';         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
     $path=&escape($env{'form.pagepath'});      }
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});      $line.="$extresform</td>";
  }      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
  $url='/adm/coursedocs?'.$pathvar.'='.$path;      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
     }      if (($allowed) && ($folder!~/^supplemental/)) {
     my $course_type = &Apache::loncommon::course_type();    my %lt=&Apache::lonlocal::texthash(
     if (!defined($message)) {         'hd' => 'Hidden',
  $message='Changes will become active for your current session after [_1], or the next time you log in.';         'ec' => 'URL hidden');
     }   my $enctext=
     $r->print("\n\n".      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".   my $hidtext=
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
 '<input type="hidden" name="orgurl" value="'.$url.   $line.=(<<ENDPARMS);
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.    <td class="LC_docs_entry_parameter">
 &mt($message,' <input type="hidden" name="'.      $form_start
     $env{'request.role'}.'" value="1" /><input type="button" value="'.      $form_common
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').      <label><input type="checkbox" name="hiddenresource_$orderidx" onclick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
 $help{'Caching'}.'</span></h3></form>'."\n\n");      $form_end
 }      <br />
       $form_start
       $form_common
 sub init_breadcrumbs {      <label><input type="checkbox" name="encrypturl_$orderidx" onclick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
     my ($form,$text)=@_;      $form_end
     &Apache::lonhtmlcommon::clear_breadcrumbs();    </td>
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
     text=>"Edit ".&Apache::loncommon::course_type(),                                        $rand_order_text</td>
     faq=>273,  ENDPARMS
     bug=>'Instructor Interface',      }
                                             help => 'Docs_Adding_Course_Doc'});      $line.=&Apache::loncommon::end_data_table_row();
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',      return $line;
     text=>$text,  }
     faq=>273,  
     bug=>'Instructor Interface'});  sub newmap_suffix {
 }      my ($area,$container,$coursedom,$coursenum) = @_;
       my ($prefix,$idtype,$errtext,$locknotfreed);
       $prefix = 'docs';
       if ($area eq 'supplemental') {
           $prefix = 'supp';
 sub handler {      }
     my $r = shift;      $prefix .= $container;
     &Apache::loncommon::content_type($r,'text/html');      $idtype = 'concat';
     $r->send_http_header;      my ($suffix,$freedlock,$error) =
     return OK if $r->header_only;          &Apache::lonnet::get_timebased_id($prefix,'num','uploadedmaps',
     my $type = &Apache::loncommon::course_type();                                            $coursedom,$coursenum);
       if (!$suffix) {
           $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
 # --------------------------------------------- Initialize help topics for this          if ($error) {
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',              $errtext .= '<br />'.$error;
                'Adding_External_Resource','Navigate_Content',          }
                'Adding_Folders','Docs_Overview', 'Load_Map',      }
                'Supplemental','Score_Upload_Form','Adding_Pages',      if ($freedlock ne 'ok') {
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',          $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>';
                'Check_Resource_Versions','Verify_Content') {      }
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);      return ($suffix,$errtext,$locknotfreed);
     }  }
     # Composite help files  
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(  =pod
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');  
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(  =item tiehash()
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');  
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(  tie the hash
     'Option_Response_Simple');  
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(  =cut
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');  
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(  sub tiehash {
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');      my ($mode)=@_;
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');      $hashtied=0;
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');      if ($env{'request.course.fn'}) {
    if ($mode eq 'write') {
 # does this user have privileges to modify docs      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});      &GDBM_WRCREAT(),0640)) {
   if ($allowed && $env{'form.verify'}) {                  $hashtied=2;
       &init_breadcrumbs('verify','Verify Content');      }
       &verifycontent($r);   } else {
   } elsif ($allowed && $env{'form.listsymbs'}) {      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
       &init_breadcrumbs('listsymbs','List Symbs');      &GDBM_READER(),0640)) {
       &list_symbs($r);                  $hashtied=1;
   } elsif ($allowed && $env{'form.docslog'}) {      }
       &init_breadcrumbs('docslog','Show Log');   }
       &docs_change_log($r);      }
   } elsif ($allowed && $env{'form.versions'}) {  }
       &init_breadcrumbs('versions','Check/Set Resource Versions');  
       &checkversions($r);  sub untiehash {
   } elsif ($allowed && $env{'form.dumpcourse'}) {      if ($hashtied) { untie %hash; }
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');      $hashtied=0;
       &dumpcourse($r);      return OK;
   } elsif ($allowed && $env{'form.exportcourse'}) {  }
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');  
       &exportcourse($r);  
   } else {  
 # is this a standard course?  
   sub checkonthis {
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);      my ($r,$url,$level,$title)=@_;
     my $forcestandard = 0;      $url=&unescape($url);
     my $forcesupplement;      $alreadyseen{$url}=1;
     my $script='';      $r->rflush();
     my $showdoc=0;      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
     my $containertag;         $r->print("\n<br />");
     my $uploadtag;         if ($level==0) {
              $r->print("<br />");
          }
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},         for (my $i=0;$i<=$level*5;$i++) {
     ['folderpath','pagepath',             $r->print('&nbsp;');
      'pagesymb']);         }
 # No folderpath, no pagepath, see if we have something stored         $r->print('<a href="'.$url.'" target="cat">'.
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {   ($title?$title:$url).'</a> ');
         &Apache::loncommon::restore_course_settings('docs_folderpath',         if ($url=~/^\/res\//) {
                                               {'folderpath' => 'scalar'});    my $result=&Apache::lonnet::repcopy(
     }                                &Apache::lonnet::filelocation('',$url));
     if (!$env{'form.folderpath'}) {            if ($result eq 'ok') {
         &Apache::loncommon::restore_course_settings('docs_folderpath',               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                                               {'pagepath' => 'scalar'});               $r->rflush();
     }               &Apache::lonnet::countacc($url);
     if ($env{'form.pagepath'}) {               $url=~/\.(\w+)$/;
        $env{'form.folderpath'}='';               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
     }   $r->print('<br />');
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {                   $r->rflush();
         $env{'form.folderpath'} = 'supplemental&'.                   for (my $i=0;$i<=$level*5;$i++) {
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.                       $r->print('&nbsp;');
                                   $env{'form.folderpath'};                   }
     }                   $r->print('- '.&mt('Rendering:').' ');
     &Apache::loncommon::store_course_settings('docs_folderpath',   my ($errorcount,$warningcount)=split(/:/,
                                                 {'pagepath' => 'scalar',         &Apache::lonnet::ssi_body($url,
                                                  'folderpath' => 'scalar'});         ('grade_target'=>'web',
     if ($env{'form.folderpath'}) {   'return_only_error_and_warning_counts' => 1)));
  my (@folderpath)=split('&',$env{'form.folderpath'});                   if (($errorcount) ||
  $env{'form.foldername'}=&unescape(pop(@folderpath));                       ($warningcount)) {
  $env{'form.folder'}=pop(@folderpath);       if ($errorcount) {
     }                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
     if ($env{'form.pagepath'}) {                            &mt('[quant,_1,error]',$errorcount).'</span>');
         my (@pagepath)=split('&',$env{'form.pagepath'});                       }
         $env{'form.pagename'}=&unescape(pop(@pagepath));       if ($warningcount) {
         $env{'form.folder'}=pop(@pagepath);                          $r->print('<span class="LC_warning">'.
         $containertag = '<input type="hidden" name="pagepath" value="" />'.                            &mt('[quant,_1,warning]',$warningcount).'</span>');
     '<input type="hidden" name="pagesymb" value="" />';                       }
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.                   } else {
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     }                   }
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {                   $r->rflush();
        $showdoc='/'.$1;               }
     }       my $dependencies=
     unless ($showdoc) { # got called from remote                  &Apache::lonnet::metadata($url,'dependencies');
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||               foreach my $dep (split(/\,/,$dependencies)) {
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
            $forcestandard = 1;                      &checkonthis($r,$dep,$level+1);
        }                   }
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);               }
             } elsif ($result eq 'unavailable') {
        if ($allowed) {               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);            } elsif ($result eq 'not_found') {
          $script=&Apache::lonratedt::editscript('simple');        unless ($url=~/\$/) {
        }    $r->print('<span class="LC_error">'.&mt('not found').'</span>');
     } else { # got called in sequence from course        } else {
        $allowed=0;    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
     }        }
             } else {
 # get course data               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};            }
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};         }
       }
 # get personal data  }
     my $uname=$env{'user.name'};  
     my $udom=$env{'user.domain'};  
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));  
   =pod
 # graphics settings  
   =item list_symbs()
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");  
   List Content Identifiers
     if ($allowed) {  
  $script .= &editing_js($udom,$uname);  =cut
     }  
 # -------------------------------------------------------------------- Body tag  sub list_symbs {
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';      my ($r) = @_;
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];  
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,      my $crstype = &Apache::loncommon::course_type();
     {'force_register' => $showdoc,      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
                                      'bread_crumbs' => $brcrum}).      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
       &Apache::loncommon::help_open_menu('','',273,'RAT'));      $r->print(&startContentScreen('tools'));
        my $navmap = Apache::lonnavmaps::navmap->new();
   my %allfiles = ();      if (!defined($navmap)) {
   my %codebase = ();          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
   my ($upload_result,$upload_output);                    '<div class="LC_error">'.
   if ($allowed) {                    &mt('Unable to retrieve information about course contents').
       if (($env{'form.uploaddoc.filename'}) &&                    '</div>');
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
 # Process file upload - phase one - upload and parse primary file.        } else {
   undef($hadchanges);          $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
           $upload_result = &process_file_upload(\$upload_output,$coursenum,                    &Apache::loncommon::start_data_table().
  $coursedom,\%allfiles,                    &Apache::loncommon::start_data_table_header_row().
  \%codebase,$1);                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
   if ($hadchanges) {                    &Apache::loncommon::end_data_table_header_row()."\n");
       &mark_hash_old();          my $count;
   }          foreach my $res ($navmap->retrieveResources()) {
           if ($upload_result eq 'phasetwo') {              $r->print(&Apache::loncommon::start_data_table_row().
               $r->print($upload_output);                        '<td>'.$res->compTitle().'</td>'.
           }                        '<td>'.$res->symb().'</td>'.
       } elsif ($env{'form.phasetwo'}) {                        &Apache::loncommon::end_data_table_row());
           my %newname = ();              $count ++;
           my %origname = ();          }
           my %attribs = ();          if (!$count) {
           my $updateflag = 0;              $r->print(&Apache::loncommon::start_data_table_row().
           my $residx = $env{'form.newidx'};                        '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
           my $primary_url = &unescape($env{'form.primaryurl'});                        &Apache::loncommon::end_data_table_row()); 
 # Process file upload - phase two - gather secondary files.          }
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {          $r->print(&Apache::loncommon::end_data_table());
               if ($env{'form.embedded_item_'.$i.'.filename'}) {      }
                   my $javacodebase;      $r->print(&endContentScreen());
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);  }
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});  
                   if (exists($env{'form.embedded_codebase_'.$i})) {  
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});    sub verifycontent {
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;      my ($r) = @_;
                   }      my $crstype = &Apache::loncommon::course_type();
                   my @attributes = ();      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});      $r->print(&startContentScreen('tools'));
                   } else {      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
                       @attributes = ($env{'form.embedded_attrib_'.$i});     $hashtied=0;
                   }     undef %alreadyseen;
                   foreach my $attr (@attributes) {     %alreadyseen=();
                       push(@{$attribs{$i}},&unescape($attr));     &tiehash();
                   }     
                   if ($javacodebase) {     foreach my $key (keys(%hash)) {
                       $codebase{$i} = $javacodebase;         if ($hash{$key}=~/\.(page|sequence)$/) {
                       $codebase{$i} =~ s#/$##;     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
                       $updateflag = 1;         $r->print('<hr /><span class="LC_error">'.
                   }   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
               }   &unescape($hash{$key}).'</span><br />'.
               unless ($newname{$i} eq $origname{$i}) {   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
                   $updateflag = 1;     }
               }         }
           }         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 # Process file upload - phase three - modify primary file             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
           if ($updateflag) {         }
               my ($content,$rtncode);     }
               my $updateflag = 0;     &untiehash();
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
               if ($getstatus eq 'ok') {      $r->print(&endContentScreen());
                   foreach my $item (keys(%newname)) {  }
                       if ($newname{$item} ne $origname{$item}) {  
                           my $attrib_regexp = '';  
                           if (@{$attribs{$item}} > 1) {  sub devalidateversioncache {
                               $attrib_regexp = join('|',@{$attribs{$item}});      my $src=shift;
                           } else {      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
                               $attrib_regexp = $attribs{$item}[0];    &Apache::lonnet::clutter($src));
                           }  }
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {  
                           }  sub checkversions {
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;      my ($r) = @_;
                       }      my $crstype = &Apache::loncommon::course_type();
                       if (exists($codebase{$item})) {      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
                       }      $r->print(&startContentScreen('tools'));
                   }  
 # Save edited file.      my $header='';
                   my $saveresult;      my $startsel='';
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};      my $monthsel='';
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};      my $weeksel='';
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);      my $daysel='';
               } else {      my $allsel='';
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);      my %changes=();
               }      my $starttime=0;
           }      my $haschanged=0;
       }      my %setversions=&Apache::lonnet::dump('resourceversions',
   }    $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
   unless ($showdoc ||  $upload_result eq 'phasetwo') {  
 # -----------------------------------------------------------------------------      $hashtied=0;
        my %lt=&Apache::lonlocal::texthash(      &tiehash();
                 'uplm' => 'Upload a new main '.lc($type).' document',      my %newsetversions=();
                 'upls' => 'Upload a new supplemental '.lc($type).' document',      if ($env{'form.setmostrecent'}) {
                 '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',   $newsetversions{$1}='mostrecent';
                 'srch' => 'Search',                  &devalidateversioncache($1);
                 'impo' => 'Import',      }
  'book' => 'Import Bookmarks',   }
                 'selm' => 'Select Map',      } elsif ($env{'form.setcurrent'}) {
                 'load' => 'Load Map',   $haschanged=1;
                 'reco' => 'Recover Deleted Resources',   foreach my $key (keys(%hash)) {
                 'newf' => 'New Folder',      if ($key=~/^ids\_(\/res\/.+)$/) {
                 'newp' => 'New Composite Page',   my $getvers=&Apache::lonnet::getversion($1);
                 'extr' => 'External Resource',   if ($getvers>0) {
                 'syll' => 'Syllabus',      $newsetversions{$1}=$getvers;
                 'navc' => 'Navigate Contents',      &devalidateversioncache($1);
                 'sipa' => 'Simple Page',   }
                 'sipr' => 'Simple Problem',      }
                 'drbx' => 'Drop Box',   }
                 'scuf' => 'Score Upload Form',      } elsif ($env{'form.setversions'}) {
                 'bull' => 'Bulletin Board',   $haschanged=1;
                 'mypi' => 'My Personal Info',   foreach my $key (keys(%env)) {
                 'grpo' => 'Group Files',      if ($key=~/^form\.set_version_(.+)$/) {
                 'rost' => 'Course Roster',   my $src=$1;
  'abou' => 'About User',   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
                 'imsf' => 'Import IMS package',      $newsetversions{$src}=$env{$key};
                 'file' =>  'File',      &devalidateversioncache($src);
                 'title' => 'Title',   }
                 'comment' => 'Comment',      }
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',   }
  'nd' => 'New Document',      }
  'pm' => 'Published Map',      if ($haschanged) {
  'sd' => 'Special Document',          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
  'mo' => 'More Options',    $env{'course.'.$env{'request.course.id'}.'.domain'},
  'hao' => 'Hide all Options'    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
   );      $r->print(&Apache::loncommon::confirmwrapper(
 # -----------------------------------------------------------------------------                  &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
  my $fileupload=(<<FIUP);   } else {
  $lt{'file'}:<br />      $r->print(&Apache::loncommon::confirmwrapper(
  <input type="file" name="uploaddoc" size="40" />                  &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
 FIUP   }
    &mark_hash_old();
  my $checkbox=(<<CHBO);      }
  <!-- <label>$lt{'parse'}?      &changewarning($r,'');
  <input type="checkbox" name="parserflag" />      if ($env{'form.timerange'} eq 'all') {
  </label> -->  # show all documents
  <label>   $header=&mt('All Documents in '.$crstype);
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}   $allsel=' selected="selected"';
  </label>   foreach my $key (keys(%hash)) {
 CHBO      if ($key=~/^ids\_(\/res\/.+)$/) {
    my $src=$1;
  my $fileuploadform=(<<FUFORM);   $changes{$src}=1;
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">      }
  $fileupload   }
  <br />      } else {
  $lt{'title'}:<br />  # show documents which changed
  <input type="text" size="50" name="comment" />   %changes=&Apache::lonnet::dump
  $uploadtag   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
  <input type="hidden" name="cmd" value="upload_default" />                       $env{'course.'.$env{'request.course.id'}.'.num'});
  <br />   my $firstkey=(keys(%changes))[0];
  <span class="LC_nobreak">   unless ($firstkey=~/^error\:/) {
  $checkbox      unless ($env{'form.timerange'}) {
  </span>   $env{'form.timerange'}=604800;
  <br />      }
  <br />      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
  <span class="LC_nobreak">   .&mt('seconds');
  <input type="submit" value="$lt{'upld'}" />      if ($env{'form.timerange'}==-1) {
  $help{'Uploading_From_Harddrive'}   $seltext='since start of course';
  </span>   $startsel=' selected="selected"';
  </form>   $env{'form.timerange'}=time;
 FUFORM      }
       $starttime=time-$env{'form.timerange'};
  my $simpleeditdefaultform=(<<SEDFFORM);      if ($env{'form.timerange'}==2592000) {
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  $lt{'pubd'}<br />   $monthsel=' selected="selected"';
  $uploadtag      } elsif ($env{'form.timerange'}==604800) {
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  <br />   $weeksel=' selected="selected"';
  <span class="LC_nobreak">      } elsif ($env{'form.timerange'}==86400) {
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  $help{'Importing_LON-CAPA_Resource'}   $daysel=' selected="selected"';
  </span>      }
  <br />      $header=&mt('Content changed').' '.$seltext;
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />   } else {
  <hr />      $header=&mt('No content modifications yet.');
  <p>   }
  $lt{'copm'}<br />      }
  <input type="text" size="40" name="importmap" /><br />      %setversions=&Apache::lonnet::dump('resourceversions',
  <span class="LC_nobreak"><input type="button"    $env{'course.'.$env{'request.course.id'}.'.domain'},
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"    $env{'course.'.$env{'request.course.id'}.'.num'});
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />      my %lt=&Apache::lonlocal::texthash
  $help{'Load_Map'}</span>        ('st' => 'Version changes since start of '.$crstype,
  </p>         'lm' => 'Version changes since last Month',
  </form>         'lw' => 'Version changes since last Week',
 SEDFFORM         'sy' => 'Version changes since Yesterday',
                  'al' => 'All Resources (possibly large output)',
  my $extresourcesform=(<<ERFORM);                 'cd' => 'Change display', 
  <form action="/adm/coursedocs" method="post" name="newext">         'sd' => 'Display',
  $uploadtag         'fi' => 'File',
  <input type="hidden" name="importdetail" value="" />         'md' => 'Modification Date',
  <span class="LC_nobreak">                 'mr' => 'Most recently published Version',
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"         've' => 'Version used in '.$crstype,
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}                 'vu' => 'Set Version to be used in '.$crstype,
  </span>  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
  </form>  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 ERFORM  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
          'di' => 'Differences',
     if ($allowed) {         'save' => 'Save changes',
  &update_paste_buffer($coursenum,$coursedom);                 'vers' => 'Version choice(s) for specific resources', 
        my $dumpbut=&dumpbutton();         'act' => 'Actions');
        my $exportbut=&exportbutton();      $r->print(<<ENDHEADERS);
        my %lt=&Apache::lonlocal::texthash(  <h4 class="LC_info">$header</h4>
  'vc' => 'Verify Content',  <form action="/adm/coursedocs" method="post">
  'cv' => 'Check/Set Resource Versions',  <input type="hidden" name="versions" value="1" />
  'ls' => 'List Symbs',  <div class="LC_left_float">
                                          'sl' => 'Show Log'  <fieldset>
   );  <legend>$lt{'cd'}</legend>
   <select name="timerange">
        my $folderpath=$env{'form.folderpath'};  <option value='all'$allsel>$lt{'al'}</option>
        if (!$folderpath) {  <option value="-1"$startsel>$lt{'st'}</option>
    if ($env{'form.folder'} eq '' ||  <option value="2592000"$monthsel>$lt{'lm'}</option>
        $env{'form.folder'} eq 'supplemental') {  <option value="604800"$weeksel>$lt{'lw'}</option>
        $folderpath='default&'.  <option value="86400"$daysel>$lt{'sy'}</option>
    &escape(&mt('Main '.$type.' Documents'));  </select>
    }  <input type="submit" name="display" value="$lt{'sd'}" />
        }  </fieldset>
        unless ($env{'form.pagepath'}) {  </div>
            $containertag = '<input type="hidden" name="folderpath" value="" />';  <div class="LC_left_float">
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';  <fieldset>
        }  <legend>$lt{'act'}</legend>
   $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
        $r->print(<<ENDCOURSEVERIFY);  $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
 <form name="renameform" method="post" action="/adm/coursedocs">  </fieldset>
   <input type="hidden" name="title" />  </div>
   <input type="hidden" name="cmd" />  <br clear="all" />
   <input type="hidden" name="markcopy" />  <hr />
   <input type="hidden" name="copyfolder" />  <h4>$lt{'vers'}</h4>
   $containertag  <input type="submit" name="setversions" value="$lt{'save'}" />
 </form>  ENDHEADERS
 <form name="simpleedit" method="post" action="/adm/coursedocs">      #number of columns for version history
   <input type="hidden" name="importdetail" value="" />      $r->print(
   $uploadtag          &Apache::loncommon::start_data_table().
 </form>          &Apache::loncommon::start_data_table_header_row().
 <form action="/adm/coursedocs" method="post" name="courseverify">          '<th>'.&mt('Resources').'</th>'.
   <div class="LC_docs_course_commands">          "<th>$lt{'mr'}</th>".
           "<th>$lt{'ve'}</th>".
       <div>          "<th>$lt{'vu'}</th>".
         <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}          '<th>'.&mt('History').'</th>'.
       </div>          &Apache::loncommon::end_data_table_header_row()
       <div>      );
         <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}      foreach my $key (sort(keys(%changes))) {
       </div>          #excludes not versionable problems from resource version history:
         $dumpbut          next unless ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/);
         $exportbut          my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
       <div>          my $currentversion=&Apache::lonnet::getversion($key);
         <input type="submit" name="listsymbs" value="$lt{'ls'}" />          if ($currentversion<0) {
       </div>              $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
       <div>          }
         <input type="hidden" name="folder" value="$env{'form.folder'}" />          my $linkurl=&Apache::lonnet::clutter($key);
         <input type="submit" name="docslog" value="$lt{'sl'}" />          $r->print(
       </div>              &Apache::loncommon::start_data_table_row().
   </div>              '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
 </form>              '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
 <div style="clear: both; height: 0px;">&nbsp;</div>              '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
 ENDCOURSEVERIFY              &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',              '<td align="right">'
      &mt('Editing the Table of Contents for your '.$type)));          );
     }          # Used in course
 # --------------------------------------------------------- Standard documents          my $usedversion=$hash{'version_'.$linkurl};
     $r->print('<table class="LC_docs_documents">');          if (($usedversion) && ($usedversion ne 'mostrecent')) {
                   if ($usedversion != $currentversion) {
     if (($standard) && ($allowed) && (!$forcesupplement)) {                      $r->print('<span class="LC_warning">'.$usedversion.'</span>');
  $r->print('<tr><td class="LC_docs_document">');                  } else {
 #  '<h2>'.&mt('Main Course Documents').                      $r->print($usedversion);
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');                  }
        my $folder=$env{'form.folder'};              } else {
        if ($folder eq '' || $folder eq 'supplemental') {                  $r->print($currentversion);
            $folder='default';              }
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));          $r->print('</td><td title="'.$lt{'vu'}.'">');
            $uploadtag = '<input type="hidden" name="folderpath" value="'.          # Set version
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';          $r->print(&Apache::loncommon::select_form(
        }              $setversions{$linkurl},
        my $postexec='';              'set_version_'.$linkurl,
        if ($folder eq 'default') {              {'select_form_order' => ['',1..$currentversion,'mostrecent'],
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');               '' => '',
        } else {               'mostrecent' => &mt('most recent'),
            #$postexec='self.close();';               map {$_,$_} (1..$currentversion)}));
        }          my $lastold=1;
        $hadchanges=0;          for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,              my $url=$root.'.'.$prevvers.'.'.$extension;
    $upload_output,$type);              if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
        if ($error) {                  $lastold=$prevvers;
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');              }
        }          }
        if ($hadchanges) {          $r->print('</td>');
    &mark_hash_old();          # List all available versions
        }          $r->print('<td valign="top"><span class="LC_fontsize_medium">');
        &changewarning($r,$postexec);          for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.              my $url=$root.'.'.$prevvers.'.'.$extension;
                      '.sequence';              $r->print(
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.                  '<span class="LC_nobreak">'
                      '.page';                 .'<a href="'.&Apache::lonnet::clutter($url).'">'
  my $container='sequence';                 .&mt('Version [_1]',$prevvers).'</a>'
  if ($env{'form.pagepath'}) {                 .' ('.&Apache::lonlocal::locallocaltime(
     $container='page';                           &Apache::lonnet::metadata($url,'lastrevisiondate'))
  }                 .')');
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;              if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
                   $r->print(
                       ' <a href="/adm/diff?filename='.
                       &Apache::lonnet::clutter($root.'.'.$extension).
  my $recoverform=(<<RFORM);                      &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
  <form action="/adm/groupsort" method="post" name="recover">                      '" target="diffs">'.&mt('Diffs').'</a>');
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />              }
  </form>              $r->print('</span><br />');
 RFORM          }
           $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
  my $imspform=(<<IMSPFORM);      }
  <form action="/adm/imsimportdocs" method="post" name="ims">      $r->print(
  <input type="hidden" name="folder" value="$folder" />          &Apache::loncommon::end_data_table().
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />          '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
  </form>          '</form>'
 IMSPFORM      );
   
  my $newnavform=(<<NNFORM);      &untiehash();
  <form action="/adm/coursedocs" method="post" name="newnav">      $r->print(&endContentScreen());
  $uploadtag  }
  <input type="hidden" name="importdetail"  
  value="$lt{'navc'}=/adm/navmaps" />  sub mark_hash_old {
  <span class="LC_nobreak">      my $retie_hash=0;
  <input name="newnav" type="submit" value="$lt{'navc'}" />      if ($hashtied) {
  $help{'Navigate_Content'}   $retie_hash=1;
  </span>   &untiehash();
  </form>      }
 NNFORM      &tiehash('write');
  my $newsmppageform=(<<NSPFORM);      $hash{'old'}=1;
  <form action="/adm/coursedocs" method="post" name="newsmppg">      &untiehash();
  $uploadtag      if ($retie_hash) { &tiehash(); }
  <input type="hidden" name="importdetail" value="" />  }
  <span class="LC_nobreak">  
  <input name="newsmppg" type="button" value="$lt{'sipa'}"  sub is_hash_old {
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}      my $untie_hash=0;
  </span>      if (!$hashtied) {
  </form>   $untie_hash=1;
 NSPFORM   &tiehash();
       }
  my $newsmpproblemform=(<<NSPROBFORM);      my $return=$hash{'old'};
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">      if ($untie_hash) { &untiehash(); }
  $uploadtag      return $return;
  <input type="hidden" name="importdetail" value="" />  }
  <span class="LC_nobreak">  
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"  sub changewarning {
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}      my ($r,$postexec,$message,$url)=@_;
  </span>      if (!&is_hash_old()) { return; }
  </form>      my $pathvar='folderpath';
       my $path=&escape($env{'form.folderpath'});
 NSPROBFORM      if (!defined($url)) {
    $url='/adm/coursedocs?'.$pathvar.'='.$path;
  my $newdropboxform=(<<NDBFORM);      }
  <form action="/adm/coursedocs" method="post" name="newdropbox">      my $course_type = &Apache::loncommon::course_type();
  $uploadtag            if (!defined($message)) {
  <input type="hidden" name="importdetail" value="" />   $message='Changes will become active for your current session after [_1], or the next time you log in.';
  <span class="LC_nobreak">                }
  <input name="newdropbox" type="button" value="$lt{'drbx'}"      $r->print("\n\n".
  onClick="javascript:makedropbox();" />  '<script type="text/javascript">'."\n".
  </span>          '// <![CDATA['."\n".
  </form>  'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
 NDBFORM  '// ]]>'."\n".
   '</script>'."\n".
  my $newexuploadform=(<<NEXUFORM);  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
  <form action="/adm/coursedocs" method="post" name="newexamupload">  '<input type="hidden" name="orgurl" value="'.$url.
  $uploadtag  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
  <input type="hidden" name="importdetail" value="" />  &mt($message,' <input type="hidden" name="'.
  <span class="LC_nobreak">      $env{'request.role'}.'" value="1" /><input type="button" value="'.
  <input name="newexamupload" type="button" value="$lt{'scuf'}"      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
  onClick="javascript:makeexamupload();" />  $help{'Caching'}.'</p></form>'."\n\n");
  $help{'Score_Upload_Form'}  }
  </span>  
  </form>  
 NEXUFORM  sub init_breadcrumbs {
       my ($form,$text)=@_;
  my $newbulform=(<<NBFORM);      &Apache::lonhtmlcommon::clear_breadcrumbs();
  <form action="/adm/coursedocs" method="post" name="newbul">      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
  $uploadtag      text=>&Apache::loncommon::course_type().' Editor',
  <input type="hidden" name="importdetail" value="" />      faq=>273,
  <span class="LC_nobreak">      bug=>'Instructor Interface',
  <input name="newbulletin" type="button" value="$lt{'bull'}"                                              help => 'Docs_Adding_Course_Doc'});
  onClick="javascript:makebulboard();" />      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
  $help{'Bulletin Board'}      text=>$text,
  </span>      faq=>273,
  </form>      bug=>'Instructor Interface'});
 NBFORM  }
   
  my $newaboutmeform=(<<NAMFORM);  # subroutine to list form elements
  <form action="/adm/coursedocs" method="post" name="newaboutme">  sub create_list_elements {
  $uploadtag     my @formarr = @_;
  <input type="hidden" name="importdetail"     my $list = '';
  value="$plainname=/adm/$udom/$uname/aboutme" />     foreach my $button (@formarr){
  <span class="LC_nobreak">          foreach my $picture (keys(%{$button})) {
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />              $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
  $help{'My Personal Info'}          }
  </span>     }
  </form>     return $list;
 NAMFORM  }
   
  my $newaboutsomeoneform=(<<NASOFORM);  # subroutine to create ul from list elements
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">  sub create_form_ul {
  $uploadtag     my $list = shift;
  <input type="hidden" name="importdetail" value="" />     my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
  <span class="LC_nobreak">     return $ul;
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"  }
  onClick="javascript:makeabout();" />  
  </span>  #
  </form>  # Start tabs
 NASOFORM  #
   
   sub startContentScreen {
  my $newrosterform=(<<NROSTFORM);      my ($mode) = @_;
  <form action="/adm/coursedocs" method="post" name="newroster">      my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
  $uploadtag      if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
  <input type="hidden" name="importdetail"          $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";
  value="$lt{'rost'}=/adm/viewclasslist" />          $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";
  <span class="LC_nobreak">          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
  <input name="newroster" type="submit" value="$lt{'rost'}" />      } else {
  $help{'Course Roster'}          $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";
  </span>          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
  </form>          $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";
 NROSTFORM                     '><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>';
       }
        $r->print(<<ENDFORM);      $output .= "\n".'</ul>'."\n";
       $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
 <ul class="LC_TabContent">                 '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
 <li>$lt{'nd'}</li>                 '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
 <li>$lt{'pm'}</li>      return $output;
 <li>$lt{'pubd'}</li>  }
 <li>$lt{'sd'}</li>  
 <li>$lt{'mo'}</li>  #
 <li>$lt{'hao'}</li>  # End tabs
 </ul>  #
   
 <table class="LC_docs_adddocs">  sub endContentScreen {
 <!-- <tr>      return '</div></div></div>';
 <th>$lt{'uplm'}</th>  }
 <th>$lt{'impp'}</th>  
 <th>$lt{'spec'}</th>  sub supplemental_base {
 </tr> -->      return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
 <tr>  }
 <td>  
 $fileuploadform  sub handler {
 </td>      my $r = shift;
 <td>      &Apache::loncommon::content_type($r,'text/html');
 $simpleeditdefaultform      $r->send_http_header;
 <hr />      return OK if $r->header_only;
 $recoverform  
 ENDFORM  # get course data
        unless ($env{'form.pagepath'}) {      my $crstype = &Apache::loncommon::course_type();
    $r->print(<<ENDFORM);      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 <hr />      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 $extresourcesform  
  <br />  # graphics settings
 $imspform      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
 ENDFORM  
        }  #
        $r->print('</td><td>');  # --------------------------------------------- Initialize help topics for this
        unless ($env{'form.pagepath'}) {      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                 'Adding_External_Resource','Navigate_Content',
                  'Adding_Folders','Docs_Overview', 'Load_Map',
                  'Supplemental','Score_Upload_Form','Adding_Pages',
                  'Importing_LON-CAPA_Resource','Importing_IMS_Course',
  my $newpageform=(<<NPFORM);                         'Uploading_From_Harddrive',
  <form action="/adm/coursedocs" method="post" name="newpage">                 'Check_Resource_Versions','Verify_Content') {
  <input type="hidden" name="folderpath" value="$path" />   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
  <input type="hidden" name="importdetail" value="" />      }
  <span class="LC_nobreak">      # Composite help files
  <input name="newpage" type="button"      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
  onClick="javascript:makenewpage(this.form,'$pageseq');"      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
  value="$lt{'newp'}" />$help{'Adding_Pages'}      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
  </span>      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
  </form>      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 NPFORM      'Option_Response_Simple');
       $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
  my $newfolderform=(<<NFFORM);      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
  <form action="/adm/coursedocs" method="post" name="newfolder">      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
  <input type="hidden" name="folderpath" value="$path" />    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
  <input type="hidden" name="importdetail" value="" />      $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
  <span class="LC_nobreak">      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
  <input name="newfolder" type="button"  
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      
  value="$lt{'newf'}" />$help{'Adding_Folders'}      my $allowed;
  </span>  # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
  </form>      unless ($r->uri eq '/adm/supplemental') {
 NFFORM          # does this user have privileges to modify content.  
           $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
  my $newsylform=(<<NSYLFORM);      }
  <form action="/adm/coursedocs" method="post" name="newsyl">  
  $uploadtag      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
  <input type="hidden" name="importdetail"                                              'inhibitmenu']);
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />    if ($allowed && $env{'form.chooseserver'}) {
  <span class="LC_nobreak">        &choose_dump_server($r);
  <input name="newsyl" type="submit" value="$lt{'syll'}" />        return OK;
  $help{'Syllabus'}    } elsif ($allowed && $env{'form.verify'}) {
  </span>        &init_breadcrumbs('verify','Verify Content');
  </form>        &verifycontent($r);
 NSYLFORM    } elsif ($allowed && $env{'form.listsymbs'}) {
         &init_breadcrumbs('listsymbs','List Content IDs');
  my $newgroupfileform=(<<NGFFORM);        &list_symbs($r);
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">    } elsif ($allowed && $env{'form.docslog'}) {
  $uploadtag        &init_breadcrumbs('docslog','Show Log');
  <input type="hidden" name="importdetail"        my $folder = $env{'form.folder'};
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />        if ($folder eq '') {
  <span class="LC_nobreak">            $folder='default';
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />        }
  $help{'Group Files'}        &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
  </span>    } elsif ($allowed && $env{'form.versions'}) {
  </form>        &init_breadcrumbs('versions','Check/Set Resource Versions');
 NGFFORM        &checkversions($r);
     } elsif ($allowed && $env{'form.dumpcourse'}) {
         &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
            $r->print(<<ENDFORM);        &dumpcourse($r);
 <br />    } elsif ($allowed && $env{'form.exportcourse'}) {
 $newfolderform        &init_breadcrumbs('exportcourse','IMS Export');
 <br />        &Apache::imsexport::exportcourse($r);
 $newpageform    } else {
 <br />  #
 $newsylform  # Done catching special calls
 <br />  # The whole rest is for course and supplemental documents and utilities menu
 $newnavform  # Get the parameters that may be needed
 <br />  #
 $newsmppageform      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 <br />                                              ['folderpath',
 $newsmpproblemform                                               'forcesupplement','forcestandard',
 <br />                                               'tools','symb','command','supppath']);
 $newdropboxform  
 <br />  # standard=1: this is a "new-style" course with an uploaded map as top level
 $newexuploadform  # standard=2: this is a "old-style" course, and there is nothing we can do
 <br />  
 $newbulform      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 <br />  
 $newaboutmeform  # Decide whether this should display supplemental or main content or utilities
 <br />  # supplementalflag=1: show supplemental documents
 $newaboutsomeoneform  # supplementalflag=0: show standard documents
 <br />  # toolsflag=1: show utilities
 $newgroupfileform  
 <br />  
 $newrosterform      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 ENDFORM      if (($env{'form.folderpath'}=~/^default/) || ($env{'form.folderpath'} eq "")) {
        }         $supplementalflag=0;
        if ($env{'form.pagepath'}) {      }
            $r->print(<<ENDBLOCK);      if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 $newsmpproblemform      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
 <br />      unless ($allowed) { $supplementalflag=1; }
 $newexuploadform      unless ($standard) { $supplementalflag=1; }
 ENDBLOCK      my $toolsflag=0;
        }      if ($env{'form.tools'}) { $toolsflag=1; }
        $r->print('</td></tr>'."\n".  
 '</table>');      my $script='';
        $r->print('</td></tr>');      my $showdoc=0;
     }      my $addentries = {};
 # ----------------------------------------------------- Supplemental documents      my $container;
     if (!$forcestandard) {      my $containertag;
        $r->print('<tr><td class="LC_docs_document">');      my $pathitem;
 # '<h2>'.&mt('Supplemental Course Documents').  
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');  # Do we directly jump somewhere?
        my $folder=$env{'form.folder'};  
        unless ($folder=~/^supplemental/) {     if ($env{'form.command'} eq 'direct') {
    $folder='supplemental';         my ($mapurl,$id,$resurl);
        }         if ($env{'form.symb'} ne '') {
        if ($folder =~ /^supplemental$/ &&             $env{'form.folderpath'}=
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {                 &Apache::loncommon::symb_to_docspath($env{'form.symb'});
           $env{'form.folderpath'} = 'supplemental&'.         } elsif ($env{'form.supppath'} ne '') {
                                     &escape(&mt('Supplemental '.$type.' Documents'));             $env{'form.folderpath'}=$env{'form.supppath'};
        }         }
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);     } elsif ($env{'form.command'} eq 'editdocs') {
        if ($error) {          $env{'form.folderpath'} = 'default&'.
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');                                    &Apache::lonhtmlcommon::entity_encode('Main Course Content').
        }                                    ':::::';
        if ($allowed) {     } elsif ($env{'form.command'} eq 'editsupp') {
    my $folderseq=          $env{'form.folderpath'} = 'default&'.
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.                                    &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
        '.sequence';     }
   
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');  # Where do we store these for when we come back?
       my $stored_folderpath='docs_folderpath';
  my $supupdocform=(<<SUPDOCFORM);      if ($supplementalflag) {
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">         $stored_folderpath='docs_sup_folderpath';
  $fileupload      }
  <br />  
  <br />  # No folderpath, and in edit mode, see if we have something stored
  <span class="LC_nobreak">      if ((!$env{'form.folderpath'}) && $allowed) {
  $checkbox          &Apache::loncommon::restore_course_settings($stored_folderpath,
  </span>                                            {'folderpath' => 'scalar'});
  <br /><br />          unless (&unescape($env{'form.folderpath'}) =~ m{^(default|supplemental)&}) {
  $lt{'comment'}:<br />              undef($env{'form.folderpath'});
  <textarea cols=50 rows=4 name='comment'>          }
  </textarea>      }
  <br />     
  <input type="hidden" name="folderpath" value="$path" />  # If we are not allowed to make changes, all we can see are supplemental docs
  <input type="hidden" name="cmd" value="upload_supplemental" />      if (!$allowed) {
  <span class="LC_nobreak">          unless ($env{'form.folderpath'} =~ /^supplemental/) {
  <input type="submit" value="$lt{'upld'}" />              $env{'form.folderpath'} = &supplemental_base();
  $help{'Uploading_From_Harddrive'}          }
  </span>      }
  </form>  # Make the zeroth entry in supplemental docs page paths, so we can get to top level
 SUPDOCFORM      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
           $env{'form.folderpath'} = &supplemental_base()
  my $supnewfolderform=(<<SNFFORM);                                    .'&'.
  <form action="/adm/coursedocs" method="post" name="supnewfolder">                                    $env{'form.folderpath'};
  <input type="hidden" name="folderpath" value="$path" />      }
  <input type="hidden" name="importdetail" value="" />  # If after all of this, we still don't have any paths, make them
  <span class="LC_nobreak">      unless ($env{'form.folderpath'}) {
  <input name="newfolder" type="button"         if ($supplementalflag) {
  onClick="javascript:makenewfolder(this.form,'$folderseq');"            $env{'form.folderpath'}=&supplemental_base();
  value="$lt{'newf'}" /> $help{'Adding_Folders'}         } else {
  </span>            $env{'form.folderpath'}='default'.&escape(&mt('Main '.$crstype.' Documents')).
  </form>                                    ':::::';
 SNFFORM         }
       }
   
  my $supnewextform=(<<SNEFORM);  # Store this
  <form action="/adm/coursedocs" method="post" name="supnewext">      unless ($toolsflag) {
  <input type="hidden" name="folderpath" value="$path" />          if ($allowed) {
  <input type="hidden" name="importdetail" value="" />              &Apache::loncommon::store_course_settings($stored_folderpath,
  <span class="LC_nobreak">                                                        {'folderpath' => 'scalar'});
  <input name="newext" type="button"          }
  onClick="javascript:makenewext('supnewext');"          my $folderpath;
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}          if ($env{'form.folderpath'}) {
  </span>              $folderpath = $env{'form.folderpath'};
  </form>      my (@folders)=split('&',$env{'form.folderpath'});
 SNEFORM      $env{'form.foldername'}=&unescape(pop(@folders));
               if ($env{'form.foldername'} =~ /\:1$/) {
  my $supnewsylform=(<<SNSFORM);                  $container = 'page';
  <form action="/adm/coursedocs" method="post" name="supnewsyl">              } else {
  <input type="hidden" name="folderpath" value="$path" />                  $container = 'sequence';
  <input type="hidden" name="importdetail"              }
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />      $env{'form.folder'}=pop(@folders);
  <span class="LC_nobreak">          } else {
  <input name="newsyl" type="submit" value="$lt{'syll'}" />              if ($env{'form.folder'} eq '' ||
  $help{'Syllabus'}                  $env{'form.folder'} eq 'supplemental') {
  </span>                  $folderpath='default&'.
  </form>                              &escape(&mt('Main '.$crstype.' Documents')).
 SNSFORM                              ':::::';
               }
  my $supnewaboutmeform=(<<SNAMFORM);          }
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">          $containertag = '<input type="hidden" name="folderpath" value="" />';
  <input type="hidden" name="folderpath" value="$path" />          $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
  <input type="hidden" name="importdetail"          if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
  value="$plainname=/adm/$udom/$uname/aboutme" />             $showdoc='/'.$1;
  <span class="LC_nobreak">          }
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />          if ($showdoc) { # got called in sequence from course
  $help{'My Personal Info'}      $allowed=0; 
  </span>          } else {
  </form>              if ($allowed) {
 SNAMFORM                  &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                   $script=&Apache::lonratedt::editscript('simple');
    $r->print(<<ENDSUPFORM);              }
 <ul class="LC_TabContent">          }
 <li>$lt{'nd'}</li>      }
 <li>$lt{'sd'}</li>  
 <li>$lt{'hao'}</li>  # get personal data
 </ul>      my $uname=$env{'user.name'};
 <table class="LC_docs_adddocs">      my $udom=$env{'user.domain'};
 <tr><td>      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 $supupdocform  
 </td>      if ($allowed) {
 <td>          if ($toolsflag) {
 $supnewfolderform              $script .= &inject_data_js();
 <br />              my ($home,$other,%outhash)=&authorhosts();
 $supnewextform              if (!$home && $other) {
 <br />                  my @hosts;
 $supnewsylform                  foreach my $aurole (keys(%outhash)) {
 <br />                      unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
 $supnewaboutmeform                          push(@hosts,$outhash{$aurole});
 </td></tr>                      }
 </table></td></tr>                  }
 ENDSUPFORM                  $script .= &dump_switchserver_js(@hosts); 
        }              }
     }          } else {
     $r->print('</table>');              my @tabids;
     if ($allowed) {              if ($supplementalflag) {
  $r->print('                  @tabids = ('002','ee2','ff2');
 <form method="post" name="extimport" action="/adm/coursedocs">              } else {
   <input type="hidden" name="title" />                  @tabids = ('aa1','bb1','cc1','ff1');
   <input type="hidden" name="url" />                  unless ($env{'form.folderpath'} =~ /\:1$/) {
   <input type="hidden" name="useform" />                      unshift(@tabids,'001');
   <input type="hidden" name="residx" />                      push(@tabids,('dd1','ee1'));
 </form>');                  }
     }              }
   } else {              my $tabidstr = join("','",@tabids);
       unless ($upload_result eq 'phasetwo') {      $script .= &editing_js($udom,$uname,$supplementalflag).
 # -------------------------------------------------------- This is showdoc mode                         &history_tab_js().
           $r->print("<h1>".&mt('Uploaded Document').' - '.                         &inject_data_js().
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.                         &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr).
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".                         &Apache::lonextresedit::extedit_javascript();
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');              $addentries = {
       }                              onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
   }                            };
  }          }
  $r->print(&Apache::loncommon::end_page());          if ($env{'docs.markedcopy_url'}) {
  return OK;              $script .= &paste_popup_js(); 
 }          }
           my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
                                &mt('Switch server?');
 sub editing_js {          
     my ($udom,$uname) = @_;  
     my $now = time();      }
     my %lt = &Apache::lonlocal::texthash(  # -------------------------------------------------------------------- Body tag
                                           p_mnf => 'Name of New Folder',      $script = '<script type="text/javascript">'."\n"
                                           t_mnf => 'New Folder',                .'// <![CDATA['."\n"
                                           p_mnp => 'Name of New Page',                .$script."\n"
                                           t_mnp => 'New Page',                .'// ]]>'."\n"
                                           p_mxu => 'Title for the Uploaded Score',                .'</script>'."\n";
                                           p_msp => 'Title for the Page',  
                                           p_msb => 'Title for the Problem',      # Breadcrumbs
                                           p_mdb => 'Title for the Drop Box',      &Apache::lonhtmlcommon::clear_breadcrumbs();
                                           p_mbb => 'Title for the Bulletin Board',  
                                           p_mab => "Enter user:domain for User's 'About Me' Page",      if ($showdoc) {
                                           p_mab2 => "About [_99]",          $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
                                           p_mab_alrt1 => 'Not a valid user:domain',                                                  {'force_register' => $showdoc,}));
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',      } elsif ($r->uri eq '/adm/supplemental') {
                                           p_chn => 'New Title',          my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype);
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',          $r->print(&Apache::loncommon::start_page("Supplemental $crstype Content",undef,
                                           p_rmr2a => 'Remove[_99]',                                                  {'bread_crumbs' => $brcrum,}));
                                           p_rmr2b => '?[_99]',      } else {
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',          &Apache::lonhtmlcommon::add_breadcrumb({
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',              href=>"/adm/coursedocs",text=>"$crstype Contents"});
                                           p_ctr2a => 'Cut[_98]',  
                                           p_ctr2b => '?[_98]'          $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
                                         );                                                   {'add_entries'    => $addentries}
                                                   )
     return <<ENDNEWSCRIPT;                   .&Apache::loncommon::help_open_menu('','',273,'RAT')
 function makenewfolder(targetform,folderseq) {                   .&Apache::lonhtmlcommon::breadcrumbs(
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');                       'Editing '.$crstype.' Contents',
     if (foldername) {                       'Docs_Adding_Course_Doc')
        targetform.importdetail.value=escape(foldername)+"="+folderseq;          );
         targetform.submit();      }
     }  
 }    my %allfiles = ();
     my %codebase = ();
 function makenewpage(targetform,folderseq) {    my ($upload_result,$upload_output,$uploadphase);
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');    if ($allowed) {
     if (pagename) {        if (($env{'form.uploaddoc.filename'}) &&
         targetform.importdetail.value=escape(pagename)+"="+folderseq;    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
         targetform.submit();            my $context = $1; 
     }            # Process file upload - phase one - upload and parse primary file.
 }    undef($hadchanges);
             $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
 function makenewext(targetname) {                                                \%allfiles,\%codebase,$context);
     this.document.forms.extimport.useform.value=targetname;    if ($hadchanges) {
     this.document.forms.extimport.title.value='';        &mark_hash_old();
     this.document.forms.extimport.url.value='';    }
     this.document.forms.extimport.residx.value='';            $r->print($upload_output);
     window.open('/adm/rat/extpickframe.html');        } elsif ($env{'form.phase'} eq 'upload_embedded') {
 }            # Process file upload - phase two - upload embedded objects 
             $uploadphase = 'check_embedded';
 function edittext(targetname,residx,title,url) {            my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
     this.document.forms.extimport.useform.value=targetname;            my $state = &embedded_form_elems($uploadphase,$primaryurl,
     this.document.forms.extimport.residx.value=residx;                                             $env{'form.newidx'});
     this.document.forms.extimport.url.value=url;            my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
     this.document.forms.extimport.title.value=title;            my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
     window.open('/adm/rat/extpickframe.html');            my ($destination,$dir_root) = &embedded_destination();
 }            my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
             my $actionurl = '/adm/coursedocs';
 function makeexamupload() {            my ($result,$flag) = 
    var title=prompt('$lt{"p_mxu"}');                &Apache::loncommon::upload_embedded('coursedoc',$destination,
    if (title) {                    $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
     this.document.forms.newexamupload.importdetail.value=                    $actionurl);
  escape(title)+'=/res/lib/templates/examupload.problem';            $r->print($result.&return_to_editor());
     this.document.forms.newexamupload.submit();        } elsif ($env{'form.phase'} eq 'check_embedded') {
    }            # Process file upload - phase three - modify references in HTML file
 }            $uploadphase = 'modified_orightml';
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 function makesmppage() {            my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
    var title=prompt('$lt{"p_msp"}');            my ($destination,$dir_root) = &embedded_destination();
    if (title) {            my $result = 
     this.document.forms.newsmppg.importdetail.value=                &Apache::loncommon::modify_html_refs('coursedoc',$destination,
  escape(title)+'=/adm/$udom/$uname/$now/smppg';                                                     $docuname,$docudom,undef,
     this.document.forms.newsmppg.submit();                                                     $dir_root);
    }            $r->print($result.&return_to_editor());   
 }        } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
             $uploadphase = 'decompress_phase_one';
 function makesmpproblem() {            $r->print(&decompression_phase_one().
    var title=prompt('$lt{"p_msb"}');                      &return_to_editor());
    if (title) {        } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
     this.document.forms.newsmpproblem.importdetail.value=            $uploadphase = 'decompress_phase_two';
  escape(title)+'=/res/lib/templates/simpleproblem.problem';            $r->print(&decompression_phase_two().
     this.document.forms.newsmpproblem.submit();                      &return_to_editor());
    }        }
 }    }
   
 function makedropbox() {    if ($allowed && $toolsflag) {
    var title=prompt('$lt{"p_mdb"}');        $r->print(&startContentScreen('tools'));
    if (title) {        $r->print(&generate_admin_menu($crstype));
     this.document.forms.newdropbox.importdetail.value=        $r->print(&endContentScreen());
         escape(title)+'=/res/lib/templates/DropBox.problem';    } elsif ((!$showdoc) && (!$uploadphase)) {
     this.document.forms.newdropbox.submit();  # -----------------------------------------------------------------------------
    }         my %lt=&Apache::lonlocal::texthash(
 }                  'uplm' => 'Upload a new main '.lc($crstype).' document',
                   'upls' => 'Upload a new supplemental '.lc($crstype).' document',
 function makebulboard() {                  'impp' => 'Import a document',
    var title=prompt('$lt{"p_mbb"}');   'copm' => 'All documents out of a published map into this folder',
    if (title) {                  'upfi' => 'Upload File',
     this.document.forms.newbul.importdetail.value=                  'upld' => 'Import Content',
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';                  'srch' => 'Search',
     this.document.forms.newbul.submit();                  'impo' => 'Import',
    }   'lnks' => 'Import from Stored Links',
 }                  'impm' => 'Import from Assembled Map',
                   'selm' => 'Select Map',
 function makeabout() {                  'load' => 'Load Map',
    var user=prompt("$lt{'p_mab'}");                  'reco' => 'Recover Deleted Documents',
    if (user) {                  'newf' => 'New Folder',
        var comp=new Array();                  'newp' => 'New Composite Page',
        comp=user.split(':');                  'extr' => 'External Resource',
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {                  'syll' => 'Syllabus',
    if ((comp[0]) && (comp[1])) {                  'navc' => 'Table of Contents',
        this.document.forms.newaboutsomeone.importdetail.value=                  'sipa' => 'Simple Course Page',
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';                  'sipr' => 'Simple Problem',
        this.document.forms.newaboutsomeone.submit();                  'drbx' => 'Drop Box',
    } else {                  'scuf' => 'External Scores (handgrade, upload, clicker)',
                alert("$lt{'p_mab_alrt1'}");                  'bull' => 'Discussion Board',
            }                  'mypi' => 'My Personal Information Page',
        } else {                  'grpo' => 'Group Portfolio',
            alert("$lt{'p_mab_alrt2'}");                  'rost' => 'Course Roster',
        }   'abou' => 'Personal Information Page for a User',
    }                  'imsf' => 'IMS Import',
 }                  'imsl' => 'Import IMS package',
                   'cms'  => 'Origin of IMS package',
 function makeims() {                  'se'   => 'Select',
     var caller = document.forms.ims.folder.value;                  'file' =>  'File',
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";                  'title' => 'Title',
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");                  'comment' => 'Comment',
     newWindow.location.href = newlocation;                  'url'  => 'URL',
 }                  'prev' => 'Preview',
                   'lnk'  => 'Add Link', 
                   'parse' => 'Upload embedded images/multimedia files if HTML file',
 function finishpick() {    );
     var title=this.document.forms.extimport.title.value;  # -----------------------------------------------------------------------------
     var url=this.document.forms.extimport.url.value;   my $fileupload=(<<FIUP);
     var form=this.document.forms.extimport.useform.value;   $lt{'file'}:<br />
     var residx=this.document.forms.extimport.residx.value;   <input type="file" name="uploaddoc" size="40" />
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');  FIUP
 }  
    my $checkbox=(<<CHBO);
 function changename(folderpath,index,oldtitle,container,pagesymb) {   <!-- <label>$lt{'parse'}?
     var title=prompt('$lt{"p_chn"}',oldtitle);   <input type="checkbox" name="parserflag" />
     if (title) {   </label> -->
  this.document.forms.renameform.markcopy.value=-1;   <label>
  this.document.forms.renameform.title.value=title;   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
  this.document.forms.renameform.cmd.value='rename_'+index;   </label>
         if (container == 'sequence') {  CHBO
     this.document.forms.renameform.folderpath.value=folderpath;          my $imsfolder = $env{'form.folder'};
         }          if ($imsfolder eq '') {
         if (container == 'page') {              $imsfolder = 'default';  
             this.document.forms.renameform.pagepath.value=folderpath;          }
             this.document.forms.renameform.pagesymb.value=pagesymb;          my $imspform=(<<IMSFORM);
         }          <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
         this.document.forms.renameform.submit();          $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
     }          <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
 }          <fieldset id="uploadimsform" style="display: none;">
           <legend>$lt{'imsf'}</legend>
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {          $fileupload
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {          <br />
  this.document.forms.renameform.markcopy.value=-1;          <p>
  this.document.forms.renameform.cmd.value='del_'+index;          $lt{'cms'}:&nbsp; 
         if (container == 'sequence') {          <select name="source">
             this.document.forms.renameform.folderpath.value=folderpath;          <option value="-1" selected="selected">$lt{'se'}</option>
         }          <option value="bb5">Blackboard 5</option>
         if (container == 'page') {          <option value="bb6">Blackboard 6</option>
             this.document.forms.renameform.pagepath.value=folderpath;          <option value="angel5">ANGEL 5.5</option>
             this.document.forms.renameform.pagesymb.value=pagesymb;          <option value="webctce4">WebCT 4 Campus Edition</option>
         }          </select>
         this.document.forms.renameform.submit();          <input type="hidden" name="folder" value="$imsfolder" />
     }          </p>
 }          <input type="hidden" name="phase" value="one" />
           <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" />
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {          </fieldset>
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {          </form>
  this.document.forms.renameform.cmd.value='cut_'+index;  IMSFORM
  this.document.forms.renameform.markcopy.value=index;  
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;   my $fileuploadform=(<<FUFORM);
         if (container == 'sequence') {          <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
             this.document.forms.renameform.folderpath.value=folderpath;          $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
         }          <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
         if (container == 'page') {          <fieldset id="uploaddocform" style="display: none;">
             this.document.forms.renameform.pagepath.value=folderpath;          <legend>$lt{'upfi'}</legend>
             this.document.forms.renameform.pagesymb.value=pagesymb;   <input type="hidden" name="active" value="aa" />
         }   $fileupload
         this.document.forms.renameform.submit();   <br />
     }   $lt{'title'}:<br />
 }   <input type="text" size="60" name="comment" />
    $pathitem
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {   <input type="hidden" name="cmd" value="upload_default" />
     this.document.forms.renameform.markcopy.value=index;   <br />
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;   <span class="LC_nobreak" style="float:left">
     if (container == 'sequence') {   $checkbox
  this.document.forms.renameform.folderpath.value=folderpath;   </span>
     }          <br clear="all" />
     if (container == 'page') {          <input type="submit" value="$lt{'upld'}" />
  this.document.forms.renameform.pagepath.value=folderpath;          </fieldset>
  this.document.forms.renameform.pagesymb.value=pagesymb;          </form>
     }  FUFORM
     this.document.forms.renameform.submit();  
 }   my $importpubform=(<<SEDFFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleMap('map');">
           $lt{'impm'}</a>$help{'Load_Map'}
 ENDNEWSCRIPT   <form action="/adm/coursedocs" method="post" name="mapimportform">
 }          <fieldset id="importmapform" style="display: none;">
 1;          <legend>$lt{'impm'}</legend>
 __END__   <input type="hidden" name="active" value="bb" />
           $lt{'copm'}<br />
           <span class="LC_nobreak">
 =head1 NAME          <input type="text" name="importmap" size="40" value="" 
           onfocus="this.blur();openbrowser('mapimportform','importmap','sequence,page','');" />
 Apache::londocs.pm          &nbsp;<a href="javascript:openbrowser('mapimportform','importmap','sequence,page','');">$lt{'selm'}</a></span><br />
           <input type="submit" name="loadmap" value="$lt{'load'}" />
 =head1 SYNOPSIS          </fieldset>
           </form>
 This is part of the LearningOnline Network with CAPA project  
 described at http://www.lon-capa.org.  SEDFFORM
    my @importpubforma = (
 =head1 SUBROUTINES   { '<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'}" },
 =over   { '<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 %help=()   );
    $importpubform = &create_form_ul(&create_list_elements(@importpubforma));
 Available help topics          my $extresourcesform =
               &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
 =item mapread()                                                   $help{'Adding_External_Resource'});
       if ($allowed) {
 Mapread read maps into LONCAPA::map:: global arrays          my $folder = $env{'form.folder'};
 @order and @resources, determines status          if ($folder eq '') {
 sets @order - pointer to resources in right order              $folder='default';
 sets @resources - array with the resources with correct idx          }
    &update_paste_buffer($coursenum,$coursedom,$folder);
 =item authorhosts()   $r->print(<<HIDDENFORM);
    <form name="renameform" method="post" action="/adm/coursedocs">
 Return hash with valid author names     <input type="hidden" name="title" />
      <input type="hidden" name="cmd" />
 =item dumpbutton()     <input type="hidden" name="markcopy" />
      <input type="hidden" name="copyfolder" />
 Generate "dump" button     $containertag
    </form>
 =item clean()  
   HIDDENFORM
 =item dumpcourse()          $r->print(&makesimpleeditform($pathitem)."\n".
                     &makedocslogform($pathitem."\n".
     Actually dump course                                     '<input type="hidden" name="folder" value="'.
                                      $env{'form.folder'}.'" />'."\n"));
       }
 =item exportbutton()  
   # Generate the tabs
     Generate "export" button      my ($mode,$needs_end);
       if (($supplementalflag) && (!$allowed)) {
 =item exportcourse()          my @folders = split('&',$env{'form.folderpath'});
           unless (@folders > 2) {
 =item create_ims_store()              &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
               $needs_end = 1;
 =item build_package()          }
       } else {
 =item get_dependencies()          $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
           $needs_end = 1;
 =item process_content()      }
   
 =item replicate_content()  #
   
 =item extract_media()      my $savefolderpath;
   
 =item store_template()      if ($allowed) {
          my $folder=$env{'form.folder'};
 =item group_import()         if ($folder eq '' || $supplementalflag) {
              $folder='default';
     Imports the given (name, url) resources into the course     $savefolderpath = $env{'form.folderpath'};
     coursenum, coursedom, and folder must precede the list     $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
              $pathitem = '<input type="hidden" name="folderpath" value="'.
 =item breadcrumbs()         &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
 =item log_docs()         my $postexec='';
          if ($folder eq 'default') {
 =item docs_change_log()             $r->print('<script type="text/javascript">'."\n"
                       .'// <![CDATA['."\n"
 =item update_paste_buffer()                      .'this.window.name="loncapaclient";'."\n"
                       .'// ]]>'."\n"
 =item print_paste_buffer()                      .'</script>'."\n"
          );
 =item do_paste_from_buffer()         } else {
              #$postexec='self.close();';
 =item update_parameter()         }
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.sequence';
 =item handle_edit_cmd()         my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.page';
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 =item editor()  
    my $newnavform=(<<NNFORM);
 =item process_file_upload()   <form action="/adm/coursedocs" method="post" name="newnav">
    <input type="hidden" name="active" value="cc" />
 =item process_secondary_uploads()   $pathitem
    <input type="hidden" name="importdetail" 
 =item is_supplemental_title()   value="$lt{'navc'}=/adm/navmaps" />
    <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
 =item parse_supplemental_title()   $help{'Navigate_Content'}
    </form>
 =item entryline()  NNFORM
    my $newsmppageform=(<<NSPFORM);
 =item tiehash()   <form action="/adm/coursedocs" method="post" name="newsmppg">
    <input type="hidden" name="active" value="cc" />
 =item untiehash()   $pathitem
    <input type="hidden" name="importdetail" value="" />
 =item checkonthis()   <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
    $help{'Simple Page'}
 check on this   </form>
   NSPFORM
 =item verifycontent()  
    my $newsmpproblemform=(<<NSPROBFORM);
 Verify Content   <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    <input type="hidden" name="active" value="cc" />
 =item devalidateversioncache() & checkversions()   $pathitem
    <input type="hidden" name="importdetail" value="" />
 Check Versions   <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
    $help{'Simple Problem'}
 =item mark_hash_old()   </form>
   
 =item is_hash_old()  NSPROBFORM
   
 =item changewarning()   my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
 =item init_breadcrumbs()   <input type="hidden" name="active" value="cc" />
    $pathitem
 Breadcrumbs for special functions   <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
 =back   </form>
   NDBFORM
 =cut  
    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.484.2.19


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