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

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


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