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

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


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