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

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

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


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