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

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

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


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