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

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

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


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