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

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


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