Diff for /loncom/interface/londocs.pm between versions 1.234 and 1.328

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


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