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

version 1.242, 2006/07/20 20:42:48 version 1.326, 2009/01/28 11:51:22
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;  
   
 use strict;  package Apache::londocs;
 use Apache::Constants qw(:common :http);  
 use Apache::imsexport;  use strict;
 use Apache::lonnet;  use Apache::Constants qw(:common :http);
 use Apache::loncommon;  use Apache::imsexport;
 use Apache::lonratedt;  use Apache::lonnet;
 use Apache::lonratsrv;  use Apache::loncommon;
 use Apache::lonxml;  use LONCAPA::map();
 use Apache::loncreatecourse;  use Apache::lonratedt();
 use Apache::lonnavmaps;  use Apache::lonxml;
 use HTML::Entities;  use Apache::lonclonecourse;
 use GDBM_File;  use Apache::lonnavmaps;
 use Apache::lonlocal;  use HTML::Entities;
 use Cwd;  use GDBM_File;
 use lib '/home/httpd/lib/perl/';  use Apache::lonlocal;
 use LONCAPA;  use Cwd;
   use LONCAPA qw(:DEFAULT :match);
 my $iconpath;  
   my $iconpath;
 my %hash;  
   my %hash;
 my $hashtied;  
 my %alreadyseen=();  my $hashtied;
   my %alreadyseen=();
 my $hadchanges;  
   my $hadchanges;
 # Available help topics  
   
 my %help=();  my %help=();
   
 # Mapread read maps into lonratedt::global arrays   
 # @order and @resources, determines status  sub mapread {
 # sets @order - pointer to resources in right order      my ($coursenum,$coursedom,$map)=@_;
 # sets @resources - array with the resources with correct idx      return
 #        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
        $map);
 sub mapread {  }
     my ($coursenum,$coursedom,$map)=@_;  
     return  sub storemap {
       &Apache::lonratedt::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map)=@_;
                                 $map);      my ($outtext,$errtext)=
 }        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1);
 sub storemap {      if ($errtext) { return ($errtext,2); }
     my ($coursenum,$coursedom,$map)=@_;     
     my ($outtext,$errtext)=      $hadchanges=1;
       &Apache::lonratedt::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      return ($errtext,0);
                                 $map,1);  }
     if ($errtext) { return ($errtext,2); }  
       
     $hadchanges=1;  
     return ($errtext,0);  sub authorhosts {
 }      my %outhash=();
       my $home=0;
 # ----------------------------------------- Return hash with valid author names      my $other=0;
       foreach my $key (keys(%env)) {
 sub authorhosts {   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     my %outhash=();      my $role=$1;
     my $home=0;      my $realm=$2;
     my $other=0;      my ($start,$end)=split(/\./,$env{$key});
     foreach (keys %env) {      if (($start) && ($start>time)) { next; }
  if ($_=~/^user\.role\.(au|ca)\.(.+)$/) {      if (($end) && (time>$end)) { next; }
     my $role=$1;      my ($ca,$cd);
     my $realm=$2;      if ($1 eq 'au') {
     my ($start,$end)=split(/\./,$env{$_});   $ca=$env{'user.name'};
     if (($start) && ($start>time)) { next; }   $cd=$env{'user.domain'};
     if (($end) && (time>$end)) { next; }      } else {
     my $ca; my $cd;   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
     if ($1 eq 'au') {      }
  $ca=$env{'user.name'};      my $allowed=0;
  $cd=$env{'user.domain'};      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
     } else {      my @ids=&Apache::lonnet::current_machine_ids();
  ($cd,$ca)=($realm=~/^\/(\w+)\/(\w+)$/);      foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }
     }      if ($allowed) {
     my $allowed=0;   $home++;
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);   $outhash{'home_'.$ca.'@'.$cd}=1;
     my @ids=&Apache::lonnet::current_machine_ids();      } else {
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }   $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;
     if ($allowed) {   $other++;
  $home++;      }
  $outhash{'home_'.$ca.'@'.$cd}=1;   }
     } else {      }
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      return ($home,$other,%outhash);
  $other++;  }
     }  
  }  
     }  sub dumpbutton {
     return ($home,$other,%outhash);      my ($home,$other,%outhash)=&authorhosts();
 }      my $type = &Apache::loncommon::course_type();
 # ------------------------------------------------------ Generate "dump" button      if ($home+$other==0) { return ''; }
       if ($home) {
 sub dumpbutton {   return '<div>'.
     my ($home,$other,%outhash)=&authorhosts();      '<input type="submit" name="dumpcourse" value="'.
     my $type = &Apache::loncommon::course_type();      &mt('Dump '.$type.' DOCS to Construction Space').'" />'.
     if ($home+$other==0) { return ''; }      &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs').
     my $output='</td><td bgcolor="#DDDDCC">';      '</div>';
     if ($home) {      } else {
  return '</td><td bgcolor="#DDDDCC">'.   return '<div>'.
     '<input type="submit" name="dumpcourse" value="'.       &mt('Dump '.$type.
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.   ' DOCS to Construction Space: available on other servers').
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');   '</div>';
     } else {      }
  return'</td><td bgcolor="#DDDDCC">'.  }
      &mt('Dump '.$type.  
  ' DOCS to Construction Space: available on other servers');  sub clean {
     }      my ($title)=@_;
 }      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
       return $title;
 sub clean {  }
     my ($title)=@_;  
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;  
     return $title;  
 }  sub dumpcourse {
 # -------------------------------------------------------- Actually dump course      my ($r) = @_;
       my $type = &Apache::loncommon::course_type();
 sub dumpcourse {      $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').
     my ($r) = @_;        '<form name="dumpdoc" method="post">');
     my $type = &Apache::loncommon::course_type();      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').      my ($home,$other,%outhash)=&authorhosts();
       '<form name="dumpdoc" method="post">');      unless ($home) { return ''; }
     my ($home,$other,%outhash)=&authorhosts();      my $origcrsid=$env{'request.course.id'};
     unless ($home) { return ''; }      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my $origcrsid=$env{'request.course.id'};      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);  # Do the dumping
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {   unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }
 # Do the dumping   my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});   my $title=$env{'form.authorfolder'};
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   $title=&clean($title);
  my $title=$env{'form.authorfolder'};   my %replacehash=();
  $title=&clean($title);   foreach my $key (keys(%env)) {
  my %replacehash=();      if ($key=~/^form\.namefor\_(.+)/) {
  foreach (keys %env) {   $replacehash{$1}=$env{$key};
     if ($_=~/^form\.namefor\_(.+)/) {      }
  $replacehash{$1}=$env{$_};   }
     }   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  }   $crs=~s/\_/\//g;
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   foreach my $item (keys(%replacehash)) {
  $crs=~s/\_/\//g;      my $newfilename=$title.'/'.$replacehash{$item};
  foreach (keys %replacehash) {      $newfilename=~s/\.(\w+)$//;
     my $newfilename=$title.'/'.$replacehash{$_};      my $ext=$1;
     $newfilename=~s/\.(\w+)$//;      $newfilename=&clean($newfilename);
     my $ext=$1;      $newfilename.='.'.$ext;
     $newfilename=&clean($newfilename);      my @dirs=split(/\//,$newfilename);
     $newfilename.='.'.$ext;      my $path='/home/'.$ca.'/public_html';
     my @dirs=split(/\//,$newfilename);      my $makepath=$path;
     my $path='/home/'.$ca.'/public_html';      my $fail=0;
     my $makepath=$path;      for (my $i=0;$i<$#dirs;$i++) {
     my $fail=0;   $makepath.='/'.$dirs[$i];
     for (my $i=0;$i<$#dirs;$i++) {   unless (-e $makepath) {
  $makepath.='/'.$dirs[$i];      unless(mkdir($makepath,0777)) { $fail=1; }
  unless (-e $makepath) {    }
     unless(mkdir($makepath,0777)) { $fail=1; }       }
  }      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
     }      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     $r->print('<br /><tt>'.$_.'</tt> => <tt>'.$newfilename.'</tt>: ');   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {      print $fh &Apache::lonclonecourse::rewritefile(
  if ($_=~/\.(sequence|page|html|htm|xml|xhtml)$/) {           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
     print $fh &Apache::loncreatecourse::rewritefile(       (%replacehash,$crs => '')
          &Apache::loncreatecourse::readfile($env{'request.course.id'},$_),      );
      (%replacehash,$crs => '')   } else {
     );      print $fh
  } else {           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
     print $fh         }
          &Apache::loncreatecourse::readfile($env{'request.course.id'},$_);   $fh->close();
        }      } else {
  $fh->close();   $fail=1;
     } else {      }
  $fail=1;      if ($fail) {
     }   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
     if ($fail) {      } else {
  $r->print('<font color="red">fail</font>');   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     } else {      }
  $r->print('<font color="green">ok</font>');   }
     }      } else {
  }  # Input form
     } else {   unless ($home==1) {
 # Input form      $r->print(
  unless ($home==1) {        '<h3>'.&mt('Select the Construction Space').'</h3><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 (sort keys %outhash) {   if ($home==1) {
     if ($_=~/^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>');
  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('<h3>'.&mt('Folder in Construction Space').'</h3>'
  $title=&clean($title);                   .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3><input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');   &tiehash();
  &tiehash();   $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3><table border="2"><tr><th>'.&mt('Internal Filename').'</th><th>'.&mt('Title').'</th><th>'.&mt('Save as ...').'</th></tr>');                   .&Apache::loncommon::start_data_table()
  foreach (&Apache::loncreatecourse::crsdirlist($origcrsid,'userfiles')) {                   .&Apache::loncommon::start_data_table_header_row()
     $r->print('<tr><td>'.$_.'</td>');                   .'<th>'.&mt('Internal Filename').'</th>'
     my ($ext)=($_=~/\.(\w+)$/);                   .'<th>'.&mt('Title').'</th>'
     my $title=$hash{'title_'.$hash{                   .'<th>'.&mt('Save as ...').'</th>'
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$_}};                   .&Apache::loncommon::end_data_table_header_row());
     $title=~s/&colon;/:/g;   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');      $r->print(&Apache::loncommon::start_data_table_row()
     if (!$title) {                       .'<td>'.$file.'</td>');
  $title=$_;      my ($ext)=($file=~/\.(\w+)$/);
     } else {      my $title=$hash{'title_'.$hash{
  $title=~s|/|_|g;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     }      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
     $title=~s/\.(\w+)$//;      if (!$title) {
     $title=&clean($title);   $title=$file;
     $title.='.'.$ext;      } else {
     $r->print("\n<td><input type='text' size='60' name='namefor_".$_."' value='".$title."' /></td></tr>\n");   $title=~s|/|_|g;
  }      }
  $r->print("</table>\n");      $title=~s/\.(\w+)$//;
  &untiehash();      $title=&clean($title);
  $r->print(      $title.='.'.$ext;
   '<p><input type="submit" name="dumpcourse" value="'.&mt('Dump [_1] DOCS',$type).'" /></p></form>');      $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());
 # ------------------------------------------------------ Generate "export" button   &untiehash();
    $r->print(
 sub exportbutton {    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');
     my $type = &Apache::loncommon::course_type();      }
     return '</td><td bgcolor="#DDDDCC">'.  }
             '<input type="submit" name="exportcourse" value="'.  
             &mt('Export '.$type.' to IMS').'" />'.  
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');  
 }  sub exportbutton {
       my $type = &Apache::loncommon::course_type();
 sub exportcourse {      return '<div>'.
     my $r=shift;              '<input type="submit" name="exportcourse" value="'.
     my $type = &Apache::loncommon::course_type();              &mt('Export '.$type.' to IMS').'" />'.
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',      &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs').'</div>';
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});  }
     my $numdisc = keys %discussiontime;  
     my $navmap = Apache::lonnavmaps::navmap->new();  
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);  
     my $curRes;  sub exportcourse {
     my $outcome;      my $r=shift;
       my $type = &Apache::loncommon::course_type();
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      my %discussiontime = &Apache::lonnet::dump('discussiontimes',
                                             ['finishexport']);                                                 $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});
     if ($env{'form.finishexport'}) {      my $numdisc = keys(%discussiontime);
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      my $navmap = Apache::lonnavmaps::navmap->new();
                                             ['archive','discussion']);      if (!defined($navmap)) {
           $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');                    '<h2>IMS Export Failed</h2>'.
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');                    '<div class="LC_error">'.
         if (@exportitems == 0 && @discussions == 0) {                    &mt('Unable to retrieve information about course contents').
             $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';                    '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');
         } else {          &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
             my $now = time;          return;
             my %symbs;      }
             my $manifestok = 0;      my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);
             my $imsresources;      my $curRes;
             my $tempexport;      my $outcome;
             my $copyresult;  
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
             if ($manifestok) {                                              ['finishexport']);
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);      if ($env{'form.finishexport'}) {
                 close($ims_manifest);          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                               ['archive','discussion']);
 #Create zip file in prtspool  
                 my $imszipfile = '/prtspool/'.          my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.          my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');
                    time.'_'.rand(1000000000).'.zip';          if (@exportitems == 0 && @discussions == 0) {
                 my $cwd = &Cwd::getcwd();              $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';
                 my $imszip = '/home/httpd/'.$imszipfile;          } else {
                 chdir $tempexport;              my $now = time;
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");              my %symbs;
                 close(OUTPUT);              my $manifestok = 0;
                 chdir $cwd;              my $imsresources;
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);              my $tempexport;
                 if ($copyresult) {              my $copyresult;
                     $outcome .= 'The following errors occurred during export - '.$copyresult;              my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);
                 }              if ($manifestok) {
             } else {                  &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);
                 $outcome = '<br />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 />';                  close($ims_manifest);
             }  
         }  #Create zip file in prtspool
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));                  my $imszipfile = '/prtspool/'.
         $r->print($outcome);                  $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
         $r->print(&Apache::loncommon::end_page());                     time.'_'.rand(1000000000).'.zip';
     } else {                  my $cwd = &Cwd::getcwd();
         my $display;                  my $imszip = '/home/httpd/'.$imszipfile;
         $display = '<form name="exportdoc" method="post">'."\n";                  chdir $tempexport;
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');                  open(OUTPUT, "zip -r $imszip *  2> /dev/null |");
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                  close(OUTPUT);
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.                  chdir $cwd;
                     '<input type="button" value="check all" '.                  $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.                  if ($copyresult) {
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.                      $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.                  }
                     '<td>&nbsp;</td><td>&nbsp;</td>'.              } else {
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.                  $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 />';
                     '</b></legend><input type="button" value="check all"'.              }
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.          }
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.          $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.   $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));
                     '</tr></table>';          $r->print($outcome);
         my $curRes;          $r->print(&Apache::loncommon::end_page());
         my $depth = 0;      } else {
         my $count = 0;          my $display;
         my $boards = 0;          $display = '<form name="exportdoc" method="post">'."\n";
         my $startcount = 5;          $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');
         my %parent = ();          $display .= '<table border="0" cellspacing="0" cellpadding="3">'.
         my %children = ();                      '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.
         my $lastcontainer = $startcount;                      '<input type="button" value="check all" '.
         my @bgcolors = ('#F6F6F6','#FFFFFF');                      'onclick="javascript:checkAll(document.exportdoc.archive)" />'.
         $display .= '<table cellspacing="0"><tr>'.                      '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";                      ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.
         if ($numdisc > 0) {                      '<td>&nbsp;</td><td>&nbsp;</td>'.
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";                      '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.
         }                      '</b></legend><input type="button" value="check all"'.
         $display.='&nbsp;</td></tr>';                      ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.
         while ($curRes = $it->next()) {                      '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
             if (ref($curRes)) {                      ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.
                 $count ++;                      '</tr></table>';
             }          my $curRes;
             if ($curRes == $it->BEGIN_MAP()) {          my $depth = 0;
                 $depth++;          my $count = 0;
                 $parent{$depth} = $lastcontainer;          my $boards = 0;
             }          my $startcount = 5;
             if ($curRes == $it->END_MAP()) {          my %parent = ();
                 $depth--;          my %children = ();
                 $lastcontainer = $parent{$depth};          my $lastcontainer = $startcount;
             }          my @bgcolors = ('#F6F6F6','#FFFFFF');
             if (ref($curRes)) {          $display .= '<table cellspacing="0"><tr>'.
                 my $symb = $curRes->symb();              '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";
                 my $ressymb = $symb;          if ($numdisc > 0) {
                 if ($ressymb =~ m|adm/(\w+)/(\w+)/(\d+)/bulletinboard$|) {              $display.='<b>Export&nbsp;discussion posts?</b>'."\n";
                     unless ($ressymb =~ m|adm/wrapper/adm|) {          }
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';          $display.='&nbsp;</td></tr>';
                     }          while ($curRes = $it->next()) {
                 }              if (ref($curRes)) {
                 my $color = $count%2;                  $count ++;
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".              }
                     '<input type="checkbox" name="archive" value="'.$count.'" ';              if ($curRes == $it->BEGIN_MAP()) {
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {                  $depth++;
                     my $checkitem = $count + $boards + $startcount;                  $parent{$depth} = $lastcontainer;
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';              }
                 }              if ($curRes == $it->END_MAP()) {
                 $display .= ' />'."\n";                  $depth--;
                 for (my $i=0; $i<$depth; $i++) {                  $lastcontainer = $parent{$depth};
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" width="25" height="1" alt="" border="0" /><img src="/adm/lonIcons/whitespace1.gif" width="25" height="1" alt="" border="0" />'."\n";              }
                 }              if (ref($curRes)) {
                 if ($curRes->is_sequence()) {                  my $symb = $curRes->symb();
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";                  my $ressymb = $symb;
                     $lastcontainer = $count + $startcount + $boards;                  if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
                 } elsif ($curRes->is_page()) {                      unless ($ressymb =~ m|adm/wrapper/adm|) {
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";                          $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
                     $lastcontainer = $count + $startcount + $boards;                      }
                 }                  }
                 my $currelem = $count+$boards+$startcount;                  my $color = $count%2;
                 $children{$parent{$depth}} .= $currelem.':';                  $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".
                 $display .= '&nbsp;'.$curRes->title().'</td>';                      '<input type="checkbox" name="archive" value="'.$count.'" ';
                 if ($discussiontime{$ressymb} > 0) {                  if (($curRes->is_sequence()) || ($curRes->is_page())) {
                     $boards ++;                      my $checkitem = $count + $boards + $startcount;
                     $currelem = $count+$boards+$startcount;                      $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";                  }
                 } else {                  $display .= ' />'."\n";
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";                  for (my $i=0; $i<$depth; $i++) {
                 }                      $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";
             }                  }
         }                  if ($curRes->is_sequence()) {
         my $scripttag = qq|                      $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";
 <script>                      $lastcontainer = $count + $startcount + $boards;
                   } elsif ($curRes->is_page()) {
 function checkAll(field) {                      $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";
     if (field.length > 0) {                      $lastcontainer = $count + $startcount + $boards;
         for (i = 0; i < field.length; i++) {                  }
             field[i].checked = true ;                  my $currelem = $count+$boards+$startcount;
         }                  $children{$parent{$depth}} .= $currelem.':';
     } else {                  $display .= '&nbsp;'.$curRes->title().'</td>';
         field.checked = true                  if ($discussiontime{$ressymb} > 0) {
     }                      $boards ++;
 }                      $currelem = $count+$boards+$startcount;
                                                                                                       $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";
 function uncheckAll(field) {                  } else {
     if (field.length > 0) {                      $display .= '<td colspan="2">&nbsp;</td>'."\n";
         for (i = 0; i < field.length; i++) {                  }
             field[i].checked = false ;              }
         }          }
     } else {          my $scripttag = qq|
         field.checked = false ;  <script>
     }  
 }  function checkAll(field) {
       if (field.length > 0) {
 function propagateCheck(item) {          for (i = 0; i < field.length; i++) {
     if (document.exportdoc.elements[item].checked == true) {              field[i].checked = true ;
         containerCheck(item)          }
     }      } else {
 }           field.checked = true
       }
 function containerCheck(item) {  }
     document.exportdoc.elements[item].checked = true                                                                                 
     var numitems = $count + $boards + $startcount  function uncheckAll(field) {
     var parents = new Array(numitems)      if (field.length > 0) {
     for (var i=$startcount; i<numitems; i++) {          for (i = 0; i < field.length; i++) {
         parents[i] = new Array              field[i].checked = false ;
     }          }
         |;      } else {
           field.checked = false ;
         foreach my $container (sort { $a <=> $b } keys %children) {      }
             my @contents = split/:/,$children{$container};  }
             for (my $i=0; $i<@contents; $i ++) {  
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";  function propagateCheck(item) {
             }      if (document.exportdoc.elements[item].checked == true) {
         }          containerCheck(item)
       }
         $scripttag .= qq|  }
     if (parents[item].length > 0) {  
         for (var j=0; j<parents[item].length; j++) {  function containerCheck(item) {
             containerCheck(parents[item][j])      document.exportdoc.elements[item].checked = true
         }      var numitems = $count + $boards + $startcount
      }         var parents = new Array(numitems)
 }      for (var i=$startcount; i<numitems; i++) {
           parents[i] = new Array
 </script>      }
         |;          |;
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',  
  $scripttag));          foreach my $container (sort { $a <=> $b } (keys(%children))) {
  $r->print($display.'</table>'.              my @contents = split(/:/,$children{$container});
                   '<p><input type="hidden" name="finishexport" value="1">'.              for (my $i=0; $i<@contents; $i ++) {
                   '<input type="submit" name="exportcourse" value="'.                  $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   &mt('Export '.$type.' DOCS').'" /></p></form>'.              }
   &Apache::loncommon::end_page());          }
     }  
 }          $scripttag .= qq|
       if (parents[item].length > 0) {
 sub create_ims_store {          for (var j=0; j<parents[item].length; j++) {
     my ($now,$manifestok,$outcome,$tempexport) = @_;              containerCheck(parents[item][j])
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';          }
     my $ims_manifest;       }  
     if (!-e $$tempexport) {  }
         mkdir($$tempexport,0700);  
     }  </script>
     $$tempexport .= '/'.$now;          |;
     if (!-e $$tempexport) {   $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',
         mkdir($$tempexport,0700);   $scripttag));
     }   $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};   $r->print($display.'</table>'.
     if (!-e $$tempexport) {                    '<p><input type="hidden" name="finishexport" value="1">'.
         mkdir($$tempexport,0700);                    '<input type="submit" name="exportcourse" value="'.
     }                    &mt('Export '.$type.' DOCS').'" /></p></form>');
     if (!-e "$$tempexport/resources") {      }
         mkdir("$$tempexport/resources",0700);  }
     }  
 # open manifest file  sub create_ims_store {
     my $manifest = '/imsmanifest.xml';      my ($now,$manifestok,$outcome,$tempexport) = @_;
     my $manifestfilename = $$tempexport.$manifest;      $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      my $ims_manifest;
         $$manifestok=1;      if (!-e $$tempexport) {
         print $ims_manifest          mkdir($$tempexport,0700);
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".      }
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.      $$tempexport .= '/'.$now;
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.      if (!-e $$tempexport) {
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.          mkdir($$tempexport,0700);
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.      }
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.      $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      if (!-e $$tempexport) {
 '  <metadata>          mkdir($$tempexport,0700);
     <schema></schema>      }
     <imsmd:lom>      if (!-e "$$tempexport/resources") {
       <imsmd:general>          mkdir("$$tempexport/resources",0700);
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>      }
         <imsmd:title>  # open manifest file
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>      my $manifest = '/imsmanifest.xml';
         </imsmd:title>      my $manifestfilename = $$tempexport.$manifest;
       </imsmd:general>      if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {
     </imsmd:lom>          $$manifestok=1;
   </metadata>'."\n".          print $ims_manifest
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".  '<?xml version="1.0" encoding="UTF-8"?>'."\n".
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.  '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.
 ' structure="hierarchical">'."\n".  ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'  ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.
     } else {  ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'  '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.
 ;  '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".
     }  '  <metadata>
     return $ims_manifest;      <schema></schema>
 }      <imsmd:lom>
         <imsmd:general>
 sub build_package {          <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;          <imsmd:title>
 # first iterator to look for dependencies            <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);          </imsmd:title>
     my $curRes;        </imsmd:general>
     my $count = 0;      </imsmd:lom>
     my $depth = 0;    </metadata>'."\n".
     my $lastcontainer = 0;  '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".
     my %parent = ();  '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.
     my @dependencies = ();  ' structure="hierarchical">'."\n".
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};  '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};      } else {
     while ($curRes = $it->next()) {          $$outcome .= 'An error occurred opening the IMS manifest file.<br />'
         if (ref($curRes)) {  ;
             $count ++;      }
         }      return $ims_manifest;
         if ($curRes == $it->BEGIN_MAP()) {  }
             $depth++;  
             $parent{$depth} = $lastcontainer;  sub build_package {
         }      my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;
         if ($curRes == $it->END_MAP()) {  # first iterator to look for dependencies
             $depth--;      my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
             $lastcontainer = $parent{$depth};      my $curRes;
         }      my $count = 0;
         if (ref($curRes)) {      my $depth = 0;
             if ($curRes->is_sequence() || $curRes->is_page()) {      my $lastcontainer = 0;
                 $lastcontainer = $count;      my %parent = ();
             }      my @dependencies = ();
             if (grep/^$count$/,@$exportitems) {      my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);      my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
             }      while ($curRes = $it->next()) {
         }          if (ref($curRes)) {
     }              $count ++;
 # second iterator to build manifest and store resources          }
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);          if ($curRes == $it->BEGIN_MAP()) {
     $depth = 0;              $depth++;
     my $prevdepth;              $parent{$depth} = $lastcontainer;
     $count = 0;          }
     my $imsresources;          if ($curRes == $it->END_MAP()) {
     my $pkgdepth;              $depth--;
     while ($curRes = $it->next()) {              $lastcontainer = $parent{$depth};
         if ($curRes == $it->BEGIN_MAP()) {          }
             $prevdepth = $depth;          if (ref($curRes)) {
             $depth++;              if ($curRes->is_sequence() || $curRes->is_page()) {
         }                  $lastcontainer = $count;
         if ($curRes == $it->END_MAP()) {              }
             $prevdepth = $depth;              if (grep(/^$count$/,@$exportitems)) {
             $depth--;                  &get_dependencies($exportitems,\%parent,$depth,\@dependencies);
         }              }
           }
         if (ref($curRes)) {      }
             $count ++;  # second iterator to build manifest and store resources
             if ((grep/^$count$/,@$exportitems) || (grep/^$count$/,@dependencies)) {      $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
                 my $symb = $curRes->symb();      $depth = 0;
                 my $isvisible = 'true';      my $prevdepth;
                 my $resourceref;      $count = 0;
                 if ($curRes->randomout()) {      my $imsresources;
                     $isvisible = 'false';      my $pkgdepth;
                 }      while ($curRes = $it->next()) {
                 unless ($curRes->is_sequence()) {          if ($curRes == $it->BEGIN_MAP()) {
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';              $prevdepth = $depth;
                 }              $depth++;
                 my $step = $prevdepth - $depth;          }
                 if (($step >= 0) && ($count > 1)) {          if ($curRes == $it->END_MAP()) {
                     while ($step >= 0) {              $prevdepth = $depth;
                         print $ims_manifest "\n".'  </item>'."\n";              $depth--;
                         $step --;          }
                     }  
                 }          if (ref($curRes)) {
                 $prevdepth = $depth;              $count ++;
               if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {
                 my $itementry =                  my $symb = $curRes->symb();
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.                  my $isvisible = 'true';
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.                  my $resourceref;
               '<title>'.$curRes->title().'</title>';                  if ($curRes->randomout()) {
                 print $ims_manifest "\n".$itementry;                      $isvisible = 'false';
                   }
                 unless ($curRes->is_sequence()) {                  unless ($curRes->is_sequence()) {
                     my $content_file;                      $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';
                     my @hrefs = ();                  }
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);                  my $step = $prevdepth - $depth;
                     if ($content_file) {                  if (($step >= 0) && ($count > 1)) {
                         $imsresources .= "\n".                      while ($step >= 0) {
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.                          print $ims_manifest "\n".'  </item>'."\n";
                      '" type="webcontent" href="'.$content_file.'">'."\n".                          $step --;
                      '       <file href="'.$content_file.'" />'."\n";                      }
                         foreach (@hrefs) {                  }
                             $imsresources .=                  $prevdepth = $depth;
                      '        <file href="'.$_.'" />'."\n";  
                         }                  my $itementry =
                         if (grep/^$count$/,@$discussions) {                '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.
                             my $ressymb = $symb;                '" isvisible="'.$isvisible.'" '.$resourceref.'>'.
                             my $mode;                '<title>'.$curRes->title().'</title>';
                             if ($ressymb =~ m|adm/(\w+)/(\w+)/(\d+)/bulletinboard$|) {                  print $ims_manifest "\n".$itementry;
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {  
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';                  unless ($curRes->is_sequence()) {
                                 }                      my $content_file;
                                 $mode = 'board';                      my @hrefs = ();
                             }                      &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);
                             my %extras = (                      if ($content_file) {
                                           caller => 'imsexport',                          $imsresources .= "\n".
                                           tempexport => $tempexport.'/resources',                       '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.
                                           count => $count                       '" type="webcontent" href="'.$content_file.'">'."\n".
                                          );                       '       <file href="'.$content_file.'" />'."\n";
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);                          foreach my $item (@hrefs) {
                         }                              $imsresources .=
                         $imsresources .= '    </resource>'."\n";                       '        <file href="'.$item.'" />'."\n";
                     }                          }
                 }                          if (grep(/^$count$/,@$discussions)) {
                 $pkgdepth = $depth;                              my $ressymb = $symb;
             }                              my $mode;
         }                              if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
     }                                  unless ($ressymb =~ m|adm/wrapper/adm|) {
     while ($pkgdepth > 0) {                                      $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
         print $ims_manifest "    </item>\n";                                  }
         $pkgdepth --;                                  $mode = 'board';
     }                              }
     my $resource_text = qq|                              my %extras = (
     </organization>                                            caller => 'imsexport',
   </organizations>                                            tempexport => $tempexport.'/resources',
   <resources>                                            count => $count
     $imsresources                                           );
   </resources>                              my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);
 </manifest>                          }
     |;                          $imsresources .= '    </resource>'."\n";
     print $ims_manifest $resource_text;                      }
 }                  }
                   $pkgdepth = $depth;
 sub get_dependencies {              }
     my ($exportitems,$parent,$depth,$dependencies) = @_;          }
     if ($depth > 1) {      }
         if ((!grep/^$$parent{$depth}$/,@$exportitems) && (!grep/^$$parent{$depth}$/,@$dependencies)) {      while ($pkgdepth > 0) {
             push @$dependencies, $$parent{$depth};          print $ims_manifest "    </item>\n";
             if ($depth > 2) {          $pkgdepth --;
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);      }
             }      my $resource_text = qq|
         }      </organization>
     }    </organizations>
 }    <resources>
       $imsresources
 sub process_content {    </resources>
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;  </manifest>
     my $content_type;      |;
     my $message;      print $ims_manifest $resource_text;
     my @uploads = ();  }
     if ($curRes->is_sequence()) {  
         $content_type = 'sequence';  sub get_dependencies {
     } elsif ($curRes->is_page()) {      my ($exportitems,$parent,$depth,$dependencies) = @_;
         $content_type = 'page'; # need to handle individual items in pages.      if ($depth > 1) {
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {          if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {
         $content_type = 'syllabus';              push(@{$dependencies},$$parent{$depth});
         my $contents = &Apache::imsexport::templatedpage($content_type);              if ($depth > 2) {
         if ($contents) {                  &get_dependencies($exportitems,$parent,$depth-1,$dependencies);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              }
         }          }
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {      }
         $content_type = 'external';  }
         my $title = $curRes->title;  
         my $contents =  &Apache::imsexport::external($symb,$title);  sub process_content {
         if ($contents) {      my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      my $content_type;
         }      my $message;
     } elsif ($symb =~ m-adm/navmaps$-) {      my @uploads = ();
         $content_type =  'navmap';      if ($curRes->is_sequence()) {
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {          $content_type = 'sequence';
         $content_type = 'simplepage';      } elsif ($curRes->is_page()) {
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);          $content_type = 'page'; # need to handle individual items in pages.
         if ($contents) {      } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          $content_type = 'syllabus';
         }          my $contents = &Apache::imsexport::templatedpage($content_type);
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {          if ($contents) {
         $content_type = 'simpleproblem';              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         my $contents =  &Apache::imsexport::simpleproblem($symb);          }
         if ($contents) {      } elsif ($symb =~ m-\.sequence___\d+___ext-) {
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          $content_type = 'external';
         }          my $title = $curRes->title;
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {          my $contents =  &Apache::imsexport::external($symb,$title);
         $content_type = 'examupload';          if ($contents) {
     } elsif ($symb =~ m-adm/(\w+)/(\w+)/(\d+)/bulletinboard$-) {              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         $content_type = 'bulletinboard';          }
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);      } elsif ($symb =~ m-adm/navmaps$-) {
         if ($contents) {          $content_type =  'navmap';
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {
         }          $content_type = 'simplepage';
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {          my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);
         $content_type = 'aboutme';          if ($contents) {
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         if ($contents) {          }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {
         }          $content_type = 'simpleproblem';
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {          my $contents =  &Apache::imsexport::simpleproblem($symb);
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');          if ($contents) {
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         my $canedit = 0;          }
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {      } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {
             $canedit= 1;          $content_type = 'examupload';
         }      } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {
 # only include problem code where current user is author          $content_type = 'bulletinboard';
         if ($canedit) {          my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');          if ($contents) {
         } else {              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');          }
         }      } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {          $content_type = 'aboutme';
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');          my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);
     }          if ($contents) {
     if (@uploads > 0) {              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
         foreach my $item (@uploads) {          }
             my $uploadmsg = '';      } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');          $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
             if ($uploadmsg) {      } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {
                 $$copyresult .= $uploadmsg."\n";          my $canedit = 0;
             }          if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {
         }              $canedit= 1;
     }          }
     if ($message) {  # only include problem code where current user is author
         $$copyresult .= $message."\n";          if ($canedit) {
     }              $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');
 }          } else {
               $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');
 sub replicate_content {          }
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;      } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {
     my ($map,$ind,$url);          $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
     if ($caller eq 'templateupload') {      }
         $url = $symb;      if (@uploads > 0) {
         $url =~ s#//#/#g;          foreach my $item (@uploads) {
     } else {               my $uploadmsg = '';
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);              &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');
     }              if ($uploadmsg) {
     my $content;                  $$copyresult .= $uploadmsg."\n";
     my $filename;              }
     my $repstatus;          }
     my $content_name;      }
     if ($url =~ m-/([^/]+)$-) {      if ($message) {
         $filename = $1;          $$copyresult .= $message."\n";
         if (!-e $tempexport.'/resources') {      }
             mkdir($tempexport.'/resources',0700);  }
         }  
         if (!-e $tempexport.'/resources/'.$count) {  sub replicate_content {
             mkdir($tempexport.'/resources/'.$count,0700);      my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;
         }      my ($map,$ind,$url);
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;      if ($caller eq 'templateupload') {
         my $copiedfile;          $url = $symb;
         if ($copiedfile = Apache::File->new('>'.$destination)) {          $url =~ s#//#/#g;
             my $content;      } else {
             if ($caller eq 'resource') {          ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';      }
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);      my $content;
                 $content = &Apache::lonnet::getfile($filepath);      my $filename;
                 if ($content eq -1) {      my $repstatus;
                     $$message = 'Could not copy file '.$filename;      my $content_name;
                 } else {      if ($url =~ m-/([^/]+)$-) {
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');          $filename = $1;
                     $repstatus = 'ok';          if (!-e $tempexport.'/resources') {
                 }              mkdir($tempexport.'/resources',0700);
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {          }
                 my $rtncode;          if (!-e $tempexport.'/resources/'.$count) {
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);              mkdir($tempexport.'/resources/'.$count,0700);
                 if ($repstatus eq 'ok') {          }
                     if ($url =~ /\.html?$/i) {          my $destination = $tempexport.'/resources/'.$count.'/'.$filename;
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');          my $copiedfile;
                     }          if ($copiedfile = Apache::File->new('>'.$destination)) {
                 } else {              my $content;
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";              if ($caller eq 'resource') {
                 }                  my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';
             } elsif ($caller eq 'noedit') {                  my $filepath = &Apache::lonnet::filelocation($respath,$url);
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.                   $content = &Apache::lonnet::getfile($filepath);
                 $repstatus = 'ok';                  if ($content eq -1) {
                 $content = 'Not the owner of this resource';                       $$message = 'Could not copy file '.$filename;
             }                  } else {
             if ($repstatus eq 'ok') {                      &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');
                 print $copiedfile $content;                      $repstatus = 'ok';
             }                  }
             close($copiedfile);              } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {
         } else {                  my $rtncode;
             $$message = 'Could not open destination file for '.$filename."<br />\n";                  $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);
         }                  if ($repstatus eq 'ok') {
     } else {                      if ($url =~ /\.html?$/i) {
         $$message = 'Could not determine name of file for '.$symb."<br />\n";                          &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');
     }                      }
     if ($repstatus eq 'ok') {                  } else {
         $content_name = 'resources/'.$count.'/'.$filename;                      $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";
     }                  }
     return $content_name;              } elsif ($caller eq 'noedit') {
 }  # 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';
 sub extract_media {                  $content = 'Not the owner of this resource';
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;              }
     my ($dirpath,$container);              if ($repstatus eq 'ok') {
     my %allfiles = ();                  print $copiedfile $content;
     my %codebase = ();              }
     if ($url =~ m-(.*/)([^/]+)$-) {              close($copiedfile);
         $dirpath = $1;          } else {
         $container = $2;              $$message = 'Could not open destination file for '.$filename."<br />\n";
     } else {          }
         $dirpath = $url;      } else {
         $container = '';          $$message = 'Could not determine name of file for '.$symb."<br />\n";
     }      }
     &Apache::lonnet::extract_embedded_items(undef,undef,\%allfiles,\%codebase,$content);      if ($repstatus eq 'ok') {
     foreach my $embed_file (keys(%allfiles)) {          $content_name = 'resources/'.$count.'/'.$filename;
         my $filename;      }
         if ($embed_file =~ m#([^/]+)$#) {      return $content_name;
             $filename = $1;  }
         } else {  
             $filename = $embed_file;  sub extract_media {
         }      my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;
         my $newname = 'res/'.$filename;      my ($dirpath,$container);
         my ($rtncode,$embed_content,$repstatus);      my %allfiles = ();
         my $embed_url;      my %codebase = ();
         if ($embed_file =~ m-^/-) {      if ($url =~ m-(.*/)([^/]+)$-) {
             $embed_url = $embed_file;           # points to absolute path          $dirpath = $1;
         } else {          $container = $2;
             if ($embed_file =~ m-https?://-) {      } else {
                 next;                           # points to url          $dirpath = $url;
             } else {          $container = '';
                 $embed_url = $dirpath.$embed_file;  # points to relative path      }
             }      &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);
         }      foreach my $embed_file (keys(%allfiles)) {
         if ($caller eq 'resource') {          my $filename;
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';            if ($embed_file =~ m#([^/]+)$#) {
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);               $filename = $1;
             $embed_content = &Apache::lonnet::getfile($embed_path);          } else {
             unless ($embed_content eq -1) {              $filename = $embed_file;
                 $repstatus = 'ok';          }
             }          my $newname = 'res/'.$filename;
         } elsif ($caller eq 'uploaded') {          my ($rtncode,$embed_content,$repstatus);
                       my $embed_url;
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);          if ($embed_file =~ m-^/-) {
         }              $embed_url = $embed_file;           # points to absolute path
         if ($repstatus eq 'ok') {          } else {
             my $destination = $tempexport.'/resources/'.$count.'/res';              if ($embed_file =~ m-https?://-) {
             if (!-e "$destination") {                  next;                           # points to url
                 mkdir($destination,0755);              } else {
             }                  $embed_url = $dirpath.$embed_file;  # points to relative path
             $destination .= '/'.$filename;              }
             my $copiedfile;          }
             if ($copiedfile = Apache::File->new('>'.$destination)) {          if ($caller eq 'resource') {
                 print $copiedfile $embed_content;              my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';  
                 push @{$href}, 'resources/'.$count.'/res/'.$filename;              my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);
                 my $attrib_regexp = '';              $embed_content = &Apache::lonnet::getfile($embed_path);
                 if (@{$allfiles{$embed_file}} > 1) {              unless ($embed_content eq -1) {
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});                  $repstatus = 'ok';
                 } else {              }
                     $attrib_regexp = $allfiles{$embed_file}[0];          } elsif ($caller eq 'uploaded') {
                 }             
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;              $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {          }
                     $$content =~ s#\Q$embed_file\E#$newname#gi;          if ($repstatus eq 'ok') {
                 }              my $destination = $tempexport.'/resources/'.$count.'/res';
             }              if (!-e "$destination") {
         } else {                  mkdir($destination,0755);
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";              }
         }              $destination .= '/'.$filename;
     }              my $copiedfile;
     return;              if ($copiedfile = Apache::File->new('>'.$destination)) {
 }                  print $copiedfile $embed_content;
                   push(@{$href},'resources/'.$count.'/res/'.$filename);
 sub store_template {                  my $attrib_regexp = '';
     my ($contents,$tempexport,$count,$content_type) = @_;                  if (@{$allfiles{$embed_file}} > 1) {
     if ($contents) {                      $attrib_regexp = join('|',@{$allfiles{$embed_file}});
         if ($tempexport) {                  } else {
             if (!-e $tempexport.'/resources') {                      $attrib_regexp = $allfiles{$embed_file}[0];
                 mkdir($tempexport.'/resources',0700);                  }
             }                  $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;
             if (!-e $tempexport.'/resources/'.$count) {                  if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {
                 mkdir($tempexport.'/resources/'.$count,0700);                      $$content =~ s#\Q$embed_file\E#$newname#gi;
             }                  }
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';              }
             my $storetemplate;          } else {
             if ($storetemplate = Apache::File->new('>'.$destination)) {              $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";
                 print $storetemplate $contents;          }
                 close($storetemplate);      }
             }      return;
             if ($content_type eq 'external') {  }
                 return 'resources/'.$count.'/'.$content_type.'.html';  
             } else {  sub store_template {
                 return 'resources/'.$count.'/'.$content_type.'.xml';      my ($contents,$tempexport,$count,$content_type) = @_;
             }      if ($contents) {
         }          if ($tempexport) {
     }              if (!-e $tempexport.'/resources') {
 }                  mkdir($tempexport.'/resources',0700);
               }
 # Imports the given (name, url) resources into the course              if (!-e $tempexport.'/resources/'.$count) {
 # coursenum, coursedom, and folder must precede the list                  mkdir($tempexport.'/resources/'.$count,0700);
 sub group_import {              }
     my $coursenum = shift;              my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';
     my $coursedom = shift;              my $storetemplate;
     my $folder = shift;              if ($storetemplate = Apache::File->new('>'.$destination)) {
     my $container = shift;                  print $storetemplate $contents;
     my $caller = shift;                  close($storetemplate);
     while (@_) {              }
  my $name = shift;              if ($content_type eq 'external') {
  my $url = shift;                  return 'resources/'.$count.'/'.$content_type.'.html';
         if (($url =~ m#^/uploaded/$coursedom/$coursenum/(default_\d+\.)(page|sequence)$#) && ($caller eq 'londocs')) {              } else {
             my $errtext = '';                  return 'resources/'.$count.'/'.$content_type.'.xml';
             my $fatal = 0;              }
             my $newmapstr = '<map>'."\n".          }
                             '<resource id="1" src="" type="start"></resource>'."\n".      }
                             '<link from="1" to="2" index="1"></link>'."\n".  }
                             '<resource id="2" src="" type="finish"></resource>'."\n".  
                             '</map>';  
             $env{'form.output'}=$newmapstr;  sub group_import {
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
                                                 'output',$1.$2);  
             if ($result != m|^/uploaded/|) {      while (@files) {
                 $errtext.='Map not saved: A network error occured when trying to save the new map. ';   my ($name, $url, $residx) = @{ shift(@files) };
                 $fatal = 2;          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
             }       && ($caller eq 'londocs')
             if ($fatal) {       && (!&Apache::lonnet::stat_file($url))) {
                 return ($errtext,$fatal);      
             }              my $errtext = '';
         }              my $fatal = 0;
  if ($url) {              my $newmapstr = '<map>'."\n".
     my $idx = &Apache::lonratedt::getresidx($url);                              '<resource id="1" src="" type="start"></resource>'."\n".
     $Apache::lonratedt::order[$#Apache::lonratedt::order+1]=$idx;                              '<link from="1" to="2" index="1"></link>'."\n".
     my $ext = 'false';                              '<resource id="2" src="" type="finish"></resource>'."\n".
     if ($url=~/^http:\/\//) { $ext = 'true'; }                              '</map>';
     $url =~ s/:/\&colon;/g;              $env{'form.output'}=$newmapstr;
     $name =~ s/:/\&colon;/g;              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
     $Apache::lonratedt::resources[$idx] =                                                   'output',$1.$2);
  join ':', ($name, $url, $ext, 'normal', 'res');              if ($result != m|^/uploaded/|) {
  }                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
     }                  $fatal = 2;
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);              }
 }              if ($fatal) {
                   return ($errtext,$fatal);
 sub breadcrumbs {              }
     my ($where)=@_;          }
     &Apache::lonhtmlcommon::clear_breadcrumbs();   if ($url) {
     my (@folders);      if (!$residx
     if ($env{'form.pagepath'}) {   || defined($LONCAPA::map::zombies[$residx])) {
         @folders = split('&',$env{'form.pagepath'});   $residx = &LONCAPA::map::getresidx($url,$residx);
     } else {   push(@LONCAPA::map::order, $residx);
         @folders=split('&',$env{'form.folderpath'});      }
     }      my $ext = 'false';
     my $folderpath;      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
     my $cpinfo='';      $url  = &LONCAPA::map::qtunescape($url);
     if ($env{'form.markedcopy_url'}) {      $name = &LONCAPA::map::qtunescape($name);
        $cpinfo='&markedcopy_url='.      $LONCAPA::map::resources[$residx] =
                &escape($env{'form.markedcopy_url'}).   join(':', ($name, $url, $ext, 'normal', 'res'));
                '&markedcopy_title='.   }
                &escape($env{'form.markedcopy_title'});      }
     }      return &storemap($coursenum, $coursedom, $folder.'.'.$container);
     my $randompick=-1;  }
     my $isencrypted=0;  
     my $ishidden=0;  sub breadcrumbs {
     while (@folders) {      my ($where,$allowed,$type)=@_;
  my $folder=shift(@folders);      &Apache::lonhtmlcommon::clear_breadcrumbs();
  my $foldername=shift(@folders);      my (@folders);
  if ($folderpath) {$folderpath.='&';}      if ($env{'form.pagepath'}) {
  $folderpath.=$folder.'&'.$foldername;          @folders = split('&',$env{'form.pagepath'});
  my $url='/adm/coursedocs?folderpath='.      } else {
     &escape($folderpath);          @folders=split('&',$env{'form.folderpath'});
             my $name=&unescape($foldername);      }
 # randompick number, hidden, encrypted is appended with ":"s to the foldername      my $folderpath;
             $name=~s/\:(\d*)\:(\w*)\:(\w*)$//;      my $cpinfo='';
             if ($1 ne '') {       my $plain='';
                $randompick=$1;      my $randompick=-1;
             } else {      my $isencrypted=0;
                $randompick=-1;      my $ishidden=0;
             }      my $is_random_order=0;
             if ($2) { $ishidden=1; }      while (@folders) {
             if ($3) { $isencrypted=1; }   my $folder=shift(@folders);
     &Apache::lonhtmlcommon::add_breadcrumb(      my $foldername=shift(@folders);
       {'href'=>$url.$cpinfo,   if ($folderpath) {$folderpath.='&';}
        'title'=>$name,   $folderpath.=$folder.'&'.$foldername;
        'text'=>'<font size="+1">'.   my $url='/adm/coursedocs?folderpath='.
    $name.'</font>'      &escape($folderpath);
        });      my $name=&unescape($foldername);
     }  # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',       $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
        'LC_docs_path'),$randompick,$ishidden,$isencrypted);      if ($1 ne '') {
 }                 $randompick=$1;
               } else {
 sub editor {                 $randompick=-1;
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output)=@_;              }
     my $errtext='';              if ($2) { $ishidden=1; }
     my $fatal=0;              if ($3) { $isencrypted=1; }
     my $container='sequence';      if ($4 ne '') { $is_random_order = 1; }
     if ($env{'form.pagepath'}) {              if ($folder eq 'supplemental') {
         $container='page';                  if ($allowed) {
     }                      $name = &mt('Supplemental '.$type.' Documents');
     ($errtext,$fatal)=                  } else {
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                      $name = &mt($type.' Documents');
     if ($#Apache::lonratedt::order<1) {                  }
  my $idx=&Apache::lonratedt::getresidx();              }
  if ($idx<=0) { $idx=1; }      &Apache::lonhtmlcommon::add_breadcrumb(
         $Apache::lonratedt::order[0]=$idx;        {'href'=>$url.$cpinfo,
         $Apache::lonratedt::resources[$idx]='';         'title'=>$name,
     }         'text'=>'<font size="+1">'.
     if (defined($env{'form.markcopy'})) {     $name.'</font>',
 # Mark for copying         'no_mt'=>1,
  my ($title,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$env{'form.markcopy'}]]);         });
  $env{'form.markedcopy_title'}=$title;   $plain.=$name.' &gt; ';
  $env{'form.markedcopy_url'}=$url;      }
     }      $plain=~s/\&gt\;\s*$//;
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted)=&breadcrumbs($folder);      return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
     $r->print($breadcrumbtrail);         'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);
     if ($fatal) {  }
    $r->print('<p><font color="red">'.$errtext.'</font></p>');  
     } else {  sub log_docs {
 # ------------------------------------------------------------ Process commands      return &Apache::lonnet::instructor_log('docslog',@_);
   }
 # ---------------- if they are for this folder and user allowed to make changes  
  if (($allowed) && ($env{'form.folder'} eq $folder)) {  {
 # set parameters and change order      my @oldresources=();
     if (defined($env{'form.setparms'})) {      my @oldorder=();
  my $idx=$env{'form.setparms'};      my $parmidx;
 # set parameters      my %parmaction=();
  if ($env{'form.randpick_'.$idx}) {      my %parmvalue=();
     &Apache::lonratedt::storeparameter($idx,'parameter_randompick',$env{'form.randpick_'.$idx},'int_pos');      my $changedflag;
  } else {  
     &Apache::lonratedt::delparameter($idx,'parameter_randompick');      sub snapshotbefore {
  }          @oldresources=@LONCAPA::map::resources;
  if ($env{'form.hidprs_'.$idx}) {          @oldorder=@LONCAPA::map::order;
     &Apache::lonratedt::storeparameter($idx,'parameter_hiddenresource','yes','string_yesno');          $parmidx=undef;
  } else {          %parmaction=();
     &Apache::lonratedt::delparameter($idx,'parameter_hiddenresource');          %parmvalue=();
  }          $changedflag=0;
  if ($env{'form.encprs_'.$idx}) {      }
     &Apache::lonratedt::storeparameter($idx,'parameter_encrypturl','yes','string_yesno');  
  } else {      sub remember_parms {
     &Apache::lonratedt::delparameter($idx,'parameter_encrypturl');          my ($idx,$parameter,$action,$value)=@_;
  }          $parmidx=$idx;
           $parmaction{$parameter}=$action;
  if ($env{'form.newpos'}) {          $parmvalue{$parameter}=$value;
 # change order          $changedflag=1;
       }
     my $newpos=$env{'form.newpos'}-1;  
     my $currentpos=$env{'form.currentpos'}-1;      sub log_differences {
     my $i;          my ($plain)=@_;
     my @neworder=();          my %storehash=('folder' => $plain,
     if ($newpos>$currentpos) {                         'currentfolder' => $env{'form.folder'});
 # moving stuff up          if ($parmidx) {
  for ($i=0;$i<$currentpos;$i++) {             $storehash{'parameter_res'}=$oldresources[$parmidx];
     $neworder[$i]=$Apache::lonratedt::order[$i];             foreach my $parm (keys(%parmaction)) {
  }                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
  for ($i=$currentpos;$i<$newpos;$i++) {                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
     $neworder[$i]=$Apache::lonratedt::order[$i+1];             }
  }          }
                         $neworder[$newpos]=$Apache::lonratedt::order[$currentpos];          my $maxidx=$#oldresources;
  for ($i=$newpos+1;$i<=$#Apache::lonratedt::order;$i++) {          if ($#LONCAPA::map::resources>$#oldresources) {
     $neworder[$i]=$Apache::lonratedt::order[$i];             $maxidx=$#LONCAPA::map::resources;
  }          }
     } else {          for (my $idx=0; $idx<=$maxidx; $idx++) {
 # moving stuff down             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
  for ($i=0;$i<$newpos;$i++) {                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
     $neworder[$i]=$Apache::lonratedt::order[$i];                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
  }                $changedflag=1;
  $neworder[$newpos]=$Apache::lonratedt::order[$currentpos];             }
  for ($i=$newpos+1;$i<$currentpos+1;$i++) {             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
     $neworder[$i]=$Apache::lonratedt::order[$i-1];                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
  }                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  for ($i=$currentpos+1;$i<=$#Apache::lonratedt::order;$i++) {                $changedflag=1;
     $neworder[$i]=$Apache::lonratedt::order[$i];             }
  }          }
     }   $storehash{'maxidx'}=$maxidx;
     @Apache::lonratedt::order=@neworder;          if ($changedflag) { &log_docs(\%storehash); }
  }      }
 # store the changed version  }
   
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);  
  if ($fatal) {  
     $r->print('<p><font color="red">'.$errtext.'</font></p>');  
     return;  
  }  sub docs_change_log {
       my ($r)=@_;
     }      my $folder=$env{'form.folder'};
     if ($env{'form.pastemarked'}) {      $r->print(&Apache::loncommon::start_page('Course Document Change Log'));
 # paste resource to end of list      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));
                 my $url=$env{'form.markedcopy_url'};      my %docslog=&Apache::lonnet::dump('nohist_docslog',
  my $title=$env{'form.markedcopy_title'};                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 # Maps need to be copied first                                        $env{'course.'.$env{'request.course.id'}.'.num'});
  if (($url=~/\.(page|sequence)$/) || ($url=~/^\/uploaded\//)) {  
     $title=&mt('Copy of').' '.$title;      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
                     my $newid=$$.time;  
     $url=~/^(.+)\.(\w+)$/;      $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.
     my $newurl=$1.$newid.'.'.$2;                '<input type="hidden" name="docslog" value="1" />');
     my $storefn=$newurl;  
                     $storefn=~s/^\/\w+\/\w+\/\w+\///;      my %saveable_parameters = ('show' => 'scalar',);
     &Apache::loncreatecourse::writefile      &Apache::loncommon::store_course_settings('docs_log',
  ($env{'request.course.id'},$storefn,                                                \%saveable_parameters);
  &Apache::lonnet::getfile($url));      &Apache::loncommon::restore_course_settings('docs_log',
     $url=$newurl;                                                  \%saveable_parameters);
  }      if (!$env{'form.show'}) { $env{'form.show'}=10; }
  $title=~s/\</\&lt\;/g;      my %lt=('hiddenresource' => 'Resources hidden',
  $title=~s/\>/\&gt\;/g;      'encrypturl'     => 'URL hidden',
  $title=~s/\:/\&colon;/g;      'randompick'     => 'Randomly pick',
  my $ext='false';      'randomorder'    => 'Randomly ordered',
  if ($url=~/^http\:\/\//) { $ext='true'; }      'set'            => 'set to',
  $url=~s/\:/\&colon;/g;      'del'            => 'deleted');
 # Now insert the URL at the bottom      $r->print(&Apache::loncommon::display_filter().
                 my $newidx=&Apache::lonratedt::getresidx($url);                '<input type="hidden" name="folder" value="'.$folder.'" />'.
  $Apache::lonratedt::resources[$newidx]=                '<input type="submit" value="'.&mt('Display').'" /></form>');
     $title.':'.$url.':'.$ext.':normal:res';      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
  $Apache::lonratedt::order[1+$#Apache::lonratedt::order]=$newidx;                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
 # Store the result                &mt('After').'</th>'.
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                &Apache::loncommon::end_data_table_header_row());
  if ($fatal) {      my $shown=0;
     $r->print('<p><font color="red">'.$errtext.'</font></p>');      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     return;   if ($env{'form.displayfilter'} eq 'currentfolder') {
  }      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
    }
     }          my @changes=keys(%{$docslog{$id}{'logentry'}});
             $r->print($upload_output);          if ($env{'form.displayfilter'} eq 'containing') {
     if ($env{'form.cmd'}) {      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
                 my ($cmd,$idx)=split(/\_/,$env{'form.cmd'});   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
                 if ($cmd eq 'del') {      foreach my $key (@changes) {
     my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
     if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&      }
  ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }        
  &Apache::lonnet::removeuploadedurl($url);   }
     } else {          my $count = 0;
  &Apache::lonratedt::makezombie($Apache::lonratedt::order[$idx]);          my $time =
     }              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
     for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {          my $plainname =
                         $Apache::lonratedt::order[$i]=              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
                           $Apache::lonratedt::order[$i+1];                                            $docslog{$id}{'exe_udom'});
                     }          my $about_me_link =
                     $#Apache::lonratedt::order--;              &Apache::loncommon::aboutmewrapper($plainname,
                 } elsif ($cmd eq 'cut') {                                                 $docslog{$id}{'exe_uname'},
     my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);                                                 $docslog{$id}{'exe_udom'});
     &Apache::lonratedt::makezombie($Apache::lonratedt::order[$idx]);          my $send_msg_link='';
     for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
                         $Apache::lonratedt::order[$i]=               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
                           $Apache::lonratedt::order[$i+1];              $send_msg_link ='<br />'.
                     }                  &Apache::loncommon::messagewrapper(&mt('Send message'),
                     $#Apache::lonratedt::order--;                                                     $docslog{$id}{'exe_uname'},
                 } elsif ($cmd eq 'up') {                                                     $docslog{$id}{'exe_udom'});
   if (($idx) && (defined($Apache::lonratedt::order[$idx-1]))) {          }
                     my $i=$Apache::lonratedt::order[$idx-1];          $r->print(&Apache::loncommon::start_data_table_row());
                     $Apache::lonratedt::order[$idx-1]=          $r->print('<td>'.$time.'</td>
  $Apache::lonratedt::order[$idx];                         <td>'.$about_me_link.
                     $Apache::lonratedt::order[$idx]=$i;                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
    }                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
                 } elsif ($cmd eq 'down') {                    $send_msg_link.'</td><td>'.
    if (defined($Apache::lonratedt::order[$idx+1])) {                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
                     my $i=$Apache::lonratedt::order[$idx+1];  # Before
                     $Apache::lonratedt::order[$idx+1]=   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  $Apache::lonratedt::order[$idx];      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
                     $Apache::lonratedt::order[$idx]=$i;      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
    }      if ($oldname ne $newname) {
                 } elsif ($cmd eq 'rename') {   $r->print(&LONCAPA::map::qtescape($oldname));
                     my $ratstr = $Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]];      }
                     my ($rtitle,@rrest)=split(/\:/,   }
                        $Apache::lonratedt::resources[   $r->print('<ul>');
        $Apache::lonratedt::order[$idx]]);   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                     my $comment=              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
                      &HTML::Entities::decode($env{'form.title'});   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
                     $comment=~s/\</\&lt\;/g;      }
                     $comment=~s/\>/\&gt\;/g;   }
                     $comment=~s/\:/\&colon;/g;   $r->print('</ul>');
     if ($comment=~/\S/) {  # After
  $Apache::lonratedt::resources[          $r->print('</td><td>');
        $Apache::lonratedt::order[$idx]]=  
             $comment.':'.join(':',@rrest);   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     }      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
 # Devalidate title cache      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
                     my $renamed_url=$rrest[0];      if ($oldname ne '' && $oldname ne $newname) {
 # Has the &colon;-escaping   $r->print(&LONCAPA::map::qtescape($newname));
                     $renamed_url=~s/\&colon\;/\:/g;      }
     &Apache::lonnet::devalidate_title_cache($renamed_url);   }        
                 }   $r->print('<ul>');
 # Store the changed version   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
     $folder.'.'.$container);   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
  if ($fatal) {      }
     $r->print('<p><font color="red">'.$errtext.'</font></p>');   }
     return;   $r->print('</ul>');
  }   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
             }      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
 # Group import/search      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
     if ($env{'form.importdetail'}) {   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
  my @imports;      $r->print('<li>'.
  &Apache::lonnet::logthis("imp detail ".$env{'form.importdetail'});        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
  foreach (split(/\&/,$env{'form.importdetail'})) {    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
     if (defined($_)) {        .'</li>');
  my ($name,$url)=split(/\=/,$_);   }
  $name=&unescape($name);      }
  $url=&unescape($url);      $r->print('</ul>');
  push @imports, $name, $url;   }
     }  # End
  }          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
 # Store the changed version          $shown++;
  ($errtext,$fatal)=group_import($coursenum, $coursedom, $folder,          if (!($env{'form.show'} eq &mt('all')
        $container,'londocs',@imports);                || $shown<=$env{'form.show'})) { last; }
  if ($fatal) {      }
     $r->print('<p><font color="red">'.$errtext.'</font></p>');      $r->print(&Apache::loncommon::end_data_table());
     return;  }
  }  
             }  sub update_paste_buffer {
 # Loading a complete map      my ($coursenum,$coursedom) = @_;
    if ($env{'form.loadmap'}) {  
                if ($env{'form.importmap'}=~/\w/) {      return if (!defined($env{'form.markcopy'}));
           foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {      return if (!defined($env{'form.copyfolder'}));
       my ($title,$url,$ext,$type)=split(/\:/,$_);      return if ($env{'form.markcopy'} < 0);
                       my $idx=&Apache::lonratedt::getresidx($url);  
                       $Apache::lonratedt::resources[$idx]=$_;      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                       $Apache::lonratedt::order      $env{'form.copyfolder'});
           [$#Apache::lonratedt::order+1]=$idx;     
           }      return if ($fatal);
 # Store the changed version  
            ($errtext,$fatal)=&storemap($coursenum,$coursedom,  # Mark for copying
    $folder.'.'.$container);      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
           if ($fatal) {      if (&is_supplemental_title($title)) {
       $r->print('<p><font color="red">'.$errtext.'</font></p>');          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
       return;   ($title) = &parse_supplemental_title($title);
           }      } elsif ($env{'docs.markedcopy_supplemental'}) {
                } else {          &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');
                    $r->print('<p><font color="red">'.&mt('No map selected.').'</font></p>');      }
                }      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
            }  
        }      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
 # ---------------------------------------------------------------- End commands      'docs.markedcopy_url'   => $url});
 # ---------------------------------------------------------------- Print screen      delete($env{'form.markcopy'});
         my $idx=0;  }
  my $shown=0;  
         if (($ishidden) || ($isencrypted) || ($randompick>=0)) {  sub print_paste_buffer {
            $r->print('<p>'.&mt('Parameters').':<ul>'.      my ($r,$container) = @_;
                      ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').      return if (!defined($env{'docs.markedcopy_url'}));
                      ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').  
                      ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').      $r->print(<<ENDPASTE);
                      '</ul></p>');  <form name="pasteform" action="/adm/coursedocs" method="post"><p>
         }                                                                                                       ENDPASTE
         if ($randompick>=0) {      $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');
            $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 $type;
         $r->print('<table>');      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
         foreach (@Apache::lonratedt::order) {   $type = &mt('External Resource');
            my ($name,$url)=split(/\:/,$Apache::lonratedt::resources[$_]);   $r->print($type.': '.
    $name=&Apache::lonratsrv::qtescape($name);    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
    $url=&Apache::lonratsrv::qtescape($url);    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
            unless ($name) {  $name=(split(/\//,$url))[-1]; }      }  else {
            unless ($name) { $idx++; next; }   my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));   my $icon = &Apache::loncommon::icon($extension);
            $idx++;   if ($extension eq 'sequence' &&
    $shown++;      $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
         }      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
  unless ($shown) {      $icon .= '/folder_closed.gif';
     $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');   }
  }   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
         $r->print("\n</table>\n");   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
  if ($env{'form.markedcopy_url'}) {      }
     $r->print(<<ENDPASTE);      if ($container eq 'page') {
 <p><form name="pasteform" action="/adm/coursedocs" method="post">   $r->print('
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />   <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
 ENDPASTE  ');
             $r->print(      } else {
    '<input type="submit" name="pastemarked" value="'.&mt('Paste').   $r->print('
       '" /> '.&Apache::loncommon::filedescription(          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
  (split(/\./,$env{'form.markedcopy_url'}))[-1]).': '.  ');
       $env{'form.markedcopy_title'});      }
             if ($container eq 'page') {      $r->print('</p></form>');
  $r->print(<<PAGEINFO);  }
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />  
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />  sub do_paste_from_buffer {
 PAGEINFO      my ($coursenum,$coursedom,$folder) = @_;
             } else {  
  $r->print(<<FOLDERINFO);      if (!$env{'form.pastemarked'}) {
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />          return;
 FOLDERINFO      }
     }  
     $r->print('</form></p>');  # paste resource to end of list
  }      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
     }      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
 }  # Maps need to be copied first
       if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
 sub process_file_upload {   $title=&mt('Copy of').' '.$title;
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;   my $newid=$$.int(rand(100)).time;
 # upload a file, if present   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
     my $parseaction;          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
    if ($env{'form.parserflag'}) {              my $path = $1;
         $parseaction = 'parse';              my $prefix = $2;
     }              my $ancestor = $3;
     my $phase_status;              if (length($ancestor) > 10) {
     my $folder=$env{'form.folder'};                  $ancestor = substr($ancestor,-10,10);
     if ($folder eq '') {              }
         $folder='default';              $oldid = $path.$prefix.$ancestor;
     }          }
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {          my $counter = 0;
         my $errtext='';          my $newurl=$oldid.$newid.'.'.$ext;
         my $fatal=0;          my $is_unique = &uniqueness_check($newurl);
         my $container='sequence';          while (!$is_unique && $counter < 100) {
         if ($env{'form.pagepath'}) {              $counter ++;
             $container='page';              $newid ++;
         }              $newurl = $oldid.$newid;
         ($errtext,$fatal)=              $is_unique = &uniqueness_check($newurl);
               &mapread($coursenum,$coursedom,$folder.'.'.$container);          }
         if ($#Apache::lonratedt::order<1) {          if (!$is_unique) {
             $Apache::lonratedt::order[0]=1;              if ($url=~/\.page$/) {
             $Apache::lonratedt::resources[1]='';                  return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
         }              } else {
         if ($fatal) {                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
             return 'failed';              }
         }          }
         my $destination = 'docs/';   my $storefn=$newurl;
         if ($folder =~ /^supplemental/) {   $storefn=~s{^/\w+/$match_domain/$match_username/}{};
             $destination = 'supplemental/';   my $paste_map_result =
         }              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
         if (($folder eq 'default') || ($folder eq 'supplemental')) {         &Apache::lonnet::getfile($url));
             $destination .= 'default/';          if ($paste_map_result eq '/adm/notfound.html') {
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {              if ($url=~/\.page$/) {
             $destination .=  $2.'/';                  return &mt('Paste failed: an error occurred saving the composite page');
         }              } else {
 # this is for a course, not a user, so set coursedoc flag                  return &mt('Paste failed: an error occurred saving the folder');
 # probably the only place in the system where this should be "1"              }
         my $newidx=&Apache::lonratedt::getresidx();          }
         $destination .= $newidx;   $url = $newurl;
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,      }
  $parseaction,$allfiles,  # published maps can only exists once, so remove it from paste buffer when done
  $codebase);      if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
         my $ext='false';   &Apache::lonnet::delenv('docs\\.markedcopy');
         if ($url=~/^http\:\/\//) { $ext='true'; }      }
         $url=~s/\:/\&colon;/g;      if ($url=~ m{/smppg$}) {
         my $comment=$env{'form.comment'};   my $db_name = &Apache::lonsimplepage::get_db_name($url);
         $comment=~s/\</\&lt\;/g;   if ($db_name =~ /^smppage_/) {
         $comment=~s/\>/\&gt\;/g;      #simple pages, need to copy the db contents to a new one.
         $comment=~s/\:/\&colon;/g;      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
         if ($folder=~/^supplemental/) {      my $now = time();
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.      $db_name =~ s{_\d*$ }{_$now}x;
                   $env{'user.domain'}.'___&&&___'.$comment;      my $result=&Apache::lonnet::put($db_name,\%contents,
         }      $coursedom,$coursenum);
       $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
         $Apache::lonratedt::resources[$newidx]=      $title=&mt('Copy of').' '.$title;
                   $comment.':'.$url.':'.$ext.':normal:res';   }
         $Apache::lonratedt::order[$#Apache::lonratedt::order+1]= $newidx;      }
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,      $title = &LONCAPA::map::qtunescape($title);
     $folder.'.'.$container);      my $ext='false';
         if ($fatal) {      if ($url=~m{^http(|s)://}) { $ext='true'; }
             $$upload_output .= '<p><font color="red">'.$errtext.'</font></p>';      $url       = &LONCAPA::map::qtunescape($url);
             return 'failed';  # Now insert the URL at the bottom
         } else {      my $newidx = &LONCAPA::map::getresidx($url);
             if ($parseaction eq 'parse') {      if ($env{'docs.markedcopy_supplemental'}) {
                 my $total_embedded = keys(%{$allfiles});          if ($folder =~ /^supplemental/) {
                 if ($total_embedded > 0) {              $title = $env{'docs.markedcopy_supplemental'};
                     my $num = 0;          } else {
                     $$upload_output .= 'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />              (undef,undef,$title) =
    <form name="upload_embedded" action="/adm/coursedocs"                  &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
                   method="post" enctype="multipart/form-data">          }
    <input type="hidden" name="folderpath" value="'.$env{'form.folderpath'}.'" />   <input type="hidden" name="cmd" value="upload_embedded" />      } else {
    <input type="hidden" name="newidx" value="'.$newidx.'" />          if ($folder=~/^supplemental/) {
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';                    $env{'user.domain'}.'___&&&___'.$title;
                     $$upload_output .= '<b>Upload embedded files</b>:<br />          }
    <table>';      }
                     foreach my $embed_file (keys(%{$allfiles})) {  
                         $$upload_output .= '<tr><td>'.$embed_file.      $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
           '<input name="embedded_item_'.$num.'" type="file" />      push(@LONCAPA::map::order, $newidx);
            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';      return 'ok';
                         my $attrib;  # Store the result
                         if (@{$$allfiles{$embed_file}} > 1) {  }
                             $attrib = join(':',@{$$allfiles{$embed_file}});  
                         } else {  sub uniqueness_check {
                             $attrib = $$allfiles{$embed_file}[0];      my ($newurl) = @_;
                         }      my $unique = 1;
                         $$upload_output .=      foreach my $res (@LONCAPA::map::order) {
            '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.$attrib.'" />';          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
                         if (exists($$codebase{$embed_file})) {          $url=&LONCAPA::map::qtescape($url);
                             $$upload_output .=           if ($newurl eq $url) {
           '<input name="codebase_'.$num.'" type="hidden" value="'.&escape($$codebase{$embed_file}).'" />';              $unique = 0;
                         }              last;    
                         $$upload_output .= '</td></tr>';          }
                         $num ++;      }
                     }      return $unique;
                     $phase_status = 'phasetwo';  }
                     $$upload_output .= '</table><br />  
    <input type ="submit" value="Complete upload" />  my %parameter_type = ( 'randompick'     => 'int_pos',
    </form>';         'hiddenresource' => 'string_yesno',
                 } else {         'encrypturl'     => 'string_yesno',
                     $$upload_output .= 'No embedded items identified<br />';         'randomorder'    => 'string_yesno',);
                 }  my $valid_parameters_re = join('|',keys(%parameter_type));
             }  # set parameters
         }  sub update_parameter {
     }  
     return $phase_status;      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
 }  
       my $which = $env{'form.changeparms'};
 sub process_secondary_uploads {      my $idx = $env{'form.setparms'};
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;      if ($env{'form.'.$which.'_'.$idx}) {
     my $folder=$env{'form.folder'};   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
     my $destination = 'docs/';                                       : 'yes';
     if ($folder =~ /^supplemental/) {   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
         $destination = 'supplemental/';        $parameter_type{$which});
     }   &remember_parms($idx,$which,'set',$value);
     if (($folder eq 'default') || ($folder eq 'supplemental')) {      } else {
         $destination .= 'default/';   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {  
         $destination .=  $2.'/';   &remember_parms($idx,$which,'del');
     }      }
     $destination .= $newidx;      return 1;
     my ($url,$filename);  }
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);  
     ($filename) = ($url =~ m-^/uploaded/$coursedom/$coursenum/$destination/(.+)$-);  
     return $filename;  sub handle_edit_cmd {
 }      my ($coursenum,$coursedom) =@_;
   
 # --------------------------------------------------------------- An entry line      my ($cmd,$idx)=split('_',$env{'form.cmd'});
   
 sub entryline {      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;      my ($title, $url, @rrest) = split(':', $ratstr);
     $title=~s/\&colon\;/\:/g;  
     $title=&HTML::Entities::encode(&HTML::Entities::decode(      if ($cmd eq 'del') {
      &unescape($title)),'"<>&\'');   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
     my $renametitle=$title;      ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
     my $foldertitle=$title;      &Apache::lonnet::removeuploadedurl($url);
     my $pagetitle=$title;   } else {
     my $orderidx=$Apache::lonratedt::order[$index];      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     if ($title=~ /^(\d+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(.*)$/ ) {    }
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);   splice(@LONCAPA::map::order, $idx, 1);
  $renametitle=$4;  
  $title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.      } elsif ($cmd eq 'cut') {
     &Apache::loncommon::plainname($2,$3).': <br />'.   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     $foldertitle;   splice(@LONCAPA::map::order, $idx, 1);
     }  
     $renametitle=~s/\\/\\\\/g;      } elsif ($cmd eq 'up'
     $renametitle=~s/\&quot\;/\\\"/g;       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     my $line='<tr>';   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
 # Edit commands  
     my $container;      } elsif ($cmd eq 'down'
     my $folderpath;       && defined($LONCAPA::map::order[$idx+1])) {
     if ($env{'form.folderpath'}) {   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
         $container = 'sequence';  
  $folderpath=&escape($env{'form.folderpath'});      } elsif ($cmd eq 'rename') {
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');  
     }   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
     my ($pagepath,$pagesymb);   if ($comment=~/\S/) {
     if ($env{'form.pagepath'}) {      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
         $container = 'page';   $comment.':'.join(':', $url, @rrest);
         $pagepath=&escape($env{'form.pagepath'});   }
         $pagesymb=&escape($env{'form.pagesymb'});  # Devalidate title cache
     }   my $renamed_url=&LONCAPA::map::qtescape($url);
     my $cpinfo='';   &Apache::lonnet::devalidate_title_cache($renamed_url);
     if ($env{'form.markedcopy_url'}) {      } else {
        $cpinfo='&markedcopy_url='.   return 0;
                &escape($env{'form.markedcopy_url'}).      }
                '&markedcopy_title='.      return 1;
                &escape($env{'form.markedcopy_title'});  }
     }  
     if ($allowed) {  sub editor {
  my $incindex=$index+1;      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;
  my $selectbox='';  
  if (($folder!~/^supplemental/) &&      my $container= ($env{'form.pagepath'}) ? 'page'
     ($#Apache::lonratedt::order>0) &&                              : 'sequence';
     ((split(/\:/,  
      $Apache::lonratedt::resources[$Apache::lonratedt::order[0]]))[1]       my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
      ne '') &&       $folder.'.'.$container);
     ((split(/\:/,      return $errtext if ($fatal);
      $Apache::lonratedt::resources[$Apache::lonratedt::order[1]]))[1]   
      ne '')) {      if ($#LONCAPA::map::order<1) {
     $selectbox=   my $idx=&LONCAPA::map::getresidx();
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.   if ($idx<=0) { $idx=1; }
  '<select name="newpos" onChange="this.form.submit()">';          $LONCAPA::map::order[0]=$idx;
     for (my $i=1;$i<=$#Apache::lonratedt::order+1;$i++) {          $LONCAPA::map::resources[$idx]='';
  if ($i==$incindex) {      }
     $selectbox.='<option value="" selected="1">('.$i.')</option>';     
  } else {      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';   &breadcrumbs($folder,$allowed,$type);
  }      $r->print($breadcrumbtrail);
     }     
     $selectbox.='</select>';  # ------------------------------------------------------------ Process commands
  }  
  my %lt=&Apache::lonlocal::texthash(  # ---------------- if they are for this folder and user allowed to make changes
                 'up' => 'Move Up',      if (($allowed) && ($env{'form.folder'} eq $folder)) {
  'dw' => 'Move Down',  # set parameters and change order
  'rm' => 'Remove',   &snapshotbefore();
                 'ct' => 'Cut',  
  'rn' => 'Rename',   if (&update_parameter()) {
  'cp' => 'Copy');      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
  my $nocopy=0;      return $errtext if ($fatal);
         if ($url=~/\.(page|sequence)$/) {   }
     foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url))) {  
  my ($title,$url,$ext,$type)=split(/\:/,$_);   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
  if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {  # change order
     $nocopy=1;      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
     last;      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
  }  
     }      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
  }      return $errtext if ($fatal);
         my $copylink='&nbsp;';   }
         if ($env{'form.pagepath'}) {      
            unless ($nocopy) {   if ($env{'form.pastemarked'}) {
                $copylink=(<<ENDCOPY);              my $paste_res =
 <a href='javascript:markcopy("$pagepath","$index","$renametitle","page","$pagesymb");'>                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>              if ($paste_res eq 'ok') {
 ENDCOPY                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
             }                  return $errtext if ($fatal);
             $line.=(<<END);              } elsif ($paste_res ne '') {
 <form name="entry_$index" action="/adm/coursedocs" method="post">                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />              }
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />   }
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />  
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />   $r->print($upload_output);
 <input type="hidden" name="setparms" value="$orderidx" />  
 <td><table border='0' cellspacing='2' cellpadding='0'>   if (&handle_edit_cmd()) {
 <tr><td bgcolor="#DDDDDD">      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>      return $errtext if ($fatal);
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>   }
 <tr><td bgcolor="#DDDDDD">  # Group import/search
 <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>   if ($env{'form.importdetail'}) {
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>      my @imports;
 </table></td>      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
 <td>$selectbox   if (defined($item)) {
 </td><td bgcolor="#DDDDDD">      my ($name,$url,$residx)=
 <a href='javascript:removeres("$pagepath","$index","$renametitle","page","$pagesymb");'>   map {&unescape($_)} split(/\=/,$item);
 <font size="-2" color="#990000">$lt{'rm'}</font></a>      push(@imports, [$name, $url, $residx]);
 <a href='javascript:cutres("$pagepath","$index","$renametitle","page","$pagesymb");'>   }
 <font size="-2" color="#550044">$lt{'ct'}</font></a>      }
 <a href='javascript:changename("$pagepath","$index","$renametitle","page","$pagesymb");'>      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
 <font size="-2" color="#009900">$lt{'rn'}</font></a>      $container,'londocs',@imports);
 $copylink      return $errtext if ($fatal);
 END   }
         } else {  # Loading a complete map
            unless ($nocopy) {   if ($env{'form.loadmap'}) {
                $copylink=(<<ENDCOPY);      if ($env{'form.importmap'}=~/\w/) {
 <a href='javascript:markcopy("$folderpath","$index","$renametitle","sequence");'>   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>      my ($title,$url,$ext,$type)=split(/\:/,$res);
 ENDCOPY      my $idx=&LONCAPA::map::getresidx($url);
             }      $LONCAPA::map::resources[$idx]=$res;
             $line.=(<<END);       $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
 <form name="entry_$index" action="/adm/coursedocs" method="post">   }
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />      $folder.'.'.$container);
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />   return $errtext if ($fatal);
 <input type="hidden" name="setparms" value="$orderidx" />      } else {
 <td><table border='0' cellspacing='2' cellpadding='0'>   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
 <tr><td bgcolor="#DDDDDD">  
 <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath$cpinfo'>      }
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>   }
 <tr><td bgcolor="#DDDDDD">   &log_differences($plain);
 <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath$cpinfo'>      }
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>  # ---------------------------------------------------------------- End commands
 </table></td>  # ---------------------------------------------------------------- Print screen
 <td>$selectbox      my $idx=0;
 </td><td bgcolor="#DDDDDD">      my $shown=0;
 <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
 <font size="-2" color="#990000">$lt{'rm'}</font></a>   $r->print('<p>'.&mt('Parameters').':<ul>'.
 <a href='javascript:cutres("$folderpath","$index","$renametitle","sequence");'>    ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
 <font size="-2" color="#550044">$lt{'ct'}</font></a>    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
 <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
 <font size="-2" color="#009900">$lt{'rn'}</font></a>    '</ul></p>');
 $copylink      }                                                                                                    
 END      if ($randompick>=0) {
         }   $r->print('<p>'.&mt('Caution: this folder is set to randomly pick a subset of resources. Adding or removing resources from this folder will change the set of resources that the students see, resulting in spurious or missing credit for completed problems, not limited to ones you modify. Do not modify the contents of this folder if it is in active student use.').'</p>');
     }      }
 # Figure out what kind of a resource this is      if ($is_random_order) {
     my ($extension)=($url=~/\.(\w+)$/);   $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');
     my $uploaded=($url=~/^\/*uploaded\//);      }
     my $icon=&Apache::loncommon::icon($url);      $r->print('<table class="LC_docs_editor">');
     my $isfolder=0;      foreach my $res (@LONCAPA::map::order) {
     my $ispage=0;   my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     my $folderarg;   $name=&LONCAPA::map::qtescape($name);
     my $pagearg;   $url=&LONCAPA::map::qtescape($url);
     my $pagefile;   unless ($name) {  $name=(split(/\//,$url))[-1]; }
     if ($uploaded) {   unless ($name) { $idx++; next; }
  if ($extension eq 'sequence') {   $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,
     $icon=$iconpath.'/folder_closed.gif';       $coursenum));
     $url=~/$coursenum\/([\/\w]+)\.sequence$/;   $idx++;
     $url='/adm/coursedocs?';   $shown++;
     $folderarg=$1;      }
     $isfolder=1;      unless ($shown) {
         } elsif ($extension eq 'page') {   $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
             $icon=$iconpath.'/page.gif';      }
             $url=~/$coursenum\/([\/\w]+)\.page$/;      $r->print("\n</table>\n");
             $pagearg=$1;      if ($allowed) {
             $url='/adm/coursedocs?';          &print_paste_buffer($r,$container);
             $ispage=1;      }
  } else {      return;
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);  }
  }  
     }  sub process_file_upload {
     $url=~s-^http(\&colon\;|:)//-/adm/wrapper/ext/-;      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {  # upload a file, if present
  my $symb=&Apache::lonnet::symbclean(      my $parseaction;
           &Apache::lonnet::declutter('uploaded/'.     if ($env{'form.parserflag'}) {
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.          $parseaction = 'parse';
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.      }
            '.sequence').      my $phase_status;
            '___'.$residx.'___'.      my $folder=$env{'form.folder'};
    &Apache::lonnet::declutter($url));      if ($folder eq '') {
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);          $folder='default';
  $url=&Apache::lonnet::clutter($url);      }
  if ($url=~/^\/*uploaded\//) {      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
     $url=~/\.(\w+)$/;          my $errtext='';
     my $embstyle=&Apache::loncommon::fileembstyle($1);          my $fatal=0;
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {          my $container='sequence';
  $url='/adm/wrapper'.$url;          if ($env{'form.pagepath'}) {
     } elsif ($embstyle eq 'ssi') {              $container='page';
  #do nothing with these          }
     } elsif ($url!~/\.(sequence|page)$/) {          ($errtext,$fatal)=
  $url='/adm/coursedocs/showdoc'.$url;                &mapread($coursenum,$coursedom,$folder.'.'.$container);
     }          if ($#LONCAPA::map::order<1) {
  } elsif ($url=~m|^/ext/|) {               $LONCAPA::map::order[0]=1;
     $url='/adm/wrapper'.$url;              $LONCAPA::map::resources[1]='';
  }          }
         if (&Apache::lonnet::symbverify($symb,$url)) {          if ($fatal) {
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);              return 'failed';
         } else {          }
             $url='';          my $destination = 'docs/';
         }          if ($folder =~ /^supplemental/) {
  if ($container eq 'page') {              $destination = 'supplemental/';
     my $symb=$env{'form.pagesymb'};          }
                   if (($folder eq 'default') || ($folder eq 'supplemental')) {
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);              $destination .= 'default/';
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
  }              $destination .=  $2.'/';
     }          }
     my $parameterset='&nbsp;';  # this is for a course, not a user, so set coursedoc flag
     if ($isfolder || $extension eq 'sequence') {  # probably the only place in the system where this should be "1"
  my $foldername=&escape($foldertitle);          my $newidx=&LONCAPA::map::getresidx();
  my $folderpath=$env{'form.folderpath'};          $destination .= $newidx;
  if ($folderpath) { $folderpath.='&' };          my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
 # Append randompick number, hidden, and encrypted with ":" to foldername,    $parseaction,$allfiles,
 # so it gets transferred between levels   $codebase);
  $folderpath.=$folderarg.'&'.$foldername.':'.(&Apache::lonratedt::getparameter($orderidx,          my $ext='false';
                                               'parameter_randompick'))[0]          if ($url=~m{^http://}) { $ext='true'; }
                                                .':'.((&Apache::lonratedt::getparameter($orderidx,   $url     = &LONCAPA::map::qtunescape($url);
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)          my $comment=$env{'form.comment'};
                                                .':'.((&Apache::lonratedt::getparameter($orderidx,   $comment = &LONCAPA::map::qtunescape($comment);
                                               'parameter_encrypturl'))[0]=~/^yes$/i);          if ($folder=~/^supplemental/) {
  $url.='folderpath='.&escape($folderpath).$cpinfo;                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  $parameterset='<label>'.&mt('Randomly Pick: ').                    $env{'user.domain'}.'___&&&___'.$comment;
     '<input type="text" size="4" onChange="this.form.submit()" name="randpick_'.$orderidx.'" value="'.          }
     (&Apache::lonratedt::getparameter($orderidx,  
                                               'parameter_randompick'))[0].          $LONCAPA::map::resources[$newidx]=
                                               '" />'.      $comment.':'.$url.':'.$ext.':normal:res';
 '<font size="-2"><a href="javascript:void(0)">'.&mt('Store').'</a></font></label>';          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
                  ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     }      $folder.'.'.$container);
     if ($ispage) {          if ($fatal) {
         my $pagename=&escape($pagetitle);              $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';
         my $pagepath;              return 'failed';
         my $folderpath=$env{'form.folderpath'};          } else {
         if ($folderpath) { $pagepath = $folderpath.'&' };              if ($parseaction eq 'parse') {
         $pagepath.=$pagearg.'&'.$pagename;                  my $total_embedded = keys(%{$allfiles});
  my $symb=$env{'form.pagesymb'};                  if ($total_embedded > 0) {
  if (!$symb) {                      my $num = 0;
     my $path='uploaded/'.      my $state = '
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.     <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';     <input type="hidden" name="cmd" value="upload_embedded" />
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',     <input type="hidden" name="newidx" value="'.$newidx.'" />
        $residx,     <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
        $path.$pagearg.'.page');     <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
  }      $phase_status = 'phasetwo';
  $url.='pagepath='.&escape($pagepath).  
     '&pagesymb='.&escape($symb).$cpinfo;                      $$upload_output .=
     }   'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.
     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.   &Apache::loncommon::ask_for_embedded_content(
  '" border="0"></a></td>'.                              '/adm/coursedocs',$state,$allfiles,$codebase);
         "<td bgcolor='#FFFFBB'>".($url?"<a href=\"$url\">":'').$title.                  } else {
         ($url?'</a>':' <font size="-2">'.&mt('(re-initialize course to access)').'</font>')."</td>";                      $$upload_output .= 'No embedded items identified<br />';
     if (($allowed) && ($folder!~/^supplemental/)) {                  }
   my %lt=&Apache::lonlocal::texthash(              }
        'hd' => 'Hidden',          }
        'ec' => 'URL hidden');      }
  my $enctext=      return $phase_status;
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');  }
  my $hidtext=  
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');  sub process_secondary_uploads {
  $line.=(<<ENDPARMS);      my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
 <td bgcolor="#BBBBFF"><font size='-2'>      my $folder=$env{'form.folder'};
 <nobr><label><input type="checkbox" name="hidprs_$orderidx" onClick="this.form.submit()" $hidtext /> $lt{'hd'}</label></nobr></td>      my $destination = 'docs/';
 <td bgcolor="#BBBBFF"><font size='-2'>      if ($folder =~ /^supplemental/) {
 <nobr><label><input type="checkbox" name="encprs_$orderidx" onClick="this.form.submit()" $enctext /> $lt{'ec'}</label></nobr></td>          $destination = 'supplemental/';
 <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>      }
 ENDPARMS      if (($folder eq 'default') || ($folder eq 'supplemental')) {
     }          $destination .= 'default/';
     $line.="</form></tr>";      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
     return $line;          $destination .=  $2.'/';
 }      }
       $destination .= $newidx;
 # ---------------------------------------------------------------- tie the hash      my ($url,$filename);
       $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
 sub tiehash {      ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});
     my ($mode)=@_;      return $filename;
     $hashtied=0;  }
     if ($env{'request.course.fn'}) {  
  if ($mode eq 'write') {  sub is_supplemental_title {
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      my ($title) = @_;
     &GDBM_WRCREAT(),0640)) {      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
                 $hashtied=2;  }
     }  
  } else {  sub parse_supplemental_title {
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      my ($title) = @_;
     &GDBM_READER(),0640)) {  
                 $hashtied=1;      my ($foldertitle,$renametitle);
     }      if ($title =~ /&amp;&amp;&amp;/) {
  }   $title = &HTML::Entites::decode($title);
     }          }
 }   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
    $renametitle=$4;
 sub untiehash {   my ($time,$uname,$udom) = ($1,$2,$3);
     if ($hashtied) { untie %hash; }   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
     $hashtied=0;   my $name =  &Apache::loncommon::plainname($uname,$udom);
     return OK;   $name = &HTML::Entities::encode($name,'"<>&\'');
 }   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
       $name.': <br />'.$foldertitle;
 # --------------------------------------------------------------- check on this      }
       if (wantarray) {
 sub checkonthis {   return ($title,$foldertitle,$renametitle);
     my ($r,$url,$level,$title)=@_;      }
     $url=&unescape($url);      return $title;
     $alreadyseen{$url}=1;  }
     $r->rflush();  
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {  # --------------------------------------------------------------- An entry line
        $r->print("\n<br />");  
        for (my $i=0;$i<=$level*5;$i++) {  sub entryline {
            $r->print('&nbsp;');      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
        }  
        $r->print('<a href="'.$url.'" target="cat">'.      my ($foldertitle,$pagetitle,$renametitle);
  ($title?$title:$url).'</a> ');      if (&is_supplemental_title($title)) {
        if ($url=~/^\/res\//) {   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
   my $result=&Apache::lonnet::repcopy(   $pagetitle = $foldertitle;
                               &Apache::lonnet::filelocation('',$url));      } else {
           if ($result eq 'ok') {   $title=&HTML::Entities::encode($title,'"<>&\'');
              $r->print('<font color="green">'.&mt('ok').'</font>');   $renametitle=$title;
              $r->rflush();   $foldertitle=$title;
              &Apache::lonnet::countacc($url);   $pagetitle=$title;
              $url=~/\.(\w+)$/;      }
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {  
  $r->print('<br />');      my $orderidx=$LONCAPA::map::order[$index];
                  $r->rflush();     
                  for (my $i=0;$i<=$level*5;$i++) {  
                      $r->print('&nbsp;');      $renametitle=~s/\\/\\\\/g;
                  }      $renametitle=~s/\&quot\;/\\\"/g;
                  $r->print('- '.&mt('Rendering').': ');      $renametitle=~s/ /%20/g;
  my ($errorcount,$warningcount)=split(/:/,      my $line='<tr>';
        &Apache::lonnet::ssi_body($url,      my ($form_start,$form_end);
        ('grade_target'=>'web',  # Edit commands
  'return_only_error_and_warning_counts' => 1)));      my ($container, $type, $esc_path, $path, $symb);
                  if (($errorcount) ||      if ($env{'form.folderpath'}) {
                      ($warningcount)) {   $type = 'folder';
      if ($errorcount) {          $container = 'sequence';
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.   $esc_path=&escape($env{'form.folderpath'});
   $errorcount.' '.   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   &mt('error(s)').'</b></font> ');   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
                      }      }
      if ($warningcount) {      if ($env{'form.pagepath'}) {
                         $r->print('<font color="blue">'.          $type = $container = 'page';
   $warningcount.' '.          $esc_path=&escape($path = $env{'form.pagepath'});
   &mt('warning(s)').'</font>');   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
                      }          $symb=&escape($env{'form.pagesymb'});
                  } else {      }
                      $r->print('<font color="green">'.&mt('ok').'</font>');      my $cpinfo='';
                  }      if ($allowed) {
                  $r->rflush();   my $incindex=$index+1;
              }   my $selectbox='';
      my $dependencies=   if (($folder!~/^supplemental/) &&
                 &Apache::lonnet::metadata($url,'dependencies');      ($#LONCAPA::map::order>0) &&
              foreach (split(/\,/,$dependencies)) {      ((split(/\:/,
  if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
                     &checkonthis($r,$_,$level+1);       ne '') &&
                  }      ((split(/\:/,
              }       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
           } elsif ($result eq 'unavailable') {       ne '')) {
              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');      $selectbox=
           } elsif ($result eq 'not_found') {   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
       unless ($url=~/\$/) {   '<select name="newpos" onChange="this.form.submit()">';
   $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
       } else {   if ($i==$incindex) {
   $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');      $selectbox.='<option value="" selected="1">('.$i.')</option>';
       }   } else {
           } else {      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');   }
           }      }
       }      $selectbox.='</select>';
    }   }
 }   my %lt=&Apache::lonlocal::texthash(
                   'up' => 'Move Up',
    'dw' => 'Move Down',
 #   'rm' => 'Remove',
 # ----------------------------------------------------------------- List Symbs                  'ct' => 'Cut',
 #    'rn' => 'Rename',
 sub list_symbs {   'cp' => 'Copy');
     my ($r) = @_;   my $nocopy=0;
           my $nocut=0;
     $r->print(&Apache::loncommon::start_page('Symb List'));          if ($url=~/\.(page|sequence)$/) {
     my $navmap = Apache::lonnavmaps::navmap->new();      if ($url =~ m{/res/}) {
     $r->print("<pre>\n");   # no copy for published maps
     foreach my $res ($navmap->retrieveResources()) {   $nocopy = 1;
  $r->print($res->compTitle()."\t".$res->symb()."\n");      } else {
     }   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
     $r->print("\n</pre>\n");      my ($title,$url,$ext,$type)=split(/\:/,$item);
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
 }   $nocopy=1;
    last;
       }
 #   }
 # -------------------------------------------------------------- Verify Content      }
 #    }
 sub verifycontent {          if ($url=~/^\/res\/lib\/templates\//) {
     my ($r) = @_;             $nocopy=1;
     my $type = &Apache::loncommon::course_type();             $nocut=1;
    my $loaderror=&Apache::lonnet::overloaderror($r);          }
    if ($loaderror) { return $loaderror; }          my $copylink='&nbsp;';
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));          my $cutlink='&nbsp;';
    $hashtied=0;  
    undef %alreadyseen;   my $skip_confirm = 0;
    %alreadyseen=();   if ( $folder =~ /^supplemental/
    &tiehash();       || ($url =~ m{( /smppg$
    foreach (keys %hash) {      |/syllabus$
        if ($hash{$_}=~/\.(page|sequence)$/) {      |/aboutme$
    if (($_=~/^src_/) && ($alreadyseen{&unescape($hash{$_})})) {      |/navmaps$
        $r->print('<hr /><font color="red">'.      |/bulletinboard$
  &mt('The following sequence or page is included more than once in your '.$type.': ').      |\.html$
  &unescape($hash{$_}).'</font><br />'.      |^/adm/wrapper/ext)}x)) {
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));      $skip_confirm = 1;
    }   }
        }  
        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$_})})) {   if (!$nocopy) {
            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});      $copylink=(<<ENDCOPY);
        }  <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
    }  ENDCOPY
    &untiehash();          }
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.   if (!$nocut) {
      &mt('Return to DOCS').'</a>');      $cutlink=(<<ENDCUT);
 }  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
   ENDCUT
           }
 # -------------------------------------------------------------- Check Versions   $form_start = (<<END);
      <form  action="/adm/coursedocs" method="post">
 sub devalidateversioncache {     <input type="hidden" name="${type}path" value="$path" />
     my $src=shift;     <input type="hidden" name="${type}symb" value="$symb" />
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.     <input type="hidden" name="setparms" value="$orderidx" />
   &Apache::lonnet::clutter($src));     <input type="hidden" name="changeparms" value="0" />
 }  END
           $form_end = '</form>';
 sub checkversions {   $line.=(<<END);
     my ($r) = @_;  <td>
     my $type = &Apache::loncommon::course_type();     <table class="LC_docs_entry_move">
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));        <tr>
     my $header='';           <td>
     my $startsel='';              <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>
     my $monthsel='';           </td>
     my $weeksel='';        </tr>
     my $daysel='';        <tr>
     my $allsel='';          <td>
     my %changes=();             <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 $starttime=0;          </td>
     my $haschanged=0;        </tr>
     my %setversions=&Apache::lonnet::dump('resourceversions',      </table>
   $env{'course.'.$env{'request.course.id'}.'.domain'},  </td>
   $env{'course.'.$env{'request.course.id'}.'.num'});  <td>
      $form_start
     $hashtied=0;     $selectbox
     &tiehash();     $form_end
     my %newsetversions=();  </td>
     if ($env{'form.setmostrecent'}) {  <td class="LC_docs_entry_commands">
  $haschanged=1;     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
  foreach (keys %hash) {  $cutlink
     if ($_=~/^ids\_(\/res\/.+)$/) {     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
  $newsetversions{$1}='mostrecent';  $copylink
                 &devalidateversioncache($1);  </td>
     }  END
  }  
     } elsif ($env{'form.setcurrent'}) {      }
  $haschanged=1;  # Figure out what kind of a resource this is
  foreach (keys %hash) {      my ($extension)=($url=~/\.(\w+)$/);
     if ($_=~/^ids\_(\/res\/.+)$/) {      my $uploaded=($url=~/^\/*uploaded\//);
  my $getvers=&Apache::lonnet::getversion($1);      my $icon=&Apache::loncommon::icon($url);
  if ($getvers>0) {      my $isfolder=0;
     $newsetversions{$1}=$getvers;      my $ispage=0;
     &devalidateversioncache($1);      my $folderarg;
  }      my $pagearg;
     }      my $pagefile;
  }      if ($uploaded) {
     } elsif ($env{'form.setversions'}) {   if ($extension eq 'sequence') {
  $haschanged=1;      $icon=$iconpath.'/folder_closed.gif';
  foreach (keys %env) {      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
     if ($_=~/^form\.set_version_(.+)$/) {      $url='/adm/coursedocs?';
  my $src=$1;      $folderarg=$1;
  if (($env{$_}) && ($env{$_} ne $setversions{$src})) {      $isfolder=1;
     $newsetversions{$src}=$env{$_};          } elsif ($extension eq 'page') {
     &devalidateversioncache($src);              $icon=$iconpath.'/page.gif';
  }              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
     }              $pagearg=$1;
  }              $url='/adm/coursedocs?';
     }              $ispage=1;
     if ($haschanged) {   } else {
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
   $env{'course.'.$env{'request.course.id'}.'.domain'},   }
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {      }
     $r->print('<h1>'.&mt('Your Version Settings have been Stored').'</h1>');     
  } else {      my $orig_url = $url;
     $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Store your Version Settings').'</font></h1>');      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
  }      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
  &mark_hash_old();   my $symb=&Apache::lonnet::symbclean(
     }            &Apache::lonnet::declutter('uploaded/'.
     &changewarning($r,'');             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
     if ($env{'form.timerange'} eq 'all') {             $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
 # show all documents             '.sequence').
  $header=&mt('All Documents in '.$type);             '___'.$residx.'___'.
  $allsel=1;     &Apache::lonnet::declutter($url));
  foreach (keys %hash) {   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
     if ($_=~/^ids\_(\/res\/.+)$/) {   $url=&Apache::lonnet::clutter($url);
  my $src=$1;   if ($url=~/^\/*uploaded\//) {
  $changes{$src}=1;      $url=~/\.(\w+)$/;
     }      my $embstyle=&Apache::loncommon::fileembstyle($1);
  }      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
     } else {   $url='/adm/wrapper'.$url;
 # show documents which changed      } elsif ($embstyle eq 'ssi') {
  %changes=&Apache::lonnet::dump   #do nothing with these
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},      } elsif ($url!~/\.(sequence|page)$/) {
                      $env{'course.'.$env{'request.course.id'}.'.num'});   $url='/adm/coursedocs/showdoc'.$url;
  my $firstkey=(keys %changes)[0];      }
  unless ($firstkey=~/^error\:/) {   } elsif ($url=~m|^/ext/|) {
     unless ($env{'form.timerange'}) {      $url='/adm/wrapper'.$url;
  $env{'form.timerange'}=604800;      $external = 1;
     }   }
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '          if (&Apache::lonnet::symbverify($symb,$url)) {
  .&mt('seconds');      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
     if ($env{'form.timerange'}==-1) {          } else {
  $seltext='since start of course';              $url='';
  $startsel='selected';          }
  $env{'form.timerange'}=time;   if ($container eq 'page') {
     }      my $symb=$env{'form.pagesymb'};
     $starttime=time-$env{'form.timerange'};          
     if ($env{'form.timerange'}==2592000) {      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  $monthsel='selected';   }
     } elsif ($env{'form.timerange'}==604800) {      }
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
  $weeksel='selected';      if ($isfolder || $extension eq 'sequence') {
     } elsif ($env{'form.timerange'}==86400) {   my $foldername=&escape($foldertitle);
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   my $folderpath=$env{'form.folderpath'};
  $daysel='selected';   if ($folderpath) { $folderpath.='&' };
     }  # Append randompick number, hidden, and encrypted with ":" to foldername,
     $header=&mt('Content changed').' '.$seltext;  # so it gets transferred between levels
  } else {   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
     $header=&mt('No content modifications yet.');                                                'parameter_randompick'))[0]
  }                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     }                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
     %setversions=&Apache::lonnet::dump('resourceversions',                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
   $env{'course.'.$env{'request.course.id'}.'.domain'},                                                'parameter_encrypturl'))[0]=~/^yes$/i)
   $env{'course.'.$env{'request.course.id'}.'.num'});                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     my %lt=&Apache::lonlocal::texthash                                                'parameter_randomorder'))[0]=~/^yes$/i);
       ('st' => 'Version changes since start of '.$type,   $url.='folderpath='.&escape($folderpath).$cpinfo;
        'lm' => 'Version changes since last Month',   $parameterset='<label>'.&mt('Randomly Pick: ').
        'lw' => 'Version changes since last Week',      '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
        'sy' => 'Version changes since Yesterday',      (&LONCAPA::map::getparameter($orderidx,
                'al' => 'All Resources (possibly large output)',                                                'parameter_randompick'))[0].
        'sd' => 'Display',                                                '" />'.
        'fi' => 'File',  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
        'md' => 'Modification Date',      my $ro_set=
                'mr' => 'Most recently published Version',      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
        've' => 'Version used in '.$type,   $rand_order_text ='
                'vu' => 'Set Version to be used in '.$type,  <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>';  
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      }
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      if ($ispage) {
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',          my $pagename=&escape($pagetitle);
        'di' => 'Differences');          my $pagepath;
     $r->print(<<ENDHEADERS);          my $folderpath=$env{'form.folderpath'};
 <form action="/adm/coursedocs" method="post">          if ($folderpath) { $pagepath = $folderpath.'&' };
 <input type="hidden" name="versions" value="1" />          $pagepath.=$pagearg.'&'.$pagename;
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />   my $symb=$env{'form.pagesymb'};
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />   if (!$symb) {
 <select name="timerange">      my $path='uploaded/'.
 <option value='all' $allsel>$lt{'al'}</option>   $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 <option value="-1" $startsel>$lt{'st'}</option>   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 <option value="2592000" $monthsel>$lt{'lm'}</option>      $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
 <option value="604800" $weeksel>$lt{'lw'}</option>         $residx,
 <option value="86400" $daysel>$lt{'sy'}</option>         $path.$pagearg.'.page');
 </select>   }
 <input type="submit" name="display" value="$lt{'sd'}" />   $url.='pagepath='.&escape($pagepath).
 <h3>$header</h3>      '&amp;pagesymb='.&escape($symb).$cpinfo;
 <input type="submit" name="setversions" value="$lt{'sv'}" />      }
 <table border="0">      if ($external) {
 ENDHEADERS   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
     foreach (sort keys %changes) {   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
  if ($changes{$_}>$starttime) {      } else {
     my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);   undef($external);
     my $currentversion=&Apache::lonnet::getversion($_);      }
     if ($currentversion<0) {      $line.='
  $currentversion=&mt('Could not be determined.');    <td class="LC_docs_entry_icon">
     }      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
     my $linkurl=&Apache::lonnet::clutter($_);    </td>
     $r->print(    <td class="LC_docs_entry_title">
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.      '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."
       &Apache::lonnet::gettitle($linkurl).    </td>";
                       '</b></font></td></tr>'.      if (($allowed) && ($folder!~/^supplemental/)) {
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.    my %lt=&Apache::lonlocal::texthash(
                       '<td colspan="4">'.         'hd' => 'Hidden',
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.         'ec' => 'URL hidden');
       '</a></td></tr>'.   my $enctext=
                       '<tr><td></td>'.      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
                       '<td title="'.$lt{'md'}.'">'.   my $hidtext=
       &Apache::lonlocal::locallocaltime(      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
                            &Apache::lonnet::metadata($root.'.'.$extension,   $line.=(<<ENDPARMS);
                                                      'lastrevisiondate')    <td class="LC_docs_entry_parameter">
                                                         ).      $form_start
                       '</td>'.      <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.      $form_end
                       '<font size="+1">'.$currentversion.'</font>'.    </td>
                       '</nobr></td>'.    <td class="LC_docs_entry_parameter">
                       '<td title="'.$lt{'ve'}.'"><nobr>In '.$type.': '.      $form_start
                       '<font size="+1">');      <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
 # Used in course      $form_end
     my $usedversion=$hash{'version_'.$linkurl};    </td>
     if (($usedversion) && ($usedversion ne 'mostrecent')) {    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
  $r->print($usedversion);    <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
     } else {  ENDPARMS
  $r->print($currentversion);      }
     }      $line.="</tr>";
     $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.      return $line;
                       '<nobr>Use: ');  }
 # Set version  
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},  =pod
       'set_version_'.$linkurl,  
       ('select_form_order' =>  =item tiehash()
        ['',1..$currentversion,'mostrecent'],  
        '' => '',  tie the hash
        'mostrecent' => 'most recent',  
        map {$_,$_} (1..$currentversion))));  =cut
     $r->print('</nobr></td></tr><tr><td></td>');  
     my $lastold=1;  sub tiehash {
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {      my ($mode)=@_;
  my $url=$root.'.'.$prevvers.'.'.$extension;      $hashtied=0;
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<      if ($env{'request.course.fn'}) {
     $starttime) {   if ($mode eq 'write') {
     $lastold=$prevvers;      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  }      &GDBM_WRCREAT(),0640)) {
     }                  $hashtied=2;
             #       }
             # Code to figure out how many version entries should go in   } else {
             # each of the four columns      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
             my $entries_per_col = 0;      &GDBM_READER(),0640)) {
             my $num_entries = ($currentversion-$lastold);                  $hashtied=1;
             if ($num_entries % 4 == 0) {      }
                 $entries_per_col = $num_entries/4;   }
             } else {      }    
                 $entries_per_col = $num_entries/4 + 1;  }
             }  
             my $entries_count = 0;  sub untiehash {
             $r->print('<td valign="top"><font size="-2">');       if ($hashtied) { untie %hash; }
             my $cols_output = 1;      $hashtied=0;
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {      return OK;
  my $url=$root.'.'.$prevvers.'.'.$extension;  }
  $r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).  
   '">'.&mt('Version').' '.$prevvers.'</a> ('.  
   &Apache::lonlocal::locallocaltime(  
                                 &Apache::lonnet::metadata($url,  
                                                           'lastrevisiondate')  sub checkonthis {
                                                             ).      my ($r,$url,$level,$title)=@_;
   ')');      $url=&unescape($url);
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {      $alreadyseen{$url}=1;
                     $r->print(' <a href="/adm/diff?filename='.      $r->rflush();
       &Apache::lonnet::clutter($root.'.'.$extension).      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
       '&versionone='.$prevvers.         $r->print("\n<br />");
       '">'.&mt('Diffs').'</a>');         if ($level==0) {
  }             $r->print("<br />");
  $r->print('</nobr><br />');         }
                 if (++$entries_count % $entries_per_col == 0) {         for (my $i=0;$i<=$level*5;$i++) {
                     $r->print('</font></td>');             $r->print('&nbsp;');
                     if ($cols_output != 4) {         }
                         $r->print('<td valign="top"><font size="-2">');         $r->print('<a href="'.$url.'" target="cat">'.
                         $cols_output++;   ($title?$title:$url).'</a> ');
                     }         if ($url=~/^\/res\//) {
                 }    my $result=&Apache::lonnet::repcopy(
     }                                &Apache::lonnet::filelocation('',$url));
             while($cols_output++ < 4) {            if ($result eq 'ok') {
                 $r->print('</font></td><td><font>')               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
             }               $r->rflush();
     $r->print('</font></td></tr>'."\n");               &Apache::lonnet::countacc($url);
  }               $url=~/\.(\w+)$/;
     }               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
     $r->print('</table></form>');   $r->print('<br />');
     $r->print('<h1>'.&mt('Done').'.</h1>');                   $r->rflush();
                    for (my $i=0;$i<=$level*5;$i++) {
     &untiehash();                       $r->print('&nbsp;');
 }                   }
                    $r->print('- '.&mt('Rendering:').' ');
 sub mark_hash_old {   my ($errorcount,$warningcount)=split(/:/,
     my $retie_hash=0;         &Apache::lonnet::ssi_body($url,
     if ($hashtied) {         ('grade_target'=>'web',
  $retie_hash=1;   'return_only_error_and_warning_counts' => 1)));
  &untiehash();                   if (($errorcount) ||
     }                       ($warningcount)) {
     &tiehash('write');       if ($errorcount) {
     $hash{'old'}=1;                          $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.
     &untiehash();                            &mt('[quant,_1,error]',$errorcount).'</span>');
     if ($retie_hash) { &tiehash(); }                       }
 }       if ($warningcount) {
                           $r->print('<span class="LC_warning">'.
 sub is_hash_old {                            &mt('[quant,_1,warning]',$warningcount).'</span>');
     my $untie_hash=0;                       }
     if (!$hashtied) {                   } else {
  $untie_hash=1;                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  &tiehash();                   }
     }                   $r->rflush();
     my $return=$hash{'old'};               }
     if ($untie_hash) { &untiehash(); }       my $dependencies=
     return $return;                  &Apache::lonnet::metadata($url,'dependencies');
 }               foreach my $dep (split(/\,/,$dependencies)) {
    if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 sub changewarning {                      &checkonthis($r,$dep,$level+1);
     my ($r,$postexec,$message,$url)=@_;                   }
     if (!&is_hash_old()) { return; }               }
     my $pathvar='folderpath';            } elsif ($result eq 'unavailable') {
     my $path=&escape($env{'form.folderpath'});               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
     if (!defined($url)) {            } elsif ($result eq 'not_found') {
  if (defined($env{'form.pagepath'})) {        unless ($url=~/\$/) {
     $pathvar='pagepath';    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
     $path=&escape($env{'form.pagepath'});        } else {
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});    $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');
  }        }
  $url='/adm/coursedocs?'.$pathvar.'='.$path;            } else {
     }               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
     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".  
 '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".   
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.  
 '<input type="hidden" name="orgurl" value="'.$url.  =pod
 '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.  
 &mt($message,' <input type="hidden" name="'.  =item list_symbs()
     $env{'request.role'}.'" value="1" /><input type="button" value="'.  
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').  List Symbs
 $help{'Caching'}.'</font></h3></form>'."\n\n");  
 }  =cut
   
 # ================================================================ Main Handler  sub list_symbs {
 sub handler {      my ($r) = @_;
     my $r = shift;  
     &Apache::loncommon::content_type($r,'text/html');      my $type = &Apache::loncommon::course_type();
     $r->send_http_header;      $r->print(&Apache::loncommon::start_page('Symb List'));
     return OK if $r->header_only;      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
     my $type = &Apache::loncommon::course_type();      my $navmap = Apache::lonnavmaps::navmap->new();
       if (!defined($navmap)) {
 # --------------------------------------------- Initialize help topics for this          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
     foreach ('Adding_Course_Doc','Main_Course_Documents',                    '<div class="LC_error">'.
      'Adding_External_Resource','Navigate_Content',                    &mt('Unable to retrieve information about course contents').
      'Adding_Folders','Docs_Overview', 'Load_Map',                    '</div>');
      'Supplemental','Score_Upload_Form','Adding_Pages',          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
      'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',      } else {
      'Check_Resource_Versions','Verify_Content') {          $r->print("<pre>\n");
  $help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);          foreach my $res ($navmap->retrieveResources()) {
     }      $r->print($res->compTitle()."\t".$res->symb()."\n");
     # Composite help files          }
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(          $r->print("\n</pre>\n");
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');      }
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(      $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');  }
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(  
     'Option_Response_Simple');  
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(  sub verifycontent {
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');      my ($r) = @_;
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(      my $type = &Apache::loncommon::course_type();
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');     my $loaderror=&Apache::lonnet::overloaderror($r);
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');     if ($loaderror) { return $loaderror; }
      $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
 # does this user have privileges to modify docs     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});     $hashtied=0;
      undef %alreadyseen;
   if ($allowed && $env{'form.verify'}) {     %alreadyseen=();
       &verifycontent($r);     &tiehash();
   } elsif ($allowed && $env{'form.listsymbs'}) {     foreach my $key (keys(%hash)) {
       &list_symbs($r);         if ($hash{$key}=~/\.(page|sequence)$/) {
   } elsif ($allowed && $env{'form.versions'}) {     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
       &checkversions($r);         $r->print('<hr /><span class="LC_error">'.
   } elsif ($allowed && $env{'form.dumpcourse'}) {   &mt('The following sequence or page is included more than once in your '.$type.': ').
       &dumpcourse($r);   &unescape($hash{$key}).'</span><br />'.
   } elsif ($allowed && $env{'form.exportcourse'}) {   &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
       &exportcourse($r);     }
   } else {         }
 # is this a standard course?         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
              &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);         }
     my $forcestandard = 0;     }
     my $forcesupplement;     &untiehash();
     my $script='';     $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
     my $showdoc=0;       &mt('Return to DOCS').'</a>');
     my $containertag;  }
     my $uploadtag;  
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  
     ['folderpath','pagepath',  sub devalidateversioncache {
      'pagesymb','markedcopy_url',      my $src=shift;
      'markedcopy_title']);      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
     if ($env{'form.folderpath'}) {    &Apache::lonnet::clutter($src));
  my (@folderpath)=split('&',$env{'form.folderpath'});  }
  $env{'form.foldername'}=&unescape(pop(@folderpath));  
  $env{'form.folder'}=pop(@folderpath);  sub checkversions {
     }      my ($r) = @_;
     if ($env{'form.pagepath'}) {      my $type = &Apache::loncommon::course_type();
         my (@pagepath)=split('&',$env{'form.pagepath'});      $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
         $env{'form.pagename'}=&unescape(pop(@pagepath));      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));
         $env{'form.folder'}=pop(@pagepath);      my $header='';
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      my $startsel='';
     '<input type="hidden" name="pagesymb" value="" />';      my $monthsel='';
         $uploadtag = '<input type="hidden" name="pagepath" value="'.$env{'form.pagepath'}.'" />'.      my $weeksel='';
     '<input type="hidden" name="pagesymb" value="'.$env{'form.pagesymb'}.'" />';      my $daysel='';
     }      my $allsel='';
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {      my %changes=();
        $showdoc='/'.$1;      my $starttime=0;
     }      my $haschanged=0;
     unless ($showdoc) { # got called from remote      my %setversions=&Apache::lonnet::dump('resourceversions',
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||     $env{'course.'.$env{'request.course.id'}.'.domain'},
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {    $env{'course.'.$env{'request.course.id'}.'.num'});
            $forcestandard = 1;  
        }       $hashtied=0;
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);      &tiehash();
       my %newsetversions=();
        if ($allowed) {       if ($env{'form.setmostrecent'}) {
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);   $haschanged=1;
          $script=&Apache::lonratedt::editscript('simple');    foreach my $key (keys(%hash)) {
        }      if ($key=~/^ids\_(\/res\/.+)$/) {
     } else { # got called in sequence from course   $newsetversions{$1}='mostrecent';
        $allowed=0;                  &devalidateversioncache($1);
     }      }
    }
 # get course data      } elsif ($env{'form.setcurrent'}) {
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};   $haschanged=1;
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};   foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
 # get personal data    my $getvers=&Apache::lonnet::getversion($1);
     my $uname=$env{'user.name'};   if ($getvers>0) {
     my $udom=$env{'user.domain'};      $newsetversions{$1}=$getvers;
     my $plainname=&escape(      &devalidateversioncache($1);
                      &Apache::loncommon::plainname($uname,$udom));   }
       }
 # graphics settings   }
       } elsif ($env{'form.setversions'}) {
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");   $haschanged=1;
    foreach my $key (keys(%env)) {
     if ($allowed) {      if ($key=~/^form\.set_version_(.+)$/) {
  $script .= &editing_js($udom,$uname);   my $src=$1;
     }   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
 # -------------------------------------------------------------------- Body tag      $newsetversions{$src}=$env{$key};
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';      &devalidateversioncache($src);
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,   }
      {'force_register' => $showdoc,}).      }
       &Apache::loncommon::help_open_menu('','',273,'RAT'));   }
         }
   my %allfiles = ();      if ($haschanged) {
   my %codebase = ();          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
   my ($upload_result,$upload_output);    $env{'course.'.$env{'request.course.id'}.'.domain'},
   if ($allowed) {    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
       if (($env{'form.uploaddoc.filename'}) &&                                               ($env{'form.cmd'}=~/^upload_(\w+)/)) {      $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
 # Process file upload - phase one - upload and parse primary file.     } else {
           $upload_result = &process_file_upload(\$upload_output,$coursenum,      $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
  $coursedom,\%allfiles,   }
  \%codebase,$1);   &mark_hash_old();
           if ($upload_result eq 'phasetwo') {      }
               $r->print($upload_output);      &changewarning($r,'');
           }      if ($env{'form.timerange'} eq 'all') {
       } elsif ($env{'form.phasetwo'}) {  # show all documents
           my %newname = ();   $header=&mt('All Documents in '.$type);
           my %origname = ();   $allsel=1;
           my %attribs = ();   foreach my $key (keys(%hash)) {
           my $updateflag = 0;      if ($key=~/^ids\_(\/res\/.+)$/) {
           my $residx = $env{'form.newidx'};   my $src=$1;
           my $primary_url = &unescape($env{'form.primaryurl'});   $changes{$src}=1;
 # Process file upload - phase two - gather secondary files.      }
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {   }
               if ($env{'form.embedded_item_'.$i.'.filename'}) {      } else {
                   my $javacodebase;  # show documents which changed
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);   %changes=&Apache::lonnet::dump
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
                   if (exists($env{'form.embedded_codebase_'.$i})) {                       $env{'course.'.$env{'request.course.id'}.'.num'});
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});     my $firstkey=(keys(%changes))[0];
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;    unless ($firstkey=~/^error\:/) {
                   }      unless ($env{'form.timerange'}) {
                   my @attributes = ();   $env{'form.timerange'}=604800;
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {      }
                       @attributes = split/:/,$env{'form.embedded_attrib_'.$i};      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
                   } else {   .&mt('seconds');
                       @attributes = ($env{'form.embedded_attrib_'.$i});      if ($env{'form.timerange'}==-1) {
                   }   $seltext='since start of course';
                   foreach (@attributes) {   $startsel='selected';
                       push(@{$attribs{$i}},&unescape($_));   $env{'form.timerange'}=time;
                   }      }
                   if ($javacodebase) {      $starttime=time-$env{'form.timerange'};
                       $codebase{$i} = $javacodebase;      if ($env{'form.timerange'}==2592000) {
                       $codebase{$i} =~ s#/$##;   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
                       $updateflag = 1;   $monthsel='selected';
                   }      } elsif ($env{'form.timerange'}==604800) {
               }   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
               unless ($newname{$i} eq $origname{$i}) {   $weeksel='selected';
                   $updateflag = 1;      } elsif ($env{'form.timerange'}==86400) {
               }   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
           }   $daysel='selected';
 # Process file upload - phase three - modify primary file      }
           if ($updateflag) {      $header=&mt('Content changed').' '.$seltext;
               my ($content,$rtncode);   } else {
               my $updateflag = 0;      $header=&mt('No content modifications yet.');
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);   }
               if ($getstatus eq 'ok') {      }
                   foreach my $item (keys %newname) {      %setversions=&Apache::lonnet::dump('resourceversions',
                       if ($newname{$item} ne $origname{$item}) {    $env{'course.'.$env{'request.course.id'}.'.domain'},
                           my $attrib_regexp = '';    $env{'course.'.$env{'request.course.id'}.'.num'});
                           if (@{$attribs{$item}} > 1) {      my %lt=&Apache::lonlocal::texthash
                               $attrib_regexp = join('|',@{$attribs{$item}});        ('st' => 'Version changes since start of '.$type,
                           } else {         'lm' => 'Version changes since last Month',
                               $attrib_regexp = $attribs{$item}[0];         'lw' => 'Version changes since last Week',
                           }         'sy' => 'Version changes since Yesterday',
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {                 'al' => 'All Resources (possibly large output)',
                           }          'sd' => 'Display',
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;          'fi' => 'File',
                       }         'md' => 'Modification Date',
                       if (exists($codebase{$item})) {                 'mr' => 'Most recently published Version',
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs         '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',
 # Save edited file.  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
                   my $saveresult;  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};         'di' => 'Differences');
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};      $r->print(<<ENDHEADERS);
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);  <form action="/adm/coursedocs" method="post">
               } else {  <input type="hidden" name="versions" value="1" />
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);   <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
               }  <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
           }  <select name="timerange">
       }  <option value='all' $allsel>$lt{'al'}</option>
   }  <option value="-1" $startsel>$lt{'st'}</option>
   <option value="2592000" $monthsel>$lt{'lm'}</option>
   unless ($showdoc ||  $upload_result eq 'phasetwo') {  <option value="604800" $weeksel>$lt{'lw'}</option>
 # -----------------------------------------------------------------------------  <option value="86400" $daysel>$lt{'sy'}</option>
        my %lt=&Apache::lonlocal::texthash(  </select>
                 'uplm' => 'Upload a new main '.lc($type).' document',  <input type="submit" name="display" value="$lt{'sd'}" />
                 'upls' => 'Upload a new supplemental '.lc($type).' document',  <h3>$header</h3>
                 'impp' => 'Import a document',  <input type="submit" name="setversions" value="$lt{'sv'}" />
                 'pubd' => 'Published documents',  <table border="0">
  'copm' => 'All documents out of a published map into this folder',  ENDHEADERS
                 'spec' => 'Special documents',      foreach my $key (sort(keys(%changes))) {
                 'upld' => 'Upload Document',   if ($changes{$key}>$starttime) {
                 'srch' => 'Search',      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
                 'impo' => 'Import',      my $currentversion=&Apache::lonnet::getversion($key);
  'book' => 'Import Bookmarks',      if ($currentversion<0) {
                 'selm' => 'Select Map',   $currentversion=&mt('Could not be determined.');
                 'load' => 'Load Map',      }
                 'reco' => 'Recover Deleted Resources',      my $linkurl=&Apache::lonnet::clutter($key);
                 'newf' => 'New Folder',      $r->print(
                 'newp' => 'New Composite Page',        '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
                 'extr' => 'External Resource',        &Apache::lonnet::gettitle($linkurl).
                 'syll' => 'Syllabus',                        '</b></font></td></tr>'.
                 'navc' => 'Navigate Contents',                        '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
                 'sipa' => 'Simple Page',                        '<td colspan="4">'.
                 'sipr' => 'Simple Problem',                        '<a href="'.$linkurl.'" target="cat">'.$linkurl.
                 'drbx' => 'Drop Box',        '</a></td></tr>'.
                 'scuf' => 'Score Upload Form',                        '<tr><td></td>'.
                 'bull' => 'Bulletin Board',                        '<td title="'.$lt{'md'}.'">'.
                 'mypi' => 'My Personal Info',        &Apache::lonlocal::locallocaltime(
  'abou' => 'About User',                             &Apache::lonnet::metadata($root.'.'.$extension,
                 'imsf' => 'Import IMS package',                                                       'lastrevisiondate')
                 'file' =>  'File',                                                          ).
                 'title' => 'Title',                        '</td>'.
                 'comment' => 'Comment',                        '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
                 'parse' => 'If HTML file, upload embedded images/multimedia files'                        '<font size="+1">'.$currentversion.'</font>'.
   );                        '</span></td>'.
 # -----------------------------------------------------------------------------                        '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.
     if ($allowed) {                        '<font size="+1">');
        my $dumpbut=&dumpbutton();  # Used in course
        my $exportbut=&exportbutton();      my $usedversion=$hash{'version_'.$linkurl};
        my %lt=&Apache::lonlocal::texthash(      if (($usedversion) && ($usedversion ne 'mostrecent')) {
  'vc' => 'Verify Content',   $r->print($usedversion);
  'cv' => 'Check/Set Resource Versions',      } else {
  'ls' => 'List Symbs',   $r->print($currentversion);
   );      }
       $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
        my $folderpath=$env{'form.folderpath'};                        '<span class="LC_nobreak">Use: ');
        if (!$folderpath) {  # Set version
    if ($env{'form.folder'} eq '' ||      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
        $env{'form.folder'} eq 'supplemental') {        'set_version_'.$linkurl,
        $folderpath='default&'.        ('select_form_order' =>
    &escape(&mt('Main '.$type.' Documents'));         ['',1..$currentversion,'mostrecent'],
    }         '' => '',
        }         'mostrecent' => 'most recent',
        unless ($env{'form.pagepath'}) {         map {$_,$_} (1..$currentversion))));
            $containertag = '<input type="hidden" name="folderpath" value="" />';      $r->print('</span></td></tr><tr><td></td>');
            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';      my $lastold=1;
        }      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
    my $url=$root.'.'.$prevvers.'.'.$extension;
        $r->print(<<ENDCOURSEVERIFY);   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
 <form name="renameform" method="post" action="/adm/coursedocs">      $starttime) {
 <input type="hidden" name="title" />      $lastold=$prevvers;
 <input type="hidden" name="cmd" />   }
 <input type="hidden" name="markcopy" />      }
 $containertag              #
 </form>              # Code to figure out how many version entries should go in
 <form name="simpleedit" method="post" action="/adm/coursedocs">              # each of the four columns
 <input type=hidden name="importdetail" value="">              my $entries_per_col = 0;
 $uploadtag              my $num_entries = ($currentversion-$lastold);
 </form>              if ($num_entries % 4 == 0) {
 <form action="/adm/coursedocs" method="post" name="courseverify">                  $entries_per_col = $num_entries/4;
 <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">              } else {
 <tr><td bgcolor="#DDDDCC">                  $entries_per_col = $num_entries/4 + 1;
 <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}              }
 </td><td bgcolor="#DDDDCC">              my $entries_count = 0;
     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}              $r->print('<td valign="top"><font size="-2">');
 $dumpbut              my $cols_output = 1;
 $exportbut              for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
 </td><td bgcolor="#DDDDCC">   my $url=$root.'.'.$prevvers.'.'.$extension;
     <input type="submit" name="listsymbs" value="$lt{'ls'}" />   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
 </td></tr></table>    '">'.&mt('Version').' '.$prevvers.'</a> ('.
 </form>    &Apache::lonlocal::locallocaltime(
 ENDCOURSEVERIFY                                  &Apache::lonnet::metadata($url,
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',                                                            'lastrevisiondate')
      &mt('Editing the Table of Contents for your '.$type)));                                                              ).
     }    ')');
 # --------------------------------------------------------- Standard documents   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
     $r->print('<table border=2 cellspacing=4 cellpadding=4>');                      $r->print(' <a href="/adm/diff?filename='.
     if (($standard) && ($allowed) && (!$forcesupplement)) {        &Apache::lonnet::clutter($root.'.'.$extension).
  $r->print('<tr><td bgcolor="#BBBBBB">');        '&versionone='.$prevvers.
 #  '<h2>'.&mt('Main Course Documents').        '">'.&mt('Diffs').'</a>');
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');   }
        my $folder=$env{'form.folder'};   $r->print('</span><br />');
        if ($folder eq '' || $folder eq 'supplemental') {                  if (++$entries_count % $entries_per_col == 0) {
            $folder='default';                      $r->print('</font></td>');
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));                      if ($cols_output != 4) {
        }                          $r->print('<td valign="top"><font size="-2">');
        my $postexec='';                          $cols_output++;
        if ($folder eq 'default') {                      }
    $r->print('<script>this.window.name="loncapaclient";</script>');                  }
        } else {      }
            #$postexec='self.close();';              while($cols_output++ < 4) {
        }                  $r->print('</font></td><td><font>')
        $hadchanges=0;              }
        &editor($r,$coursenum,$coursedom,$folder,$allowed,$upload_output);      $r->print('</font></td></tr>'."\n");
        if ($hadchanges) {   }
    &mark_hash_old()      }
        }      $r->print('</table></form>');
        &changewarning($r,$postexec);      $r->print('<h1>'.&mt('Done').'.</h1>');
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  
                      '.sequence';      &untiehash();
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  }
                      '.page';  
  my $container='sequence';  sub mark_hash_old {
  if ($env{'form.pagepath'}) {      my $retie_hash=0;
     $container='page';      if ($hashtied) {
  }   $retie_hash=1;
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;   &untiehash();
        $r->print(<<ENDFORM);      }
 <table cellspacing=4 cellpadding=4><tr>      &tiehash('write');
 <th bgcolor="#DDDDDD">$lt{'uplm'}</th>      $hash{'old'}=1;
 <th bgcolor="#DDDDDD">$lt{'impp'}</th>      &untiehash();
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>      if ($retie_hash) { &tiehash(); }
 </tr>  }
 <tr><td bgcolor="#DDDDDD">  
 $lt{'file'}:<br />  sub is_hash_old {
 <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">      my $untie_hash=0;
 <input type="file" name="uploaddoc" size="40">      if (!$hashtied) {
 <br />   $untie_hash=1;
 $lt{'title'}:<br />   &tiehash();
 <input type="text" size="50" name="comment">      }
 $uploadtag      my $return=$hash{'old'};
 <input type="hidden" name="cmd" value="upload_default">      if ($untie_hash) { &untiehash(); }
 <br />      return $return;
 <nobr>  }
 <label>$lt{'parse'}?  
 <input type="checkbox" name="parserflag" />  sub changewarning {
 </label>      my ($r,$postexec,$message,$url)=@_;
 </nobr>      if (!&is_hash_old()) { return; }
 <br />      my $pathvar='folderpath';
 <br />      my $path=&escape($env{'form.folderpath'});
 <nobr>      if (!defined($url)) {
 <input type="submit" value="$lt{'upld'}">   if (defined($env{'form.pagepath'})) {
  $help{'Uploading_From_Harddrive'}      $pathvar='pagepath';
 </nobr>      $path=&escape($env{'form.pagepath'});
 </form>      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
 </td>   }
 <td bgcolor="#DDDDDD">   $url='/adm/coursedocs?'.$pathvar.'='.$path;
 <form action="/adm/coursedocs" method="post" name="simpleeditdefault">      }
 $lt{'pubd'}<br />      my $course_type = &Apache::loncommon::course_type();
 $uploadtag      if (!defined($message)) {
 <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}" />   $message='Changes will become active for your current session after [_1], or the next time you log in.';
 <br />      }
 <nobr>      $r->print("\n\n".
 <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}" />  '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".
 $help{'Importing_LON-CAPA_Resource'}  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 </nobr>  '<input type="hidden" name="orgurl" value="'.$url.
 <br />  '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.
 <input type=button onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />  &mt($message,' <input type="hidden" name="'.
 <p>      $env{'request.role'}.'" value="1" /><input type="button" value="'.
 <hr />      &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
 $lt{'copm'}<br />  $help{'Caching'}.'</span></h3></form>'."\n\n");
 <input type="text" size="40" name="importmap"><br />  }
 <nobr><input type=button   
 onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"  
 value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">  sub init_breadcrumbs {
 $help{'Load_Map'}</nobr>      my ($form,$text)=@_;
 </p>      &Apache::lonhtmlcommon::clear_breadcrumbs();
 </form>      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
 <hr />      text=>"Edit ".&Apache::loncommon::course_type(),
 <form action="/adm/groupsort" method="post" name="recover">      faq=>273,
 <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />      bug=>'Instructor Interface',
 </form>                                              help => 'Docs_Adding_Course_Doc'});
 ENDFORM      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
        unless ($env{'form.pagepath'}) {      text=>$text,
    $r->print(<<ENDFORM);      faq=>273,
 <hr />      bug=>'Instructor Interface'});
 <form action="/adm/coursedocs" method="post" name="newext">  }
 $uploadtag  
 <input type=hidden name="importdetail" value="">  
 <nobr>  
 <input name="newext" type="button" onClick="javascript:makenewext('newext');"  
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}  sub handler {
 </nobr>      my $r = shift;
 </form>      &Apache::loncommon::content_type($r,'text/html');
 <br /><form action="/adm/imsimportdocs" method="post" name="ims">      $r->send_http_header;
 <input type="hidden" name="folder" value="$folder" />      return OK if $r->header_only;
 <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />      my $type = &Apache::loncommon::course_type();
 </nobr>  
 </form>  
 ENDFORM  # --------------------------------------------- Initialize help topics for this
        }      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
        $r->print('</td><td bgcolor="#DDDDDD">');                 'Adding_External_Resource','Navigate_Content',
        unless ($env{'form.pagepath'}) {                 'Adding_Folders','Docs_Overview', 'Load_Map',
            $r->print(<<ENDFORM);                 'Supplemental','Score_Upload_Form','Adding_Pages',
 <br /><form action="/adm/coursedocs" method="post" name="newfolder">                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                 'Check_Resource_Versions','Verify_Content') {
 <input type=hidden name="importdetail" value="">   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 <nobr>      }
 <input name="newfolder" type="button"      # Composite help files
 onClick="javascript:makenewfolder(this.form,'$folderseq');"      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 value="$lt{'newf'}" />$help{'Adding_Folders'}      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 </nobr>      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 </form>      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 <br /><form action="/adm/coursedocs" method="post" name="newpage">      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      'Option_Response_Simple');
 <input type=hidden name="importdetail" value="">      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 <nobr>      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 <input name="newpage" type="button"      $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
 onClick="javascript:makenewpage(this.form,'$pageseq');"    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 value="$lt{'newp'}" />$help{'Adding_Pages'}      $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 </nobr>      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 </form>  
 <br /><form action="/adm/coursedocs" method="post" name="newsyl">  # does this user have privileges to modify docs
 $uploadtag      my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 <input type=hidden name="importdetail"     if ($allowed && $env{'form.verify'}) {
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">        &init_breadcrumbs('verify','Verify Content');
 <nobr>        &verifycontent($r);
 <input name="newsyl" type="submit" value="$lt{'syll'}" />     } elsif ($allowed && $env{'form.listsymbs'}) {
  $help{'Syllabus'}        &init_breadcrumbs('listsymbs','List Symbs');
 </nobr>        &list_symbs($r);
 </form>    } elsif ($allowed && $env{'form.docslog'}) {
 <br /><form action="/adm/coursedocs" method="post" name="newnav">        &init_breadcrumbs('docslog','Show Log');
 $uploadtag        &docs_change_log($r);
 <input type=hidden name="importdetail"     } elsif ($allowed && $env{'form.versions'}) {
 value="Navigate Content=/adm/navmaps">        &init_breadcrumbs('versions','Check/Set Resource Versions');
 <nobr>        &checkversions($r);
 <input name="newnav" type="submit" value="$lt{'navc'}" />    } elsif ($allowed && $env{'form.dumpcourse'}) {
 $help{'Navigate_Content'}        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
 </nobr>        &dumpcourse($r);
 </form>    } elsif ($allowed && $env{'form.exportcourse'}) {
 <br /><form action="/adm/coursedocs" method="post" name="newsmppg">        &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');
 $uploadtag        &exportcourse($r);
 <input type=hidden name="importdetail" value="">    } else {
 <nobr>  # is this a standard course?
 <input name="newsmppg" type="button" value="$lt{'sipa'}"  
 onClick="javascript:makesmppage();" /> $help{'Simple Page'}      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 </nobr>      my $forcestandard = 0;
 </form>      my $forcesupplement;
 <br /><form action="/adm/coursedocs" method="post" name="newsmpproblem">      my $script='';
 $uploadtag      my $showdoc=0;
 <input type=hidden name="importdetail" value="">      my $containertag;
 <nobr>      my $uploadtag;
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"  
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}  
 </nobr>      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 </form>      ['folderpath','pagepath',
 <br /><form action="/adm/coursedocs" method="post" name="newdropbox">       'pagesymb']);
 $uploadtag        # No folderpath, no pagepath, see if we have something stored
 <input type=hidden name="importdetail" value="">      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
 <nobr>                    &Apache::loncommon::restore_course_settings('docs_folderpath',
 <input name="newdropbox" type="button" value="$lt{'drbx'}"                                                {'folderpath' => 'scalar'});
 onClick="javascript:makedropbox();" />      }
 </nobr>               if (!$env{'form.folderpath'}) {
 </form>           &Apache::loncommon::restore_course_settings('docs_folderpath',
 <br /><form action="/adm/coursedocs" method="post" name="newexamupload">                                                {'pagepath' => 'scalar'});
 $uploadtag      }
 <input type=hidden name="importdetail" value="">      if ($env{'form.pagepath'}) {
 <nobr>         $env{'form.folderpath'}='';
 <input name="newexamupload" type="button" value="$lt{'scuf'}"      }
 onClick="javascript:makeexamupload();" />      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 $help{'Score_Upload_Form'}          $env{'form.folderpath'} = 'supplemental&'.
 </nobr>                                    &escape(&mt('Supplemental '.$type.' Documents')).'&'.
 </form>                                    $env{'form.folderpath'};
 <br /><form action="/adm/coursedocs" method="post" name="newbul">      }
 $uploadtag      &Apache::loncommon::store_course_settings('docs_folderpath',
 <input type=hidden name="importdetail" value="">                                                  {'pagepath' => 'scalar',
 <nobr>                                                   'folderpath' => 'scalar'});
 <input name="newbulletin" type="button" value="$lt{'bull'}"      if ($env{'form.folderpath'}) {
 onClick="javascript:makebulboard();" />   my (@folderpath)=split('&',$env{'form.folderpath'});
 $help{'Bulletin Board'}   $env{'form.foldername'}=&unescape(pop(@folderpath));
 </nobr>   $env{'form.folder'}=pop(@folderpath);
 </form>      }
 <br /><form action="/adm/coursedocs" method="post" name="newaboutme">      if ($env{'form.pagepath'}) {
 $uploadtag          my (@pagepath)=split('&',$env{'form.pagepath'});
 <input type=hidden name="importdetail"           $env{'form.pagename'}=&unescape(pop(@pagepath));
 value="$plainname=/adm/$udom/$uname/aboutme">          $env{'form.folder'}=pop(@pagepath);
 <nobr>          $containertag = '<input type="hidden" name="pagepath" value="" />'.
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      '<input type="hidden" name="pagesymb" value="" />';
 $help{'My Personal Info'}          $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
 </nobr>      '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';
 </form>      }
 <br /><form action="/adm/coursedocs" method="post" name="newaboutsomeone">      if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 $uploadtag         $showdoc='/'.$1;
 <input type=hidden name="importdetail" value="">      }
 <nobr>      unless ($showdoc) { # got called from remote
 <input name="newaboutsomeone" type="button" value="$lt{'abou'}"          if (($env{'form.folder'}=~/^(?:group|default)_/) ||
 onClick="javascript:makeabout();" />            ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
 </nobr>             $forcestandard = 1;
 </form>         }
 ENDFORM         $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
        }  
        if ($env{'form.pagepath'}) {         if ($allowed) {
            $r->print(<<ENDBLOCK);           &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">           $script=&Apache::lonratedt::editscript('simple');
 $uploadtag         }
 <input type=hidden name="importdetail" value="">      } else { # got called in sequence from course
 <nobr>         $allowed=0;
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"      }
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}  
 </nobr>  # get course data
 </form>      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 <br /><form action="/adm/coursedocs" method="post" name="newexamupload">      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 $uploadtag  
 <input type=hidden name="importdetail" value="">  # get personal data
 <nobr>      my $uname=$env{'user.name'};
 <input name="newexamupload" type="button" value="$lt{'scuf'}"      my $udom=$env{'user.domain'};
 onClick="javascript:makeexamupload();" />      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 $help{'Score_Upload_Form'}  
 </nobr>  # graphics settings
 </form>  
 ENDBLOCK      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
        }  
        $r->print('</td></tr>'."\n".      if ($allowed) {
 '</table>');   $script .= &editing_js($udom,$uname);
        $r->print('</td></tr>');      }
     }  # -------------------------------------------------------------------- Body tag
 # ----------------------------------------------------- Supplemental documents      $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
     if (!$forcestandard) {      my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];
        $r->print('<tr><td bgcolor="#BBBBBB">');      $r->print(&Apache::loncommon::start_page("$type Documents", $script,
 # '<h2>'.&mt('Supplemental Course Documents').      {'force_register' => $showdoc,
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');                                       'bread_crumbs' => $brcrum}).
        my $folder=$env{'form.folder'};        &Apache::loncommon::help_open_menu('','',273,'RAT'));
        unless ($folder=~/^supplemental/) {   
    $folder='supplemental';    my %allfiles = ();
        }    my %codebase = ();
        if ($folder =~ /^supplemental$/ &&    my ($upload_result,$upload_output);
    $env{'form.folderpath'} =~ /^default\&/) {    if ($allowed) {
    $env{'form.folderpath'}='supplemental&'.        if (($env{'form.uploaddoc.filename'}) &&
        &escape(&mt('Supplemental '.$type.' Documents'));    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
        }  # Process file upload - phase one - upload and parse primary file.  
        &editor($r,$coursenum,$coursedom,$folder,$allowed);    undef($hadchanges);
        if ($allowed) {            $upload_result = &process_file_upload(\$upload_output,$coursenum,
        my $folderseq=   $coursedom,\%allfiles,
                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.   \%codebase,$1);
                      '.sequence';    if ($hadchanges) {
         &mark_hash_old();
           $r->print(<<ENDSUPFORM);    }
 <table cellspacing=4 cellpadding=4><tr>            if ($upload_result eq 'phasetwo') {
 <th bgcolor="#DDDDDD">$lt{'upls'}</th>                $r->print($upload_output);
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>            }
 </tr>        } elsif ($env{'form.phasetwo'}) {
 <tr><td bgcolor="#DDDDDD">            my %newname = ();
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">            my %origname = ();
 <input type="file" name="uploaddoc" size="40">            my %attribs = ();
 <br />            my $updateflag = 0;
 <br />            my $residx = $env{'form.newidx'};
 <nobr>            my $primary_url = &unescape($env{'form.primaryurl'});
 <label>$lt{'parse'}?  # Process file upload - phase two - gather secondary files.
 <input type="checkbox" name="parserflag" />            for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
 </label>                if ($env{'form.embedded_item_'.$i.'.filename'}) {
 </nobr>                    my $javacodebase;
 <br /><br />                    $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
 $lt{'comment'}:<br />                    $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
 <textarea cols=50 rows=4 name='comment'>                    if (exists($env{'form.embedded_codebase_'.$i})) {
 </textarea>                        $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
 <br />                        $origname{$i} =~ s#^\Q$javacodebase\E/##;
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                    }
 <input type="hidden" name="cmd" value="upload_supplemental">                    my @attributes = ();
 <nobr>                    if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
 <input type="submit" value="$lt{'upld'}">                        @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
  $help{'Uploading_From_Harddrive'}                    } else {
 </nobr>                        @attributes = ($env{'form.embedded_attrib_'.$i});
 </form>                    }
 </td>                    foreach my $attr (@attributes) {
 <td bgcolor="#DDDDDD">                        push(@{$attribs{$i}},&unescape($attr));
 <form action="/adm/coursedocs" method="post" name="supnewfolder">                    }
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                    if ($javacodebase) {
 <input type=hidden name="importdetail" value="">                        $codebase{$i} = $javacodebase;
 <nobr>                        $codebase{$i} =~ s#/$##;
 <input name="newfolder" type="button"                        $updateflag = 1;
 onClick="javascript:makenewfolder(this.form,'$folderseq');"                    }
 value="$lt{'newf'}" /> $help{'Adding_Folders'}                }
 </nobr>                unless ($newname{$i} eq $origname{$i}) {
 </form>                    $updateflag = 1;
 <br /><form action="/adm/coursedocs" method="post" name="supnewext">                }
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />            }
 <input type=hidden name="importdetail" value="">  # Process file upload - phase three - modify primary file
 <nobr>            if ($updateflag) {
 <input name="newext" type="button"                 my ($content,$rtncode);
 onClick="javascript:makenewext('supnewext');"                my $updateflag = 0;
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}                my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
 </nobr>                if ($getstatus eq 'ok') {
 </form>                    foreach my $item (keys(%newname)) {
 <br /><form action="/adm/coursedocs" method="post" name="supnewsyl">                        if ($newname{$item} ne $origname{$item}) {
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                            my $attrib_regexp = '';
 <input type=hidden name="importdetail"                             if (@{$attribs{$item}} > 1) {
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">                                $attrib_regexp = join('|',@{$attribs{$item}});
 <nobr>                            } else {
 <input name="newsyl" type="submit" value="$lt{'syll'}" />                                $attrib_regexp = $attribs{$item}[0];
 $help{'Syllabus'}                            }
 </nobr>                            if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
 </form>                            }
 <br /><form action="/adm/coursedocs" method="post" name="subnewaboutme">                            $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                        }
 <input type=hidden name="importdetail"                         if (exists($codebase{$item})) {
 value="$plainname=/adm/$udom/$uname/aboutme">                            $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
 <nobr>                        }
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />                    }
 $help{'My Personal Info'}  # Save edited file.
 </nobr>                    my $saveresult;
 </form>                    my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 </td></tr>                    my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 </table></td></tr>                    my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
 ENDSUPFORM                } else {
        }                    &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
     }                }
     if ($allowed) {            }
  $r->print('<form method="POST" name="extimport" action="/adm/coursedocs"><input type="hidden" name="title" /><input type="hidden" name="url" /><input type="hidden" name="useform" /></form>');        }
     }    }
     $r->print('</table>');  
   } else {    unless ($showdoc ||  $upload_result eq 'phasetwo') {
       unless ($upload_result eq 'phasetwo') {  # -----------------------------------------------------------------------------
 # -------------------------------------------------------- This is showdoc mode         my %lt=&Apache::lonlocal::texthash(
           $r->print("<h1>".&mt('Uploaded Document').' - '.                  'uplm' => 'Upload a new main '.lc($type).' document',
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.                  'upls' => 'Upload a new supplemental '.lc($type).' document',
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".                  'impp' => 'Import a document',
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');                  'pubd' => 'Published Documents',
       }   'copm' => 'All documents out of a published map into this folder',
   }                  'upld' => 'Upload Document',
  }                  'srch' => 'Search',
  $r->print(&Apache::loncommon::end_page());                  'impo' => 'Import',
  return OK;   'book' => 'Import Bookmarks',
 }                   'selm' => 'Select Map',
                   'load' => 'Load Map',
                   'reco' => 'Recover Deleted Resources',
 sub editing_js {                  'newf' => 'New Folder',
     my ($udom,$uname) = @_;                  'newp' => 'New Composite Page',
     my $now = time();                  'extr' => 'External Resource',
                   'syll' => 'Syllabus',
     return <<ENDNEWSCRIPT;                  'navc' => 'Navigate Contents',
 function makenewfolder(targetform,folderseq) {                  'sipa' => 'Simple Page',
     var foldername=prompt('Name of New Folder','New Folder');                  'sipr' => 'Simple Problem',
     if (foldername) {                  'drbx' => 'Drop Box',
        targetform.importdetail.value=escape(foldername)+"="+folderseq;                  'scuf' => 'Score Upload Form',
         targetform.submit();                  'bull' => 'Bulletin Board',
     }                  'mypi' => 'My Personal Info',
 }                  'grpo' => 'Group Files',
                   'rost' => 'Course Roster',
 function makenewpage(targetform,folderseq) {   'abou' => 'About User',
     var pagename=prompt('Name of New Page','New Page');                  'imsf' => 'Import IMS package',
     if (pagename) {                  'file' =>  'File',
         targetform.importdetail.value=escape(pagename)+"="+folderseq;                  'title' => 'Title',
         targetform.submit();                  'comment' => 'Comment',
     }                  'parse' => 'Upload embedded images/multimedia files if HTML file!',
 }   'nd' => 'New Document',
    'pm' => 'Published Map',
 function makenewext(targetname) {   'sd' => 'Special Document',
     this.document.forms.extimport.useform.value=targetname;   'mo' => 'More Options',
     window.open('/adm/rat/extpickframe.html');   'hao' => 'Hide all Options'
 }    );
   # -----------------------------------------------------------------------------
 function makeexamupload() {   my $fileupload=(<<FIUP);
    var title=prompt('Listed Title for the Uploaded Score');   $lt{'file'}:<br />
    if (title) {    <input type="file" name="uploaddoc" size="40" />
     this.document.forms.newexamupload.importdetail.value=  FIUP
  escape(title)+'=/res/lib/templates/examupload.problem';  
     this.document.forms.newexamupload.submit();   my $checkbox=(<<CHBO);
    }   <!-- <label>$lt{'parse'}?
 }   <input type="checkbox" name="parserflag" />
    </label> -->
 function makesmppage() {   <label>
    var title=prompt('Listed Title for the Page');   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
    if (title) {    </label>
     this.document.forms.newsmppg.importdetail.value=  CHBO
  escape(title)+'=/adm/$udom/$uname/$now/smppg';  
     this.document.forms.newsmppg.submit();   my $fileuploadform=(<<FUFORM);
    }   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 }   $fileupload
    <br />
 function makesmpproblem() {   $lt{'title'}:<br />
    var title=prompt('Listed Title for the Problem');   <input type="text" size="50" name="comment" />
    if (title) {    $uploadtag
     this.document.forms.newsmpproblem.importdetail.value=   <input type="hidden" name="cmd" value="upload_default" />
  escape(title)+'=/res/lib/templates/simpleproblem.problem';   <br />
     this.document.forms.newsmpproblem.submit();   <span class="LC_nobreak">
    }   $checkbox
 }   </span>
    <br />
 function makedropbox() {   <br />
    var title=prompt('Listed Title for the Drop Box');   <span class="LC_nobreak">
    if (title) {    <input type="submit" value="$lt{'upld'}" />
     this.document.forms.newdropbox.importdetail.value=   $help{'Uploading_From_Harddrive'}
         escape(title)+'=/res/lib/templates/DropBox.problem';   </span>
     this.document.forms.newdropbox.submit();   </form>
    }  FUFORM
 }  
    my $simpleeditdefaultform=(<<SEDFFORM);
 function makebulboard() {   <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
    var title=prompt('Listed Title for the Bulletin Board');   $lt{'pubd'}<br />
    if (title) {   $uploadtag
     this.document.forms.newbul.importdetail.value=   <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';   <br />
     this.document.forms.newbul.submit();   <span class="LC_nobreak">
    }   <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />
 }   $help{'Importing_LON-CAPA_Resource'}
    </span>
 function makeabout() {   <br />
    var user=prompt("Enter user:domain for User's 'About Me' Page");   <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
    if (user) {   <hr />
        var comp=new Array();   <p>
        comp=user.split(':');   $lt{'copm'}<br />
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {   <input type="text" size="40" name="importmap" /><br />
    if ((comp[0]) && (comp[1])) {   <span class="LC_nobreak"><input type="button"
        this.document.forms.newaboutsomeone.importdetail.value=   onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
    'About '+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';   value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
        this.document.forms.newaboutsomeone.submit();   $help{'Load_Map'}</span>
    } else {   </p>
                alert("Not a valid user:domain");   </form>
            }  SEDFFORM
        } else {  
            alert("Please enter both user and domain in the format user:domain");    my $extresourcesform=(<<ERFORM);
        }   <form action="/adm/coursedocs" method="post" name="newext">
    }   $uploadtag
 }   <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
 function makeims() {   <input name="newext" type="button" onClick="javascript:makenewext('newext');"
     var caller = document.forms.ims.folder.value;   value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";   </span>
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");   </form>
     newWindow.location.href = newlocation;  ERFORM
 }  
       if ($allowed) {
    &update_paste_buffer($coursenum,$coursedom);
 function finishpick() {         my $dumpbut=&dumpbutton();
     var title=this.document.forms.extimport.title.value;         my $exportbut=&exportbutton();
     var url=this.document.forms.extimport.url.value;         my %lt=&Apache::lonlocal::texthash(
     var form=this.document.forms.extimport.useform.value;   'vc' => 'Verify Content',
     eval   'cv' => 'Check/Set Resource Versions',
      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+   'ls' => 'List Symbs',
     '";this.document.forms.'+form+'.submit();');                                           'sl' => 'Show Log'
 }    );
   
 function changename(folderpath,index,oldtitle,container,pagesymb) {         my $folderpath=$env{'form.folderpath'};
     var title=prompt('New Title',oldtitle);         if (!$folderpath) {
     if (title) {     if ($env{'form.folder'} eq '' ||
  this.document.forms.renameform.title.value=title;         $env{'form.folder'} eq 'supplemental') {
  this.document.forms.renameform.cmd.value='rename_'+index;         $folderpath='default&'.
         if (container == 'sequence') {     &escape(&mt('Main '.$type.' Documents'));
     this.document.forms.renameform.folderpath.value=folderpath;     }
         }         }
         if (container == 'page') {         unless ($env{'form.pagepath'}) {
             this.document.forms.renameform.pagepath.value=folderpath;             $containertag = '<input type="hidden" name="folderpath" value="" />';
             this.document.forms.renameform.pagesymb.value=pagesymb;             $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
         }         }
         this.document.forms.renameform.submit();  
     }         $r->print(<<ENDCOURSEVERIFY);
 }  <form name="renameform" method="post" action="/adm/coursedocs">
     <input type="hidden" name="title" />
 function removeres(folderpath,index,oldtitle,container,pagesymb) {    <input type="hidden" name="cmd" />
     if (confirm('WARNING: Removing a resource makes associated grades and scores inaccessible!\\nRemove "'+oldtitle+'"?')) {    <input type="hidden" name="markcopy" />
  this.document.forms.renameform.cmd.value='del_'+index;    <input type="hidden" name="copyfolder" />
         if (container == 'sequence') {    $containertag
             this.document.forms.renameform.folderpath.value=folderpath;  </form>
         }  <form name="simpleedit" method="post" action="/adm/coursedocs">
         if (container == 'page') {    <input type="hidden" name="importdetail" value="" />
             this.document.forms.renameform.pagepath.value=folderpath;    $uploadtag
             this.document.forms.renameform.pagesymb.value=pagesymb;  </form>
         }  <form action="/adm/coursedocs" method="post" name="courseverify">
         this.document.forms.renameform.submit();    <div class="LC_docs_course_commands">
     }  
 }        <div>
           <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}
 function cutres(folderpath,index,oldtitle,container,pagesymb) {        </div>
     if (confirm('WARNING: Cutting a resource makes associated grades and scores inaccessible!\\nGrades remain inaccessible if resource is pasted into another folder.\\nCut "'+oldtitle+'"?')) {        <div>
  this.document.forms.renameform.cmd.value='cut_'+index;          <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}
  this.document.forms.renameform.markcopy.value=index;        </div>
         if (container == 'sequence') {          $dumpbut
             this.document.forms.renameform.folderpath.value=folderpath;          $exportbut
         }        <div>
         if (container == 'page') {          <input type="submit" name="listsymbs" value="$lt{'ls'}" />
             this.document.forms.renameform.pagepath.value=folderpath;        </div>
             this.document.forms.renameform.pagesymb.value=pagesymb;        <div>
         }          <input type="hidden" name="folder" value="$env{'form.folder'}" />
         this.document.forms.renameform.submit();          <input type="submit" name="docslog" value="$lt{'sl'}" />
     }        </div>
 }    </div>
   </form>
 function markcopy(folderpath,index,oldtitle,container,pagesymb) {  <div style="clear: both; height: 0px;">&nbsp;</div>
     this.document.forms.renameform.markcopy.value=index;  ENDCOURSEVERIFY
     if (container == 'sequence') {         $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',
  this.document.forms.renameform.folderpath.value=folderpath;       &mt('Editing the Table of Contents for your '.$type)));
     }      }
     if (container == 'page') {  # --------------------------------------------------------- Standard documents
  this.document.forms.renameform.pagepath.value=folderpath;      $r->print('<table class="LC_docs_documents">');
  this.document.forms.renameform.pagesymb.value=pagesymb;  
     }      if (($standard) && ($allowed) && (!$forcesupplement)) {
     this.document.forms.renameform.submit();   $r->print('<tr><td class="LC_docs_document">');
 }  #  '<h2>'.&mt('Main Course Documents').
   #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');
 ENDNEWSCRIPT         my $folder=$env{'form.folder'};
 }         if ($folder eq '' || $folder eq 'supplemental') {
 1;             $folder='default';
 __END__     $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));
              $uploadtag = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
          my $postexec='';
          if ($folder eq 'default') {
      $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');
          } else {
              #$postexec='self.close();';
          }
          $hadchanges=0;
          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,
      $upload_output,$type);
          if ($error) {
      $r->print('<p><span class="LC_error">'.$error.'</span></p>');
          }
          if ($hadchanges) {
      &mark_hash_old();
          }
          &changewarning($r,$postexec);
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                        '.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                        '.page';
    my $container='sequence';
    if ($env{'form.pagepath'}) {
       $container='page';
    }
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
   
   
   
    my $recoverform=(<<RFORM);
    <form action="/adm/groupsort" method="post" name="recover">
    <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />
    </form>
   RFORM
   
    my $imspform=(<<IMSPFORM);
    <form action="/adm/imsimportdocs" method="post" name="ims">
    <input type="hidden" name="folder" value="$folder" />
    <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />
    </form>
   IMSPFORM
   
    my $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'navc'}=/adm/navmaps" />
    <span class="LC_nobreak">
    <input name="newnav" type="submit" value="$lt{'navc'}" />
    $help{'Navigate_Content'}
    </span>
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newsmppg" type="button" value="$lt{'sipa'}"
    onClick="javascript:makesmppage();" /> $help{'Simple Page'}
    </span>
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newsmpproblem" type="button" value="$lt{'sipr'}"
    onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}
    </span>
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    $uploadtag      
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">          
    <input name="newdropbox" type="button" value="$lt{'drbx'}"
    onClick="javascript:makedropbox();" />
    </span>        
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newexamupload" type="button" value="$lt{'scuf'}"
    onClick="javascript:makeexamupload();" />
    $help{'Score_Upload_Form'}
    </span>
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newbulletin" type="button" value="$lt{'bull'}"
    onClick="javascript:makebulboard();" />
    $help{'Bulletin Board'}
    </span>
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <span class="LC_nobreak">
    <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
    $help{'My Personal Info'}
    </span>
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newaboutsomeone" type="button" value="$lt{'abou'}"
    onClick="javascript:makeabout();" />
    </span>
    </form>
   NASOFORM
   
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'rost'}=/adm/viewclasslist" />
    <span class="LC_nobreak">
    <input name="newroster" type="submit" value="$lt{'rost'}" />
    $help{'Course Roster'}
    </span>
    </form>
   NROSTFORM
   
          $r->print(<<ENDFORM);
   
   <ul class="LC_TabContent">
   <li>$lt{'nd'}</li>
   <li>$lt{'pm'}</li>
   <li>$lt{'pubd'}</li>
   <li>$lt{'sd'}</li>
   <li>$lt{'mo'}</li>
   <li>$lt{'hao'}</li>
   </ul>
   
   <table class="LC_docs_adddocs">
   <!-- <tr>
   <th>$lt{'uplm'}</th>
   <th>$lt{'impp'}</th>
   <th>$lt{'spec'}</th>
   </tr> -->
   <tr>
   <td>
   $fileuploadform
   </td>
   <td>
   $simpleeditdefaultform
   <hr />
   $recoverform
   ENDFORM
          unless ($env{'form.pagepath'}) {
      $r->print(<<ENDFORM);
   <hr />
   $extresourcesform
    <br />
   $imspform
   ENDFORM
          }
          $r->print('</td><td>');
          unless ($env{'form.pagepath'}) {
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
   
   
    my $newpageform=(<<NPFORM);
    <form action="/adm/coursedocs" method="post" name="newpage">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newpage" type="button"
    onClick="javascript:makenewpage(this.form,'$pageseq');"
    value="$lt{'newp'}" />$help{'Adding_Pages'}
    </span>
    </form>
   NPFORM
   
    my $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newfolder" type="button"
    onClick="javascript:makenewfolder(this.form,'$folderseq');"
    value="$lt{'newf'}" />$help{'Adding_Folders'}
    </span>
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <span class="LC_nobreak">
    <input name="newsyl" type="submit" value="$lt{'syll'}" />
    $help{'Syllabus'}
    </span>
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <span class="LC_nobreak">
    <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />
    $help{'Group Files'}
    </span>
    </form>
   NGFFORM
   
   
              $r->print(<<ENDFORM);
   <br />
   $newfolderform
   <br />
   $newpageform
   <br />
   $newsylform
   <br />
   $newnavform
   <br />
   $newsmppageform
   <br />
   $newsmpproblemform
   <br />
   $newdropboxform
   <br />
   $newexuploadform
   <br />
   $newbulform
   <br />
   $newaboutmeform
   <br />
   $newaboutsomeoneform
   <br />
   $newgroupfileform
   <br />
   $newrosterform
   ENDFORM
          }
          if ($env{'form.pagepath'}) {
              $r->print(<<ENDBLOCK);
   $newsmpproblemform
   <br />
   $newexuploadform
   ENDBLOCK
          }
          $r->print('</td></tr>'."\n".
   '</table>');
          $r->print('</td></tr>');
       }
   # ----------------------------------------------------- Supplemental documents
       if (!$forcestandard) {
          $r->print('<tr><td class="LC_docs_document">');
   # '<h2>'.&mt('Supplemental Course Documents').
   #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');
          my $folder=$env{'form.folder'};
          unless ($folder=~/^supplemental/) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = 'supplemental&'.
                                       &escape(&mt('Supplemental '.$type.' Documents'));
          }
          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);
          if ($error) {
      $r->print('<p><span class="LC_error">'.$error.'</span></p>');
          }
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
          '.sequence';
   
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $supupdocform=(<<SUPDOCFORM);
    <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">
    $fileupload
    <br />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br /><br />
    $lt{'comment'}:<br />
    <textarea cols=50 rows=4 name='comment'>
    </textarea>
    <br />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="cmd" value="upload_supplemental" />
    <span class="LC_nobreak">
    <input type="submit" value="$lt{'upld'}" />
    $help{'Uploading_From_Harddrive'}
    </span>
    </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newfolder" type="button"
    onClick="javascript:makenewfolder(this.form,'$folderseq');"
    value="$lt{'newf'}" /> $help{'Adding_Folders'}
    </span>
    </form>
   SNFFORM
   
   
    my $supnewextform=(<<SNEFORM);
    <form action="/adm/coursedocs" method="post" name="supnewext">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newext" type="button"
    onClick="javascript:makenewext('supnewext');"
    value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
    </span>
    </form>
   SNEFORM
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail"
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <span class="LC_nobreak">
    <input name="newsyl" type="submit" value="$lt{'syll'}" />
    $help{'Syllabus'}
    </span>
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="subnewaboutme">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail"
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <span class="LC_nobreak">
    <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
    $help{'My Personal Info'}
    </span>
    </form>
   SNAMFORM
   
      $r->print(<<ENDSUPFORM);
   <ul class="LC_TabContent">
   <li>$lt{'nd'}</li>
   <li>$lt{'sd'}</li>
   <li>$lt{'hao'}</li>
   </ul>
   <table class="LC_docs_adddocs">
   <tr><td>
   $supupdocform
   </td>
   <td>
   $supnewfolderform
   <br />
   $supnewextform
   <br />
   $supnewsylform
   <br />
   $supnewaboutmeform
   </td></tr>
   </table></td></tr>
   ENDSUPFORM
          }
       }
       $r->print('</table>');
       if ($allowed) {
    $r->print('
   <form method="post" name="extimport" action="/adm/coursedocs">
     <input type="hidden" name="title" />
     <input type="hidden" name="url" />
     <input type="hidden" name="useform" />
     <input type="hidden" name="residx" />
   </form>');
       }
     } else {
         unless ($upload_result eq 'phasetwo') {
   # -------------------------------------------------------- This is showdoc mode
             $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p>'.
   &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
             &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
         }
     }
    }
    $r->print(&Apache::loncommon::end_page());
    return OK;
   }
   
   
   sub editing_js {
       my ($udom,$uname) = @_;
       my $now = time();
       my %lt = &Apache::lonlocal::texthash(
                                             p_mnf => 'Name of New Folder',
                                             t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
                                             t_mnp => 'New Page',
                                             p_mxu => 'Title for the Uploaded Score',
                                             p_msp => 'Title for the Page',
                                             p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Bulletin Board',
                                             p_mab => "Enter user:domain for User's 'About Me' Page",
                                             p_mab2 => "About [_99]",
                                             p_mab_alrt1 => 'Not a valid user:domain',
                                             p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                             p_chn => 'New Title',
                                             p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
                                             p_rmr2a => 'Remove[_99]',
                                             p_rmr2b => '?[_99]',
                                             p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                             p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                             p_ctr2a => 'Cut[_98]',
                                             p_ctr2b => '?[_98]'
                                           );
   
       return <<ENDNEWSCRIPT;
   function makenewfolder(targetform,folderseq) {
       var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
       if (foldername) {
          targetform.importdetail.value=escape(foldername)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makenewpage(targetform,folderseq) {
       var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
       if (pagename) {
           targetform.importdetail.value=escape(pagename)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makenewext(targetname) {
       this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.title.value='';
       this.document.forms.extimport.url.value='';
       this.document.forms.extimport.residx.value='';
       window.open('/adm/rat/extpickframe.html');
   }
   
   function edittext(targetname,residx,title,url) {
       this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.residx.value=residx;
       this.document.forms.extimport.url.value=url;
       this.document.forms.extimport.title.value=title;
       window.open('/adm/rat/extpickframe.html');
   }
   
   function makeexamupload() {
      var title=prompt('$lt{"p_mxu"}');
      if (title) {
       this.document.forms.newexamupload.importdetail.value=
    escape(title)+'=/res/lib/templates/examupload.problem';
       this.document.forms.newexamupload.submit();
      }
   }
   
   function makesmppage() {
      var title=prompt('$lt{"p_msp"}');
      if (title) {
       this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/smppg';
       this.document.forms.newsmppg.submit();
      }
   }
   
   function makesmpproblem() {
      var title=prompt('$lt{"p_msb"}');
      if (title) {
       this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
       this.document.forms.newsmpproblem.submit();
      }
   }
   
   function makedropbox() {
      var title=prompt('$lt{"p_mdb"}');
      if (title) {
       this.document.forms.newdropbox.importdetail.value=
           escape(title)+'=/res/lib/templates/DropBox.problem';
       this.document.forms.newdropbox.submit();
      }
   }
   
   function makebulboard() {
      var title=prompt('$lt{"p_mbb"}');
      if (title) {
       this.document.forms.newbul.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
       this.document.forms.newbul.submit();
      }
   }
   
   function makeabout() {
      var user=prompt("$lt{'p_mab'}");
      if (user) {
          var comp=new Array();
          comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
      if ((comp[0]) && (comp[1])) {
          this.document.forms.newaboutsomeone.importdetail.value=
      '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
          this.document.forms.newaboutsomeone.submit();
      } else {
                  alert("$lt{'p_mab_alrt1'}");
              }
          } else {
              alert("$lt{'p_mab_alrt2'}");
          }
      }
   }
   
   function makeims() {
       var caller = document.forms.ims.folder.value;
       var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
       newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");
       newWindow.location.href = newlocation;
   }
   
   
   function finishpick() {
       var title=this.document.forms.extimport.title.value;
       var url=this.document.forms.extimport.url.value;
       var form=this.document.forms.extimport.useform.value;
       var residx=this.document.forms.extimport.residx.value;
       eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');
   }
   
   function changename(folderpath,index,oldtitle,container,pagesymb) {
       var title=prompt('$lt{"p_chn"}',oldtitle);
       if (title) {
    this.document.forms.renameform.markcopy.value=-1;
    this.document.forms.renameform.title.value=title;
    this.document.forms.renameform.cmd.value='rename_'+index;
           if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   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.markcopy.value=-1;
    this.document.forms.renameform.cmd.value='del_'+index;
           if (container == 'sequence') {
               this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {
       if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
    this.document.forms.renameform.cmd.value='cut_'+index;
    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;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
       this.document.forms.renameform.markcopy.value=index;
       this.document.forms.renameform.copyfolder.value=folder+'.'+container;
       if (container == 'sequence') {
    this.document.forms.renameform.folderpath.value=folderpath;
       }
       if (container == 'page') {
    this.document.forms.renameform.pagepath.value=folderpath;
    this.document.forms.renameform.pagesymb.value=pagesymb;
       }
       this.document.forms.renameform.submit();
   }
   
   
   ENDNEWSCRIPT
   }
   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 dumpbutton()
   
   Generate "dump" button
   
   =item clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   
   =item exportbutton()
   
       Generate "export" button
   
   =item exportcourse()
   
   =item create_ims_store()
   
   =item build_package()
   
   =item get_dependencies()
   
   =item process_content()
   
   =item replicate_content()
   
   =item extract_media()
   
   =item store_template()
   
   =item group_import()
   
       Imports the given (name, url) resources into the course
       coursenum, coursedom, and folder must precede the list
   
   =item breadcrumbs()
   
   =item log_docs()
   
   =item docs_change_log()
   
   =item update_paste_buffer()
   
   =item print_paste_buffer()
   
   =item do_paste_from_buffer()
   
   =item update_parameter()
   
   =item handle_edit_cmd()
   
   =item editor()
   
   =item process_file_upload()
   
   =item process_secondary_uploads()
   
   =item is_supplemental_title()
   
   =item parse_supplemental_title()
   
   =item entryline()
   
   =item tiehash()
   
   =item untiehash()
   
   =item checkonthis()
   
   check on this
   
   =item verifycontent()
   
   Verify Content
   
   =item devalidateversioncache() & checkversions()
   
   Check Versions
   
   =item mark_hash_old()
   
   =item is_hash_old()
   
   =item changewarning()
   
   =item init_breadcrumbs()
   
   Breadcrumbs for special functions
   
   =back
   
   =cut

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


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