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

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

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


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