Diff for /loncom/interface/londocs.pm between versions 1.327 and 1.411.2.7

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


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