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

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

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


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