Diff for /loncom/interface/londocs.pm between versions 1.170 and 1.327

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

Removed from v.1.170  
changed lines
  Added in v.1.327


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