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

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

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


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