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

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


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