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

version 1.326, 2009/01/28 11:51:22 version 1.484.2.1, 2012/05/07 02:19:44
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 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
                 &Apache::lonnet::metadata($url,'dependencies');      } else {
              foreach my $dep (split(/\,/,$dependencies)) {          $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";
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
                     &checkonthis($r,$dep,$level+1);          $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') {      $output .= "\n".'</ul>'."\n";
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');      $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
           } elsif ($result eq 'not_found') {                 '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
       unless ($url=~/\$/) {                 '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');      return $output;
       } else {  }
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');  
       }  #
           } else {  # End tabs
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');  #
           }  
        }  sub endContentScreen {
     }      return '</div></div></div>';
 }  }
   
   sub supplemental_base {
       return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
 =pod  }
   
 =item list_symbs()  sub handler {
       my $r = shift;
 List Symbs      &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
 =cut      return OK if $r->header_only;
   
 sub list_symbs {  # get course data
     my ($r) = @_;      my $crstype = &Apache::loncommon::course_type();
       my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
     my $type = &Apache::loncommon::course_type();      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
     $r->print(&Apache::loncommon::start_page('Symb List'));  
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));  # graphics settings
     my $navmap = Apache::lonnavmaps::navmap->new();      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
     if (!defined($navmap)) {  
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.  #
                   '<div class="LC_error">'.  # --------------------------------------------- Initialize help topics for this
                   &mt('Unable to retrieve information about course contents').      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
                   '</div>');                 'Adding_External_Resource','Navigate_Content',
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                 'Adding_Folders','Docs_Overview', 'Load_Map',
     } else {                 'Supplemental','Score_Upload_Form','Adding_Pages',
         $r->print("<pre>\n");                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
         foreach my $res ($navmap->retrieveResources()) {                 'Check_Resource_Versions','Verify_Content') {
     $r->print($res->compTitle()."\t".$res->symb()."\n");   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
         }      }
         $r->print("\n</pre>\n");      # Composite help files
     }      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 }      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
       $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 sub verifycontent {      'Option_Response_Simple');
     my ($r) = @_;      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
     my $type = &Apache::loncommon::course_type();      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
    my $loaderror=&Apache::lonnet::overloaderror($r);      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
    if ($loaderror) { return $loaderror; }    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));      $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
    $hashtied=0;  
    undef %alreadyseen;      
    %alreadyseen=();      my $allowed;
    &tiehash();  # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
    foreach my $key (keys(%hash)) {      unless ($r->uri eq '/adm/supplemental') {
        if ($hash{$key}=~/\.(page|sequence)$/) {          # does this user have privileges to modify content.  
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {          $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
        $r->print('<hr /><span class="LC_error">'.      }
  &mt('The following sequence or page is included more than once in your '.$type.': ').  
  &unescape($hash{$key}).'</span><br />'.      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));                                              'inhibitmenu']);
    }    if ($allowed && $env{'form.chooseserver'}) {
        }        &choose_dump_server($r);
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {        return OK;
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});    } elsif ($allowed && $env{'form.verify'}) {
        }        &init_breadcrumbs('verify','Verify Content');
    }        &verifycontent($r);
    &untiehash();    } elsif ($allowed && $env{'form.listsymbs'}) {
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.        &init_breadcrumbs('listsymbs','List Content IDs');
      &mt('Return to DOCS').'</a>');        &list_symbs($r);
 }    } elsif ($allowed && $env{'form.docslog'}) {
         &init_breadcrumbs('docslog','Show Log');
         my $folder = $env{'form.folder'};
 sub devalidateversioncache {        if ($folder eq '') {
     my $src=shift;            $folder='default';
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.        }
   &Apache::lonnet::clutter($src));        &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
 }    } elsif ($allowed && $env{'form.versions'}) {
         &init_breadcrumbs('versions','Check/Set Resource Versions');
 sub checkversions {        &checkversions($r);
     my ($r) = @_;    } elsif ($allowed && $env{'form.dumpcourse'}) {
     my $type = &Apache::loncommon::course_type();        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));        &dumpcourse($r);
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));    } elsif ($allowed && $env{'form.exportcourse'}) {
     my $header='';        &init_breadcrumbs('exportcourse','IMS Export');
     my $startsel='';        &Apache::imsexport::exportcourse($r);
     my $monthsel='';    } else {
     my $weeksel='';  #
     my $daysel='';  # Done catching special calls
     my $allsel='';  # The whole rest is for course and supplemental documents and utilities menu
     my %changes=();  # Get the parameters that may be needed
     my $starttime=0;  #
     my $haschanged=0;      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
     my %setversions=&Apache::lonnet::dump('resourceversions',                                              ['folderpath','pagepath',
   $env{'course.'.$env{'request.course.id'}.'.domain'},                                               'pagesymb','forcesupplement','forcestandard',
   $env{'course.'.$env{'request.course.id'}.'.num'});                                               'tools','symb','command']);
   
     $hashtied=0;  # standard=1: this is a "new-style" course with an uploaded map as top level
     &tiehash();  # standard=2: this is a "old-style" course, and there is nothing we can do
     my %newsetversions=();  
     if ($env{'form.setmostrecent'}) {      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
  $haschanged=1;  
  foreach my $key (keys(%hash)) {  # Decide whether this should display supplemental or main content or utilities
     if ($key=~/^ids\_(\/res\/.+)$/) {  # supplementalflag=1: show supplemental documents
  $newsetversions{$1}='mostrecent';  # supplementalflag=0: show standard documents
                 &devalidateversioncache($1);  # toolsflag=1: show utilities
     }  
  }  
     } elsif ($env{'form.setcurrent'}) {      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
  $haschanged=1;      if (($env{'form.folderpath'}=~/^default/) || $env{'form.folderpath'} eq "" || ($env{'form.pagepath'})) {
  foreach my $key (keys(%hash)) {         $supplementalflag=0;
     if ($key=~/^ids\_(\/res\/.+)$/) {      }
  my $getvers=&Apache::lonnet::getversion($1);      if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
  if ($getvers>0) {      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
     $newsetversions{$1}=$getvers;      unless ($allowed) { $supplementalflag=1; }
     &devalidateversioncache($1);      unless ($standard) { $supplementalflag=1; }
  }      my $toolsflag=0;
     }      if ($env{'form.tools'}) { $toolsflag=1; }
  }  
     } elsif ($env{'form.setversions'}) {      my $script='';
  $haschanged=1;      my $showdoc=0;
  foreach my $key (keys(%env)) {      my $addentries = {};
     if ($key=~/^form\.set_version_(.+)$/) {      my $container;
  my $src=$1;      my $containertag;
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {      my $uploadtag;
     $newsetversions{$src}=$env{$key};  
     &devalidateversioncache($src);  # Do we directly jump somewhere?
  }  
     }     if ($env{'form.command'} eq 'direct') {
  }         my ($mapurl,$id,$resurl);
     }         if ($env{'form.symb'} ne '') {
     if ($haschanged) {             ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,             if ($resurl=~/\.(sequence|page)$/) {
   $env{'course.'.$env{'request.course.id'}.'.domain'},                 $mapurl=$resurl;
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {             } elsif ($resurl eq 'adm/navmaps') {
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');                 $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
  } else {             }
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');             my $mapresobj;
  }             my $navmap = Apache::lonnavmaps::navmap->new();
  &mark_hash_old();             if (ref($navmap)) {
     }                 $mapresobj = $navmap->getResourceByUrl($mapurl);
     &changewarning($r,'');             }
     if ($env{'form.timerange'} eq 'all') {             $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
 # show all documents             my $type=$2;
  $header=&mt('All Documents in '.$type);             my $path;
  $allsel=1;             if (ref($mapresobj)) {
  foreach my $key (keys(%hash)) {                 my $pcslist = $mapresobj->map_hierarchy();
     if ($key=~/^ids\_(\/res\/.+)$/) {                 if ($pcslist ne '') {
  my $src=$1;                     foreach my $pc (split(/,/,$pcslist)) {
  $changes{$src}=1;                         next if ($pc <= 1);
     }                         my $res = $navmap->getByMapPc($pc);
  }                         if (ref($res)) {
     } else {                             my $thisurl = $res->src();
 # show documents which changed                             $thisurl=~s{^.*/([^/]+)\.\w+$}{$1}; 
  %changes=&Apache::lonnet::dump                             my $thistitle = $res->title();
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},                             $path .= '&'.
                      $env{'course.'.$env{'request.course.id'}.'.num'});                                      &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
  my $firstkey=(keys(%changes))[0];                                      &Apache::lonhtmlcommon::entity_encode($thistitle).
  unless ($firstkey=~/^error\:/) {                                      ':'.$res->randompick().
     unless ($env{'form.timerange'}) {                                      ':'.$res->randomout().
  $env{'form.timerange'}=604800;                                      ':'.$res->encrypted().
     }                                      ':'.$res->randomorder();
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '                         }
  .&mt('seconds');                     }
     if ($env{'form.timerange'}==-1) {                 }
  $seltext='since start of course';                 $path .= '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
  $startsel='selected';                      &Apache::lonhtmlcommon::entity_encode($mapresobj->title()).
  $env{'form.timerange'}=time;                      ':'.$mapresobj->randompick().
     }                      ':'.$mapresobj->randomout().
     $starttime=time-$env{'form.timerange'};                      ':'.$mapresobj->encrypted().
     if ($env{'form.timerange'}==2592000) {                      ':'.$mapresobj->randomorder();
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';             } else {
  $monthsel='selected';                 my $maptitle = &Apache::lonnet::gettitle($mapurl);
     } elsif ($env{'form.timerange'}==604800) {                 $path = '&default&...::::'.
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                     '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
  $weeksel='selected';                     &Apache::lonhtmlcommon::entity_encode($maptitle).'::::';
     } elsif ($env{'form.timerange'}==86400) {             }
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';             $path = 'default&'.
  $daysel='selected';                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
     }                     $path;
     $header=&mt('Content changed').' '.$seltext;             if ($type eq 'sequence') {
  } else {                 $env{'form.folderpath'}=$path;
     $header=&mt('No content modifications yet.');                 $env{'form.pagepath'}='';
  }             } else {
     }                 $env{'form.pagepath'}=$path;
     %setversions=&Apache::lonnet::dump('resourceversions',                 $env{'form.folderpath'}='';
   $env{'course.'.$env{'request.course.id'}.'.domain'},             }
   $env{'course.'.$env{'request.course.id'}.'.num'});         } elsif ($env{'form.supppath'} ne '') {
     my %lt=&Apache::lonlocal::texthash             $env{'form.folderpath'}=$env{'form.supppath'};
       ('st' => 'Version changes since start of '.$type,         }
        'lm' => 'Version changes since last Month',     } elsif ($env{'form.command'} eq 'editdocs') {
        'lw' => 'Version changes since last Week',          $env{'form.folderpath'} = 'default&'.
        'sy' => 'Version changes since Yesterday',                                    &Apache::lonhtmlcommon::entity_encode('Main Course Content');
                'al' => 'All Resources (possibly large output)',          $env{'form.pagepath'}='';
        'sd' => 'Display',     } elsif ($env{'form.command'} eq 'editsupp') {
        'fi' => 'File',          $env{'form.folderpath'} = 'default&'.
        'md' => 'Modification Date',                                    &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
                'mr' => 'Most recently published Version',          $env{'form.pagepath'}='';
        've' => 'Version used in '.$type,     }
                'vu' => 'Set Version to be used in '.$type,  
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',  # Where do we store these for when we come back?
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      my $stored_folderpath='docs_folderpath';
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      if ($supplementalflag) {
        'di' => 'Differences');         $stored_folderpath='docs_sup_folderpath';
     $r->print(<<ENDHEADERS);      }
 <form action="/adm/coursedocs" method="post">  
 <input type="hidden" name="versions" value="1" />  # No folderpath, no pagepath, see if we have something stored
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />          &Apache::loncommon::restore_course_settings($stored_folderpath,
 <select name="timerange">                                                {'folderpath' => 'scalar'});
 <option value='all' $allsel>$lt{'al'}</option>      }
 <option value="-1" $startsel>$lt{'st'}</option>     
 <option value="2592000" $monthsel>$lt{'lm'}</option>  # If we are not allowed to make changes, all we can see are supplemental docs
 <option value="604800" $weeksel>$lt{'lw'}</option>      if (!$allowed) {
 <option value="86400" $daysel>$lt{'sy'}</option>          $env{'form.pagepath'}='';
 </select>          unless ($env{'form.folderpath'} =~ /^supplemental/) {
 <input type="submit" name="display" value="$lt{'sd'}" />              $env{'form.folderpath'} = &supplemental_base();
 <h3>$header</h3>          }
 <input type="submit" name="setversions" value="$lt{'sv'}" />      }
 <table border="0">  # If we still not have a folderpath, see if we can resurrect at pagepath
 ENDHEADERS      if (!$env{'form.folderpath'} && $allowed) {
     foreach my $key (sort(keys(%changes))) {          &Apache::loncommon::restore_course_settings($stored_folderpath,
  if ($changes{$key}>$starttime) {                                                {'pagepath' => 'scalar'});
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);      }
     my $currentversion=&Apache::lonnet::getversion($key);  # Make the zeroth entry in supplemental docs page paths, so we can get to top level
     if ($currentversion<0) {      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
  $currentversion=&mt('Could not be determined.');          $env{'form.folderpath'} = &supplemental_base()
     }                                    .'&'.
     my $linkurl=&Apache::lonnet::clutter($key);                                    $env{'form.folderpath'};
     $r->print(      }
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.  # If after all of this, we still don't have any paths, make them
       &Apache::lonnet::gettitle($linkurl).      unless (($env{'form.pagepath'}) || ($env{'form.folderpath'})) {
                       '</b></font></td></tr>'.         if ($supplementalflag) {
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.            $env{'form.folderpath'}=&supplemental_base();
                       '<td colspan="4">'.         } else {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.            $env{'form.folderpath'}='default';
       '</a></td></tr>'.         }
                       '<tr><td></td>'.      }
                       '<td title="'.$lt{'md'}.'">'.  
       &Apache::lonlocal::locallocaltime(  # Store this
                            &Apache::lonnet::metadata($root.'.'.$extension,      unless ($toolsflag) {
                                                      'lastrevisiondate')          &Apache::loncommon::store_course_settings($stored_folderpath,
                                                         ).                                                    {'pagepath' => 'scalar',
                       '</td>'.                                                     'folderpath' => 'scalar'});
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.          if ($env{'form.folderpath'}) {
                       '<font size="+1">'.$currentversion.'</font>'.      my (@folderpath)=split('&',$env{'form.folderpath'});
                       '</span></td>'.      $env{'form.foldername'}=&unescape(pop(@folderpath));
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.      $env{'form.folder'}=pop(@folderpath);
                       '<font size="+1">');              $container='sequence';
 # Used in course          }
     my $usedversion=$hash{'version_'.$linkurl};          if ($env{'form.pagepath'}) {
     if (($usedversion) && ($usedversion ne 'mostrecent')) {              my (@pagepath)=split('&',$env{'form.pagepath'});
  $r->print($usedversion);              $env{'form.pagename'}=&unescape(pop(@pagepath));
     } else {              $env{'form.folder'}=pop(@pagepath);
  $r->print($currentversion);              $container='page';
     }              $containertag = '<input type="hidden" name="pagepath" value="" />'.
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.                      '<input type="hidden" name="pagesymb" value="" />';
                       '<span class="LC_nobreak">Use: ');              $uploadtag = 
 # Set version                  '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},          '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />'.
       'set_version_'.$linkurl,                  '<input type="hidden" name="folderpath" value="" />';
       ('select_form_order' =>          } else {
        ['',1..$currentversion,'mostrecent'],              my $folderpath=$env{'form.folderpath'};
        '' => '',              if (!$folderpath) {
        'mostrecent' => 'most recent',                  if ($env{'form.folder'} eq '' ||
        map {$_,$_} (1..$currentversion))));                      $env{'form.folder'} eq 'supplemental') {
     $r->print('</span></td></tr><tr><td></td>');                      $folderpath='default&'.
     my $lastold=1;                          &escape(&mt('Main '.$crstype.' Documents'));
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {                  }
  my $url=$root.'.'.$prevvers.'.'.$extension;              }
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<              $containertag = '<input type="hidden" name="folderpath" value="" />';
     $starttime) {              $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
     $lastold=$prevvers;          }
  }          if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
     }             $showdoc='/'.$1;
             #          }
             # Code to figure out how many version entries should go in          if ($showdoc) { # got called in sequence from course
             # each of the four columns      $allowed=0; 
             my $entries_per_col = 0;          } else {
             my $num_entries = ($currentversion-$lastold);              if ($allowed) {
             if ($num_entries % 4 == 0) {                  &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                 $entries_per_col = $num_entries/4;                  $script=&Apache::lonratedt::editscript('simple');
             } else {              }
                 $entries_per_col = $num_entries/4 + 1;          }
             }      }
             my $entries_count = 0;  
             $r->print('<td valign="top"><font size="-2">');  # get personal data
             my $cols_output = 1;      my $uname=$env{'user.name'};
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {      my $udom=$env{'user.domain'};
  my $url=$root.'.'.$prevvers.'.'.$extension;      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).  
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      if ($allowed) {
   &Apache::lonlocal::locallocaltime(          if ($toolsflag) {
                                 &Apache::lonnet::metadata($url,              $script .= &inject_data_js();
                                                           'lastrevisiondate')              my ($home,$other,%outhash)=&authorhosts();
                                                             ).              if (!$home && $other) {
   ')');                  my @hosts;
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {                  foreach my $aurole (keys(%outhash)) {
                     $r->print(' <a href="/adm/diff?filename='.                      unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
       &Apache::lonnet::clutter($root.'.'.$extension).                          push(@hosts,$outhash{$aurole});
       '&versionone='.$prevvers.                      }
       '">'.&mt('Diffs').'</a>');                  }
  }                  $script .= &dump_switchserver_js(@hosts); 
  $r->print('</span><br />');              }
                 if (++$entries_count % $entries_per_col == 0) {          } else {
                     $r->print('</font></td>');              my @tabids;
                     if ($cols_output != 4) {              if ($supplementalflag) {
                         $r->print('<td valign="top"><font size="-2">');                  @tabids = ('002','ee2','ff2');
                         $cols_output++;              } else {
                     }                  @tabids = ('aa1','bb1','cc1','ff1');
                 }                  unless ($env{'form.pagepath'}) {
     }                      unshift(@tabids,'001');
             while($cols_output++ < 4) {                      push(@tabids,('dd1','ee1'));
                 $r->print('</font></td><td><font>')                  }
             }              }
     $r->print('</font></td></tr>'."\n");              my $tabidstr = join("','",@tabids);
  }      $script .= &editing_js($udom,$uname,$supplementalflag).
     }                         &history_tab_js().
     $r->print('</table></form>');                         &inject_data_js().
     $r->print('<h1>'.&mt('Done').'.</h1>');                         &resize_contentdiv_js($tabidstr);
               $addentries = {
     &untiehash();                              onload   => "javascript:resize_contentdiv('contentscroll','1','1');",
 }                            };
           }
 sub mark_hash_old {      }
     my $retie_hash=0;  # -------------------------------------------------------------------- Body tag
     if ($hashtied) {      $script = '<script type="text/javascript">'."\n"
  $retie_hash=1;                .'// <![CDATA['."\n"
  &untiehash();                .$script."\n"
     }                .'// ]]>'."\n"
     &tiehash('write');                .'</script>'."\n";
     $hash{'old'}=1;  
     &untiehash();      # Breadcrumbs
     if ($retie_hash) { &tiehash(); }      &Apache::lonhtmlcommon::clear_breadcrumbs();
 }      unless ($showdoc) {
           &Apache::lonhtmlcommon::add_breadcrumb({
 sub is_hash_old {              href=>"/adm/coursedocs",text=>"$crstype Contents"});
     my $untie_hash=0;  
     if (!$hashtied) {          $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
  $untie_hash=1;                                                   {'force_register' => $showdoc,
  &tiehash();                                                    'add_entries'    => $addentries,
     }                                                   })
     my $return=$hash{'old'};                   .&Apache::loncommon::help_open_menu('','',273,'RAT')
     if ($untie_hash) { &untiehash(); }                   .&Apache::lonhtmlcommon::breadcrumbs(
     return $return;                       'Editing '.$crstype.' Contents',
 }                       'Docs_Adding_Course_Doc')
           );
 sub changewarning {      } else {
     my ($r,$postexec,$message,$url)=@_;          $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
     if (!&is_hash_old()) { return; }                                                  {'force_register' => $showdoc,}));
     my $pathvar='folderpath';      }
     my $path=&escape($env{'form.folderpath'});  
     if (!defined($url)) {    my %allfiles = ();
  if (defined($env{'form.pagepath'})) {    my %codebase = ();
     $pathvar='pagepath';    my ($upload_result,$upload_output,$uploadphase);
     $path=&escape($env{'form.pagepath'});    if ($allowed) {
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});        if (($env{'form.uploaddoc.filename'}) &&
  }    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
  $url='/adm/coursedocs?'.$pathvar.'='.$path;            my $context = $1; 
     }            # Process file upload - phase one - upload and parse primary file.
     my $course_type = &Apache::loncommon::course_type();    undef($hadchanges);
     if (!defined($message)) {            $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
  $message='Changes will become active for your current session after [_1], or the next time you log in.';                                                \%allfiles,\%codebase,$context);
     }    if ($hadchanges) {
     $r->print("\n\n".        &mark_hash_old();
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".    }
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.            $r->print($upload_output);
 '<input type="hidden" name="orgurl" value="'.$url.        } elsif ($env{'form.phase'} eq 'upload_embedded') {
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.            # Process file upload - phase two - upload embedded objects 
 &mt($message,' <input type="hidden" name="'.            $uploadphase = 'check_embedded';
     $env{'request.role'}.'" value="1" /><input type="button" value="'.            my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').            my $state = &embedded_form_elems($uploadphase,$primaryurl,
 $help{'Caching'}.'</span></h3></form>'."\n\n");                                             $env{'form.newidx'});
 }            my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
 sub init_breadcrumbs {            my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
     my ($form,$text)=@_;            my $actionurl = '/adm/coursedocs';
     &Apache::lonhtmlcommon::clear_breadcrumbs();            my ($result,$flag) = 
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",                &Apache::loncommon::upload_embedded('coursedoc',$destination,
     text=>"Edit ".&Apache::loncommon::course_type(),                    $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
     faq=>273,                    $actionurl);
     bug=>'Instructor Interface',            $r->print($result.&return_to_editor());
                                             help => 'Docs_Adding_Course_Doc'});        } elsif ($env{'form.phase'} eq 'check_embedded') {
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',            # Process file upload - phase three - modify references in HTML file
     text=>$text,            $uploadphase = 'modified_orightml';
     faq=>273,            my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
     bug=>'Instructor Interface'});            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,
                                                      $dir_root);
 sub handler {            $r->print($result.&return_to_editor());   
     my $r = shift;        } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
     &Apache::loncommon::content_type($r,'text/html');            $uploadphase = 'decompress_phase_one';
     $r->send_http_header;            $r->print(&decompression_phase_one().
     return OK if $r->header_only;                      &return_to_editor());
     my $type = &Apache::loncommon::course_type();        } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
             $uploadphase = 'decompress_phase_two';
             $r->print(&decompression_phase_two().
 # --------------------------------------------- Initialize help topics for this                      &return_to_editor());
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',        }
                'Adding_External_Resource','Navigate_Content',    }
                'Adding_Folders','Docs_Overview', 'Load_Map',  
                'Supplemental','Score_Upload_Form','Adding_Pages',    if ($allowed && $toolsflag) {
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',        $r->print(&startContentScreen('tools'));
                'Check_Resource_Versions','Verify_Content') {        $r->print(&generate_admin_menu($crstype));
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);        $r->print(&endContentScreen());
     }    } elsif ((!$showdoc) && (!$uploadphase)) {
     # Composite help files  # -----------------------------------------------------------------------------
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(         my %lt=&Apache::lonlocal::texthash(
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');                  'uplm' => 'Upload a new main '.lc($crstype).' document',
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(                  'upls' => 'Upload a new supplemental '.lc($crstype).' document',
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');                  'impp' => 'Import a document',
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(   'copm' => 'All documents out of a published map into this folder',
     'Option_Response_Simple');                  'upld' => 'Import Document',
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(                  'srch' => 'Search',
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');                  'impo' => 'Import',
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(   'wish' => 'Import from Wishlist',
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');                  'selm' => 'Select Map',
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');                  'load' => 'Load Map',
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');                  'reco' => 'Recover Deleted Documents',
                   'newf' => 'New Folder',
 # does this user have privileges to modify docs                  'newp' => 'New Composite Page',
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});                  'extr' => 'External Resource',
   if ($allowed && $env{'form.verify'}) {                  'syll' => 'Syllabus',
       &init_breadcrumbs('verify','Verify Content');                  'navc' => 'Table of Contents',
       &verifycontent($r);                  'sipa' => 'Simple Course Page',
   } elsif ($allowed && $env{'form.listsymbs'}) {                  'sipr' => 'Simple Problem',
       &init_breadcrumbs('listsymbs','List Symbs');                  'drbx' => 'Drop Box',
       &list_symbs($r);                  'scuf' => 'External Scores (handgrade, upload, clicker)',
   } elsif ($allowed && $env{'form.docslog'}) {                  'bull' => 'Discussion Board',
       &init_breadcrumbs('docslog','Show Log');                  'mypi' => 'My Personal Information Page',
       &docs_change_log($r);                  'grpo' => 'Group Portfolio',
   } elsif ($allowed && $env{'form.versions'}) {                  'rost' => 'Course Roster',
       &init_breadcrumbs('versions','Check/Set Resource Versions');   'abou' => 'Personal Information Page for a User',
       &checkversions($r);                  'imsf' => 'IMS Import',
   } elsif ($allowed && $env{'form.dumpcourse'}) {                  'imsl' => 'Import IMS package',
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');                  'file' =>  'File',
       &dumpcourse($r);                  'title' => 'Title',
   } elsif ($allowed && $env{'form.exportcourse'}) {                  'comment' => 'Comment',
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');                  'parse' => 'Upload embedded images/multimedia files if HTML file',
       &exportcourse($r);   'nd' => 'Upload Document',
   } else {   'pm' => 'Published Map',
 # is this a standard course?   'sd' => 'Special Document',
    'mo' => 'More Options',
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);    );
     my $forcestandard = 0;  # -----------------------------------------------------------------------------
     my $forcesupplement;   my $fileupload=(<<FIUP);
     my $script='';   $lt{'file'}:<br />
     my $showdoc=0;   <input type="file" name="uploaddoc" size="40" />
     my $containertag;  FIUP
     my $uploadtag;  
    my $checkbox=(<<CHBO);
    <!-- <label>$lt{'parse'}?
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},   <input type="checkbox" name="parserflag" />
     ['folderpath','pagepath',   </label> -->
      'pagesymb']);   <label>
 # No folderpath, no pagepath, see if we have something stored   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {   </label>
         &Apache::loncommon::restore_course_settings('docs_folderpath',  CHBO
                                               {'folderpath' => 'scalar'});  
     }      my $fileuploada = "<br clear='all' /><input type='submit' value='".$lt{'upld'}."' /> $help{'Uploading_From_Harddrive'}";
     if (!$env{'form.folderpath'}) {   my $fileuploadform=(<<FUFORM);
         &Apache::loncommon::restore_course_settings('docs_folderpath',   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
                                               {'pagepath' => 'scalar'});   <input type="hidden" name="active" value="aa" />
     }   $fileupload
     if ($env{'form.pagepath'}) {   <br />
        $env{'form.folderpath'}='';   $lt{'title'}:<br />
     }   <input type="text" size="60" name="comment" />
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {   $uploadtag
         $env{'form.folderpath'} = 'supplemental&'.   <input type="hidden" name="cmd" value="upload_default" />
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.   <br />
                                   $env{'form.folderpath'};   <span class="LC_nobreak" style="float:left">
     }   $checkbox
     &Apache::loncommon::store_course_settings('docs_folderpath',   </span>
                                                 {'pagepath' => 'scalar',  FUFORM
                                                  'folderpath' => 'scalar'});      $fileuploadform .= $fileuploada.'</form>';
     if ($env{'form.folderpath'}) {  
  my (@folderpath)=split('&',$env{'form.folderpath'});   my $simpleeditdefaultform=(<<SEDFFORM);
  $env{'form.foldername'}=&unescape(pop(@folderpath));   <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
  $env{'form.folder'}=pop(@folderpath);   <input type="hidden" name="active" value="bb" />
     }  SEDFFORM
     if ($env{'form.pagepath'}) {   my @simpleeditdefaultforma = ( 
         my (@pagepath)=split('&',$env{'form.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.pagename'}=&unescape(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'}" },
         $env{'form.folder'}=pop(@pagepath);   { '<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>" },
         $containertag = '<input type="hidden" name="pagepath" value="" />'.   );
     '<input type="hidden" name="pagesymb" value="" />';   $simpleeditdefaultform .= &create_form_ul(&create_list_elements(@simpleeditdefaultforma));
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.   $simpleeditdefaultform .=(<<SEDFFORM);
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';   <hr id="bb_hrule" style="width:0px;text-align:left;margin-left:0" />
     }   $lt{'copm'}<br />
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {   <input type="text" size="40" name="importmap" /><br />
        $showdoc='/'.$1;   <span class="LC_nobreak" style="float:left"><input type="button"
     }   onclick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
     unless ($showdoc) { # got called from remote   value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||   $help{'Load_Map'}</span>
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {   </form>
            $forcestandard = 1;  SEDFFORM
        }  
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);        my $extresourcesform=(<<ERFORM);
         <form action="/adm/coursedocs" method="post" name="newext">
        if ($allowed) {        $uploadtag
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);        <input type="hidden" name="importdetail" value="" />
          $script=&Apache::lonratedt::editscript('simple');        <a class="LC_menubuttons_link" href="javascript:makenewext('newext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
        }        </form>
     } else { # got called in sequence from course  ERFORM
        $allowed=0;  
     }  
       if ($allowed) {
 # get course data   &update_paste_buffer($coursenum,$coursedom);
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};   $r->print(<<HIDDENFORM);
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};   <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
 # get personal data     <input type="hidden" name="cmd" />
     my $uname=$env{'user.name'};     <input type="hidden" name="markcopy" />
     my $udom=$env{'user.domain'};     <input type="hidden" name="copyfolder" />
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));     $containertag
    </form>
 # graphics settings  
   HIDDENFORM
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");          $r->print(&makesimpleeditform($uploadtag)."\n".
                     &makedocslogform($uploadtag."\n".
     if ($allowed) {                                     '<input type="hidden" name="folder" value="'.
  $script .= &editing_js($udom,$uname);                                     $env{'form.folder'}.'" />'."\n"));
     }      }
 # -------------------------------------------------------------------- Body tag  
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';  # Generate the tabs
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];      my $mode;
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,      if (($supplementalflag) && (!$allowed)) {
     {'force_register' => $showdoc,          &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
                                      'bread_crumbs' => $brcrum}).      } else {
       &Apache::loncommon::help_open_menu('','',273,'RAT'));          $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
        }
   my %allfiles = ();  
   my %codebase = ();  #
   my ($upload_result,$upload_output);  
   if ($allowed) {      my $savefolderpath;
       if (($env{'form.uploaddoc.filename'}) &&  
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {      if ($allowed) {
 # Process file upload - phase one - upload and parse primary file.           my $folder=$env{'form.folder'};
   undef($hadchanges);         if ($folder eq '' || $supplementalflag) {
           $upload_result = &process_file_upload(\$upload_output,$coursenum,             $folder='default';
  $coursedom,\%allfiles,     $savefolderpath = $env{'form.folderpath'};
  \%codebase,$1);     $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
   if ($hadchanges) {             $uploadtag = '<input type="hidden" name="folderpath" value="'.
       &mark_hash_old();         &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
   }         }
           if ($upload_result eq 'phasetwo') {         my $postexec='';
               $r->print($upload_output);         if ($folder eq 'default') {
           }             $r->print('<script type="text/javascript">'."\n"
       } elsif ($env{'form.phasetwo'}) {                      .'// <![CDATA['."\n"
           my %newname = ();                      .'this.window.name="loncapaclient";'."\n"
           my %origname = ();                      .'// ]]>'."\n"
           my %attribs = ();                      .'</script>'."\n"
           my $updateflag = 0;         );
           my $residx = $env{'form.newidx'};         } else {
           my $primary_url = &unescape($env{'form.primaryurl'});             #$postexec='self.close();';
 # Process file upload - phase two - gather secondary files.         }
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {         my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
               if ($env{'form.embedded_item_'.$i.'.filename'}) {                       '.sequence';
                   my $javacodebase;         my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);                       '.page';
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});   my $container='sequence';
                   if (exists($env{'form.embedded_codebase_'.$i})) {   if ($env{'form.pagepath'}) {
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});        $container='page';
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;   }
                   }   my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
                   my @attributes = ();  
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {   my $imspform=(<<IMSPFORM);
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});   <form action="/adm/imsimportdocs" method="post" name="ims">
                   } else {   <input type="hidden" name="folder" value="$folder" />
                       @attributes = ($env{'form.embedded_attrib_'.$i});   <a class="LC_menubuttons_link" href="javascript:makeims();">$lt{'imsf'}</a>
                   }   </form>
                   foreach my $attr (@attributes) {  IMSPFORM
                       push(@{$attribs{$i}},&unescape($attr));  
                   }   my $newnavform=(<<NNFORM);
                   if ($javacodebase) {   <form action="/adm/coursedocs" method="post" name="newnav">
                       $codebase{$i} = $javacodebase;   <input type="hidden" name="active" value="cc" />
                       $codebase{$i} =~ s#/$##;   $uploadtag
                       $updateflag = 1;   <input type="hidden" name="importdetail" 
                   }   value="$lt{'navc'}=/adm/navmaps" />
               }   <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
               unless ($newname{$i} eq $origname{$i}) {   $help{'Navigate_Content'}
                   $updateflag = 1;   </form>
               }  NNFORM
           }   my $newsmppageform=(<<NSPFORM);
 # Process file upload - phase three - modify primary file   <form action="/adm/coursedocs" method="post" name="newsmppg">
           if ($updateflag) {   <input type="hidden" name="active" value="cc" />
               my ($content,$rtncode);   $uploadtag
               my $updateflag = 0;   <input type="hidden" name="importdetail" value="" />
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);   <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
               if ($getstatus eq 'ok') {   $help{'Simple Page'}
                   foreach my $item (keys(%newname)) {   </form>
                       if ($newname{$item} ne $origname{$item}) {  NSPFORM
                           my $attrib_regexp = '';  
                           if (@{$attribs{$item}} > 1) {   my $newsmpproblemform=(<<NSPROBFORM);
                               $attrib_regexp = join('|',@{$attribs{$item}});   <form action="/adm/coursedocs" method="post" name="newsmpproblem">
                           } else {   <input type="hidden" name="active" value="cc" />
                               $attrib_regexp = $attribs{$item}[0];   $uploadtag
                           }   <input type="hidden" name="importdetail" value="" />
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {   <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
                           }   $help{'Simple Problem'}
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;   </form>
                       }  
                       if (exists($codebase{$item})) {  NSPROBFORM
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs  
                       }   my $newdropboxform=(<<NDBFORM);
                   }   <form action="/adm/coursedocs" method="post" name="newdropbox">
 # Save edited file.   <input type="hidden" name="active" value="cc" />
                   my $saveresult;   $uploadtag
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};   <input type="hidden" name="importdetail" value="" />
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};   <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);   </form>
               } else {  NDBFORM
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);  
               }   my $newexuploadform=(<<NEXUFORM);
           }   <form action="/adm/coursedocs" method="post" name="newexamupload">
       }   <input type="hidden" name="active" value="cc" />
   }   $uploadtag
    <input type="hidden" name="importdetail" value="" />
   unless ($showdoc ||  $upload_result eq 'phasetwo') {   <a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
 # -----------------------------------------------------------------------------   $help{'Score_Upload_Form'}
        my %lt=&Apache::lonlocal::texthash(   </form>
                 'uplm' => 'Upload a new main '.lc($type).' document',  NEXUFORM
                 'upls' => 'Upload a new supplemental '.lc($type).' document',  
                 'impp' => 'Import a document',   my $newbulform=(<<NBFORM);
                 'pubd' => 'Published Documents',   <form action="/adm/coursedocs" method="post" name="newbul">
  'copm' => 'All documents out of a published map into this folder',   <input type="hidden" name="active" value="cc" />
                 'upld' => 'Upload Document',   $uploadtag
                 'srch' => 'Search',   <input type="hidden" name="importdetail" value="" />
                 'impo' => 'Import',   <a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
  'book' => 'Import Bookmarks',   $help{'Bulletin Board'}
                 'selm' => 'Select Map',   </form>
                 'load' => 'Load Map',  NBFORM
                 'reco' => 'Recover Deleted Resources',  
                 'newf' => 'New Folder',   my $newaboutmeform=(<<NAMFORM);
                 'newp' => 'New Composite Page',   <form action="/adm/coursedocs" method="post" name="newaboutme">
                 'extr' => 'External Resource',   <input type="hidden" name="active" value="cc" />
                 'syll' => 'Syllabus',   $uploadtag
                 'navc' => 'Navigate Contents',   <input type="hidden" name="importdetail" 
                 'sipa' => 'Simple Page',   value="$plainname=/adm/$udom/$uname/aboutme" />
                 'sipr' => 'Simple Problem',   <a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
                 'drbx' => 'Drop Box',   $help{'My Personal Information Page'}
                 'scuf' => 'Score Upload Form',   </form>
                 'bull' => 'Bulletin Board',  NAMFORM
                 'mypi' => 'My Personal Info',  
                 'grpo' => 'Group Files',   my $newaboutsomeoneform=(<<NASOFORM);
                 'rost' => 'Course Roster',   <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
  'abou' => 'About User',   <input type="hidden" name="active" value="cc" />
                 'imsf' => 'Import IMS package',   $uploadtag
                 'file' =>  'File',   <input type="hidden" name="importdetail" value="" />
                 'title' => 'Title',   <a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
                 'comment' => 'Comment',   </form>
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',  NASOFORM
  'nd' => 'New Document',  
  'pm' => 'Published Map',  
  'sd' => 'Special Document',   my $newrosterform=(<<NROSTFORM);
  'mo' => 'More Options',   <form action="/adm/coursedocs" method="post" name="newroster">
  'hao' => 'Hide all Options'   <input type="hidden" name="active" value="cc" />
   );   $uploadtag
 # -----------------------------------------------------------------------------   <input type="hidden" name="importdetail" 
  my $fileupload=(<<FIUP);   value="$lt{'rost'}=/adm/viewclasslist" />
  $lt{'file'}:<br />   <a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
  <input type="file" name="uploaddoc" size="40" />   $help{'Course Roster'}
 FIUP   </form>
   NROSTFORM
  my $checkbox=(<<CHBO);  
  <!-- <label>$lt{'parse'}?  my $specialdocumentsform;
  <input type="checkbox" name="parserflag" />  my @specialdocumentsforma;
  </label> -->  my $gradingform;
  <label>  my @gradingforma;
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}  my $communityform;
  </label>  my @communityforma;
 CHBO  my $newfolderform;
   my $newfolderb;
  my $fileuploadform=(<<FUFORM);  
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">   my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  $fileupload  
  <br />   my $newpageform=(<<NPFORM);
  $lt{'title'}:<br />   <form action="/adm/coursedocs" method="post" name="newpage">
  <input type="text" size="50" name="comment" />   <input type="hidden" name="folderpath" value="$path" />
  $uploadtag   <input type="hidden" name="importdetail" value="" />
  <input type="hidden" name="cmd" value="upload_default" />   <input type="hidden" name="active" value="cc" />
  <br />   <a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
  <span class="LC_nobreak">   $help{'Adding_Pages'}
  $checkbox   </form>
  </span>  NPFORM
  <br />  
  <br />  
  <span class="LC_nobreak">   $newfolderform=(<<NFFORM);
  <input type="submit" value="$lt{'upld'}" />   <form action="/adm/coursedocs" method="post" name="newfolder">
  $help{'Uploading_From_Harddrive'}   <input type="hidden" name="folderpath" value="$path" />
  </span>   <input type="hidden" name="importdetail" value="" />
  </form>   <input type="hidden" name="active" value="aa" />
 FUFORM   <a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
    </form>
  my $simpleeditdefaultform=(<<SEDFFORM);  NFFORM
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">  
  $lt{'pubd'}<br />   my $newsylform=(<<NSYLFORM);
  $uploadtag   <form action="/adm/coursedocs" method="post" name="newsyl">
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />   <input type="hidden" name="active" value="cc" />
  <br />   $uploadtag
  <span class="LC_nobreak">   <input type="hidden" name="importdetail" 
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />   value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
  $help{'Importing_LON-CAPA_Resource'}   <a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
  </span>   $help{'Syllabus'}
  <br />  
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />   </form>
  <hr />  NSYLFORM
  <p>  
  $lt{'copm'}<br />   my $newgroupfileform=(<<NGFFORM);
  <input type="text" size="40" name="importmap" /><br />   <form action="/adm/coursedocs" method="post" name="newgroupfiles">
  <span class="LC_nobreak"><input type="button"   <input type="hidden" name="active" value="cc" />
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"   $uploadtag
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />   <input type="hidden" name="importdetail"
  $help{'Load_Map'}</span>   value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
  </p>   <a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
  </form>   $help{'Group Portfolio'}
 SEDFFORM   </form>
   NGFFORM
  my $extresourcesform=(<<ERFORM);   @specialdocumentsforma=(
  <form action="/adm/coursedocs" method="post" name="newext">   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
  $uploadtag   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
  <input type="hidden" name="importdetail" value="" />   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
  <span class="LC_nobreak">          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"          );
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}          $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
  </span>  
  </form>  
 ERFORM          my @importdoc = (
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'newext\');" />'=>$extresourcesform},
     if ($allowed) {          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:makeims();" />'=>$imspform},);
  &update_paste_buffer($coursenum,$coursedom);          $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc)) . '<hr id="cc_hrule" style="width:0px;text-align:left;margin-left:0" />' . $fileuploadform;
        my $dumpbut=&dumpbutton();  
        my $exportbut=&exportbutton();          @gradingforma=(
        my %lt=&Apache::lonlocal::texthash(          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
  'vc' => 'Verify Content',          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
  'cv' => 'Check/Set Resource Versions',          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
  'ls' => 'List Symbs',  
                                          'sl' => 'Show Log'          );
   );          $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
   
        my $folderpath=$env{'form.folderpath'};          @communityforma=(
        if (!$folderpath) {         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
    if ($env{'form.folder'} eq '' ||          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
        $env{'form.folder'} eq 'supplemental') {          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
        $folderpath='default&'.          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
    &escape(&mt('Main '.$type.' Documents'));          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
    }          );
        }          $communityform = &create_form_ul(&create_list_elements(@communityforma));
        unless ($env{'form.pagepath'}) {  
            $containertag = '<input type="hidden" name="folderpath" value="" />';  my %orderhash = (
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';                  'aa' => ['Import Documents',$fileuploadform],
        }                  'bb' => ['Published Resources',$simpleeditdefaultform],
                   'cc' => ['Grading Resources',$gradingform],
        $r->print(<<ENDCOURSEVERIFY);                  );
 <form name="renameform" method="post" action="/adm/coursedocs">  unless ($env{'form.pagepath'}) {
   <input type="hidden" name="title" />      $orderhash{'00'} = ['Newfolder',$newfolderform];
   <input type="hidden" name="cmd" />      $orderhash{'dd'} = ['Collaboration',$communityform];
   <input type="hidden" name="markcopy" />      $orderhash{'ee'} = ['Special Documents',$specialdocumentsform];
   <input type="hidden" name="copyfolder" />  }
   $containertag  
 </form>   $hadchanges=0;
 <form name="simpleedit" method="post" action="/adm/coursedocs">         unless (($supplementalflag || $toolsflag)) {
   <input type="hidden" name="importdetail" value="" />            my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
   $uploadtag                                $supplementalflag,\%orderhash,$iconpath);
 </form>            if ($error) {
 <form action="/adm/coursedocs" method="post" name="courseverify">               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
   <div class="LC_docs_course_commands">            }
             if ($hadchanges) {
       <div>               &mark_hash_old();
         <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}            }
       </div>  
       <div>            &changewarning($r,'');
         <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}          }
       </div>      }
         $dumpbut  
         $exportbut  # Supplemental documents start here
       <div>  
         <input type="submit" name="listsymbs" value="$lt{'ls'}" />         my $folder=$env{'form.folder'};
       </div>         unless ($supplementalflag) {
       <div>     $folder='supplemental';
         <input type="hidden" name="folder" value="$env{'form.folder'}" />         }
         <input type="submit" name="docslog" value="$lt{'sl'}" />         if ($folder =~ /^supplemental$/ &&
       </div>     (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
   </div>            $env{'form.folderpath'} = &supplemental_base();
 </form>         } elsif ($allowed) {
 <div style="clear: both; height: 0px;">&nbsp;</div>    $env{'form.folderpath'} = $savefolderpath;
 ENDCOURSEVERIFY         }
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',         $env{'form.pagepath'} = '';
      &mt('Editing the Table of Contents for your '.$type)));         if ($allowed) {
     }     my $folderseq=
 # --------------------------------------------------------- Standard documents         '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
     $r->print('<table class="LC_docs_documents">');         '.sequence';
   
     if (($standard) && ($allowed) && (!$forcesupplement)) {     my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  $r->print('<tr><td class="LC_docs_document">');  
 #  '<h2>'.&mt('Main Course Documents').   my $supupdocformbtn = "<input type='submit' value='".$lt{'upld'}."' />$help{'Uploading_From_Harddrive'}";
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');   my $supupdocform=(<<SUPDOCFORM);
        my $folder=$env{'form.folder'};   <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
        if ($folder eq '' || $folder eq 'supplemental') {   <input type="hidden" name="active" value="ee" />
            $folder='default';   $fileupload
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));   <br />
            $uploadtag = '<input type="hidden" name="folderpath" value="'.   <br />
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';   <span class="LC_nobreak">
        }   $checkbox
        my $postexec='';   </span>
        if ($folder eq 'default') {   <br /><br />
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');   $lt{'comment'}:<br />
        } else {   <textarea cols="50" rows="4" name="comment"></textarea>
            #$postexec='self.close();';   <br />
        }   <input type="hidden" name="folderpath" value="$path" />
        $hadchanges=0;   <input type="hidden" name="cmd" value="upload_supplemental" />
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,  SUPDOCFORM
    $upload_output,$type);   $supupdocform .=  &create_form_ul(&Apache::lonhtmlcommon::htmltag('li',$supupdocformbtn,{class => 'LC_menubuttons_inline_text'}))."</form>";
        if ($error) {  
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');   my $supnewfolderform=(<<SNFFORM);
        }   <form action="/adm/coursedocs" method="post" name="supnewfolder">
        if ($hadchanges) {   <input type="hidden" name="active" value="ee" />
    &mark_hash_old();   <input type="hidden" name="folderpath" value="$path" />
        }   <input type="hidden" name="importdetail" value="" />
        &changewarning($r,$postexec);   <a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.   $help{'Adding_Folders'}
                      '.sequence';   </form>
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  SNFFORM
                      '.page';  
  my $container='sequence';  
  if ($env{'form.pagepath'}) {   my $supnewextform=(<<SNEFORM);
     $container='page';   <form action="/adm/coursedocs" method="post" name="supnewext">
  }   <input type="hidden" name="active" value="ff" />
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;   <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'}
    </form>
  my $recoverform=(<<RFORM);  SNEFORM
  <form action="/adm/groupsort" method="post" name="recover">  
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />   my $supnewsylform=(<<SNSFORM);
  </form>   <form action="/adm/coursedocs" method="post" name="supnewsyl">
 RFORM   <input type="hidden" name="active" value="ff" />
    <input type="hidden" name="folderpath" value="$path" />
  my $imspform=(<<IMSPFORM);   <input type="hidden" name="importdetail" 
  <form action="/adm/imsimportdocs" method="post" name="ims">   value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
  <input type="hidden" name="folder" value="$folder" />   <a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />   $help{'Syllabus'}
  </form>   </form>
 IMSPFORM  SNSFORM
   
  my $newnavform=(<<NNFORM);   my $supnewaboutmeform=(<<SNAMFORM);
  <form action="/adm/coursedocs" method="post" name="newnav">   <form action="/adm/coursedocs" method="post" name="supnewaboutme">
  $uploadtag   <input type="hidden" name="active" value="ff" />
  <input type="hidden" name="importdetail"   <input type="hidden" name="folderpath" value="$path" />
  value="$lt{'navc'}=/adm/navmaps" />   <input type="hidden" name="importdetail" 
  <span class="LC_nobreak">   value="$plainname=/adm/$udom/$uname/aboutme" />
  <input name="newnav" type="submit" value="$lt{'navc'}" />   <a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
  $help{'Navigate_Content'}   $help{'My Personal Information Page'}
  </span>   </form>
  </form>  SNAMFORM
 NNFORM  
  my $newsmppageform=(<<NSPFORM);  
  <form action="/adm/coursedocs" method="post" name="newsmppg">  my @specialdocs = (
  $uploadtag   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.supnewsyl.submit()" />'
  <input type="hidden" name="importdetail" value="" />              =>$supnewsylform},
  <span class="LC_nobreak">   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
  <input name="newsmppg" type="button" value="$lt{'sipa'}"              =>$supnewaboutmeform},
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}   );
  </span>  my @supimportdoc = (
  </form>   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'supnewext\');" />'
 NSPFORM              =>$supnewextform},
           );
  my $newsmpproblemform=(<<NSPROBFORM);  $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc)) . '<hr id="ee_hrule" style="width:0px;text-align:left;margin-left:0" />' . $supupdocform;
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">  my %suporderhash = (
  $uploadtag   '00' => ['Supnewfolder', $supnewfolderform],
  <input type="hidden" name="importdetail" value="" />                  'ee' => ['Import Documents',$supupdocform],
  <span class="LC_nobreak">                  'ff' => ['Special Documents',&create_form_ul(&create_list_elements(@specialdocs))]
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"                  );
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}          if ($supplementalflag) {
  </span>             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
  </form>                                 $supplementalflag,\%suporderhash,$iconpath);
              if ($error) {
 NSPROBFORM                $r->print('<p><span class="LC_error">'.$error.'</span></p>');
              }
  my $newdropboxform=(<<NDBFORM);          }
  <form action="/adm/coursedocs" method="post" name="newdropbox">      } elsif ($supplementalflag) {
  $uploadtag                my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
  <input type="hidden" name="importdetail" value="" />                              $supplementalflag,'',$iconpath);
  <span class="LC_nobreak">                    if ($error) {
  <input name="newdropbox" type="button" value="$lt{'drbx'}"              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
  onClick="javascript:makedropbox();" />          }
  </span>              }
  </form>  
 NDBFORM      $r->print(&endContentScreen());
   
  my $newexuploadform=(<<NEXUFORM);      if ($allowed) {
  <form action="/adm/coursedocs" method="post" name="newexamupload">   $r->print('
  $uploadtag  <form method="post" name="extimport" action="/adm/coursedocs">
  <input type="hidden" name="importdetail" value="" />    <input type="hidden" name="title" />
  <span class="LC_nobreak">    <input type="hidden" name="url" />
  <input name="newexamupload" type="button" value="$lt{'scuf'}"    <input type="hidden" name="useform" />
  onClick="javascript:makeexamupload();" />    <input type="hidden" name="residx" />
  $help{'Score_Upload_Form'}  </form>');
  </span>      }
  </form>    } elsif ($showdoc) {
 NEXUFORM  # -------------------------------------------------------- This is showdoc mode
         $r->print("<h1>".&mt('Uploaded Document').' - '.
  my $newbulform=(<<NBFORM);   &Apache::lonnet::gettitle($r->uri).'</h1><p>'.
  <form action="/adm/coursedocs" method="post" name="newbul">  &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
  $uploadtag                  &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
  <input type="hidden" name="importdetail" value="" />    }
  <span class="LC_nobreak">   }
  <input name="newbulletin" type="button" value="$lt{'bull'}"   $r->print(&Apache::loncommon::end_page());
  onClick="javascript:makebulboard();" />   return OK;
  $help{'Bulletin Board'}  }
  </span>  
  </form>  sub embedded_form_elems {
 NBFORM      my ($phase,$primaryurl,$newidx) = @_;
       my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  my $newaboutmeform=(<<NAMFORM);      return <<STATE;
  <form action="/adm/coursedocs" method="post" name="newaboutme">      <input type="hidden" name="folderpath" value="$folderpath" />
  $uploadtag      <input type="hidden" name="cmd" value="upload_embedded" />
  <input type="hidden" name="importdetail"      <input type="hidden" name="newidx" value="$newidx" />
  value="$plainname=/adm/$udom/$uname/aboutme" />      <input type="hidden" name="phase" value="$phase" />
  <span class="LC_nobreak">      <input type="hidden" name="primaryurl" value="$primaryurl" />
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />  STATE
  $help{'My Personal Info'}  }
  </span>  
  </form>  sub embedded_destination {
 NAMFORM      my $folder=$env{'form.folder'};
       my $destination = 'docs/';
  my $newaboutsomeoneform=(<<NASOFORM);      if ($folder =~ /^supplemental/) {
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">          $destination = 'supplemental/';
  $uploadtag      }
  <input type="hidden" name="importdetail" value="" />      if (($folder eq 'default') || ($folder eq 'supplemental')) {
  <span class="LC_nobreak">          $destination .= 'default/';
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
  onClick="javascript:makeabout();" />          $destination .=  $2.'/';
  </span>      }
  </form>      $destination .= $env{'form.newidx'};
 NASOFORM      my $dir_root = '/userfiles';
       return ($destination,$dir_root);
   }
  my $newrosterform=(<<NROSTFORM);  
  <form action="/adm/coursedocs" method="post" name="newroster">  sub return_to_editor {
  $uploadtag      my $actionurl = '/adm/coursedocs';
  <input type="hidden" name="importdetail"      return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
  value="$lt{'rost'}=/adm/viewclasslist" />             '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
  <span class="LC_nobreak">             '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
  <input name="newroster" type="submit" value="$lt{'rost'}" />             '</a></p>';
  $help{'Course Roster'}  }
  </span>  
  </form>  sub decompression_info {
 NROSTFORM      my ($destination,$dir_root) = &embedded_destination();
       my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
        $r->print(<<ENDFORM);      my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
       my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 <ul class="LC_TabContent">      my $container='sequence';
 <li>$lt{'nd'}</li>      my ($pathitem,$hiddenelem);
 <li>$lt{'pm'}</li>      my @hiddens = ('newidx','comment','position');
 <li>$lt{'pubd'}</li>      if ($env{'form.pagepath'}) {
 <li>$lt{'sd'}</li>          $container='page';
 <li>$lt{'mo'}</li>          $pathitem = 'pagepath';
 <li>$lt{'hao'}</li>      } else {
 </ul>          $pathitem = 'folderpath';
       }
 <table class="LC_docs_adddocs">      unshift(@hiddens,$pathitem);
 <!-- <tr>      foreach my $item (@hiddens) {
 <th>$lt{'uplm'}</th>          if ($env{'form.'.$item}) {
 <th>$lt{'impp'}</th>              $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
 <th>$lt{'spec'}</th>                             $env{'form.'.$item}.'" />'."\n";
 </tr> -->          }
 <tr>      }
 <td>      return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
 $fileuploadform              $hiddenelem);
 </td>  }
 <td>  
 $simpleeditdefaultform  sub decompression_phase_one {
 <hr />      my ($dir,$file,$warning,$error,$output);
 $recoverform      my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
 ENDFORM          &decompression_info();
        unless ($env{'form.pagepath'}) {      if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/docs/\E(?:default|supplemental|\d+).*/([^/]+)$}) {
    $r->print(<<ENDFORM);          $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
 <hr />      } else {
 $extresourcesform          my $file = $1;
  <br />          $output = 
 $imspform              &Apache::loncommon::process_decompression($docudom,$docuname,$file,
 ENDFORM                                                        $destination,$dir_root,
        }                                                        $hiddenelem);
        $r->print('</td><td>');          if ($env{'form.autoextract_camtasia'}) {
        unless ($env{'form.pagepath'}) {              $output .= &remove_archive($docudom,$docuname,$container);
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');          }
       }
       if ($error) {
           $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
  my $newpageform=(<<NPFORM);                     $error.'</p>'."\n";
  <form action="/adm/coursedocs" method="post" name="newpage">      }
  <input type="hidden" name="folderpath" value="$path" />      if ($warning) {
  <input type="hidden" name="importdetail" value="" />          $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
  <span class="LC_nobreak">      }
  <input name="newpage" type="button"      return $output;
  onClick="javascript:makenewpage(this.form,'$pageseq');"  }
  value="$lt{'newp'}" />$help{'Adding_Pages'}  
  </span>  sub decompression_phase_two {
  </form>      my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
 NPFORM          &decompression_info();
       my $output;
  my $newfolderform=(<<NFFORM);      if ($env{'form.archivedelete'}) {
  <form action="/adm/coursedocs" method="post" name="newfolder">          $output = &remove_archive($docudom,$docuname,$container);
  <input type="hidden" name="folderpath" value="$path" />      }
  <input type="hidden" name="importdetail" value="" />      $output .= 
  <span class="LC_nobreak">          &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
  <input name="newfolder" type="button"                                                      $destination,$dir_root,$hiddenelem);
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      return $output;
  value="$lt{'newf'}" />$help{'Adding_Folders'}  }
  </span>  
  </form>  sub remove_archive {
 NFFORM      my ($docudom,$docuname,$container) = @_;
       my $map = $env{'form.folder'}.'.'.$container;
  my $newsylform=(<<NSYLFORM);      my ($output,$delwarning,$delresult,$url);
  <form action="/adm/coursedocs" method="post" name="newsyl">      my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
  $uploadtag      if ($fatal) {
  <input type="hidden" name="importdetail"          if ($container eq 'page') {
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />              $delwarning = &mt('An error occurred retrieving the contents of the current page.');
  <span class="LC_nobreak">          } else {
  <input name="newsyl" type="submit" value="$lt{'syll'}" />              $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
  $help{'Syllabus'}          }
  </span>          $delwarning .= &mt('As a result the archive file has not been removed.');
  </form>      } else {
 NSYLFORM          my $currcmd = $env{'form.cmd'};
           my $position = $env{'form.position'};
  my $newgroupfileform=(<<NGFFORM);          if ($position > 0) { 
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">              $env{'form.cmd'} = 'del_'.$position;
  $uploadtag              my ($title,$url,@rrest) = 
  <input type="hidden" name="importdetail"                  split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$position]]);
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />              if (&handle_edit_cmd($docuname,$docudom)) {
  <span class="LC_nobreak">                  ($errtext,$fatal) = &storemap($docuname,$docudom,$map);
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />                  if ($fatal) {
  $help{'Group Files'}                      if ($container eq 'page') {
  </span>                          $delwarning = &mt('An error occurred updating the contents of the current page.');
  </form>                      } else {
 NGFFORM                          $delwarning = &mt('An error occurred updating the contents of the current folder.');
                       }
                   } else {
            $r->print(<<ENDFORM);                      $delresult = &mt('Archive file removed.');
 <br />                  }
 $newfolderform              }
 <br />          }
 $newpageform          $env{'form.cmd'} = $currcmd;
 <br />      }
 $newsylform      if ($delwarning) {
 <br />          $output = '<p class="LC_warning">'.
 $newnavform                     $delwarning.
 <br />                     '</p>';
 $newsmppageform      }
 <br />      if ($delresult) {
 $newsmpproblemform          $output .= '<p class="LC_info">'.
 <br />                     $delresult.
 $newdropboxform                     '</p>';
 <br />      }
 $newexuploadform      return $output;
 <br />  }
 $newbulform  
 <br />  sub generate_admin_menu {
 $newaboutmeform      my ($crstype) = @_;
 <br />      my $lc_crstype = lc($crstype);
 $newaboutsomeoneform      my ($home,$other,%outhash)=&authorhosts();
 <br />      my %lt=&Apache::lonlocal::texthash (
 $newgroupfileform                                           'vc'   => 'Verify Content',
 <br />                                           'cv'   => 'Check/Set Resource Versions',
 $newrosterform                                           'ls'   => 'List Resource Identifiers',
 ENDFORM                                           'imse' => 'Export contents to IMS Archive',
        }                                           'dcd'  => "Dump $crstype Content to Authoring Space",
        if ($env{'form.pagepath'}) {                                         );
            $r->print(<<ENDBLOCK);      my ($candump,$dumpurl);
 $newsmpproblemform      if ($home + $other > 0) {
 <br />          $candump = 'F';
 $newexuploadform          if ($home) {
 ENDBLOCK              $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
        }          } else {
        $r->print('</td></tr>'."\n".              my @hosts;
 '</table>');              foreach my $aurole (keys(%outhash)) {
        $r->print('</td></tr>');                  unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
     }                      push(@hosts,$outhash{$aurole});
 # ----------------------------------------------------- Supplemental documents                  }  
     if (!$forcestandard) {              }
        $r->print('<tr><td class="LC_docs_document">');              if (@hosts == 1) {
 # '<h2>'.&mt('Supplemental Course Documents').                  my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');                                 '&amp;role='.
        my $folder=$env{'form.folder'};                                 &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
        unless ($folder=~/^supplemental/) {                                 &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
    $folder='supplemental';                  $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
        }              } else {
        if ($folder =~ /^supplemental$/ &&                  $dumpurl = "javascript:choose_switchserver_window()";
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {              }
           $env{'form.folderpath'} = 'supplemental&'.          }
                                     &escape(&mt('Supplemental '.$type.' Documents'));      }
        }      my @menu=
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);          ({  categorytitle=>'Administration',
        if ($error) {              items =>[
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');                  {   linktext   => $lt{'vc'},
        }                      url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
        if ($allowed) {                      permission => 'F',
    my $folderseq=                      help       => 'Verify_Content',
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.                      icon       => 'verify.png',
        '.sequence';                      linktitle  => 'Verify contents can be retrieved/rendered',
                   },
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                  {   linktext => $lt{'cv'},
                       url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
  my $supupdocform=(<<SUPDOCFORM);                      permission => 'F',
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">                      help       => 'Check_Resource_Versions',
  $fileupload                      icon       => 'resversion.png',
  <br />                      linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
  <br />                  },
  <span class="LC_nobreak">                  {   linktext   => $lt{'ls'},
  $checkbox                      url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
  </span>                      permission => 'F',
  <br /><br />                      #help => '',
  $lt{'comment'}:<br />                      icon       => 'symbs.png',
  <textarea cols=50 rows=4 name='comment'>                      linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
  </textarea>                  },
  <br />                  ]
  <input type="hidden" name="folderpath" value="$path" />          },
  <input type="hidden" name="cmd" value="upload_supplemental" />          {   categorytitle=>'Export',
  <span class="LC_nobreak">              items =>[
  <input type="submit" value="$lt{'upld'}" />                  {   linktext   => $lt{'imse'},
  $help{'Uploading_From_Harddrive'}                      url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
  </span>                      permission => 'F',
  </form>                      help       => 'Docs_Export_Course_Docs',
 SUPDOCFORM                      icon       => 'imsexport.png',
                       linktitle  => $lt{'imse'},
  my $supnewfolderform=(<<SNFFORM);                  },
  <form action="/adm/coursedocs" method="post" name="supnewfolder">                  {   linktext   => $lt{'dcd'},
  <input type="hidden" name="folderpath" value="$path" />                      url        => $dumpurl,
  <input type="hidden" name="importdetail" value="" />                      permission => $candump,
  <span class="LC_nobreak">                      #help => '',
  <input name="newfolder" type="button"                      icon       => 'dump.png',
  onClick="javascript:makenewfolder(this.form,'$folderseq');"                      linktitle  => $lt{'dcd'},
  value="$lt{'newf'}" /> $help{'Adding_Folders'}                  },
  </span>                  ]
  </form>          });
 SNFFORM      return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
              '<input type="hidden" id="dummy" />'."\n".
              &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
  my $supnewextform=(<<SNEFORM);             '</form>';
  <form action="/adm/coursedocs" method="post" name="supnewext">  }
  <input type="hidden" name="folderpath" value="$path" />  
  <input type="hidden" name="importdetail" value="" />  sub generate_edit_table {
  <span class="LC_nobreak">      my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile) = @_;
  <input name="newext" type="button"      return unless(ref($orderhash_ref) eq 'HASH');
  onClick="javascript:makenewext('supnewext');"      my %orderhash = %{$orderhash_ref};
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      my $form;
  </span>      my $activetab;
  </form>      my $active;
 SNEFORM      if($env{'form.active'} ne ''){
           $activetab = $env{'form.active'};
  my $supnewsylform=(<<SNSFORM);      }
  <form action="/adm/coursedocs" method="post" name="supnewsyl">      my $backicon = $iconpath.'clickhere.gif';
  <input type="hidden" name="folderpath" value="$path" />      my $backtext = &mt('To Overview');
  <input type="hidden" name="importdetail"      $form = '<div class="LC_Box" style="margin:0;">'.
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />               '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
  <span class="LC_nobreak">               '<li class="goback">'.
  <input name="newsyl" type="submit" value="$lt{'syll'}" />               '<a href="javascript:toContents('."'$jumpto'".');">'.
  $help{'Syllabus'}               '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
  </span>               '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n";
  </form>      if ($tid == 1) {
 SNSFORM          $form .= '<li>'.
                    '<a href="javascript:groupopen('."'$readfile'".',1);">'.
  my $supnewaboutmeform=(<<SNAMFORM);                   &mt('Undo Delete').'</a></li>'."\n";
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">          if ($env{'form.docslog'}) {
  <input type="hidden" name="folderpath" value="$path" />              $form .= '<li class="active">';
  <input type="hidden" name="importdetail"          } else {
  value="$plainname=/adm/$udom/$uname/aboutme" />              $form .= '<li>';
  <span class="LC_nobreak">          }
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />          $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
  $help{'My Personal Info'}                    &mt('History').'</a></li>'."\n";
  </span>          if ($env{'form.docslog'}) {
  </form>              $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
 SNAMFORM                    &mt('Edit').'</a></li>'."\n";
           }
    $r->print(<<ENDSUPFORM);      }
 <ul class="LC_TabContent">      foreach my $name (reverse(sort(keys(%orderhash)))) {
 <li>$lt{'nd'}</li>          if($name ne '00'){
 <li>$lt{'sd'}</li>              if($activetab eq '' || $activetab ne $name){
 <li>$lt{'hao'}</li>                 $active = '';
 </ul>              }elsif($activetab eq $name){
 <table class="LC_docs_adddocs">                 $active = 'class="active"';
 <tr><td>              }
 $supupdocform              $form .= '<li style="float:right" '.$active
 </td>                  .' onmouseover="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"'
 <td>                  .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
 $supnewfolderform          } else {
 <br />      $form .= '<li '.$active.' style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
 $supnewextform  
 <br />   }
 $supnewsylform      }
 <br />      $form .= '</ul>'."\n";
 $supnewaboutmeform      $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
 </td></tr>  
 </table></td></tr>      if ($to_show ne '') {
 ENDSUPFORM          $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'."\n";
        }      }
     }      foreach my $field (keys(%orderhash)){
     $r->print('</table>');   if($field ne '00'){
     if ($allowed) {              if($activetab eq '' || $activetab ne $field){
  $r->print('                  $active = 'style="display: none;float:left"';
 <form method="post" name="extimport" action="/adm/coursedocs">              }elsif($activetab eq $field){
   <input type="hidden" name="title" />                  $active = 'style="display:block;float:left"';
   <input type="hidden" name="url" />              }
   <input type="hidden" name="useform" />              $form .= '<div id="'.$field.$tid.'"'
   <input type="hidden" name="residx" />                      .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
 </form>');                      .'</div>'."\n";
     }          }
   } else {      }
       unless ($upload_result eq 'phasetwo') {      unless ($env{'form.docslog'}) {
 # -------------------------------------------------------- This is showdoc mode          $form .= '</div></div>'."\n";
           $r->print("<h1>".&mt('Uploaded Document').' - '.      }
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.      return $form;
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".  }
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');  
       }  sub editing_js {
   }      my ($udom,$uname,$supplementalflag) = @_;
  }      my $now = time();
  $r->print(&Apache::loncommon::end_page());      my %lt = &Apache::lonlocal::texthash(
  return OK;                                            p_mnf => 'Name of New Folder',
 }                                            t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
                                             t_mnp => 'New Page',
 sub editing_js {                                            p_mxu => 'Title for the External Score',
     my ($udom,$uname) = @_;                                            p_msp => 'Name of Simple Course Page',
     my $now = time();                                            p_msb => 'Title for the Problem',
     my %lt = &Apache::lonlocal::texthash(                                            p_mdb => 'Title for the Drop Box',
                                           p_mnf => 'Name of New Folder',                                            p_mbb => 'Title for the Discussion Board',
                                           t_mnf => 'New Folder',                                            p_mab => "Enter user:domain for User's Personal Information Page",
                                           p_mnp => 'Name of New Page',                                            p_mab2 => 'Personal Information Page of ',
                                           t_mnp => 'New Page',                                            p_mab_alrt1 => 'Not a valid user:domain',
                                           p_mxu => 'Title for the Uploaded Score',                                            p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                           p_msp => 'Title for the Page',                                            p_chn => 'New Title',
                                           p_msb => 'Title for the Problem',                                            p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
                                           p_mdb => 'Title for the Drop Box',                                            p_rmr2a => 'Remove[_99]',
                                           p_mbb => 'Title for the Bulletin Board',                                            p_rmr2b => '?[_99]',
                                           p_mab => "Enter user:domain for User's 'About Me' Page",                                            p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                           p_mab2 => "About [_99]",                                            p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                           p_mab_alrt1 => 'Not a valid user:domain',                                            p_ctr2a => 'Cut[_98]',
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',                                            p_ctr2b => '?[_98]',
                                           p_chn => 'New Title',                                            rpck    => 'Enter number to pick (e.g., 3)',
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',                                          );
                                           p_rmr2a => 'Remove[_99]',  
                                           p_rmr2b => '?[_99]',      my $crstype = &Apache::loncommon::course_type();
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',      my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',      my $docs_pagepath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.pagepath'},'<>&"');
                                           p_ctr2a => 'Cut[_98]',      my $main_container_page;
                                           p_ctr2b => '?[_98]'      if ($docs_folderpath eq '') {
                                         );          if ($docs_pagepath ne '') {
               $main_container_page = 1;
     return <<ENDNEWSCRIPT;          }
 function makenewfolder(targetform,folderseq) {      }
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');      my $toplevelmain = 'default&Main%20'.$crstype.'%20Documents';
     if (foldername) {      my $toplevelsupp = &supplemental_base();
        targetform.importdetail.value=escape(foldername)+"="+folderseq;  
         targetform.submit();      my $backtourl = '/adm/navmaps';
     }      if ($supplementalflag) {
 }          $backtourl = '/adm/supplemental';
       }
 function makenewpage(targetform,folderseq) {  
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');      return <<ENDNEWSCRIPT;
     if (pagename) {  function makenewfolder(targetform,folderseq) {
         targetform.importdetail.value=escape(pagename)+"="+folderseq;      var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
         targetform.submit();      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='';  function makenewpage(targetform,folderseq) {
     this.document.forms.extimport.url.value='';      var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
     this.document.forms.extimport.residx.value='';      if (pagename) {
     window.open('/adm/rat/extpickframe.html');          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;  function makenewext(targetname) {
     this.document.forms.extimport.url.value=url;      this.document.forms.extimport.useform.value=targetname;
     this.document.forms.extimport.title.value=title;      this.document.forms.extimport.title.value='';
     window.open('/adm/rat/extpickframe.html');      this.document.forms.extimport.url.value='';
 }      this.document.forms.extimport.residx.value='';
       window.open('/adm/rat/extpickframe.html');
 function makeexamupload() {  }
    var title=prompt('$lt{"p_mxu"}');  
    if (title) {  function edittext(targetname,residx,title,url) {
     this.document.forms.newexamupload.importdetail.value=      this.document.forms.extimport.useform.value=targetname;
  escape(title)+'=/res/lib/templates/examupload.problem';      this.document.forms.extimport.residx.value=residx;
     this.document.forms.newexamupload.submit();      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"}');  function makeexamupload() {
    if (title) {     var title=prompt('$lt{"p_mxu"}');
     this.document.forms.newsmppg.importdetail.value=     if (title) {
  escape(title)+'=/adm/$udom/$uname/$now/smppg';      this.document.forms.newexamupload.importdetail.value=
     this.document.forms.newsmppg.submit();   escape(title)+'=/res/lib/templates/examupload.problem';
    }      this.document.forms.newexamupload.submit();
 }     }
   }
 function makesmpproblem() {  
    var title=prompt('$lt{"p_msb"}');  function makesmppage() {
    if (title) {     var title=prompt('$lt{"p_msp"}');
     this.document.forms.newsmpproblem.importdetail.value=     if (title) {
  escape(title)+'=/res/lib/templates/simpleproblem.problem';      this.document.forms.newsmppg.importdetail.value=
     this.document.forms.newsmpproblem.submit();   escape(title)+'=/adm/$udom/$uname/$now/smppg';
    }      this.document.forms.newsmppg.submit();
 }     }
   }
 function makedropbox() {  
    var title=prompt('$lt{"p_mdb"}');  function makesmpproblem() {
    if (title) {     var title=prompt('$lt{"p_msb"}');
     this.document.forms.newdropbox.importdetail.value=     if (title) {
         escape(title)+'=/res/lib/templates/DropBox.problem';      this.document.forms.newsmpproblem.importdetail.value=
     this.document.forms.newdropbox.submit();   escape(title)+'=/res/lib/templates/simpleproblem.problem';
    }      this.document.forms.newsmpproblem.submit();
 }     }
   }
 function makebulboard() {  
    var title=prompt('$lt{"p_mbb"}');  function makedropbox() {
    if (title) {     var title=prompt('$lt{"p_mdb"}');
     this.document.forms.newbul.importdetail.value=     if (title) {
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';      this.document.forms.newdropbox.importdetail.value=
     this.document.forms.newbul.submit();          escape(title)+'=/res/lib/templates/DropBox.problem';
    }      this.document.forms.newdropbox.submit();
 }     }
   }
 function makeabout() {  
    var user=prompt("$lt{'p_mab'}");  function makebulboard() {
    if (user) {     var title=prompt('$lt{"p_mbb"}');
        var comp=new Array();     if (title) {
        comp=user.split(':');      this.document.forms.newbul.importdetail.value=
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {   escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
    if ((comp[0]) && (comp[1])) {      this.document.forms.newbul.submit();
        this.document.forms.newaboutsomeone.importdetail.value=     }
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';  }
        this.document.forms.newaboutsomeone.submit();  
    } else {  function makeabout() {
                alert("$lt{'p_mab_alrt1'}");     var user=prompt("$lt{'p_mab'}");
            }     if (user) {
        } else {         var comp=new Array();
            alert("$lt{'p_mab_alrt2'}");         comp=user.split(':');
        }         if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
    }     if ((comp[0]) && (comp[1])) {
 }         this.document.forms.newaboutsomeone.importdetail.value=
      '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
 function makeims() {         this.document.forms.newaboutsomeone.submit();
     var caller = document.forms.ims.folder.value;     } else {
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";         alert("$lt{'p_mab_alrt1'}");
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");     }
     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;  function makeims() {
     var form=this.document.forms.extimport.useform.value;  var caller = document.forms.ims.folder.value;
     var residx=this.document.forms.extimport.residx.value;  var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');  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);  function finishpick() {
     if (title) {  var title=this.document.forms.extimport.title.value;
  this.document.forms.renameform.markcopy.value=-1;  var url=this.document.forms.extimport.url.value;
  this.document.forms.renameform.title.value=title;  var form=this.document.forms.extimport.useform.value;
  this.document.forms.renameform.cmd.value='rename_'+index;  var residx=this.document.forms.extimport.residx.value;
         if (container == 'sequence') {  eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');
     this.document.forms.renameform.folderpath.value=folderpath;  }
         }  
         if (container == 'page') {  function changename(folderpath,index,oldtitle,container,pagesymb) {
             this.document.forms.renameform.pagepath.value=folderpath;  var title=prompt('$lt{"p_chn"}',oldtitle);
             this.document.forms.renameform.pagesymb.value=pagesymb;  if (title) {
         }  this.document.forms.renameform.markcopy.value=-1;
         this.document.forms.renameform.submit();  this.document.forms.renameform.title.value=title;
     }  this.document.forms.renameform.cmd.value='rename_'+index;
 }  if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {  }
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {  if (container == 'page') {
  this.document.forms.renameform.markcopy.value=-1;      this.document.forms.renameform.pagepath.value=folderpath;
  this.document.forms.renameform.cmd.value='del_'+index;      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 removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {
         }  if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
         this.document.forms.renameform.submit();  this.document.forms.renameform.markcopy.value=-1;
     }  this.document.forms.renameform.cmd.value='del_'+index;
 }  if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
 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"}')) {  if (container == 'page') {
  this.document.forms.renameform.cmd.value='cut_'+index;      this.document.forms.renameform.pagepath.value=folderpath;
  this.document.forms.renameform.markcopy.value=index;      this.document.forms.renameform.pagesymb.value=pagesymb;
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;  }
         if (container == 'sequence') {  this.document.forms.renameform.submit();
             this.document.forms.renameform.folderpath.value=folderpath;  }
         }  }
         if (container == 'page') {  
             this.document.forms.renameform.pagepath.value=folderpath;  function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {
             this.document.forms.renameform.pagesymb.value=pagesymb;  if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
         }  this.document.forms.renameform.cmd.value='cut_'+index;
         this.document.forms.renameform.submit();  this.document.forms.renameform.markcopy.value=index;
     }  this.document.forms.renameform.copyfolder.value=folder+'.'+container;
 }  if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {  }
     this.document.forms.renameform.markcopy.value=index;  if (container == 'page') {
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;      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 markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
     this.document.forms.renameform.submit();  this.document.forms.renameform.markcopy.value=index;
 }  this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   if (container == 'sequence') {
   this.document.forms.renameform.folderpath.value=folderpath;
 ENDNEWSCRIPT  }
 }  if (container == 'page') {
 1;  this.document.forms.renameform.pagepath.value=folderpath;
 __END__  this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
 =head1 NAME  }
   
 Apache::londocs.pm  function updatePick(targetform,index,caller) {
       var pickitem = document.getElementById('rpick_'+index);
 =head1 SYNOPSIS      var picknumitem = document.getElementById('rpicknum_'+index);
       if (pickitem.checked) {
 This is part of the LearningOnline Network with CAPA project          var picknum=prompt('$lt{"rpck"}',picknumitem.value);
 described at http://www.lon-capa.org.          if (picknum == '' || picknum == null) {
               if (caller == 'check') {
 =head1 SUBROUTINES                  pickitem.checked=false;
                   return;
 =over              }
           } else {
 =item %help=()              picknum.toString();
               var regexdigit=/^\\d+\$/;
 Available help topics              if (regexdigit.test(picknum)) {
                   picknumitem.value = picknum;
 =item mapread()                  targetform.changeparms.value='randompick';
                   targetform.submit();
 Mapread read maps into LONCAPA::map:: global arrays              } else {
 @order and @resources, determines status                  if (caller == 'check') {
 sets @order - pointer to resources in right order                      pickitem.checked=false;
 sets @resources - array with the resources with correct idx                  }
                   return;
 =item authorhosts()              }
           }
 Return hash with valid author names      } else {
           picknumitem.value = 0;
 =item dumpbutton()          targetform.changeparms.value='randompick';
           targetform.submit();
 Generate "dump" button      }
   }
 =item clean()  
   function unselectInactive(nav) {
 =item dumpcourse()  currentNav = document.getElementById(nav);
   currentLis = currentNav.getElementsByTagName('LI');
     Actually dump course  for (i = 0; i < currentLis.length; i++) {
           if (currentLis[i].className == 'goback') {
               currentLis[i].className = 'goback';
 =item exportbutton()          } else {
       if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
     Generate "export" button   currentLis[i].className = 'right';
       } else {
 =item exportcourse()   currentLis[i].className = 'i';
       }
 =item create_ims_store()          }
   }
 =item build_package()  }
   
 =item get_dependencies()  function hideAll(current, nav, data) {
   unselectInactive(nav);
 =item process_content()  if(current.className == 'right'){
    current.className = 'right active'
 =item replicate_content()   }else{
    current.className = 'active';
 =item extract_media()  }
   currentData = document.getElementById(data);
 =item store_template()  currentDivs = currentData.getElementsByTagName('DIV');
   for (i = 0; i < currentDivs.length; i++) {
 =item group_import()   if(currentDivs[i].className == 'LC_ContentBox'){
    currentDivs[i].style.display = 'none';
     Imports the given (name, url) resources into the course   }
     coursenum, coursedom, and folder must precede the list  }
   }
 =item breadcrumbs()  
   function openTabs(pageId) {
 =item log_docs()   tabnav = document.getElementById(pageId).getElementsByTagName('UL');
    if(tabnav.length > 2 ){
 =item docs_change_log()   currentNav = document.getElementById(tabnav[1].id);
    currentLis = currentNav.getElementsByTagName('LI');
 =item update_paste_buffer()   for(i = 0; i< currentLis.length; i++){
    if(currentLis[i].className == 'active') {
 =item print_paste_buffer()   funcString = currentLis[i].onclick.toString();
    tab = funcString.split('"');
 =item do_paste_from_buffer()                                  if(tab.length < 2) {
                                      tab = funcString.split("'");
 =item update_parameter()                                  }
    currentData = document.getElementById(tab[1]);
 =item handle_edit_cmd()          currentData.style.display = 'block';
    }
 =item editor()   }
    }
 =item process_file_upload()  }
   
 =item process_secondary_uploads()  function showPage(current, pageId, nav, data) {
    hideAll(current, nav, data);
 =item is_supplemental_title()   openTabs(pageId);
    unselectInactive(nav);
 =item parse_supplemental_title()   current.className = 'active';
    currentData = document.getElementById(pageId);
 =item entryline()   currentData.style.display = 'block';
           activeTab = pageId;
 =item tiehash()          if (nav == 'mainnav') {
               var storedpath = "$docs_folderpath";
 =item untiehash()              if (storedpath == '') {
                   storedpath = "$docs_pagepath";
 =item checkonthis()              }
               var storedpage = "$main_container_page";
 check on this              var reg = new RegExp("^supplemental");
               if (pageId == 'mainCourseDocuments') {
 =item verifycontent()                  if (storedpage == 1) {
                       document.simpleedit.folderpath.value = '';
 Verify Content                      document.uploaddocument.folderpath.value = '';
                   } else {
 =item devalidateversioncache() & checkversions()                      if (reg.test(storedpath)) {
                           document.simpleedit.folderpath.value = '$toplevelmain';
 Check Versions                          document.uploaddocument.folderpath.value = '$toplevelmain';
                           document.newext.folderpath.value = '$toplevelmain';
 =item mark_hash_old()                      } else {
                           document.simpleedit.folderpath.value = storedpath;
 =item is_hash_old()                          document.uploaddocument.folderpath.value = storedpath;
                           document.newext.folderpath.value = storedpath;
 =item changewarning()                      }
                   }
 =item init_breadcrumbs()              } else {
                   if (reg.test(storedpath)) {
 Breadcrumbs for special functions                      document.simpleedit.folderpath.value = storedpath;
                       document.supuploaddocument.folderpath.value = storedpath;
 =back                      document.supnewext.folderpath.value = storedpath;
                   } else {
 =cut                      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.2.1


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