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

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


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