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

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


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