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

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

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


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