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

version 1.178, 2005/06/08 17:42:01 version 1.328, 2009/01/28 13:24:54
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::londocs;  
   
 use strict;  package Apache::londocs;
 use Apache::Constants qw(:common :http);  
 use Apache::imsexport;  use strict;
 use Apache::lonnet;  use Apache::Constants qw(:common :http);
 use Apache::loncommon;  use Apache::imsexport;
 use Apache::lonratedt;  use Apache::lonnet;
 use Apache::lonratsrv;  use Apache::loncommon;
 use Apache::lonxml;  use LONCAPA::map();
 use Apache::loncreatecourse;  use Apache::lonratedt();
 use Apache::lonnavmaps;  use Apache::lonxml;
 use HTML::Entities;  use Apache::lonclonecourse;
 use GDBM_File;  use Apache::lonnavmaps;
 use Apache::lonlocal;  use HTML::Entities;
 use Cwd;  use GDBM_File;
   use 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=1+$#Apache::lonratedt::resources;      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') ) {  
 # this is for a course, not a user, so set coursedoc flag      sub remember_parms {
 # probably the only place in the system where this should be "1"          my ($idx,$parameter,$action,$value)=@_;
               my $newidx=$#Apache::lonratedt::resources+1;          $parmidx=$idx;
       my $url=&Apache::lonnet::userfileupload('uploaddoc',1,'docs/'.$newidx);          $parmaction{$parameter}=$action;
               my $ext='false';          $parmvalue{$parameter}=$value;
               if ($url=~/^http\:\/\//) { $ext='true'; }          $changedflag=1;
               $url=~s/\:/\&colon;/g;      }
       my $comment=$env{'form.comment'};  
               $comment=~s/\</\&lt\;/g;      sub log_differences {
               $comment=~s/\>/\&gt\;/g;          my ($plain)=@_;
               $comment=~s/\:/\&colon;/g;          my %storehash=('folder' => $plain,
               if ($folder=~/^supplemental/) {                         'currentfolder' => $env{'form.folder'});
   $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.          if ($parmidx) {
       $env{'user.domain'}.'___&&&___'.$comment;             $storehash{'parameter_res'}=$oldresources[$parmidx];
               }             foreach my $parm (keys(%parmaction)) {
               $Apache::lonratedt::resources[$newidx]=                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
                   $comment.':'.$url.':'.$ext.':normal:res';                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
               $Apache::lonratedt::order[$#Apache::lonratedt::order+1]=             }
                                                               $newidx;                 }
           my $maxidx=$#oldresources;
       ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          if ($#LONCAPA::map::resources>$#oldresources) {
       if ($fatal) {             $maxidx=$#LONCAPA::map::resources;
   $r->print('<p><font color="red">'.$errtext.'</font></p>');          }
   return;          for (my $idx=0; $idx<=$maxidx; $idx++) {
       }             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
      }                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
             }                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
     if ($env{'form.cmd'}) {                $changedflag=1;
                 my ($cmd,$idx)=split(/\_/,$env{'form.cmd'});             }
                 if ($cmd eq 'del') {             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
     my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
     if ($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) {                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  &Apache::lonnet::removeuploadedurl($url);                $changedflag=1;
     }             }
     for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {          }
                         $Apache::lonratedt::order[$i]=   $storehash{'maxidx'}=$maxidx;
                           $Apache::lonratedt::order[$i+1];          if ($changedflag) { &log_docs(\%storehash); }
                     }      }
                     $#Apache::lonratedt::order--;  }
                 } elsif ($cmd eq 'cut') {  
     my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);  
     for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {  
                         $Apache::lonratedt::order[$i]=  
                           $Apache::lonratedt::order[$i+1];  
                     }  sub docs_change_log {
                     $#Apache::lonratedt::order--;      my ($r)=@_;
                 } elsif ($cmd eq 'up') {      my $folder=$env{'form.folder'};
   if (($idx) && (defined($Apache::lonratedt::order[$idx-1]))) {      $r->print(&Apache::loncommon::start_page('Course Document Change Log'));
                     my $i=$Apache::lonratedt::order[$idx-1];      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));
                     $Apache::lonratedt::order[$idx-1]=      my %docslog=&Apache::lonnet::dump('nohist_docslog',
  $Apache::lonratedt::order[$idx];                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
                     $Apache::lonratedt::order[$idx]=$i;                                        $env{'course.'.$env{'request.course.id'}.'.num'});
    }  
                 } elsif ($cmd eq 'down') {      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
    if (defined($Apache::lonratedt::order[$idx+1])) {  
                     my $i=$Apache::lonratedt::order[$idx+1];      $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.
                     $Apache::lonratedt::order[$idx+1]=                '<input type="hidden" name="docslog" value="1" />');
  $Apache::lonratedt::order[$idx];  
                     $Apache::lonratedt::order[$idx]=$i;      my %saveable_parameters = ('show' => 'scalar',);
    }      &Apache::loncommon::store_course_settings('docs_log',
                 } elsif ($cmd eq 'rename') {                                                \%saveable_parameters);
                     my $ratstr = $Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]];      &Apache::loncommon::restore_course_settings('docs_log',
                     my ($rtitle,@rrest)=split(/\:/,                                                  \%saveable_parameters);
                        $Apache::lonratedt::resources[      if (!$env{'form.show'}) { $env{'form.show'}=10; }
        $Apache::lonratedt::order[$idx]]);      my %lt=('hiddenresource' => 'Resources hidden',
                     my $comment=      'encrypturl'     => 'URL hidden',
                      &HTML::Entities::decode($env{'form.title'});      'randompick'     => 'Randomly pick',
                     $comment=~s/\</\&lt\;/g;      'randomorder'    => 'Randomly ordered',
                     $comment=~s/\>/\&gt\;/g;      'set'            => 'set to',
                     $comment=~s/\:/\&colon;/g;      'del'            => 'deleted');
     if ($comment=~/\S/) {      $r->print(&Apache::loncommon::display_filter().
  $Apache::lonratedt::resources[                '<input type="hidden" name="folder" value="'.$folder.'" />'.
        $Apache::lonratedt::order[$idx]]=                '<input type="submit" value="'.&mt('Display').'" /></form>');
             $comment.':'.join(':',@rrest);      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     }                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
                 }                &mt('After').'</th>'.
 # Store the changed version                &Apache::loncommon::end_data_table_header_row());
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,      my $shown=0;
     $folder.'.'.$container);      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
  if ($fatal) {   if ($env{'form.displayfilter'} eq 'currentfolder') {
     $r->print('<p><font color="red">'.$errtext.'</font></p>');      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
     return;   }
  }          my @changes=keys(%{$docslog{$id}{'logentry'}});
             }          if ($env{'form.displayfilter'} eq 'containing') {
 # Group import/search      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
     if ($env{'form.importdetail'}) {   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
  my @imports;      foreach my $key (@changes) {
  foreach (split(/\&/,$env{'form.importdetail'})) {   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
     if (defined($_)) {      }
  my ($name,$url)=split(/\=/,$_);      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }        
  $name=&Apache::lonnet::unescape($name);   }
  $url=&Apache::lonnet::unescape($url);          my $count = 0;
  push @imports, $name, $url;          my $time =
     }              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
  }          my $plainname =
 # Store the changed version              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
  ($errtext,$fatal)=group_import($coursenum, $coursedom, $folder,                                            $docslog{$id}{'exe_udom'});
        $container,'londocs',@imports);          my $about_me_link =
  if ($fatal) {              &Apache::loncommon::aboutmewrapper($plainname,
     $r->print('<p><font color="red">'.$errtext.'</font></p>');                                                 $docslog{$id}{'exe_uname'},
     return;                                                 $docslog{$id}{'exe_udom'});
  }          my $send_msg_link='';
             }          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
 # Loading a complete map               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
    if (($env{'form.importmap'}) && ($env{'form.loadmap'})) {              $send_msg_link ='<br />'.
        foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {                  &Apache::loncommon::messagewrapper(&mt('Send message'),
                    my $idx=$#Apache::lonratedt::resources;                                                     $docslog{$id}{'exe_uname'},
                    $idx++;                                                     $docslog{$id}{'exe_udom'});
                    $Apache::lonratedt::resources[$idx]=$_;          }
                    $Apache::lonratedt::order          $r->print(&Apache::loncommon::start_data_table_row());
        [$#Apache::lonratedt::order+1]=$idx;          $r->print('<td>'.$time.'</td>
        }                         <td>'.$about_me_link.
                     '<br /><tt>'.$docslog{$id}{'exe_uname'}.
 # Store the changed version                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
        ($errtext,$fatal)=&storemap($coursenum,$coursedom,                    $send_msg_link.'</td><td>'.
    $folder.'.'.$container);                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
        if ($fatal) {  # Before
    $r->print('<p><font color="red">'.$errtext.'</font></p>');   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
    return;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
        }      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
            }      if ($oldname ne $newname) {
        }   $r->print(&LONCAPA::map::qtescape($oldname));
 # ---------------------------------------------------------------- End commands      }
 # ---------------------------------------------------------------- Print screen   }
         my $idx=0;   $r->print('<ul>');
  my $shown=0;   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
         $r->print('<table>');              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
         foreach (@Apache::lonratedt::order) {   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
            my ($name,$url)=split(/\:/,$Apache::lonratedt::resources[$_]);      }
            unless ($name) {  $name=(split(/\//,$url))[-1]; }   }
            unless ($name) { $idx++; next; }   $r->print('</ul>');
            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));  # After
            $idx++;          $r->print('</td><td>');
    $shown++;  
         }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  unless ($shown) {      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
  }      if ($oldname ne '' && $oldname ne $newname) {
         $r->print("\n</table>\n");   $r->print(&LONCAPA::map::qtescape($newname));
  if ($env{'form.markedcopy_url'}) {      }
     $r->print(<<ENDPASTE);   }        
 <p><form name="pasteform" action="/adm/coursedocs" method="post">   $r->print('<ul>');
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
 ENDPASTE   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
             $r->print(      }
    '<input type="submit" name="pastemarked" value="'.&mt('Paste').   }
       '" /> '.&Apache::loncommon::filedescription(   $r->print('</ul>');
  (split(/\./,$env{'form.markedcopy_url'}))[-1]).': '.   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
       $env{'form.markedcopy_title'});      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
             if ($container eq 'page') {      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
  $r->print(<<PAGEINFO);   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />      $r->print('<li>'.
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
 PAGEINFO    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
             } else {        .'</li>');
  $r->print(<<FOLDERINFO);   }
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      }
 FOLDERINFO      $r->print('</ul>');
     }   }
     $r->print('</form></p>');  # End
  }          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
     }          $shown++;
 }          if (!($env{'form.show'} eq &mt('all')
                 || $shown<=$env{'form.show'})) { last; }
 # --------------------------------------------------------------- An entry line      }
       $r->print(&Apache::loncommon::end_data_table());
 sub entryline {  }
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;  
     $title=~s/\&colon\;/\:/g;  sub update_paste_buffer {
     $title=&HTML::Entities::encode(&HTML::Entities::decode(      my ($coursenum,$coursedom) = @_;
      &Apache::lonnet::unescape($title)),'"<>&\'');  
     my $renametitle=$title;      return if (!defined($env{'form.markcopy'}));
     my $foldertitle=$title;      return if (!defined($env{'form.copyfolder'}));
     my $pagetitle=$title;      return if ($env{'form.markcopy'} < 0);
     my $orderidx=$Apache::lonratedt::order[$index];  
     if ($title=~ /^(\d+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(.*)$/ ) {       my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);      $env{'form.copyfolder'});
  $renametitle=$4;     
  $title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.      return if ($fatal);
     &Apache::loncommon::plainname($2,$3).': <br />'.  
     $foldertitle;  # Mark for copying
     }      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
     $renametitle=~s/\&quot\;/\\\"/g;      if (&is_supplemental_title($title)) {
     my $line='<tr>';          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
 # Edit commands   ($title) = &parse_supplemental_title($title);
     my $container;      } elsif ($env{'docs.markedcopy_supplemental'}) {
     my $folderpath;          &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');
     if ($env{'form.folderpath'}) {      }
         $container = 'sequence';      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
  $folderpath=&Apache::lonnet::escape($env{'form.folderpath'});  
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
     }      'docs.markedcopy_url'   => $url});
     my ($pagepath,$pagesymb);      delete($env{'form.markcopy'});
     if ($env{'form.pagepath'}) {  }
         $container = 'page';  
         $pagepath=&Apache::lonnet::escape($env{'form.pagepath'});  sub print_paste_buffer {
         $pagesymb=&Apache::lonnet::escape($env{'form.pagesymb'});      my ($r,$container) = @_;
     }      return if (!defined($env{'docs.markedcopy_url'}));
     my $cpinfo='';  
     if ($env{'form.markedcopy_url'}) {      $r->print(<<ENDPASTE);
        $cpinfo='&markedcopy_url='.  <form name="pasteform" action="/adm/coursedocs" method="post"><p>
                &Apache::lonnet::escape($env{'form.markedcopy_url'}).  ENDPASTE
                '&markedcopy_title='.      $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');
                &Apache::lonnet::escape($env{'form.markedcopy_title'});  
     }      my $type;
     if ($allowed) {      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
  my $incindex=$index+1;   $type = &mt('External Resource');
  my $selectbox='';   $r->print($type.': '.
  if (($folder!~/^supplemental/) &&    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
     ($#Apache::lonratedt::order>0) &&     &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
     ((split(/\:/,      }  else {
      $Apache::lonratedt::resources[$Apache::lonratedt::order[0]]))[1]    my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
      ne '') &&    my $icon = &Apache::loncommon::icon($extension);
     ((split(/\:/,   if ($extension eq 'sequence' &&
      $Apache::lonratedt::resources[$Apache::lonratedt::order[1]]))[1]       $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
      ne '')) {      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     $selectbox=      $icon .= '/folder_closed.gif';
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.   }
  '<select name="newpos" onChange="this.form.submit()">';   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
     for (my $i=1;$i<=$#Apache::lonratedt::order+1;$i++) {   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
  if ($i==$incindex) {      }
     $selectbox.='<option value="" selected="1">('.$i.')</option>';      if ($container eq 'page') {
  } else {   $r->print('
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';   <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
  }   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
     }  ');
     $selectbox.='</select>';      } else {
  }   $r->print('
  my %lt=&Apache::lonlocal::texthash(          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
                 'up' => 'Move Up',  ');
  'dw' => 'Move Down',      }
  'rm' => 'Remove',      $r->print('</p></form>');
                 'ct' => 'Cut',  }
  'rn' => 'Rename',  
  'cp' => 'Copy');  sub do_paste_from_buffer {
         if ($env{'form.pagepath'}) {      my ($coursenum,$coursedom,$folder) = @_;
             $line.=(<<END);  
 <form name="entry_$index" action="/adm/coursedocs" method="post">      if (!$env{'form.pastemarked'}) {
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />          return;
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />      }
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />  
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />  # paste resource to end of list
 <input type="hidden" name="setparms" value="$orderidx" />      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
 <td><table border='0' cellspacing='2' cellpadding='0'>      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
 <tr><td bgcolor="#DDDDDD">  # Maps need to be copied first
 <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>      if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>   $title=&mt('Copy of').' '.$title;
 <tr><td bgcolor="#DDDDDD">   my $newid=$$.int(rand(100)).time;
 <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
 </table></td>              my $path = $1;
 <td>$selectbox              my $prefix = $2;
 </td><td bgcolor="#DDDDDD">              my $ancestor = $3;
 <a href='javascript:removeres("$pagepath","$index","$renametitle","page","$pagesymb");'>              if (length($ancestor) > 10) {
 <font size="-2" color="#990000">$lt{'rm'}</font></a>                  $ancestor = substr($ancestor,-10,10);
 <a href='javascript:cutres("$pagepath","$index","$renametitle","page","$pagesymb");'>              }
 <font size="-2" color="#550044">$lt{'ct'}</font></a>              $oldid = $path.$prefix.$ancestor;
 <a href='javascript:changename("$pagepath","$index","$renametitle","page","$pagesymb");'>          }
 <font size="-2" color="#009900">$lt{'rn'}</font></a>          my $counter = 0;
 <a href='javascript:markcopy("$pagepath","$index","$renametitle","page","$pagesymb");'>          my $newurl=$oldid.$newid.'.'.$ext;
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>          my $is_unique = &uniqueness_check($newurl);
 END          while (!$is_unique && $counter < 100) {
         } else {              $counter ++;
             $line.=(<<END);               $newid ++;
 <form name="entry_$index" action="/adm/coursedocs" method="post">              $newurl = $oldid.$newid;
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />              $is_unique = &uniqueness_check($newurl);
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />          }
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />          if (!$is_unique) {
 <input type="hidden" name="setparms" value="$orderidx" />              if ($url=~/\.page$/) {
 <td><table border='0' cellspacing='2' cellpadding='0'>                  return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
 <tr><td bgcolor="#DDDDDD">              } else {
 <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath$cpinfo'>                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>              }
 <tr><td bgcolor="#DDDDDD">          }
 <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath$cpinfo'>   my $storefn=$newurl;
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>   $storefn=~s{^/\w+/$match_domain/$match_username/}{};
 </table></td>   my $paste_map_result =
 <td>$selectbox              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
 </td><td bgcolor="#DDDDDD">         &Apache::lonnet::getfile($url));
 <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>          if ($paste_map_result eq '/adm/notfound.html') {
 <font size="-2" color="#990000">$lt{'rm'}</font></a>              if ($url=~/\.page$/) {
 <a href='javascript:cutres("$folderpath","$index","$renametitle","sequence");'>                  return &mt('Paste failed: an error occurred saving the composite page');
 <font size="-2" color="#550044">$lt{'ct'}</font></a>              } else {
 <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>                  return &mt('Paste failed: an error occurred saving the folder');
 <font size="-2" color="#009900">$lt{'rn'}</font></a>              }
 <a href='javascript:markcopy("$folderpath","$index","$renametitle","sequence");'>          }
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>   $url = $newurl;
 END      }
         }  # published maps can only exists once, so remove it from paste buffer when done
     }      if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
 # Figure out what kind of a resource this is   &Apache::lonnet::delenv('docs\\.markedcopy');
     my ($extension)=($url=~/\.(\w+)$/);      }
     my $uploaded=($url=~/^\/*uploaded\//);      if ($url=~ m{/smppg$}) {
     my $icon=&Apache::loncommon::icon($url);   my $db_name = &Apache::lonsimplepage::get_db_name($url);
     my $isfolder=0;   if ($db_name =~ /^smppage_/) {
     my $ispage=0;      #simple pages, need to copy the db contents to a new one.
     my $folderarg;      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
     my $pagearg;      my $now = time();
     my $pagefile;      $db_name =~ s{_\d*$ }{_$now}x;
     if ($uploaded) {      my $result=&Apache::lonnet::put($db_name,\%contents,
  if ($extension eq 'sequence') {      $coursedom,$coursenum);
     $icon=$iconpath.'/folder_closed.gif';      $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
     $url=~/$coursenum\/([\/\w]+)\.sequence$/;      $title=&mt('Copy of').' '.$title;
     $url='/adm/coursedocs?';   }
     $folderarg=$1;      }
     $isfolder=1;      $title = &LONCAPA::map::qtunescape($title);
         } elsif ($extension eq 'page') {      my $ext='false';
             $icon=$iconpath.'/page.gif';      if ($url=~m{^http(|s)://}) { $ext='true'; }
             $url=~/$coursenum\/([\/\w]+)\.page$/;      $url       = &LONCAPA::map::qtunescape($url);
             $pagearg=$1;  # Now insert the URL at the bottom
             $url='/adm/coursedocs?';      my $newidx = &LONCAPA::map::getresidx($url);
             $ispage=1;      if ($env{'docs.markedcopy_supplemental'}) {
  } else {          if ($folder =~ /^supplemental/) {
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);              $title = $env{'docs.markedcopy_supplemental'};
  }          } else {
     }              (undef,undef,$title) =
     $url=~s/^http\&colon\;\/\//\/adm\/wrapper\/ext\//;                  &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {          }
  my $symb=&Apache::lonnet::symbclean(      } else {
           &Apache::lonnet::declutter('uploaded/'.          if ($folder=~/^supplemental/) {
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.                    $env{'user.domain'}.'___&&&___'.$title;
            '.sequence').          }
            '___'.$residx.'___'.      }
    &Apache::lonnet::declutter($url));  
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);      $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
  $url=&Apache::lonnet::clutter($url);      push(@LONCAPA::map::order, $newidx);
  if ($url=~/^\/*uploaded\//) {      return 'ok';
     $url=~/\.(\w+)$/;  # Store the result
     my $embstyle=&Apache::loncommon::fileembstyle($1);  }
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {  
  $url='/adm/wrapper'.$url;  sub uniqueness_check {
     } elsif ($embstyle eq 'ssi') {      my ($newurl) = @_;
  #do nothing with these      my $unique = 1;
     } elsif ($url!~/\.(sequence|page)$/) {      foreach my $res (@LONCAPA::map::order) {
  $url='/adm/coursedocs/showdoc'.$url;          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     }          $url=&LONCAPA::map::qtescape($url);
  } elsif ($url=~m|^/ext/|) {           if ($newurl eq $url) {
     $url='/adm/wrapper'.$url;              $unique = 0;
  }              last;    
  $url.=(($url=~/\?/)?'&':'?').'symb='.&Apache::lonnet::escape($symb);          }
  if ($container eq 'page') {      }
     my $symb=$env{'form.pagesymb'};      return $unique;
           }
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);  
     $url.=(($url=~/\?/)?'&':'?').'symb='.&Apache::lonnet::escape($symb);  my %parameter_type = ( 'randompick'     => 'int_pos',
  }         'hiddenresource' => 'string_yesno',
     }         'encrypturl'     => 'string_yesno',
     my $parameterset='&nbsp;';         'randomorder'    => 'string_yesno',);
     if ($isfolder) {  my $valid_parameters_re = join('|',keys(%parameter_type));
  my $foldername=&Apache::lonnet::escape($foldertitle);  # set parameters
  my $folderpath=$env{'form.folderpath'};  sub update_parameter {
  if ($folderpath) { $folderpath.='&' };  
  $folderpath.=$folderarg.'&'.$foldername;      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
  $url.='folderpath='.&Apache::lonnet::escape($folderpath).$cpinfo;  
  $parameterset='<label>'.&mt('Randomly Pick: ').      my $which = $env{'form.changeparms'};
     '<input type="text" size="4" onChange="this.form.submit()" name="randpick_'.$orderidx.'" value="'.      my $idx = $env{'form.setparms'};
     (&Apache::lonratedt::getparameter($orderidx,      if ($env{'form.'.$which.'_'.$idx}) {
                                               'parameter_randompick'))[0].   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
                                               '" />'.                                       : 'yes';
 '<font size="-2"><a href="javascript:void(0)">'.&mt('Store').'</a></font></label>';   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
                $parameter_type{$which});
     }   &remember_parms($idx,$which,'set',$value);
     if ($ispage) {      } else {
         my $pagename=&Apache::lonnet::escape($pagetitle);   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
         my $pagepath;  
         my $folderpath=$env{'form.folderpath'};   &remember_parms($idx,$which,'del');
         if ($folderpath) { $pagepath = $folderpath.'&' };      }
         $pagepath.=$pagearg.'&'.$pagename;      return 1;
  my $symb=$env{'form.pagesymb'};  }
  if (!$symb) {  
     my $path='uploaded/'.  
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.  sub handle_edit_cmd {
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';      my ($coursenum,$coursedom) =@_;
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',  
        $residx,      my ($cmd,$idx)=split('_',$env{'form.cmd'});
        $path.$pagearg.'.page');  
  }      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
  $url.='pagepath='.&Apache::lonnet::escape($pagepath).      my ($title, $url, @rrest) = split(':', $ratstr);
     '&pagesymb='.&Apache::lonnet::escape($symb).$cpinfo;  
     }      if ($cmd eq 'del') {
     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  '" border="0"></a></td>'.      ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
         "<td bgcolor='#FFFFBB'><a href='$url'>$title</a></td>";      &Apache::lonnet::removeuploadedurl($url);
     if (($allowed) && ($folder!~/^supplemental/)) {   } else {
   my %lt=&Apache::lonlocal::texthash(      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
        'hd' => 'Hidden',   }
        'ec' => 'URL hidden');   splice(@LONCAPA::map::order, $idx, 1);
  my $enctext=  
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');      } elsif ($cmd eq 'cut') {
  my $hidtext=   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');   splice(@LONCAPA::map::order, $idx, 1);
  $line.=(<<ENDPARMS);  
 <td bgcolor="#BBBBFF"><font size='-2'>      } elsif ($cmd eq 'up'
 <nobr><label><input type="checkbox" name="hidprs_$orderidx" onClick="this.form.submit()" $hidtext /> $lt{'hd'}</label></nobr></td>       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
 <td bgcolor="#BBBBFF"><font size='-2'>   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
 <nobr><label><input type="checkbox" name="encprs_$orderidx" onClick="this.form.submit()" $enctext /> $lt{'ec'}</label></nobr></td>  
 <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>      } elsif ($cmd eq 'down'
 ENDPARMS       && defined($LONCAPA::map::order[$idx+1])) {
     }   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
     $line.="</form></tr>";  
     return $line;      } elsif ($cmd eq 'rename') {
 }  
    my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
 # ---------------------------------------------------------------- tie the hash   if ($comment=~/\S/) {
       $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
 sub tiehash {   $comment.':'.join(':', $url, @rrest);
     my ($mode)=@_;   }
     $hashtied=0;  # Devalidate title cache
     if ($env{'request.course.fn'}) {   my $renamed_url=&LONCAPA::map::qtescape($url);
  if ($mode eq 'write') {   &Apache::lonnet::devalidate_title_cache($renamed_url);
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      } else {
     &GDBM_WRCREAT(),0640)) {   return 0;
                 $hashtied=2;      }
     }      return 1;
  } else {  }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",  
     &GDBM_READER(),0640)) {  sub editor {
                 $hashtied=1;      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;
     }  
  }      my $container= ($env{'form.pagepath'}) ? 'page'
     }                                 : 'sequence';
 }  
       my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 sub untiehash {      $folder.'.'.$container);
     if ($hashtied) { untie %hash; }      return $errtext if ($fatal);
     $hashtied=0;  
 }      if ($#LONCAPA::map::order<1) {
    my $idx=&LONCAPA::map::getresidx();
 # --------------------------------------------------------------- check on this   if ($idx<=0) { $idx=1; }
           $LONCAPA::map::order[0]=$idx;
 sub checkonthis {          $LONCAPA::map::resources[$idx]='';
     my ($r,$url,$level,$title)=@_;      }
     $url=&Apache::lonnet::unescape($url);     
     $alreadyseen{$url}=1;      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=
     $r->rflush();   &breadcrumbs($folder,$allowed,$type);
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {      $r->print($breadcrumbtrail);
        $r->print("\n<br />");     
        for (my $i=0;$i<=$level*5;$i++) {  # ------------------------------------------------------------ Process commands
            $r->print('&nbsp;');  
        }  # ---------------- if they are for this folder and user allowed to make changes
        $r->print('<a href="'.$url.'" target="cat">'.      if (($allowed) && ($env{'form.folder'} eq $folder)) {
  ($title?$title:$url).'</a> ');  # set parameters and change order
        if ($url=~/^\/res\//) {   &snapshotbefore();
   my $result=&Apache::lonnet::repcopy(  
                               &Apache::lonnet::filelocation('',$url));   if (&update_parameter()) {
           if ($result eq 'ok') {      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
              $r->print('<font color="green">'.&mt('ok').'</font>');      return $errtext if ($fatal);
              $r->rflush();   }
              &Apache::lonnet::countacc($url);  
              $url=~/\.(\w+)$/;   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {  # change order
  $r->print('<br />');      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
                  $r->rflush();      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
                  for (my $i=0;$i<=$level*5;$i++) {  
                      $r->print('&nbsp;');      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                  }      return $errtext if ($fatal);
                  $r->print('- '.&mt('Rendering').': ');   }
  my ($errorcount,$warningcount)=split(/:/,      
        &Apache::lonnet::ssi_body($url,   if ($env{'form.pastemarked'}) {
        ('grade_target'=>'web',              my $paste_res =
  'return_only_error_and_warning_counts' => 1)));                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
                  if (($errorcount) ||              if ($paste_res eq 'ok') {
                      ($warningcount)) {                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
      if ($errorcount) {                  return $errtext if ($fatal);
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.              } elsif ($paste_res ne '') {
   $errorcount.' '.                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
   &mt('error(s)').'</b></font> ');              }
                      }   }
      if ($warningcount) {  
                         $r->print('<font color="blue">'.   $r->print($upload_output);
   $warningcount.' '.  
   &mt('warning(s)').'</font>');   if (&handle_edit_cmd()) {
                      }      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                  } else {      return $errtext if ($fatal);
                      $r->print('<font color="green">'.&mt('ok').'</font>');   }
                  }  # Group import/search
                  $r->rflush();   if ($env{'form.importdetail'}) {
              }      my @imports;
      my $dependencies=      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
                 &Apache::lonnet::metadata($url,'dependencies');   if (defined($item)) {
              foreach (split(/\,/,$dependencies)) {      my ($name,$url,$residx)=
  if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {   map {&unescape($_)} split(/\=/,$item);
                     &checkonthis($r,$_,$level+1);      push(@imports, [$name, $url, $residx]);
                  }   }
              }      }
           } elsif ($result eq 'unavailable') {      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');      $container,'londocs',@imports);
           } elsif ($result eq 'not_found') {      return $errtext if ($fatal);
       unless ($url=~/\$/) {   }
   $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');  # Loading a complete map
       } else {   if ($env{'form.loadmap'}) {
   $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');      if ($env{'form.importmap'}=~/\w/) {
       }   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
           } else {      my ($title,$url,$ext,$type)=split(/\:/,$res);
              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');      my $idx=&LONCAPA::map::getresidx($url);
           }      $LONCAPA::map::resources[$idx]=$res;
       }      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
    }   }
 }   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
       $folder.'.'.$container);
    return $errtext if ($fatal);
 #      } else {
 # -------------------------------------------------------------- Verify Content   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
 #   
 sub verifycontent {      }
    my $r=shift;    }
    my $loaderror=&Apache::lonnet::overloaderror($r);   &log_differences($plain);
    if ($loaderror) { return $loaderror; }      }
    my $html=&Apache::lonxml::xmlbegin();  # ---------------------------------------------------------------- End commands
    $r->print($html.'<head><title>Verify Content</title></head>'.  # ---------------------------------------------------------------- Print screen
               &Apache::loncommon::bodytag('Verify Course Documents'));      my $idx=0;
    $hashtied=0;      my $shown=0;
    undef %alreadyseen;      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
    %alreadyseen=();   $r->print('<p>'.&mt('Parameters').':<ul>'.
    &tiehash();    ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
    foreach (keys %hash) {    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
        if ($hash{$_}=~/\.(page|sequence)$/) {    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
    if (($_=~/^src_/) && ($alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {    '</ul></p>');
        $r->print('<hr /><font color="red">'.      }                                                                                                    
  &mt('The following sequence or page is included more than once in your course: ').      if ($randompick>=0) {
  &Apache::lonnet::unescape($hash{$_}).'</font><br />'.   $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>');
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));      }
    }      if ($is_random_order) {
        }   $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');
        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {      }
            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});      $r->print('<table class="LC_docs_editor">');
        }      foreach my $res (@LONCAPA::map::order) {
    }   my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
    &untiehash();   $name=&LONCAPA::map::qtescape($name);
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.   $url=&LONCAPA::map::qtescape($url);
      &mt('Return to DOCS').'</a>');   unless ($name) {  $name=(split(/\//,$url))[-1]; }
 }   unless ($name) { $idx++; next; }
    $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,
 # -------------------------------------------------------------- Check Versions       $coursenum));
    $idx++;
 sub checkversions {   $shown++;
     my $r=shift;      }
     my $html=&Apache::lonxml::xmlbegin();      unless ($shown) {
     $r->print($html.'<head><title>Check Versions</title></head>'.   $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
               &Apache::loncommon::bodytag('Check Course Document Versions'));      }
     my $header='';      $r->print("\n</table>\n");
     my $startsel='';      if ($allowed) {
     my $monthsel='';          &print_paste_buffer($r,$container);
     my $weeksel='';      }
     my $daysel='';      return;
     my $allsel='';  }
     my %changes=();  
     my $starttime=0;  sub process_file_upload {
     my $haschanged=0;      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
     my %setversions=&Apache::lonnet::dump('resourceversions',  # upload a file, if present
   $env{'course.'.$env{'request.course.id'}.'.domain'},      my $parseaction;
   $env{'course.'.$env{'request.course.id'}.'.num'});     if ($env{'form.parserflag'}) {
           $parseaction = 'parse';
     $hashtied=0;      }
     &tiehash();      my $phase_status;
     my %newsetversions=();      my $folder=$env{'form.folder'};
     if ($env{'form.setmostrecent'}) {      if ($folder eq '') {
  $haschanged=1;          $folder='default';
  foreach (keys %hash) {      }
     if ($_=~/^ids\_(\/res\/.+)$/) {      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  $newsetversions{$1}='mostrecent';          my $errtext='';
     }          my $fatal=0;
  }          my $container='sequence';
     } elsif ($env{'form.setcurrent'}) {          if ($env{'form.pagepath'}) {
  $haschanged=1;              $container='page';
  foreach (keys %hash) {          }
     if ($_=~/^ids\_(\/res\/.+)$/) {          ($errtext,$fatal)=
  my $getvers=&Apache::lonnet::getversion($1);                &mapread($coursenum,$coursedom,$folder.'.'.$container);
  if ($getvers>0) {          if ($#LONCAPA::map::order<1) {
     $newsetversions{$1}=$getvers;              $LONCAPA::map::order[0]=1;
  }              $LONCAPA::map::resources[1]='';
     }          }
  }          if ($fatal) {
     } elsif ($env{'form.setversions'}) {              return 'failed';
  $haschanged=1;          }
  foreach (keys %env) {          my $destination = 'docs/';
     if ($_=~/^form\.set_version_(.+)$/) {          if ($folder =~ /^supplemental/) {
  my $src=$1;              $destination = 'supplemental/';
  if (($env{$_}) && ($env{$_} ne $setversions{$src})) {          }
     $newsetversions{$src}=$env{$_};          if (($folder eq 'default') || ($folder eq 'supplemental')) {
  }              $destination .= 'default/';
     }          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
  }              $destination .=  $2.'/';
     }          }
     if ($haschanged) {  # this is for a course, not a user, so set coursedoc flag
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,  # probably the only place in the system where this should be "1"
   $env{'course.'.$env{'request.course.id'}.'.domain'},          my $newidx=&LONCAPA::map::getresidx();
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {          $destination .= $newidx;
     $r->print('<h1>'.&mt('Your Version Settings have been Stored').'</h1>');          my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
  } else {   $parseaction,$allfiles,
     $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Store your Version Settings').'</font></h1>');   $codebase);
  }          my $ext='false';
  &mark_hash_old();          if ($url=~m{^http://}) { $ext='true'; }
     }   $url     = &LONCAPA::map::qtunescape($url);
     &changewarning($r,'');          my $comment=$env{'form.comment'};
     if ($env{'form.timerange'} eq 'all') {   $comment = &LONCAPA::map::qtunescape($comment);
 # show all documents          if ($folder=~/^supplemental/) {
  $header=&mt('All Documents in Course');                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  $allsel=1;                    $env{'user.domain'}.'___&&&___'.$comment;
  foreach (keys %hash) {          }
     if ($_=~/^ids\_(\/res\/.+)$/) {  
  my $src=$1;          $LONCAPA::map::resources[$newidx]=
  $changes{$src}=1;      $comment.':'.$url.':'.$ext.':normal:res';
     }          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
  }          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     } else {      $folder.'.'.$container);
 # show documents which changed          if ($fatal) {
  %changes=&Apache::lonnet::dump              $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},              return 'failed';
                      $env{'course.'.$env{'request.course.id'}.'.num'});          } else {
  my $firstkey=(keys %changes)[0];              if ($parseaction eq 'parse') {
  unless ($firstkey=~/^error\:/) {                  my $total_embedded = keys(%{$allfiles});
     unless ($env{'form.timerange'}) {                  if ($total_embedded > 0) {
  $env{'form.timerange'}=604800;                      my $num = 0;
     }      my $state = '
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '     <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
  .&mt('seconds');     <input type="hidden" name="cmd" value="upload_embedded" />
     if ($env{'form.timerange'}==-1) {     <input type="hidden" name="newidx" value="'.$newidx.'" />
  $seltext='since start of course';     <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
  $startsel='selected';     <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
  $env{'form.timerange'}=time;      $phase_status = 'phasetwo';
     }  
     $starttime=time-$env{'form.timerange'};                      $$upload_output .=
     if ($env{'form.timerange'}==2592000) {   'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   &Apache::loncommon::ask_for_embedded_content(
  $monthsel='selected';                              '/adm/coursedocs',$state,$allfiles,$codebase);
     } elsif ($env{'form.timerange'}==604800) {                  } else {
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                      $$upload_output .= 'No embedded items identified<br />';
  $weeksel='selected';                  }
     } elsif ($env{'form.timerange'}==86400) {              }
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';          }
  $daysel='selected';      }
     }      return $phase_status;
     $header=&mt('Content changed').' '.$seltext;  }
  } else {  
     $header=&mt('No content modifications yet.');  sub process_secondary_uploads {
  }      my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
     }      my $folder=$env{'form.folder'};
     %setversions=&Apache::lonnet::dump('resourceversions',      my $destination = 'docs/';
   $env{'course.'.$env{'request.course.id'}.'.domain'},      if ($folder =~ /^supplemental/) {
   $env{'course.'.$env{'request.course.id'}.'.num'});          $destination = 'supplemental/';
     my %lt=&Apache::lonlocal::texthash      }
       ('st' => 'Version changes since start of Course',      if (($folder eq 'default') || ($folder eq 'supplemental')) {
        'lm' => 'Version changes since last Month',          $destination .= 'default/';
        'lw' => 'Version changes since last Week',      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
        'sy' => 'Version changes since Yesterday',          $destination .=  $2.'/';
                'al' => 'All Resources (possibly large output)',      }
        'sd' => 'Display',      $destination .= $newidx;
        'fi' => 'File',      my ($url,$filename);
        'md' => 'Modification Date',      $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
                'mr' => 'Most recently published Version',      ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});
        've' => 'Version used in Course',      return $filename;
                'vu' => 'Set Version to be used in Course',  }
 'sv' => 'Set Versions to be used in Course according to Selections below',  
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',  sub is_supplemental_title {
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      my ($title) = @_;
        'di' => 'Differences');      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
     $r->print(<<ENDHEADERS);  }
 <form action="/adm/coursedocs" method="post">  
 <input type="hidden" name="versions" value="1" />  sub parse_supplemental_title {
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />      my ($title) = @_;
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />  
 <select name="timerange">      my ($foldertitle,$renametitle);
 <option value='all' $allsel>$lt{'al'}</option>      if ($title =~ /&amp;&amp;&amp;/) {
 <option value="-1" $startsel>$lt{'st'}</option>   $title = &HTML::Entites::decode($title);
 <option value="2592000" $monthsel>$lt{'lm'}</option>      }
 <option value="604800" $weeksel>$lt{'lw'}</option>   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
 <option value="86400" $daysel>$lt{'sy'}</option>   $renametitle=$4;
 </select>   my ($time,$uname,$udom) = ($1,$2,$3);
 <input type="submit" name="display" value="$lt{'sd'}" />   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
 <h3>$header</h3>   my $name =  &Apache::loncommon::plainname($uname,$udom);
 <input type="submit" name="setversions" value="$lt{'sv'}" />   $name = &HTML::Entities::encode($name,'"<>&\'');
 <table border="0">   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
 ENDHEADERS      $name.': <br />'.$foldertitle;
     foreach (sort keys %changes) {      }
  if ($changes{$_}>$starttime) {      if (wantarray) {
     my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);   return ($title,$foldertitle,$renametitle);
     my $currentversion=&Apache::lonnet::getversion($_);      }
     if ($currentversion<0) {      return $title;
  $currentversion=&mt('Could not be determined.');  }
     }  
     my $linkurl=&Apache::lonnet::clutter($_);  # --------------------------------------------------------------- An entry line
     $r->print(  
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.  sub entryline {
       &Apache::lonnet::gettitle($linkurl).      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
                       '</b></font></td></tr>'.  
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      my ($foldertitle,$pagetitle,$renametitle);
                       '<td colspan="4">'.      if (&is_supplemental_title($title)) {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
       '</a></td></tr>'.   $pagetitle = $foldertitle;
                       '<tr><td></td>'.      } else {
                       '<td title="'.$lt{'md'}.'">'.   $title=&HTML::Entities::encode($title,'"<>&\'');
       &Apache::lonlocal::locallocaltime(   $renametitle=$title;
                            &Apache::lonnet::metadata($root.'.'.$extension,   $foldertitle=$title;
                                                      'lastrevisiondate')   $pagetitle=$title;
                                                         ).      }
                       '</td>'.  
                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.      my $orderidx=$LONCAPA::map::order[$index];
                       '<font size="+1">'.$currentversion.'</font>'.     
                       '</nobr></td>'.  
                       '<td title="'.$lt{'ve'}.'"><nobr>In Course: '.      $renametitle=~s/\\/\\\\/g;
                       '<font size="+1">');      $renametitle=~s/\&quot\;/\\\"/g;
 # Used in course      $renametitle=~s/ /%20/g;
     my $usedversion=$hash{'version_'.$linkurl};      my $line='<tr>';
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      my ($form_start,$form_end);
  $r->print($usedversion);  # Edit commands
     } else {      my ($container, $type, $esc_path, $path, $symb);
  $r->print($currentversion);      if ($env{'form.folderpath'}) {
     }   $type = 'folder';
     $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.          $container = 'sequence';
                       '<nobr>Use: ');   $esc_path=&escape($env{'form.folderpath'});
 # Set version   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
       'set_version_'.$linkurl,      }
       ('select_form_order' =>      if ($env{'form.pagepath'}) {
        ['',1..$currentversion,'mostrecent'],          $type = $container = 'page';
        '' => '',          $esc_path=&escape($path = $env{'form.pagepath'});
        'mostrecent' => 'most recent',   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
        map {$_,$_} (1..$currentversion))));          $symb=&escape($env{'form.pagesymb'});
     $r->print('</nobr></td></tr><tr><td></td>');      }
     my $lastold=1;      my $cpinfo='';
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {      if ($allowed) {
  my $url=$root.'.'.$prevvers.'.'.$extension;   my $incindex=$index+1;
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<   my $selectbox='';
     $starttime) {   if (($folder!~/^supplemental/) &&
     $lastold=$prevvers;      ($#LONCAPA::map::order>0) &&
  }      ((split(/\:/,
     }       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
             #        ne '') &&
             # Code to figure out how many version entries should go in      ((split(/\:/,
             # each of the four columns       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
             my $entries_per_col = 0;       ne '')) {
             my $num_entries = ($currentversion-$lastold);      $selectbox=
             if ($num_entries % 4 == 0) {   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
                 $entries_per_col = $num_entries/4;   '<select name="newpos" onChange="this.form.submit()">';
             } else {      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
                 $entries_per_col = $num_entries/4 + 1;   if ($i==$incindex) {
             }      $selectbox.='<option value="" selected="1">('.$i.')</option>';
             my $entries_count = 0;   } else {
             $r->print('<td valign="top"><font size="-2">');       $selectbox.='<option value="'.$i.'">'.$i.'</option>';
             my $cols_output = 1;   }
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {      }
  my $url=$root.'.'.$prevvers.'.'.$extension;      $selectbox.='</select>';
  $r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).   }
   '">'.&mt('Version').' '.$prevvers.'</a> ('.   my %lt=&Apache::lonlocal::texthash(
   &Apache::lonlocal::locallocaltime(                  'up' => 'Move Up',
                                 &Apache::lonnet::metadata($url,   'dw' => 'Move Down',
                                                           'lastrevisiondate')   'rm' => 'Remove',
                                                             ).                  'ct' => 'Cut',
   ')');   'rn' => 'Rename',
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {   'cp' => 'Copy');
                     $r->print(' <a href="/adm/diff?filename='.   my $nocopy=0;
       &Apache::lonnet::clutter($root.'.'.$extension).          my $nocut=0;
       '&versionone='.$prevvers.          if ($url=~/\.(page|sequence)$/) {
       '">'.&mt('Diffs').'</a>');      if ($url =~ m{/res/}) {
  }   # no copy for published maps
  $r->print('</nobr><br />');   $nocopy = 1;
                 if (++$entries_count % $entries_per_col == 0) {      } else {
                     $r->print('</font></td>');   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
                     if ($cols_output != 4) {      my ($title,$url,$ext,$type)=split(/\:/,$item);
                         $r->print('<td valign="top"><font size="-2">');      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
                         $cols_output++;   $nocopy=1;
                     }   last;
                 }      }
     }   }
             while($cols_output++ < 4) {      }
                 $r->print('</font></td><td><font>')   }
             }          if ($url=~/^\/res\/lib\/templates\//) {
     $r->print('</font></td></tr>'."\n");             $nocopy=1;
  }             $nocut=1;
     }          }
     $r->print('</table></form>');          my $copylink='&nbsp;';
     $r->print('<h1>'.&mt('Done').'.</h1>');          my $cutlink='&nbsp;';
   
     &untiehash();   my $skip_confirm = 0;
 }   if ( $folder =~ /^supplemental/
        || ($url =~ m{( /smppg$
 sub mark_hash_old {      |/syllabus$
     my $retie_hash=0;      |/aboutme$
     if ($hashtied) {      |/navmaps$
  $retie_hash=1;      |/bulletinboard$
  &untiehash();      |\.html$
     }      |^/adm/wrapper/ext)}x)) {
     &tiehash('write');      $skip_confirm = 1;
     $hash{'old'}=1;   }
     &untiehash();  
     if ($retie_hash) { &tiehash(); }   if (!$nocopy) {
 }      $copylink=(<<ENDCOPY);
   <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
 sub is_hash_old {  ENDCOPY
     my $untie_hash=0;          }
     if (!$hashtied) {   if (!$nocut) {
  $untie_hash=1;      $cutlink=(<<ENDCUT);
  &tiehash();  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
     }  ENDCUT
     my $return=$hash{'old'};          }
     if ($untie_hash) { &untiehash(); }   $form_start = (<<END);
     return $return;     <form  action="/adm/coursedocs" method="post">
 }     <input type="hidden" name="${type}path" value="$path" />
      <input type="hidden" name="${type}symb" value="$symb" />
 sub changewarning {     <input type="hidden" name="setparms" value="$orderidx" />
     my ($r,$postexec,$message,$url)=@_;     <input type="hidden" name="changeparms" value="0" />
     if (!&is_hash_old()) { return; }  END
     my $pathvar='folderpath';          $form_end = '</form>';
     my $path=&Apache::lonnet::escape($env{'form.folderpath'});   $line.=(<<END);
     if (!defined($url)) {  <td>
  if (defined($env{'form.pagepath'})) {     <table class="LC_docs_entry_move">
     $pathvar='pagepath';        <tr>
     $path=&Apache::lonnet::escape($env{'form.pagepath'});           <td>
     $path.='&amp;symb='.&Apache::lonnet::escape($env{'form.pagesymb'});              <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>
  }           </td>
  $url='/adm/coursedocs?'.$pathvar.'='.$path;        </tr>
     }        <tr>
     if (!defined($message)) {          <td>
  $message='Changes will become active for your current session after [_1], or the next time you log in.';             <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" /></a>
     }          </td>
     $r->print(        </tr>
 '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'.       </table>
 '<form method="post" action="/adm/roles" target="loncapaclient">'.  </td>
 '<input type="hidden" name="orgurl" value="'.$url.  <td>
 '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.     $form_start
 &mt($message,' <input type="hidden" name="'.     $selectbox
     $env{'request.role'}.'" value="1" /><input type="button" value="'.     $form_end
     &mt('re-initializing course').'" onClick="reinit(this.form)" />').  </td>
 $help{'Caching'}.'</font></h3></form>');  <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>
   $cutlink
 # ================================================================ Main Handler     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
 sub handler {  $copylink
     my $r = shift;  </td>
     &Apache::loncommon::content_type($r,'text/html');  END
     $r->send_http_header;  
     return OK if $r->header_only;      }
   # Figure out what kind of a resource this is
 # --------------------------------------------- Initialize help topics for this      my ($extension)=($url=~/\.(\w+)$/);
   foreach ('Adding_Course_Doc','Main_Course_Documents',      my $uploaded=($url=~/^\/*uploaded\//);
            'Adding_External_Resource','Navigate_Content',      my $icon=&Apache::loncommon::icon($url);
            'Adding_Folders','Docs_Overview', 'Load_Map',      my $isfolder=0;
            'Supplemental','Score_Upload_Form','Adding_Pages',      my $ispage=0;
            'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',      my $folderarg;
    'Check_Resource_Versions','Verify_Content') {      my $pagearg;
       $help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);      my $pagefile;
   }      if ($uploaded) {
     # Composite help files   if ($extension eq 'sequence') {
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(      $icon=$iconpath.'/folder_closed.gif';
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(      $url='/adm/coursedocs?';
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');      $folderarg=$1;
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(      $isfolder=1;
     'Option_Response_Simple');          } elsif ($extension eq 'page') {
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(              $icon=$iconpath.'/page.gif';
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(              $pagearg=$1;
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');              $url='/adm/coursedocs?';
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');              $ispage=1;
    } else {
   if ($env{'form.verify'}) {      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
       &verifycontent($r);   }
   } elsif ($env{'form.versions'}) {      }
       &checkversions($r);     
   } elsif ($env{'form.dumpcourse'}) {      my $orig_url = $url;
       &dumpcourse($r);      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
   } elsif ($env{'form.exportcourse'}) {      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
       &exportcourse($r);   my $symb=&Apache::lonnet::symbclean(
   } else {            &Apache::lonnet::declutter('uploaded/'.
 # is this a standard course?             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
              $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);             '.sequence').
     my $forcestandard = 0;             '___'.$residx.'___'.
     my $forcesupplement;     &Apache::lonnet::declutter($url));
     my $script='';   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
     my $allowed;   $url=&Apache::lonnet::clutter($url);
     my $events='';   if ($url=~/^\/*uploaded\//) {
     my $showdoc=0;      $url=~/\.(\w+)$/;
     my $containertag;      my $embstyle=&Apache::loncommon::fileembstyle($1);
     my $uploadtag;      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},   $url='/adm/wrapper'.$url;
     ['folderpath','pagepath','pagesymb','markedcopy_url','markedcopy_title']);      } elsif ($embstyle eq 'ssi') {
     if ($env{'form.folderpath'}) {   #do nothing with these
  my (@folderpath)=split('&',$env{'form.folderpath'});      } elsif ($url!~/\.(sequence|page)$/) {
  $env{'form.foldername'}=&Apache::lonnet::unescape(pop(@folderpath));   $url='/adm/coursedocs/showdoc'.$url;
  $env{'form.folder'}=pop(@folderpath);      }
     }   } elsif ($url=~m|^/ext/|) {
     if ($env{'form.pagepath'}) {      $url='/adm/wrapper'.$url;
         my (@pagepath)=split('&',$env{'form.pagepath'});      $external = 1;
         $env{'form.pagename'}=&Apache::lonnet::unescape(pop(@pagepath));   }
         $env{'form.folder'}=pop(@pagepath);          if (&Apache::lonnet::symbverify($symb,$url)) {
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
     '<input type="hidden" name="pagesymb" value="" />';          } else {
         $uploadtag = '<input type="hidden" name="pagepath" value="'.$env{'form.pagepath'}.'" />'.              $url='';
     '<input type="hidden" name="pagesymb" value="'.$env{'form.pagesymb'}.'" />';          }
     }   if ($container eq 'page') {
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {      my $symb=$env{'form.pagesymb'};
        $showdoc='/'.$1;          
     }      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
     unless ($showdoc) { # got called from remote      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
        if (($env{'form.folder'}=~/^default_/) ||    }
           ($env{'form.folder'} =~ m#^\d+/(pages|sequences)/#)) {      }
            $forcestandard = 1;      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
        }       if ($isfolder || $extension eq 'sequence') {
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);   my $foldername=&escape($foldertitle);
    my $folderpath=$env{'form.folderpath'};
 # does this user have privileges to post, etc?   if ($folderpath) { $folderpath.='&' };
        $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});  # Append randompick number, hidden, and encrypted with ":" to foldername,
        if ($allowed) {   # so it gets transferred between levels
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
          $script=&Apache::lonratedt::editscript('simple');                                                 'parameter_randompick'))[0]
        }                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     } else { # got called in sequence from course                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
        $allowed=0;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
        $script='</script>'.&Apache::lonmenu::registerurl(1,undef).'<script>';                                                'parameter_encrypturl'))[0]=~/^yes$/i)
        $events='onLoad="'.&Apache::lonmenu::loadevents.                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
            '" onUnload="'.&Apache::lonmenu::unloadevents.'"';                                                'parameter_randomorder'))[0]=~/^yes$/i);
     }   $url.='folderpath='.&escape($folderpath).$cpinfo;
    $parameterset='<label>'.&mt('Randomly Pick: ').
 # get course data      '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};      (&LONCAPA::map::getparameter($orderidx,
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};                                                'parameter_randompick'))[0].
                                                 '" />'.
 # get personal data  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
        my $ro_set=
     my $uname=$env{'user.name'};      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
     my $udom=$env{'user.domain'};   $rand_order_text ='
     my $plainname=&Apache::lonnet::escape(  <span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" onClick="this.form.changeparms.value=\'randomorder\';this.form.submit()" '.$ro_set.' /> '.&mt('Random Order').' </label></span>';  
                      &Apache::loncommon::plainname($uname,$udom));      }
       if ($ispage) {
 # graphics settings          my $pagename=&escape($pagetitle);
           my $pagepath;
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");          my $folderpath=$env{'form.folderpath'};
           if ($folderpath) { $pagepath = $folderpath.'&' };
     my $now=time;          $pagepath.=$pagearg.'&'.$pagename;
    my $symb=$env{'form.pagesymb'};
 # print screen   if (!$symb) {
        my $html=&Apache::lonxml::xmlbegin();      my $path='uploaded/'.
     $r->print(<<ENDDOCUMENT);   $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 $html   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 <head>      $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
 <title>The LearningOnline Network with CAPA</title>         $residx,
 <script>         $path.$pagearg.'.page');
 $script   }
 </script>   $url.='pagepath='.&escape($pagepath).
 ENDDOCUMENT      '&amp;pagesymb='.&escape($symb).$cpinfo;
    if ($allowed) {      }
     $r->print(<<ENDNEWSCRIPT);      if ($external) {
 <script>   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
 function makenewfolder(targetform,folderseq) {   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
     var foldername=prompt('Name of New Folder','New Folder');      } else {
     if (foldername) {   undef($external);
  targetform.importdetail.value=foldername+"="+folderseq;      }
         targetform.submit();      $line.='
     }    <td class="LC_docs_entry_icon">
 }      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
     </td>
 function makenewpage(targetform,folderseq) {    <td class="LC_docs_entry_title">
     var pagename=prompt('Name of New Page','New Page');      '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."
     if (pagename) {    </td>";
         targetform.importdetail.value=pagename+"="+folderseq;      if (($allowed) && ($folder!~/^supplemental/)) {
         targetform.submit();    my %lt=&Apache::lonlocal::texthash(
     }         'hd' => 'Hidden',
 }         'ec' => 'URL hidden');
    my $enctext=
 function makenewext(targetname) {      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
     this.document.forms.extimport.useform.value=targetname;   my $hidtext=
     window.open('/adm/rat/extpickframe.html');      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
 }   $line.=(<<ENDPARMS);
     <td class="LC_docs_entry_parameter">
 function makeexamupload() {      $form_start
    var title=prompt('Listed Title for the Uploaded Score');      <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
    if (title) {       $form_end
     this.document.forms.newexamupload.importdetail.value=    </td>
  title+'=/res/lib/templates/examupload.problem';    <td class="LC_docs_entry_parameter">
     this.document.forms.newexamupload.submit();      $form_start
    }      <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
 }      $form_end
     </td>
 function makesmppage() {    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
    var title=prompt('Listed Title for the Page');    <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
    if (title) {   ENDPARMS
     this.document.forms.newsmppg.importdetail.value=      }
  title+'=/adm/$udom/$uname/$now/smppg';      $line.="</tr>";
     this.document.forms.newsmppg.submit();      return $line;
    }  }
 }  
   =pod
 function makesmpproblem() {  
    var title=prompt('Listed Title for the Problem');  =item tiehash()
    if (title) {   
     this.document.forms.newsmpproblem.importdetail.value=  tie the hash
  title+'=/res/lib/templates/simpleproblem.problem';  
     this.document.forms.newsmpproblem.submit();  =cut
    }  
 }  sub tiehash {
       my ($mode)=@_;
 function makebulboard() {      $hashtied=0;
    var title=prompt('Listed Title for the Bulletin Board');      if ($env{'request.course.fn'}) {
    if (title) {   if ($mode eq 'write') {
     this.document.forms.newbul.importdetail.value=      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  title+'=/adm/$udom/$uname/$now/bulletinboard';      &GDBM_WRCREAT(),0640)) {
     this.document.forms.newbul.submit();                  $hashtied=2;
    }      }
 }   } else {
       if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 function makeabout() {      &GDBM_READER(),0640)) {
    var user=prompt("Enter user\@domain for User's 'About Me' Page");                  $hashtied=1;
    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=  sub untiehash {
    'About '+user+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';      if ($hashtied) { untie %hash; }
        this.document.forms.newaboutsomeone.submit();      $hashtied=0;
    } else {      return OK;
                alert("Not a valid user\@domain");  }
            }  
        } else {  
            alert("Please enter both user and domain in the format user\@domain");   
        }  
    }  sub checkonthis {
 }      my ($r,$url,$level,$title)=@_;
       $url=&unescape($url);
 function makeims() {      $alreadyseen{$url}=1;
     var caller = document.forms.ims.folder.value;      $r->rflush();
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");         $r->print("\n<br />");
     newWindow.location.href = newlocation;         if ($level==0) {
 }             $r->print("<br />");
          }
          for (my $i=0;$i<=$level*5;$i++) {
 function finishpick() {             $r->print('&nbsp;');
     var title=this.document.forms.extimport.title.value;         }
     var url=this.document.forms.extimport.url.value;         $r->print('<a href="'.$url.'" target="cat">'.
     var form=this.document.forms.extimport.useform.value;   ($title?$title:$url).'</a> ');
     eval         if ($url=~/^\/res\//) {
      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+    my $result=&Apache::lonnet::repcopy(
     '";this.document.forms.'+form+'.submit();');                                &Apache::lonnet::filelocation('',$url));
 }            if ($result eq 'ok') {
                $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 function changename(folderpath,index,oldtitle,container,pagesymb) {               $r->rflush();
     var title=prompt('New Title',oldtitle);               &Apache::lonnet::countacc($url);
     if (title) {               $url=~/\.(\w+)$/;
  this.document.forms.renameform.title.value=title;               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
  this.document.forms.renameform.cmd.value='rename_'+index;   $r->print('<br />');
         if (container == 'sequence') {                   $r->rflush();
     this.document.forms.renameform.folderpath.value=folderpath;                   for (my $i=0;$i<=$level*5;$i++) {
         }                       $r->print('&nbsp;');
         if (container == 'page') {                   }
             this.document.forms.renameform.pagepath.value=folderpath;                   $r->print('- '.&mt('Rendering:').' ');
             this.document.forms.renameform.pagesymb.value=pagesymb;   my ($errorcount,$warningcount)=split(/:/,
         }         &Apache::lonnet::ssi_body($url,
         this.document.forms.renameform.submit();         ('grade_target'=>'web',
     }   'return_only_error_and_warning_counts' => 1)));
 }                   if (($errorcount) ||
                        ($warningcount)) {
 function removeres(folderpath,index,oldtitle,container,pagesymb) {       if ($errorcount) {
     if (confirm('WARNING: Removing a resource makes associated grades and scores inaccessible!\\nRemove "'+oldtitle+'"?')) {                          $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.
  this.document.forms.renameform.cmd.value='del_'+index;                            &mt('[quant,_1,error]',$errorcount).'</span>');
         if (container == 'sequence') {                       }
             this.document.forms.renameform.folderpath.value=folderpath;       if ($warningcount) {
         }                          $r->print('<span class="LC_warning">'.
         if (container == 'page') {                            &mt('[quant,_1,warning]',$warningcount).'</span>');
             this.document.forms.renameform.pagepath.value=folderpath;                       }
             this.document.forms.renameform.pagesymb.value=pagesymb;                   } else {
         }                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
         this.document.forms.renameform.submit();                   }
     }                   $r->rflush();
 }               }
        my $dependencies=
 function cutres(folderpath,index,oldtitle,container,pagesymb) {                  &Apache::lonnet::metadata($url,'dependencies');
     if (confirm('WARNING: Cutting a resource makes associated grades and scores inaccessible,\\neven if it is pasted in again elsewhere!\\nCut "'+oldtitle+'"?')) {               foreach my $dep (split(/\,/,$dependencies)) {
  this.document.forms.renameform.cmd.value='cut_'+index;   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
  this.document.forms.renameform.markcopy.value=index;                      &checkonthis($r,$dep,$level+1);
         if (container == 'sequence') {                   }
             this.document.forms.renameform.folderpath.value=folderpath;               }
         }            } elsif ($result eq 'unavailable') {
         if (container == 'page') {               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
             this.document.forms.renameform.pagepath.value=folderpath;            } elsif ($result eq 'not_found') {
             this.document.forms.renameform.pagesymb.value=pagesymb;        unless ($url=~/\$/) {
         }    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
         this.document.forms.renameform.submit();        } else {
     }    $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');
 }        }
             } else {
 function markcopy(folderpath,index,oldtitle,container,pagesymb) {               $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()
   
 </script>  List Symbs
   
 ENDNEWSCRIPT  =cut
   }  
 # -------------------------------------------------------------------- Body tag  sub list_symbs {
   $r->print('</head>'.      my ($r) = @_;
             &Apache::loncommon::bodytag('Course Documents','',$events,  
  '','',$showdoc).      my $type = &Apache::loncommon::course_type();
     &Apache::loncommon::help_open_menu('','','','',273,'RAT'));      $r->print(&Apache::loncommon::start_page('Symb List'));
   unless ($showdoc) {      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
 # -----------------------------------------------------------------------------      my $navmap = Apache::lonnavmaps::navmap->new();
        my %lt=&Apache::lonlocal::texthash(      if (!defined($navmap)) {
                 'uplm' => 'Upload a new main course document',          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
                 'upls' => 'Upload a new supplemental course document',                    '<div class="LC_error">'.
                 'impp' => 'Import a document',                    &mt('Unable to retrieve information about course contents').
                 'pubd' => 'Published documents',                    '</div>');
  'copm' => 'All documents out of a published map',          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
                 'spec' => 'Special documents',      } else {
                 'upld' => 'Upload Document',          $r->print("<pre>\n");
                 'srch' => 'Search',          foreach my $res ($navmap->retrieveResources()) {
                 'impo' => 'Import',      $r->print($res->compTitle()."\t".$res->symb()."\n");
                 'selm' => 'Select Map',          }
                 'load' => 'Load Map',          $r->print("\n</pre>\n");
                 'newf' => 'New Folder',      }
                 'newp' => 'New Composite Page',      $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
                 'extr' => 'External Resource',  }
                 'syll' => 'Syllabus',  
                 'navc' => 'Navigate Contents',  
                 'sipa' => 'Simple Page',  sub verifycontent {
                 'sipr' => 'Simple Problem',      my ($r) = @_;
                 'scuf' => 'Score Upload Form',      my $type = &Apache::loncommon::course_type();
                 'bull' => 'Bulletin Board',     my $loaderror=&Apache::lonnet::overloaderror($r);
                 'mypi' => 'My Personal Info',     if ($loaderror) { return $loaderror; }
  'abou' => 'About User',     $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
                 'imsf' => 'Import IMS package',     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));
                 'file' =>  'File',     $hashtied=0;
                 'title' => 'Title',     undef %alreadyseen;
                 'comment' => 'Comment'      %alreadyseen=();
   );     &tiehash();
 # -----------------------------------------------------------------------------     foreach my $key (keys(%hash)) {
     if ($allowed) {         if ($hash{$key}=~/\.(page|sequence)$/) {
        my $dumpbut=&dumpbutton();     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
        my $exportbut=&exportbutton();         $r->print('<hr /><span class="LC_error">'.
        my %lt=&Apache::lonlocal::texthash(   &mt('The following sequence or page is included more than once in your '.$type.': ').
  'vc' => 'Verify Content',   &unescape($hash{$key}).'</span><br />'.
  'cv' => 'Check/Set Resource Versions',   &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
   );     }
          }
        my $folderpath=$env{'form.folderpath'};         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
        if (!$folderpath) {             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
    if ($env{'form.folder'} eq '' ||         }
        $env{'form.folder'} eq 'supplemental') {     }
        $folderpath='default&'.     &untiehash();
    &Apache::lonnet::escape(&mt('Main Course Documents'));     $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
    }       &mt('Return to DOCS').'</a>');
        }  }
        unless ($env{'form.pagepath'}) {  
            $containertag = '<input type="hidden" name="folderpath" value="" />';  
            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';  sub devalidateversioncache {
        }      my $src=shift;
       &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
        $r->print(<<ENDCOURSEVERIFY);    &Apache::lonnet::clutter($src));
 <form name="renameform" method="post" action="/adm/coursedocs">  }
 <input type="hidden" name="title" />  
 <input type="hidden" name="cmd" />  sub checkversions {
 <input type="hidden" name="markcopy" />      my ($r) = @_;
 $containertag      my $type = &Apache::loncommon::course_type();
 </form>      $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
 <form name="simpleedit" method="post" action="/adm/coursedocs">      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));
 <input type=hidden name="importdetail" value="">      my $header='';
 $uploadtag      my $startsel='';
 </form>      my $monthsel='';
 <form action="/adm/coursedocs" method="post" name="courseverify">      my $weeksel='';
 <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">      my $daysel='';
 <tr><td bgcolor="#DDDDCC">      my $allsel='';
 <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}      my %changes=();
 </td><td bgcolor="#DDDDCC">      my $starttime=0;
     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}      my $haschanged=0;
 $dumpbut      my %setversions=&Apache::lonnet::dump('resourceversions',
 $exportbut    $env{'course.'.$env{'request.course.id'}.'.domain'},
 </td></tr></table>    $env{'course.'.$env{'request.course.id'}.'.num'});
 </form>  
 ENDCOURSEVERIFY      $hashtied=0;
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',      &tiehash();
      &mt('Editing the Table of Contents for your Course')));      my %newsetversions=();
     }      if ($env{'form.setmostrecent'}) {
 # --------------------------------------------------------- Standard documents   $haschanged=1;
     $r->print('<table border=2 cellspacing=4 cellpadding=4>');   foreach my $key (keys(%hash)) {
     if (($standard) && ($allowed) && (!$forcesupplement)) {      if ($key=~/^ids\_(\/res\/.+)$/) {
  $r->print('<tr><td bgcolor="#BBBBBB">');   $newsetversions{$1}='mostrecent';
 #  '<h2>'.&mt('Main Course Documents').                  &devalidateversioncache($1);
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');      }
        my $folder=$env{'form.folder'};   }
        if ($folder eq '' || $folder eq 'supplemental') {      } elsif ($env{'form.setcurrent'}) {
            $folder='default';   $haschanged=1;
    $env{'form.folderpath'}='default&'.&Apache::lonnet::escape(&mt('Main Course Documents'));   foreach my $key (keys(%hash)) {
        }      if ($key=~/^ids\_(\/res\/.+)$/) {
        my $postexec='';   my $getvers=&Apache::lonnet::getversion($1);
        if ($folder eq 'default') {   if ($getvers>0) {
    $r->print('<script>this.window.name="loncapaclient";</script>');      $newsetversions{$1}=$getvers;
        } else {      &devalidateversioncache($1);
            #$postexec='self.close();';   }
        }      }
        $hadchanges=0;   }
        &editor($r,$coursenum,$coursedom,$folder,$allowed);      } elsif ($env{'form.setversions'}) {
        if ($hadchanges) {   $haschanged=1;
    &mark_hash_old()   foreach my $key (keys(%env)) {
        }      if ($key=~/^form\.set_version_(.+)$/) {
        &changewarning($r,$postexec);   my $src=$1;
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
                      '.sequence';      $newsetversions{$src}=$env{$key};
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      &devalidateversioncache($src);
                      '.page';   }
       }
        $r->print(<<ENDFORM);   }
 <table cellspacing=4 cellpadding=4><tr>      }
 <th bgcolor="#DDDDDD">$lt{'uplm'}</th>      if ($haschanged) {
 <th bgcolor="#DDDDDD">$lt{'impp'}</th>          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>    $env{'course.'.$env{'request.course.id'}.'.domain'},
 </tr>    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 <tr><td bgcolor="#DDDDDD">      $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
 $lt{'file'}:<br />   } else {
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">      $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
 <input type="file" name="uploaddoc" size="40">   }
 <br />   &mark_hash_old();
 $lt{'title'}:<br />      }
 <input type="text" size="50" name="comment">      &changewarning($r,'');
 $uploadtag      if ($env{'form.timerange'} eq 'all') {
 <input type="hidden" name="cmd" value="upload_default">  # show all documents
 <nobr>   $header=&mt('All Documents in '.$type);
 <input type="submit" value="$lt{'upld'}">   $allsel=1;
  $help{'Uploading_From_Harddrive'}   foreach my $key (keys(%hash)) {
 </nobr>      if ($key=~/^ids\_(\/res\/.+)$/) {
 </form>   my $src=$1;
 </td>   $changes{$src}=1;
 <td bgcolor="#DDDDDD">      }
 <form action="/adm/coursedocs" method="post" name="simpleeditdefault">   }
 $lt{'pubd'}<br />      } else {
 $uploadtag  # show documents which changed
 <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}">   %changes=&Apache::lonnet::dump
 <nobr>   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
 <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}">                       $env{'course.'.$env{'request.course.id'}.'.num'});
 $help{'Importing_LON-CAPA_Resource'}   my $firstkey=(keys(%changes))[0];
 </nobr>   unless ($firstkey=~/^error\:/) {
 <p>      unless ($env{'form.timerange'}) {
 <hr />   $env{'form.timerange'}=604800;
 $lt{'copm'}      }
 <input type="text" size="20" name="importmap"><br />      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 <nobr><input type=button    .&mt('seconds');
 onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      if ($env{'form.timerange'}==-1) {
 value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">   $seltext='since start of course';
 $help{'Load_Map'}</nobr>   $startsel='selected';
 </p>   $env{'form.timerange'}=time;
 </form>      }
 ENDFORM      $starttime=time-$env{'form.timerange'};
        unless ($env{'form.pagepath'}) {      if ($env{'form.timerange'}==2592000) {
    $r->print(<<ENDFORM);   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 <hr />   $monthsel='selected';
 <form action="/adm/coursedocs" method="post" name="newext">      } elsif ($env{'form.timerange'}==604800) {
 $uploadtag   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 <input type=hidden name="importdetail" value="">   $weeksel='selected';
 <nobr>      } elsif ($env{'form.timerange'}==86400) {
 <input name="newext" type="button" onClick="javascript:makenewext('newext');"   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   $daysel='selected';
 </nobr>      }
 </form>      $header=&mt('Content changed').' '.$seltext;
 <form action="/adm/imsimportdocs" method="post" name="ims">   } else {
 <input type="hidden" name="folder" value="$folder" />      $header=&mt('No content modifications yet.');
 <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />   }
 </nobr>      }
 </form>      %setversions=&Apache::lonnet::dump('resourceversions',
 ENDFORM    $env{'course.'.$env{'request.course.id'}.'.domain'},
        }    $env{'course.'.$env{'request.course.id'}.'.num'});
        $r->print('</td><td bgcolor="#DDDDDD">');      my %lt=&Apache::lonlocal::texthash
        unless ($env{'form.pagepath'}) {        ('st' => 'Version changes since start of '.$type,
            $r->print(<<ENDFORM);         'lm' => 'Version changes since last Month',
 <form action="/adm/coursedocs" method="post" name="newfolder">         'lw' => 'Version changes since last Week',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />         'sy' => 'Version changes since Yesterday',
 <input type=hidden name="importdetail" value="">                 'al' => 'All Resources (possibly large output)',
 <nobr>         'sd' => 'Display',
 <input name="newfolder" type="button"         'fi' => 'File',
 onClick="javascript:makenewfolder(this.form,'$folderseq');"         'md' => 'Modification Date',
 value="$lt{'newf'}" />$help{'Adding_Folders'}                 'mr' => 'Most recently published Version',
 </nobr>         've' => 'Version used in '.$type,
 </form>                 'vu' => 'Set Version to be used in '.$type,
 <form action="/adm/coursedocs" method="post" name="newpage">  'sv' => 'Set Versions to be used in '.$type.' according to Selections below',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 <input type=hidden name="importdetail" value="">  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 <nobr>         'di' => 'Differences');
 <input name="newpage" type="button"      $r->print(<<ENDHEADERS);
 onClick="javascript:makenewpage(this.form,'$pageseq');"  <form action="/adm/coursedocs" method="post">
 value="$lt{'newp'}" />$help{'Adding_Pages'}  <input type="hidden" name="versions" value="1" />
 </nobr>  <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
 </form>  <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
 <form action="/adm/coursedocs" method="post" name="newsyl">  <select name="timerange">
 $uploadtag  <option value='all' $allsel>$lt{'al'}</option>
 <input type=hidden name="importdetail"   <option value="-1" $startsel>$lt{'st'}</option>
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">  <option value="2592000" $monthsel>$lt{'lm'}</option>
 <nobr>  <option value="604800" $weeksel>$lt{'lw'}</option>
 <input name="newsyl" type="submit" value="$lt{'syll'}" />   <option value="86400" $daysel>$lt{'sy'}</option>
  $help{'Syllabus'}  </select>
 </nobr>  <input type="submit" name="display" value="$lt{'sd'}" />
 </form>  <h3>$header</h3>
 <form action="/adm/coursedocs" method="post" name="newnav">  <input type="submit" name="setversions" value="$lt{'sv'}" />
 $uploadtag  <table border="0">
 <input type=hidden name="importdetail"   ENDHEADERS
 value="Navigate Content=/adm/navmaps">      foreach my $key (sort(keys(%changes))) {
 <nobr>   if ($changes{$key}>$starttime) {
 <input name="newnav" type="submit" value="$lt{'navc'}" />      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
 $help{'Navigate_Content'}      my $currentversion=&Apache::lonnet::getversion($key);
 </nobr>      if ($currentversion<0) {
 </form>   $currentversion=&mt('Could not be determined.');
 <form action="/adm/coursedocs" method="post" name="newsmppg">      }
 $uploadtag      my $linkurl=&Apache::lonnet::clutter($key);
 <input type=hidden name="importdetail" value="">      $r->print(
 <nobr>        '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
 <input name="newsmppg" type="button" value="$lt{'sipa'}"        &Apache::lonnet::gettitle($linkurl).
 onClick="javascript:makesmppage();" /> $help{'Simple Page'}                        '</b></font></td></tr>'.
 </nobr>                        '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 </form>                        '<td colspan="4">'.
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">                        '<a href="'.$linkurl.'" target="cat">'.$linkurl.
 $uploadtag        '</a></td></tr>'.
 <input type=hidden name="importdetail" value="">                        '<tr><td></td>'.
 <nobr>                        '<td title="'.$lt{'md'}.'">'.
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"        &Apache::lonlocal::locallocaltime(
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}                             &Apache::lonnet::metadata($root.'.'.$extension,
 </nobr>                                                       'lastrevisiondate')
 </form>                                                          ).
 <form action="/adm/coursedocs" method="post" name="newexamupload">                        '</td>'.
 $uploadtag                        '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
 <input type=hidden name="importdetail" value="">                        '<font size="+1">'.$currentversion.'</font>'.
 <nobr>                        '</span></td>'.
 <input name="newexamupload" type="button" value="$lt{'scuf'}"                        '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.
 onClick="javascript:makeexamupload();" />                        '<font size="+1">');
 $help{'Score_Upload_Form'}  # Used in course
 </nobr>      my $usedversion=$hash{'version_'.$linkurl};
 </form>      if (($usedversion) && ($usedversion ne 'mostrecent')) {
 <form action="/adm/coursedocs" method="post" name="newbul">   $r->print($usedversion);
 $uploadtag      } else {
 <input type=hidden name="importdetail" value="">   $r->print($currentversion);
 <nobr>      }
 <input name="newbulletin" type="button" value="$lt{'bull'}"      $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
 onClick="javascript:makebulboard();" />                        '<span class="LC_nobreak">Use: ');
 $help{'Bulletin Board'}  # Set version
 </nobr>      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
 </form>        'set_version_'.$linkurl,
 <form action="/adm/coursedocs" method="post" name="newaboutme">        ('select_form_order' =>
 $uploadtag         ['',1..$currentversion,'mostrecent'],
 <input type=hidden name="importdetail"          '' => '',
 value="$plainname=/adm/$udom/$uname/aboutme">         'mostrecent' => 'most recent',
 <nobr>         map {$_,$_} (1..$currentversion))));
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      $r->print('</span></td></tr><tr><td></td>');
 $help{'My Personal Info'}      my $lastold=1;
 </nobr>      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
 </form>   my $url=$root.'.'.$prevvers.'.'.$extension;
 <form action="/adm/coursedocs" method="post" name="newaboutsomeone">   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
 $uploadtag      $starttime) {
 <input type=hidden name="importdetail" value="">      $lastold=$prevvers;
 <nobr>   }
 <input name="newaboutsomeone" type="button" value="$lt{'abou'}"       }
 onClick="javascript:makeabout();" />              #
 </nobr>              # Code to figure out how many version entries should go in
 ENDFORM              # each of the four columns
        }              my $entries_per_col = 0;
        if ($env{'form.pagepath'}) {              my $num_entries = ($currentversion-$lastold);
            $r->print(<<ENDBLOCK);              if ($num_entries % 4 == 0) {
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">                  $entries_per_col = $num_entries/4;
 $uploadtag              } else {
 <input type=hidden name="importdetail" value="">                  $entries_per_col = $num_entries/4 + 1;
 <nobr>              }
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"              my $entries_count = 0;
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}              $r->print('<td valign="top"><font size="-2">');
 </nobr>              my $cols_output = 1;
 </form>              for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
 <form action="/adm/coursedocs" method="post" name="newexamupload">   my $url=$root.'.'.$prevvers.'.'.$extension;
 $uploadtag   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
 <input type=hidden name="importdetail" value="">    '">'.&mt('Version').' '.$prevvers.'</a> ('.
 <nobr>    &Apache::lonlocal::locallocaltime(
 <input name="newexamupload" type="button" value="$lt{'scuf'}"                                  &Apache::lonnet::metadata($url,
 onClick="javascript:makeexamupload();" />                                                            'lastrevisiondate')
 $help{'Score_Upload_Form'}                                                              ).
 </nobr>    ')');
 ENDBLOCK   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
            $r->print('</form>');                      $r->print(' <a href="/adm/diff?filename='.
        }        &Apache::lonnet::clutter($root.'.'.$extension).
        $r->print('</td></tr>'."\n".        '&versionone='.$prevvers.
 '</table>');        '">'.&mt('Diffs').'</a>');
        $r->print('</td></tr>');   }
     }   $r->print('</span><br />');
 # ----------------------------------------------------- Supplemental documents                  if (++$entries_count % $entries_per_col == 0) {
     if (!$forcestandard) {                      $r->print('</font></td>');
        $r->print('<tr><td bgcolor="#BBBBBB">');                      if ($cols_output != 4) {
 # '<h2>'.&mt('Supplemental Course Documents').                          $r->print('<td valign="top"><font size="-2">');
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');                          $cols_output++;
        my $folder=$env{'form.folder'};                      }
        unless ($folder=~/^supplemental/) {                  }
    $folder='supplemental';      }
        }              while($cols_output++ < 4) {
        if ($folder =~ /^supplemental$/ &&                  $r->print('</font></td><td><font>')
    $env{'form.folderpath'} =~ /^default\&/) {              }
    $env{'form.folderpath'}='supplemental&'.      $r->print('</font></td></tr>'."\n");
        &Apache::lonnet::escape(&mt('Supplemental Course Documents'));   }
        }      }
        &editor($r,$coursenum,$coursedom,$folder,$allowed);      $r->print('</table></form>');
        if ($allowed) {      $r->print('<h1>'.&mt('Done').'.</h1>');
        my $folderseq=  
                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.      &untiehash();
                      '.sequence';  }
   
           $r->print(<<ENDSUPFORM);  sub mark_hash_old {
 <table cellspacing=4 cellpadding=4><tr>      my $retie_hash=0;
 <th bgcolor="#DDDDDD">$lt{'upls'}</th>      if ($hashtied) {
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>   $retie_hash=1;
 </tr>   &untiehash();
 <tr><td bgcolor="#DDDDDD">      }
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">      &tiehash('write');
 <input type="file" name="uploaddoc" size="40">      $hash{'old'}=1;
 <br />$lt{'comment'}:<br />      &untiehash();
 <textarea cols=50 rows=4 name='comment'>      if ($retie_hash) { &tiehash(); }
 </textarea>  }
 <br />  
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />  sub is_hash_old {
 <input type="hidden" name="cmd" value="upload_supplemental">      my $untie_hash=0;
 <nobr>      if (!$hashtied) {
 <input type="submit" value="$lt{'upld'}">   $untie_hash=1;
  $help{'Uploading_From_Harddrive'}   &tiehash();
 </nobr>      }
 </form>      my $return=$hash{'old'};
 </td>      if ($untie_hash) { &untiehash(); }
 <td bgcolor="#DDDDDD">      return $return;
 <form action="/adm/coursedocs" method="post" name="supnewfolder">  }
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />  
 <input type=hidden name="importdetail" value="">  sub changewarning {
 <nobr>      my ($r,$postexec,$message,$url)=@_;
 <input name="newfolder" type="button"      if (!&is_hash_old()) { return; }
 onClick="javascript:makenewfolder(this.form,'$folderseq');"      my $pathvar='folderpath';
 value="$lt{'newf'}" /> $help{'Adding_Folders'}      my $path=&escape($env{'form.folderpath'});
 </nobr>      if (!defined($url)) {
 </form>   if (defined($env{'form.pagepath'})) {
 <form action="/adm/coursedocs" method="post" name="supnewext">      $pathvar='pagepath';
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      $path=&escape($env{'form.pagepath'});
 <input type=hidden name="importdetail" value="">      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
 <nobr>   }
 <input name="newext" type="button"    $url='/adm/coursedocs?'.$pathvar.'='.$path;
 onClick="javascript:makenewext('supnewext');"      }
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      my $course_type = &Apache::loncommon::course_type();
 </nobr>      if (!defined($message)) {
 </form>   $message='Changes will become active for your current session after [_1], or the next time you log in.';
 <form action="/adm/coursedocs" method="post" name="supnewsyl">      }
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />      $r->print("\n\n".
 <input type=hidden name="importdetail"   '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 <nobr>  '<input type="hidden" name="orgurl" value="'.$url.
 <input name="newsyl" type="submit" value="$lt{'syll'}" />  '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.
 $help{'Syllabus'}  &mt($message,' <input type="hidden" name="'.
 </nobr>      $env{'request.role'}.'" value="1" /><input type="button" value="'.
 </form>      &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
 <form action="/adm/coursedocs" method="post" name="subnewaboutme">  $help{'Caching'}.'</span></h3></form>'."\n\n");
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />  }
 <input type=hidden name="importdetail"   
 value="$plainname=/adm/$udom/$uname/aboutme">  
 <nobr>  sub init_breadcrumbs {
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      my ($form,$text)=@_;
 $help{'My Personal Info'}      &Apache::lonhtmlcommon::clear_breadcrumbs();
 </nobr>      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
 </form>      text=>"Edit ".&Apache::loncommon::course_type(),
 </td></tr>      faq=>273,
 </table></td></tr>      bug=>'Instructor Interface',
 ENDSUPFORM                                              help => 'Docs_Adding_Course_Doc'});
        }      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
     }      text=>$text,
     if ($allowed) {      faq=>273,
  $r->print('<form name="extimport"><input type="hidden" name="title"><input type="hidden" name="url"><input type="hidden" name="useform"></form>');      bug=>'Instructor Interface'});
     }  }
     $r->print('</table>');  
   } else {  
 # -------------------------------------------------------- This is showdoc mode  
       $r->print("<h1>".&mt('Uploaded Document').' - '.  
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.  sub handler {
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".      my $r = shift;
          &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');      &Apache::loncommon::content_type($r,'text/html');
   }      $r->send_http_header;
  }      return OK if $r->header_only;
  $r->print('</body></html>');      my $type = &Apache::loncommon::course_type();
  return OK;  
 }   
   # --------------------------------------------- Initialize help topics for this
 1;      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
 __END__                 'Adding_External_Resource','Navigate_Content',
                  'Adding_Folders','Docs_Overview', 'Load_Map',
                  'Supplemental','Score_Upload_Form','Adding_Pages',
                  'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
                  'Check_Resource_Versions','Verify_Content') {
    $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
       }
       # Composite help files
       $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
       $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
       $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
       'Option_Response_Simple');
       $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
       $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
     'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
       $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
       $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
   
   # does this user have privileges to modify docs
       my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
     if ($allowed && $env{'form.verify'}) {
         &init_breadcrumbs('verify','Verify Content');
         &verifycontent($r);
     } elsif ($allowed && $env{'form.listsymbs'}) {
         &init_breadcrumbs('listsymbs','List Symbs');
         &list_symbs($r);
     } elsif ($allowed && $env{'form.docslog'}) {
         &init_breadcrumbs('docslog','Show Log');
         &docs_change_log($r);
     } elsif ($allowed && $env{'form.versions'}) {
         &init_breadcrumbs('versions','Check/Set Resource Versions');
         &checkversions($r);
     } elsif ($allowed && $env{'form.dumpcourse'}) {
         &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
         &dumpcourse($r);
     } elsif ($allowed && $env{'form.exportcourse'}) {
         &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');
         &exportcourse($r);
     } else {
   # is this a standard course?
   
       my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
       my $forcestandard = 0;
       my $forcesupplement;
       my $script='';
       my $showdoc=0;
       my $containertag;
       my $uploadtag;
   
   
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
       ['folderpath','pagepath',
        'pagesymb']);
   # No folderpath, no pagepath, see if we have something stored
       if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
           &Apache::loncommon::restore_course_settings('docs_folderpath',
                                                 {'folderpath' => 'scalar'});
       }
       if (!$env{'form.folderpath'}) {
           &Apache::loncommon::restore_course_settings('docs_folderpath',
                                                 {'pagepath' => 'scalar'});
       }
       if ($env{'form.pagepath'}) {
          $env{'form.folderpath'}='';
       }
       if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
           $env{'form.folderpath'} = 'supplemental&'.
                                     &escape(&mt('Supplemental '.$type.' Documents')).'&'.
                                     $env{'form.folderpath'};
       }
       &Apache::loncommon::store_course_settings('docs_folderpath',
                                                   {'pagepath' => 'scalar',
                                                    'folderpath' => 'scalar'});
       if ($env{'form.folderpath'}) {
    my (@folderpath)=split('&',$env{'form.folderpath'});
    $env{'form.foldername'}=&unescape(pop(@folderpath));
    $env{'form.folder'}=pop(@folderpath);
       }
       if ($env{'form.pagepath'}) {
           my (@pagepath)=split('&',$env{'form.pagepath'});
           $env{'form.pagename'}=&unescape(pop(@pagepath));
           $env{'form.folder'}=pop(@pagepath);
           $containertag = '<input type="hidden" name="pagepath" value="" />'.
       '<input type="hidden" name="pagesymb" value="" />';
           $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
       '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';
       }
       if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
          $showdoc='/'.$1;
       }
       unless ($showdoc) { # got called from remote
          if (($env{'form.folder'}=~/^(?:group|default)_/) ||
             ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
              $forcestandard = 1;
          }
          $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
   
          if ($allowed) {
            &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
            $script=&Apache::lonratedt::editscript('simple');
          }
       } else { # got called in sequence from course
          $allowed=0;
       }
   
   # get course data
       my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
   
   # get personal data
       my $uname=$env{'user.name'};
       my $udom=$env{'user.domain'};
       my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
   
   # graphics settings
   
       $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
   
       if ($allowed) {
    $script .= &editing_js($udom,$uname);
       }
   # -------------------------------------------------------------------- Body tag
       $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
       my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];
       $r->print(&Apache::loncommon::start_page("$type Documents", $script,
       {'force_register' => $showdoc,
                                        'bread_crumbs' => $brcrum}).
         &Apache::loncommon::help_open_menu('','',273,'RAT'));
    
     my %allfiles = ();
     my %codebase = ();
     my ($upload_result,$upload_output);
     if ($allowed) {
         if (($env{'form.uploaddoc.filename'}) &&
     ($env{'form.cmd'}=~/^upload_(\w+)/)) {
   # Process file upload - phase one - upload and parse primary file.  
     undef($hadchanges);
             $upload_result = &process_file_upload(\$upload_output,$coursenum,
    $coursedom,\%allfiles,
    \%codebase,$1);
     if ($hadchanges) {
         &mark_hash_old();
     }
             if ($upload_result eq 'phasetwo') {
                 $r->print($upload_output);
             }
         } elsif ($env{'form.phasetwo'}) {
             my %newname = ();
             my %origname = ();
             my %attribs = ();
             my $updateflag = 0;
             my $residx = $env{'form.newidx'};
             my $primary_url = &unescape($env{'form.primaryurl'});
   # Process file upload - phase two - gather secondary files.
             for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
                 if ($env{'form.embedded_item_'.$i.'.filename'}) {
                     my $javacodebase;
                     $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
                     $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
                     if (exists($env{'form.embedded_codebase_'.$i})) {
                         $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
                         $origname{$i} =~ s#^\Q$javacodebase\E/##;
                     }
                     my @attributes = ();
                     if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
                         @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
                     } else {
                         @attributes = ($env{'form.embedded_attrib_'.$i});
                     }
                     foreach my $attr (@attributes) {
                         push(@{$attribs{$i}},&unescape($attr));
                     }
                     if ($javacodebase) {
                         $codebase{$i} = $javacodebase;
                         $codebase{$i} =~ s#/$##;
                         $updateflag = 1;
                     }
                 }
                 unless ($newname{$i} eq $origname{$i}) {
                     $updateflag = 1;
                 }
             }
   # Process file upload - phase three - modify primary file
             if ($updateflag) {
                 my ($content,$rtncode);
                 my $updateflag = 0;
                 my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
                 if ($getstatus eq 'ok') {
                     foreach my $item (keys(%newname)) {
                         if ($newname{$item} ne $origname{$item}) {
                             my $attrib_regexp = '';
                             if (@{$attribs{$item}} > 1) {
                                 $attrib_regexp = join('|',@{$attribs{$item}});
                             } else {
                                 $attrib_regexp = $attribs{$item}[0];
                             }
                             if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
                             }
                             $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;
                         }
                         if (exists($codebase{$item})) {
                             $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
                         }
                     }
   # Save edited file.
                     my $saveresult;
                     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                     my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
                 } else {
                     &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
                 }
             }
         }
     }
   
     unless ($showdoc ||  $upload_result eq 'phasetwo') {
   # -----------------------------------------------------------------------------
          my %lt=&Apache::lonlocal::texthash(
                   'uplm' => 'Upload a new main '.lc($type).' document',
                   'upls' => 'Upload a new supplemental '.lc($type).' document',
                   'impp' => 'Import a document',
                   'pubd' => 'Published Documents',
    'copm' => 'All documents out of a published map into this folder',
                   'upld' => 'Upload Document',
                   'srch' => 'Search',
                   'impo' => 'Import',
    'book' => 'Import Bookmarks',
                   'selm' => 'Select Map',
                   'load' => 'Load Map',
                   'reco' => 'Recover Deleted Resources',
                   'newf' => 'New Folder',
                   'newp' => 'New Composite Page',
                   'extr' => 'External Resource',
                   'syll' => 'Syllabus',
                   'navc' => 'Navigate Contents',
                   'sipa' => 'Simple Page',
                   'sipr' => 'Simple Problem',
                   'drbx' => 'Drop Box',
                   'scuf' => 'Score Upload Form',
                   'bull' => 'Bulletin Board',
                   'mypi' => 'My Personal Info',
                   'grpo' => 'Group Files',
                   'rost' => 'Course Roster',
    'abou' => 'About User',
                   'imsf' => 'Import IMS package',
                   'file' =>  'File',
                   'title' => 'Title',
                   'comment' => 'Comment',
                   'parse' => 'Upload embedded images/multimedia files if HTML file!',
    'nd' => 'New Document',
    'pm' => 'Published Map',
    'sd' => 'Special Document',
    'mo' => 'More Options',
    'hao' => 'Hide all Options'
     );
   # -----------------------------------------------------------------------------
    my $fileupload=(<<FIUP);
    $lt{'file'}:<br />
    <input type="file" name="uploaddoc" size="40" />
   FIUP
   
    my $checkbox=(<<CHBO);
    <!-- <label>$lt{'parse'}?
    <input type="checkbox" name="parserflag" />
    </label> -->
    <label>
    <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
    </label>
   CHBO
   
    my $fileuploadform=(<<FUFORM);
    <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
    $fileupload
    <br />
    $lt{'title'}:<br />
    <input type="text" size="50" name="comment" />
    $uploadtag
    <input type="hidden" name="cmd" value="upload_default" />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br />
    <br />
    <span class="LC_nobreak">
    <input type="submit" value="$lt{'upld'}" />
    $help{'Uploading_From_Harddrive'}
    </span>
    </form>
   FUFORM
   
    my $simpleeditdefaultform=(<<SEDFFORM);
    <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
    $lt{'pubd'}<br />
    $uploadtag
    <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />
    <br />
    <span class="LC_nobreak">
    <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />
    $help{'Importing_LON-CAPA_Resource'}
    </span>
    <br />
    <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
    <hr />
    <p>
    $lt{'copm'}<br />
    <input type="text" size="40" name="importmap" /><br />
    <span class="LC_nobreak"><input type="button"
    onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
    value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
    $help{'Load_Map'}</span>
    </p>
    </form>
   SEDFFORM
   
    my $extresourcesform=(<<ERFORM);
    <form action="/adm/coursedocs" method="post" name="newext">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newext" type="button" onClick="javascript:makenewext('newext');"
    value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
    </span>
    </form>
   ERFORM
   
       if ($allowed) {
    &update_paste_buffer($coursenum,$coursedom);
          my %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.178  
changed lines
  Added in v.1.328


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