Diff for /loncom/interface/londocs.pm between versions 1.326 and 1.394

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


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