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

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


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