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

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


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