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

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


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