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

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

Removed from v.1.328  
changed lines
  Added in v.1.414


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