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

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


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