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

version 1.326, 2009/01/28 11:51:22 version 1.486, 2012/05/15 01:23:04
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
   package Apache::londocs;
   
 package Apache::londocs;  use strict;
   use Apache::Constants qw(:common :http);
 use strict;  use Apache::imsexport;
 use Apache::Constants qw(:common :http);  use Apache::lonnet;
 use Apache::imsexport;  use Apache::loncommon;
 use Apache::lonnet;  use Apache::lonhtmlcommon;
 use Apache::loncommon;  use LONCAPA::map();
 use LONCAPA::map();  use Apache::lonratedt();
 use Apache::lonratedt();  use Apache::lonxml;
 use Apache::lonxml;  use Apache::lonclonecourse;
 use Apache::lonclonecourse;  use Apache::lonnavmaps;
 use Apache::lonnavmaps;  use Apache::lonnavdisplay();
 use HTML::Entities;  use HTML::Entities;
 use GDBM_File;  use GDBM_File;
 use Apache::lonlocal;  use Apache::lonlocal;
 use Cwd;  use Cwd;
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
   
 my $iconpath;  my $iconpath;
   
 my %hash;  my %hash;
   
 my $hashtied;  my $hashtied;
 my %alreadyseen=();  my %alreadyseen=();
   
 my $hadchanges;  my $hadchanges;
   
   
 my %help=();  my %help=();
   
   
 sub mapread {  sub mapread {
     my ($coursenum,$coursedom,$map)=@_;      my ($coursenum,$coursedom,$map)=@_;
     return      return
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
      $map);       $map);
 }  }
   
 sub storemap {  sub storemap {
     my ($coursenum,$coursedom,$map)=@_;      my ($coursenum,$coursedom,$map)=@_;
     my ($outtext,$errtext)=      my ($outtext,$errtext)=
       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
       $map,1);        $map,1);
     if ($errtext) { return ($errtext,2); }      if ($errtext) { return ($errtext,2); }
      
     $hadchanges=1;      $hadchanges=1;
     return ($errtext,0);      return ($errtext,0);
 }  }
   
   
   
 sub authorhosts {  sub authorhosts {
     my %outhash=();      my %outhash=();
     my $home=0;      my $home=0;
     my $other=0;      my $other=0;
     foreach my $key (keys(%env)) {      foreach my $key (keys(%env)) {
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     my $role=$1;      my $role=$1;
     my $realm=$2;      my $realm=$2;
     my ($start,$end)=split(/\./,$env{$key});      my ($start,$end)=split(/\./,$env{$key});
     if (($start) && ($start>time)) { next; }      if (($start) && ($start>time)) { next; }
     if (($end) && (time>$end)) { next; }      if (($end) && (time>$end)) { next; }
     my ($ca,$cd);      my ($ca,$cd);
     if ($1 eq 'au') {      if ($1 eq 'au') {
  $ca=$env{'user.name'};   $ca=$env{'user.name'};
  $cd=$env{'user.domain'};   $cd=$env{'user.domain'};
     } else {      } else {
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
     }      }
     my $allowed=0;      my $allowed=0;
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
     my @ids=&Apache::lonnet::current_machine_ids();      my @ids=&Apache::lonnet::current_machine_ids();
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      foreach my $id (@ids) {
     if ($allowed) {                  if ($id eq $myhome) {
  $home++;                      $allowed=1;
  $outhash{'home_'.$ca.'@'.$cd}=1;                      last;
     } else {                  }
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;              }
  $other++;      if ($allowed) {
     }   $home++;
  }   $outhash{'home_'.$ca.':'.$cd}=1;
     }      } else {
     return ($home,$other,%outhash);   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
 }   $other++;
       }
    }
 sub dumpbutton {      }
     my ($home,$other,%outhash)=&authorhosts();      return ($home,$other,%outhash);
     my $type = &Apache::loncommon::course_type();  }
     if ($home+$other==0) { return ''; }  
     if ($home) {  
  return '<div>'.  sub clean {
     '<input type="submit" name="dumpcourse" value="'.      my ($title)=@_;
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs').      return $title;
     '</div>';  }
     } else {  
  return '<div>'.  
      &mt('Dump '.$type.  
  ' DOCS to Construction Space: available on other servers').  sub dumpcourse {
  '</div>';      my ($r) = @_;
     }      my $crstype = &Apache::loncommon::course_type();
 }      $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
                 &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
 sub clean {      $r->print(&startContentScreen('tools'));
     my ($title)=@_;      my ($home,$other,%outhash)=&authorhosts();
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;      unless ($home) {
     return $title;          $r->print(&endContentScreen());
 }          return '';
       }
       my $origcrsid=$env{'request.course.id'};
       my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
 sub dumpcourse {      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     my ($r) = @_;  # Do the dumping
     my $type = &Apache::loncommon::course_type();   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').              $r->print(&endContentScreen());
       '<form name="dumpdoc" method="post">');              return '';
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));          }
     my ($home,$other,%outhash)=&authorhosts();   my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
     unless ($home) { return ''; }   $r->print('<h3>'.&mt('Copying Files').'</h3>');
     my $origcrsid=$env{'request.course.id'};   my $title=$env{'form.authorfolder'};
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);   $title=&clean($title);
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {   my %replacehash=();
 # Do the dumping   foreach my $key (keys(%env)) {
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }      if ($key=~/^form\.namefor\_(.+)/) {
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});   $replacehash{$1}=$env{$key};
  $r->print('<h3>'.&mt('Copying Files').'</h3>');      }
  my $title=$env{'form.authorfolder'};   }
  $title=&clean($title);   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  my %replacehash=();   $crs=~s/\_/\//g;
  foreach my $key (keys(%env)) {   foreach my $item (keys(%replacehash)) {
     if ($key=~/^form\.namefor\_(.+)/) {      my $newfilename=$title.'/'.$replacehash{$item};
  $replacehash{$1}=$env{$key};      $newfilename=~s/\.(\w+)$//;
     }      my $ext=$1;
  }      $newfilename=&clean($newfilename);
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';      $newfilename.='.'.$ext;
  $crs=~s/\_/\//g;      my @dirs=split(/\//,$newfilename);
  foreach my $item (keys(%replacehash)) {      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
     my $newfilename=$title.'/'.$replacehash{$item};      my $makepath=$path;
     $newfilename=~s/\.(\w+)$//;      my $fail=0;
     my $ext=$1;      for (my $i=0;$i<$#dirs;$i++) {
     $newfilename=&clean($newfilename);   $makepath.='/'.$dirs[$i];
     $newfilename.='.'.$ext;   unless (-e $makepath) {
     my @dirs=split(/\//,$newfilename);      unless(mkdir($makepath,0777)) { $fail=1; }
     my $path='/home/'.$ca.'/public_html';   }
     my $makepath=$path;      }
     my $fail=0;      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
     for (my $i=0;$i<$#dirs;$i++) {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
  $makepath.='/'.$dirs[$i];   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  unless (-e $makepath) {      print $fh &Apache::lonclonecourse::rewritefile(
     unless(mkdir($makepath,0777)) { $fail=1; }           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  }       (%replacehash,$crs => '')
     }      );
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');   } else {
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {      print $fh
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
     print $fh &Apache::lonclonecourse::rewritefile(         }
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),   $fh->close();
      (%replacehash,$crs => '')      } else {
     );   $fail=1;
  } else {      }
     print $fh      if ($fail) {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
        }      } else {
  $fh->close();   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     } else {      }
  $fail=1;   }
     }      } else {
     if ($fail) {          $r->print(&mt('Searching ...').'<br />');
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');          $r->rflush();
     } else {  # Input form
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
     }   unless ($home==1) {
  }      $r->print('<div class="LC_left_float">'.
     } else {        '<fieldset><legend>'.
 # Input form                        &mt('Select the Authoring Space').
  unless ($home==1) {                        '</legend><select name="authorspace">');
     $r->print(   }
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');   foreach my $key (sort(keys(%outhash))) {
  }      if ($key=~/^home_(.+)$/) {
  foreach my $key (sort(keys(%outhash))) {   if ($home==1) {
     if ($key=~/^home_(.+)$/) {      $r->print(
  if ($home==1) {    '<input type="hidden" name="authorspace" value="'.$1.'" />');
     $r->print(   } else {
   '<input type="hidden" name="authorspace" value="'.$1.'" />');      $r->print('<option value="'.$1.'">'.$1.' - '.
  } else {        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
     $r->print('<option value="'.$1.'">'.$1.' - '.   }
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');      }
  }   }
     }   unless ($home==1) {
  }      $r->print('</select></fieldset></div>'."\n");
  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('<div class="LC_left_float">'.
  $title=&clean($title);                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'                    '<input type="text" size="50" name="authorfolder" value="'.
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');                    $title.'" />'.
  &tiehash();                    '</fieldset></div><br clear="all" />'."\n");
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'   &tiehash();
                  .&Apache::loncommon::start_data_table()   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
                  .&Apache::loncommon::start_data_table_header_row()                   .&Apache::loncommon::start_data_table()
                  .'<th>'.&mt('Internal Filename').'</th>'                   .&Apache::loncommon::start_data_table_header_row()
                  .'<th>'.&mt('Title').'</th>'                   .'<th>'.&mt('Internal Filename').'</th>'
                  .'<th>'.&mt('Save as ...').'</th>'                   .'<th>'.&mt('Title').'</th>'
                  .&Apache::loncommon::end_data_table_header_row());                   .'<th>'.&mt('Save as ...').'</th>'
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {                   .&Apache::loncommon::end_data_table_header_row());
     $r->print(&Apache::loncommon::start_data_table_row()   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
                      .'<td>'.$file.'</td>');      $r->print(&Apache::loncommon::start_data_table_row()
     my ($ext)=($file=~/\.(\w+)$/);                       .'<td>'.$file.'</td>');
     my $title=$hash{'title_'.$hash{      my ($ext)=($file=~/\.(\w+)$/);
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};      my $title=$hash{'title_'.$hash{
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     if (!$title) {      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
  $title=$file;      if (!$title) {
     } else {   $title=$file;
  $title=~s|/|_|g;      } else {
     }   $title=~s|/|_|g;
     $title=~s/\.(\w+)$//;      }
     $title=&clean($title);      $title=~s/\.(\w+)$//;
     $title.='.'.$ext;      $title=&clean($title);
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"      $title.='.'.$ext;
                      .&Apache::loncommon::end_data_table_row());      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
  }                       .&Apache::loncommon::end_data_table_row());
  $r->print(&Apache::loncommon::end_data_table());   }
  &untiehash();   $r->print(&Apache::loncommon::end_data_table());
  $r->print(   &untiehash();
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');   $r->print(
     }    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
 }      }
       $r->print(&endContentScreen());
   }
   
 sub exportbutton {  sub group_import {
     my $type = &Apache::loncommon::course_type();      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
     return '<div>'.  
             '<input type="submit" name="exportcourse" value="'.      while (@files) {
             &mt('Export '.$type.' to IMS').'" />'.   my ($name, $url, $residx) = @{ shift(@files) };
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs').'</div>';          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
 }       && ($caller eq 'londocs')
        && (!&Apache::lonnet::stat_file($url))) {
   
               my $errtext = '';
 sub exportcourse {              my $fatal = 0;
     my $r=shift;              my $newmapstr = '<map>'."\n".
     my $type = &Apache::loncommon::course_type();                              '<resource id="1" src="" type="start"></resource>'."\n".
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',                              '<link from="1" to="2" index="1"></link>'."\n".
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});                              '<resource id="2" src="" type="finish"></resource>'."\n".
     my $numdisc = keys(%discussiontime);                              '</map>';
     my $navmap = Apache::lonnavmaps::navmap->new();              $env{'form.output'}=$newmapstr;
     if (!defined($navmap)) {              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').                                                  'output',$1.$2);
                   '<h2>IMS Export Failed</h2>'.              if ($result != m|^/uploaded/|) {
                   '<div class="LC_error">'.                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
                   &mt('Unable to retrieve information about course contents').                  $fatal = 2;
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');              }
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});              if ($fatal) {
         return;                  return ($errtext,$fatal);
     }              }
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);          }
     my $curRes;   if ($url) {
     my $outcome;      if (!$residx
    || defined($LONCAPA::map::zombies[$residx])) {
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},   $residx = &LONCAPA::map::getresidx($url,$residx);
                                             ['finishexport']);   push(@LONCAPA::map::order, $residx);
     if ($env{'form.finishexport'}) {      }
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      my $ext = 'false';
                                             ['archive','discussion']);      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
       $url  = &LONCAPA::map::qtunescape($url);
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');      $name = &LONCAPA::map::qtunescape($name);
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');      $LONCAPA::map::resources[$residx] =
         if (@exportitems == 0 && @discussions == 0) {   join(':', ($name, $url, $ext, 'normal', 'res'));
             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';   }
         } else {      }
             my $now = time;      return &storemap($coursenum, $coursedom, $folder.'.'.$container);
             my %symbs;  }
             my $manifestok = 0;  
             my $imsresources;  sub breadcrumbs {
             my $tempexport;      my ($allowed,$crstype)=@_;
             my $copyresult;      &Apache::lonhtmlcommon::clear_breadcrumbs();
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);      my (@folders);
             if ($manifestok) {      if ($env{'form.pagepath'}) {
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);          @folders = split('&',$env{'form.pagepath'});
                 close($ims_manifest);      } else {
           @folders=split('&',$env{'form.folderpath'});
 #Create zip file in prtspool      }
                 my $imszipfile = '/prtspool/'.      my $folderpath;
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.      my $cpinfo='';
                    time.'_'.rand(1000000000).'.zip';      my $plain='';
                 my $cwd = &Cwd::getcwd();      my $randompick=-1;
                 my $imszip = '/home/httpd/'.$imszipfile;      my $isencrypted=0;
                 chdir $tempexport;      my $ishidden=0;
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");      my $is_random_order=0;
                 close(OUTPUT);      while (@folders) {
                 chdir $cwd;   my $folder=shift(@folders);
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      my $foldername=shift(@folders);
                 if ($copyresult) {   if ($folderpath) {$folderpath.='&';}
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);   $folderpath.=$folder.'&'.$foldername;
                 }          my $url;
             } else {          if ($allowed) {
                 $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 />';              $url = '/adm/coursedocs?folderpath=';
             }          } else {
         }              $url = '/adm/supplemental?folderpath=';
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));          }
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));   $url .= &escape($folderpath);
         $r->print($outcome);   my $name=&unescape($foldername);
         $r->print(&Apache::loncommon::end_page());  # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
     } else {    $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
         my $display;   if ($1 ne '') {
         $display = '<form name="exportdoc" method="post">'."\n";             $randompick=$1;
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');          } else {
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.             $randompick=-1;
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.          }
                     '<input type="button" value="check all" '.          if ($2) { $ishidden=1; }
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.          if ($3) { $isencrypted=1; }
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.   if ($4 ne '') { $is_random_order = 1; }
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.          if ($folder eq 'supplemental') {
                     '<td>&nbsp;</td><td>&nbsp;</td>'.              $name = &mt('Supplemental '.$crstype.' Content');
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.          }
                     '</b></legend><input type="button" value="check all"'.   &Apache::lonhtmlcommon::add_breadcrumb(
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.        {'href'=>$url.$cpinfo,
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.         'title'=>$name,
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.         'text'=>$name,
                     '</tr></table>';         'no_mt'=>1,
         my $curRes;         });
         my $depth = 0;   $plain.=$name.' &gt; ';
         my $count = 0;      }
         my $boards = 0;      $plain=~s/\&gt\;\s*$//;
         my $startcount = 5;      return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
         my %parent = ();         undef, undef, 1 ),$randompick,$ishidden,
         my %children = ();                                                 $isencrypted,$plain,$is_random_order);
         my $lastcontainer = $startcount;  }
         my @bgcolors = ('#F6F6F6','#FFFFFF');  
         $display .= '<table cellspacing="0"><tr>'.  sub log_docs {
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";      return &Apache::lonnet::instructor_log('docslog',@_);
         if ($numdisc > 0) {  }
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";  
         }  {
         $display.='&nbsp;</td></tr>';      my @oldresources=();
         while ($curRes = $it->next()) {      my @oldorder=();
             if (ref($curRes)) {      my $parmidx;
                 $count ++;      my %parmaction=();
             }      my %parmvalue=();
             if ($curRes == $it->BEGIN_MAP()) {      my $changedflag;
                 $depth++;  
                 $parent{$depth} = $lastcontainer;      sub snapshotbefore {
             }          @oldresources=@LONCAPA::map::resources;
             if ($curRes == $it->END_MAP()) {          @oldorder=@LONCAPA::map::order;
                 $depth--;          $parmidx=undef;
                 $lastcontainer = $parent{$depth};          %parmaction=();
             }          %parmvalue=();
             if (ref($curRes)) {          $changedflag=0;
                 my $symb = $curRes->symb();      }
                 my $ressymb = $symb;  
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {      sub remember_parms {
                     unless ($ressymb =~ m|adm/wrapper/adm|) {          my ($idx,$parameter,$action,$value)=@_;
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';          $parmidx=$idx;
                     }          $parmaction{$parameter}=$action;
                 }          $parmvalue{$parameter}=$value;
                 my $color = $count%2;          $changedflag=1;
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".      }
                     '<input type="checkbox" name="archive" value="'.$count.'" ';  
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {      sub log_differences {
                     my $checkitem = $count + $boards + $startcount;          my ($plain)=@_;
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';          my %storehash=('folder' => $plain,
                 }                         'currentfolder' => $env{'form.folder'});
                 $display .= ' />'."\n";          if ($parmidx) {
                 for (my $i=0; $i<$depth; $i++) {             $storehash{'parameter_res'}=$oldresources[$parmidx];
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";             foreach my $parm (keys(%parmaction)) {
                 }                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
                 if ($curRes->is_sequence()) {                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";             }
                     $lastcontainer = $count + $startcount + $boards;          }
                 } elsif ($curRes->is_page()) {          my $maxidx=$#oldresources;
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";          if ($#LONCAPA::map::resources>$#oldresources) {
                     $lastcontainer = $count + $startcount + $boards;             $maxidx=$#LONCAPA::map::resources;
                 }          }
                 my $currelem = $count+$boards+$startcount;          for (my $idx=0; $idx<=$maxidx; $idx++) {
                 $children{$parent{$depth}} .= $currelem.':';             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
                 $display .= '&nbsp;'.$curRes->title().'</td>';                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
                 if ($discussiontime{$ressymb} > 0) {                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
                     $boards ++;                $changedflag=1;
                     $currelem = $count+$boards+$startcount;             }
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
                 } else {                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
                 }                $changedflag=1;
             }             }
         }          }
         my $scripttag = qq|   $storehash{'maxidx'}=$maxidx;
 <script>          if ($changedflag) { &log_docs(\%storehash); }
       }
 function checkAll(field) {  }
     if (field.length > 0) {  
         for (i = 0; i < field.length; i++) {  sub docs_change_log {
             field[i].checked = true ;      my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
         }      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
     } else {      my $js = '<script type="text/javascript">'."\n".
         field.checked = true               '// <![CDATA['."\n".
     }               &Apache::loncommon::display_filter_js('docslog')."\n".
 }               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
                                                                                               &history_tab_js()."\n".
 function uncheckAll(field) {               &Apache::lonratedt::editscript('simple')."\n".
     if (field.length > 0) {               '// ]]>'."\n".
         for (i = 0; i < field.length; i++) {               '</script>'."\n";
             field[i].checked = false ;      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
         }      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
     } else {      $r->print(&startContentScreen('docs'));
         field.checked = false ;      my %orderhash;
     }      my $container='sequence';
 }      my $pathitem;
       if ($env{'form.pagepath'}) {
 function propagateCheck(item) {          $container='page';
     if (document.exportdoc.elements[item].checked == true) {          $pathitem = '<input type="hidden" name="pagepath" value="'.
         containerCheck(item)                      &HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />';
     }      } else {
 }          my $folderpath=$env{'form.folderpath'};
           if ($folderpath eq '') {
 function containerCheck(item) {              $folderpath = 'default&'.&escape(&mt('Main '.$crstype.' Documents'));
     document.exportdoc.elements[item].checked = true          }
     var numitems = $count + $boards + $startcount          $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
     var parents = new Array(numitems)      }
     for (var i=$startcount; i<numitems; i++) {      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
         parents[i] = new Array      my $jumpto = $readfile;
     }      $jumpto =~ s{^/}{};
         |;      my $tid = 1;
       my ($breadcrumbtrail) = &breadcrumbs($allowed,$crstype);
         foreach my $container (sort { $a <=> $b } (keys(%children))) {      $r->print($breadcrumbtrail.
             my @contents = split(/:/,$children{$container});                &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
             for (my $i=0; $i<@contents; $i ++) {                $readfile));
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";      my %docslog=&Apache::lonnet::dump('nohist_docslog',
             }                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
         }                                        $env{'course.'.$env{'request.course.id'}.'.num'});
   
         $scripttag .= qq|      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
     if (parents[item].length > 0) {  
         for (var j=0; j<parents[item].length; j++) {      my %saveable_parameters = ('show' => 'scalar',);
             containerCheck(parents[item][j])      &Apache::loncommon::store_course_settings('docs_log',
         }                                                \%saveable_parameters);
      }        &Apache::loncommon::restore_course_settings('docs_log',
 }                                                  \%saveable_parameters);
       if (!$env{'form.show'}) { $env{'form.show'}=10; }
 </script>  # FIXME: internationalization seems wrong here
         |;      my %lt=('hiddenresource' => 'Resources hidden',
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',      'encrypturl'     => 'URL hidden',
  $scripttag));      'randompick'     => 'Randomly pick',
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));      'randomorder'    => 'Randomly ordered',
  $r->print($display.'</table>'.      'set'            => 'set to',
                   '<p><input type="hidden" name="finishexport" value="1">'.      'del'            => 'deleted');
                   '<input type="submit" name="exportcourse" value="'.      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
                   &mt('Export '.$type.' DOCS').'" /></p></form>');                   $pathitem."\n".
     }                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
 }                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
       $r->print('<div class="LC_left_float">'.
 sub create_ims_store {                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
     my ($now,$manifestok,$outcome,$tempexport) = @_;                &makedocslogform($filter,1).
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';                '</fieldset></div><br clear="all" />');
     my $ims_manifest;      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     if (!-e $$tempexport) {                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
         mkdir($$tempexport,0700);                &mt('After').'</th>'.
     }                &Apache::loncommon::end_data_table_header_row());
     $$tempexport .= '/'.$now;      my $shown=0;
     if (!-e $$tempexport) {      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
         mkdir($$tempexport,0700);   if ($env{'form.displayfilter'} eq 'currentfolder') {
     }      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};   }
     if (!-e $$tempexport) {          my @changes=keys(%{$docslog{$id}{'logentry'}});
         mkdir($$tempexport,0700);          if ($env{'form.displayfilter'} eq 'containing') {
     }      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
     if (!-e "$$tempexport/resources") {   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
         mkdir("$$tempexport/resources",0700);      foreach my $key (@changes) {
     }   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
 # open manifest file      }
     my $manifest = '/imsmanifest.xml';      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
     my $manifestfilename = $$tempexport.$manifest;   }
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {          my $count = 0;
         $$manifestok=1;          my $time =
         print $ims_manifest              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".          my $plainname =
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.                                            $docslog{$id}{'exe_udom'});
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.          my $about_me_link =
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.              &Apache::loncommon::aboutmewrapper($plainname,
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.                                                 $docslog{$id}{'exe_uname'},
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".                                                 $docslog{$id}{'exe_udom'});
 '  <metadata>          my $send_msg_link='';
     <schema></schema>          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
     <imsmd:lom>               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
       <imsmd:general>              $send_msg_link ='<br />'.
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>                  &Apache::loncommon::messagewrapper(&mt('Send message'),
         <imsmd:title>                                                     $docslog{$id}{'exe_uname'},
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>                                                     $docslog{$id}{'exe_udom'});
         </imsmd:title>          }
       </imsmd:general>          $r->print(&Apache::loncommon::start_data_table_row());
     </imsmd:lom>          $r->print('<td>'.$time.'</td>
   </metadata>'."\n".                         <td>'.$about_me_link.
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
 ' structure="hierarchical">'."\n".                    $send_msg_link.'</td><td>'.
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
     } else {  # Before
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
 ;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     }      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
     return $ims_manifest;      if ($oldname ne $newname) {
 }   $r->print(&LONCAPA::map::qtescape($oldname));
       }
 sub build_package {   }
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;   $r->print('<ul>');
 # first iterator to look for dependencies   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
     my $curRes;   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
     my $count = 0;      }
     my $depth = 0;   }
     my $lastcontainer = 0;   $r->print('</ul>');
     my %parent = ();  # After
     my @dependencies = ();          $r->print('</td><td>');
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};  
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     while ($curRes = $it->next()) {      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
         if (ref($curRes)) {      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
             $count ++;      if ($oldname ne '' && $oldname ne $newname) {
         }   $r->print(&LONCAPA::map::qtescape($newname));
         if ($curRes == $it->BEGIN_MAP()) {      }
             $depth++;   }
             $parent{$depth} = $lastcontainer;   $r->print('<ul>');
         }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
         if ($curRes == $it->END_MAP()) {              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
             $depth--;   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
             $lastcontainer = $parent{$depth};      }
         }   }
         if (ref($curRes)) {   $r->print('</ul>');
             if ($curRes->is_sequence() || $curRes->is_page()) {   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                 $lastcontainer = $count;      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
             }      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
             if (grep(/^$count$/,@$exportitems)) {   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);  # FIXME: internationalization seems wrong here
             }      $r->print('<li>'.
         }        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
     }    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
 # second iterator to build manifest and store resources        .'</li>');
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);   }
     $depth = 0;      }
     my $prevdepth;      $r->print('</ul>');
     $count = 0;   }
     my $imsresources;  # End
     my $pkgdepth;          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
     while ($curRes = $it->next()) {          $shown++;
         if ($curRes == $it->BEGIN_MAP()) {          if (!($env{'form.show'} eq &mt('all')
             $prevdepth = $depth;                || $shown<=$env{'form.show'})) { last; }
             $depth++;      }
         }      $r->print(&Apache::loncommon::end_data_table()."\n".
         if ($curRes == $it->END_MAP()) {                &makesimpleeditform($pathitem)."\n".
             $prevdepth = $depth;                '</div></div>');
             $depth--;      $r->print(&endContentScreen());
         }  }
   
         if (ref($curRes)) {  sub update_paste_buffer {
             $count ++;      my ($coursenum,$coursedom) = @_;
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {  
                 my $symb = $curRes->symb();      return if (!defined($env{'form.markcopy'}));
                 my $isvisible = 'true';      return if (!defined($env{'form.copyfolder'}));
                 my $resourceref;      return if ($env{'form.markcopy'} < 0);
                 if ($curRes->randomout()) {  
                     $isvisible = 'false';      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
                 }      $env{'form.copyfolder'});
                 unless ($curRes->is_sequence()) {  
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';      return if ($fatal);
                 }  
                 my $step = $prevdepth - $depth;  # Mark for copying
                 if (($step >= 0) && ($count > 1)) {      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
                     while ($step >= 0) {      if (&is_supplemental_title($title)) {
                         print $ims_manifest "\n".'  </item>'."\n";          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
                         $step --;   ($title) = &parse_supplemental_title($title);
                     }      } elsif ($env{'docs.markedcopy_supplemental'}) {
                 }          &Apache::lonnet::delenv('docs.markedcopy_supplemental');
                 $prevdepth = $depth;      }
       $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
                 my $itementry =  
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.      'docs.markedcopy_url'   => $url});
               '<title>'.$curRes->title().'</title>';      delete($env{'form.markcopy'});
                 print $ims_manifest "\n".$itementry;  }
   
                 unless ($curRes->is_sequence()) {  sub print_paste_buffer {
                     my $content_file;      my ($r,$container) = @_;
                     my @hrefs = ();      return if (!defined($env{'docs.markedcopy_url'}));
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);  
                     if ($content_file) {      $r->print('<fieldset>'
                         $imsresources .= "\n".               .'<legend>'.&mt('Clipboard').'</legend>'
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.               .'<form name="pasteform" action="/adm/coursedocs" method="post">'
                      '" type="webcontent" href="'.$content_file.'">'."\n".               .'<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> '
                      '       <file href="'.$content_file.'" />'."\n";      );
                         foreach my $item (@hrefs) {  
                             $imsresources .=      my $type;
                      '        <file href="'.$item.'" />'."\n";      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
                         }   $type = &mt('External Resource');
                         if (grep(/^$count$/,@$discussions)) {   $r->print($type.': '.
                             my $ressymb = $symb;    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
                             my $mode;    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {      }  else {
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {   my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';   my $icon = &Apache::loncommon::icon($extension);
                                 }   if ($extension eq 'sequence' &&
                                 $mode = 'board';      $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
                             }      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
                             my %extras = (      $icon .= '/navmap.folder.closed.gif';
                                           caller => 'imsexport',   }
                                           tempexport => $tempexport.'/resources',   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
                                           count => $count   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
                                          );      }
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);      if ($container eq 'page') {
                         }   $r->print('
                         $imsresources .= '    </resource>'."\n";   <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
                     }   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
                 }  ');
                 $pkgdepth = $depth;      } else {
             }   $r->print('
         }          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
     }  ');
     while ($pkgdepth > 0) {      }
         print $ims_manifest "    </item>\n";      $r->print('</form></fieldset>');
         $pkgdepth --;  }
     }  
     my $resource_text = qq|  sub do_paste_from_buffer {
     </organization>      my ($coursenum,$coursedom,$folder) = @_;
   </organizations>  
   <resources>      if (!$env{'form.pastemarked'}) {
     $imsresources          return;
   </resources>      }
 </manifest>  
     |;  # paste resource to end of list
     print $ims_manifest $resource_text;      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
 }      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
   # Maps need to be copied first
 sub get_dependencies {      if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
     my ($exportitems,$parent,$depth,$dependencies) = @_;   $title=&mt('Copy of').' '.$title;
     if ($depth > 1) {   my $newid=$$.int(rand(100)).time;
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
             push(@{$dependencies},$$parent{$depth});          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
             if ($depth > 2) {              my $path = $1;
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);              my $prefix = $2;
             }              my $ancestor = $3;
         }              if (length($ancestor) > 10) {
     }                  $ancestor = substr($ancestor,-10,10);
 }              }
               $oldid = $path.$prefix.$ancestor;
 sub process_content {          }
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;          my $counter = 0;
     my $content_type;          my $newurl=$oldid.$newid.'.'.$ext;
     my $message;          my $is_unique = &uniqueness_check($newurl);
     my @uploads = ();          while (!$is_unique && $counter < 100) {
     if ($curRes->is_sequence()) {              $counter ++;
         $content_type = 'sequence';              $newid ++;
     } elsif ($curRes->is_page()) {              $newurl = $oldid.$newid;
         $content_type = 'page'; # need to handle individual items in pages.              $is_unique = &uniqueness_check($newurl);
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {          }
         $content_type = 'syllabus';          if (!$is_unique) {
         my $contents = &Apache::imsexport::templatedpage($content_type);              if ($url=~/\.page$/) {
         if ($contents) {                  return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              } else {
         }                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {              }
         $content_type = 'external';          }
         my $title = $curRes->title;   my $storefn=$newurl;
         my $contents =  &Apache::imsexport::external($symb,$title);   $storefn=~s{^/\w+/$match_domain/$match_username/}{};
         if ($contents) {   my $paste_map_result =
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
         }         &Apache::lonnet::getfile($url));
     } elsif ($symb =~ m-adm/navmaps$-) {          if ($paste_map_result eq '/adm/notfound.html') {
         $content_type =  'navmap';              if ($url=~/\.page$/) {
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {                  return &mt('Paste failed: an error occurred saving the composite page');
         $content_type = 'simplepage';              } else {
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);                  return &mt('Paste failed: an error occurred saving the folder');
         if ($contents) {              }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          }
         }   $url = $newurl;
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {      }
         $content_type = 'simpleproblem';  # published maps can only exists once, so remove it from paste buffer when done
         my $contents =  &Apache::imsexport::simpleproblem($symb);      if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
         if ($contents) {   &Apache::lonnet::delenv('docs.markedcopy');
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      }
         }      if ($url=~ m{/smppg$}) {
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {   my $db_name = &Apache::lonsimplepage::get_db_name($url);
         $content_type = 'examupload';   if ($db_name =~ /^smppage_/) {
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {      #simple pages, need to copy the db contents to a new one.
         $content_type = 'bulletinboard';      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);      my $now = time();
         if ($contents) {      $db_name =~ s{_\d*$ }{_$now}x;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      my $result=&Apache::lonnet::put($db_name,\%contents,
         }      $coursedom,$coursenum);
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {      $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
         $content_type = 'aboutme';      $title=&mt('Copy of').' '.$title;
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);   }
         if ($contents) {      }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      $title = &LONCAPA::map::qtunescape($title);
         }      my $ext='false';
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {      if ($url=~m{^http(|s)://}) { $ext='true'; }
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');      $url       = &LONCAPA::map::qtunescape($url);
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {  # Now insert the URL at the bottom
         my $canedit = 0;      my $newidx = &LONCAPA::map::getresidx($url);
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {      if ($env{'docs.markedcopy_supplemental'}) {
             $canedit= 1;          if ($folder =~ /^supplemental/) {
         }              $title = $env{'docs.markedcopy_supplemental'};
 # only include problem code where current user is author          } else {
         if ($canedit) {              (undef,undef,$title) =
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');                  &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
         } else {          }
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');      } else {
         }          if ($folder=~/^supplemental/) {
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');                    $env{'user.domain'}.'___&&&___'.$title;
     }          }
     if (@uploads > 0) {      }
         foreach my $item (@uploads) {  
             my $uploadmsg = '';      $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');      push(@LONCAPA::map::order, $newidx);
             if ($uploadmsg) {      return 'ok';
                 $$copyresult .= $uploadmsg."\n";  # Store the result
             }  }
         }  
     }  sub uniqueness_check {
     if ($message) {      my ($newurl) = @_;
         $$copyresult .= $message."\n";      my $unique = 1;
     }      foreach my $res (@LONCAPA::map::order) {
 }          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
           $url=&LONCAPA::map::qtescape($url);
 sub replicate_content {          if ($newurl eq $url) {
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;              $unique = 0;
     my ($map,$ind,$url);              last;
     if ($caller eq 'templateupload') {          }
         $url = $symb;      }
         $url =~ s#//#/#g;      return $unique;
     } else {  }
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);  
     }  my %parameter_type = ( 'randompick'     => 'int_pos',
     my $content;         'hiddenresource' => 'string_yesno',
     my $filename;         'encrypturl'     => 'string_yesno',
     my $repstatus;         'randomorder'    => 'string_yesno',);
     my $content_name;  my $valid_parameters_re = join('|',keys(%parameter_type));
     if ($url =~ m-/([^/]+)$-) {  # set parameters
         $filename = $1;  sub update_parameter {
         if (!-e $tempexport.'/resources') {  
             mkdir($tempexport.'/resources',0700);      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
         }  
         if (!-e $tempexport.'/resources/'.$count) {      my $which = $env{'form.changeparms'};
             mkdir($tempexport.'/resources/'.$count,0700);      my $idx = $env{'form.setparms'};
         }      if ($env{'form.'.$which.'_'.$idx}) {
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
         my $copiedfile;                                       : 'yes';
         if ($copiedfile = Apache::File->new('>'.$destination)) {   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
             my $content;        $parameter_type{$which});
             if ($caller eq 'resource') {   &remember_parms($idx,$which,'set',$value);
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';      } else {
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
                 $content = &Apache::lonnet::getfile($filepath);  
                 if ($content eq -1) {   &remember_parms($idx,$which,'del');
                     $$message = 'Could not copy file '.$filename;      }
                 } else {      return 1;
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');  }
                     $repstatus = 'ok';  
                 }  
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {  sub handle_edit_cmd {
                 my $rtncode;      my ($coursenum,$coursedom) =@_;
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);      my ($cmd,$idx)=split('_',$env{'form.cmd'});
                 if ($repstatus eq 'ok') {  
                     if ($url =~ /\.html?$/i) {      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');      my ($title, $url, @rrest) = split(':', $ratstr);
                     }  
                 } else {      if ($cmd eq 'del') {
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
                 }      ($url!~/$LONCAPA::assess_page_seq_re/)) {
             } elsif ($caller eq 'noedit') {      &Apache::lonnet::removeuploadedurl($url);
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.   } else {
                 $repstatus = 'ok';      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
                 $content = 'Not the owner of this resource';   }
             }   splice(@LONCAPA::map::order, $idx, 1);
             if ($repstatus eq 'ok') {  
                 print $copiedfile $content;      } elsif ($cmd eq 'cut') {
             }   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
             close($copiedfile);   splice(@LONCAPA::map::order, $idx, 1);
         } else {  
             $$message = 'Could not open destination file for '.$filename."<br />\n";      } elsif ($cmd eq 'up'
         }       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     } else {   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
         $$message = 'Could not determine name of file for '.$symb."<br />\n";  
     }      } elsif ($cmd eq 'down'
     if ($repstatus eq 'ok') {       && defined($LONCAPA::map::order[$idx+1])) {
         $content_name = 'resources/'.$count.'/'.$filename;   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
     }  
     return $content_name;      } elsif ($cmd eq 'rename') {
 }  
    my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
 sub extract_media {   if ($comment=~/\S/) {
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
     my ($dirpath,$container);   $comment.':'.join(':', $url, @rrest);
     my %allfiles = ();   }
     my %codebase = ();  # Devalidate title cache
     if ($url =~ m-(.*/)([^/]+)$-) {   my $renamed_url=&LONCAPA::map::qtescape($url);
         $dirpath = $1;   &Apache::lonnet::devalidate_title_cache($renamed_url);
         $container = $2;      } else {
     } else {   return 0;
         $dirpath = $url;      }
         $container = '';      return 1;
     }  }
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);  
     foreach my $embed_file (keys(%allfiles)) {  sub editor {
         my $filename;      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
         if ($embed_file =~ m#([^/]+)$#) {          $supplementalflag,$orderhash,$iconpath)=@_;
             $filename = $1;      my $container= ($env{'form.pagepath'}) ? 'page'
         } else {                             : 'sequence';
             $filename = $embed_file;  
         }      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order) =
         my $newname = 'res/'.$filename;          &breadcrumbs($allowed,$crstype);
         my ($rtncode,$embed_content,$repstatus);      $r->print($breadcrumbtrail);
         my $embed_url;  
         if ($embed_file =~ m-^/-) {      my $jumpto = "uploaded/$coursedom/$coursenum/$folder.$container";
             $embed_url = $embed_file;           # points to absolute path  
         } else {      unless ($allowed) {
             if ($embed_file =~ m-https?://-) {          $randompick = -1;
                 next;                           # points to url      }
             } else {  
                 $embed_url = $dirpath.$embed_file;  # points to relative path      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
             }      $folder.'.'.$container);
         }      return $errtext if ($fatal);
         if ($caller eq 'resource') {  
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';        if ($#LONCAPA::map::order<1) {
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);   my $idx=&LONCAPA::map::getresidx();
             $embed_content = &Apache::lonnet::getfile($embed_path);   if ($idx<=0) { $idx=1; }
             unless ($embed_content eq -1) {          $LONCAPA::map::order[0]=$idx;
                 $repstatus = 'ok';          $LONCAPA::map::resources[$idx]='';
             }      }
         } elsif ($caller eq 'uploaded') {  
              # ------------------------------------------------------------ Process commands
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);  
         }  # ---------------- if they are for this folder and user allowed to make changes
         if ($repstatus eq 'ok') {      if (($allowed) && ($env{'form.folder'} eq $folder)) {
             my $destination = $tempexport.'/resources/'.$count.'/res';  # set parameters and change order
             if (!-e "$destination") {   &snapshotbefore();
                 mkdir($destination,0755);  
             }   if (&update_parameter()) {
             $destination .= '/'.$filename;      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
             my $copiedfile;      return $errtext if ($fatal);
             if ($copiedfile = Apache::File->new('>'.$destination)) {   }
                 print $copiedfile $embed_content;  
                 push(@{$href},'resources/'.$count.'/res/'.$filename);   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
                 my $attrib_regexp = '';  # change order
                 if (@{$allfiles{$embed_file}} > 1) {      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
                 } else {  
                     $attrib_regexp = $allfiles{$embed_file}[0];      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                 }      return $errtext if ($fatal);
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;   }
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {  
                     $$content =~ s#\Q$embed_file\E#$newname#gi;   if ($env{'form.pastemarked'}) {
                 }              my $paste_res =
             }                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
         } else {              if ($paste_res eq 'ok') {
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
         }                  return $errtext if ($fatal);
     }              } elsif ($paste_res ne '') {
     return;                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
 }              }
    }
 sub store_template {  
     my ($contents,$tempexport,$count,$content_type) = @_;   $r->print($upload_output);
     if ($contents) {  
         if ($tempexport) {   if (&handle_edit_cmd()) {
             if (!-e $tempexport.'/resources') {      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                 mkdir($tempexport.'/resources',0700);      return $errtext if ($fatal);
             }   }
             if (!-e $tempexport.'/resources/'.$count) {  # Group import/search
                 mkdir($tempexport.'/resources/'.$count,0700);   if ($env{'form.importdetail'}) {
             }      my @imports;
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
             my $storetemplate;   if (defined($item)) {
             if ($storetemplate = Apache::File->new('>'.$destination)) {      my ($name,$url,$residx)=
                 print $storetemplate $contents;   map {&unescape($_)} split(/\=/,$item);
                 close($storetemplate);      push(@imports, [$name, $url, $residx]);
             }   }
             if ($content_type eq 'external') {      }
                 return 'resources/'.$count.'/'.$content_type.'.html';      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
             } else {      $container,'londocs',@imports);
                 return 'resources/'.$count.'/'.$content_type.'.xml';      return $errtext if ($fatal);
             }   }
         }  # Loading a complete map
     }   if ($env{'form.loadmap'}) {
 }      if ($env{'form.importmap'}=~/\w/) {
    foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
       my ($title,$url,$ext,$type)=split(/\:/,$res);
 sub group_import {      my $idx=&LONCAPA::map::getresidx($url);
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;      $LONCAPA::map::resources[$idx]=$res;
       $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
     while (@files) {   }
  my ($name, $url, $residx) = @{ shift(@files) };   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})      $folder.'.'.$container);
      && ($caller eq 'londocs')   return $errtext if ($fatal);
      && (!&Apache::lonnet::stat_file($url))) {      } else {
        $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
             my $errtext = '';  
             my $fatal = 0;      }
             my $newmapstr = '<map>'."\n".   }
                             '<resource id="1" src="" type="start"></resource>'."\n".   &log_differences($plain);
                             '<link from="1" to="2" index="1"></link>'."\n".      }
                             '<resource id="2" src="" type="finish"></resource>'."\n".  # ---------------------------------------------------------------- End commands
                             '</map>';  # ---------------------------------------------------------------- Print screen
             $env{'form.output'}=$newmapstr;      my $idx=0;
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,      my $shown=0;
                                                 'output',$1.$2);      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
             if ($result != m|^/uploaded/|) {   $r->print('<div class="LC_Box">'.
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
                 $fatal = 2;    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
             }    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
             if ($fatal) {    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
                 return ($errtext,$fatal);    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
             }    '</ol>');
         }          if ($randompick>=0) {
  if ($url) {              $r->print('<p class="LC_warning">'
     if (!$residx                   .&mt('Caution: this folder is set to randomly pick a subset'
  || defined($LONCAPA::map::zombies[$residx])) {                       .' of resources. Adding or removing resources from this'
  $residx = &LONCAPA::map::getresidx($url,$residx);                       .' folder will change the set of resources that the'
  push(@LONCAPA::map::order, $residx);                       .' students see, resulting in spurious or missing credit'
     }                       .' for completed problems, not limited to ones you'
     my $ext = 'false';                       .' modify. Do not modify the contents of this folder if'
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }                       .' it is in active student use.')
     $url  = &LONCAPA::map::qtunescape($url);                   .'</p>'
     $name = &LONCAPA::map::qtunescape($name);              );
     $LONCAPA::map::resources[$residx] =          }
  join(':', ($name, $url, $ext, 'normal', 'res'));          if ($is_random_order) {
  }              $r->print('<p class="LC_warning">'
     }                   .&mt('Caution: this folder is set to randomly order its'
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);                       .' contents. Adding or removing resources from this folder'
 }                       .' will change the order of resources shown.')
                    .'</p>'
 sub breadcrumbs {              );
     my ($where,$allowed,$type)=@_;          }
     &Apache::lonhtmlcommon::clear_breadcrumbs();          $r->print('</div>');
     my (@folders);      }
     if ($env{'form.pagepath'}) {  
         @folders = split('&',$env{'form.pagepath'});      my ($to_show,$output);
     } else {  
         @folders=split('&',$env{'form.folderpath'});      &Apache::loncommon::start_data_table_count(); #setup a row counter 
     }      foreach my $res (@LONCAPA::map::order) {
     my $folderpath;          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     my $cpinfo='';          $name=&LONCAPA::map::qtescape($name);
     my $plain='';          $url=&LONCAPA::map::qtescape($url);
     my $randompick=-1;          unless ($name) {  $name=(split(/\//,$url))[-1]; }
     my $isencrypted=0;          unless ($name) { $idx++; next; }
     my $ishidden=0;          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
     my $is_random_order=0;                                $coursenum,$crstype);
     while (@folders) {          $idx++;
  my $folder=shift(@folders);          $shown++;
     my $foldername=shift(@folders);      }
  if ($folderpath) {$folderpath.='&';}      &Apache::loncommon::end_data_table_count();
  $folderpath.=$folder.'&'.$foldername;      
  my $url='/adm/coursedocs?folderpath='.      if ($shown) {
     &escape($folderpath);          $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
     my $name=&unescape($foldername);                    .&Apache::loncommon::start_data_table(undef,'contentlist');
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername          if ($allowed) {
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;              $to_show .= &Apache::loncommon::start_data_table_header_row()
     if ($1 ne '') {                       .'<th colspan="2">'.&mt('Move').'</th>'
                $randompick=$1;                       .'<th>'.&mt('Actions').'</th>'
             } else {                       .'<th colspan="2">'.&mt('Document').'</th>';
                $randompick=-1;              if ($folder !~ /^supplemental/) {
             }                  $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
             if ($2) { $ishidden=1; }              }
             if ($3) { $isencrypted=1; }              $to_show .= &Apache::loncommon::end_data_table_header_row();
     if ($4 ne '') { $is_random_order = 1; }          }
             if ($folder eq 'supplemental') {          $to_show .= $output.' '
                 if ($allowed) {                   .&Apache::loncommon::end_data_table()
                     $name = &mt('Supplemental '.$type.' Documents');                   .'<br style="line-height:2px;" />'
                 } else {                   .&Apache::loncommon::end_scrollbox();
                     $name = &mt($type.' Documents');      } else {
                 }          $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
             }                   .'<div class="LC_info" id="contentlist">'
     &Apache::lonhtmlcommon::add_breadcrumb(                   .&mt('Currently no documents.')
       {'href'=>$url.$cpinfo,                   .'</div>'
        'title'=>$name,                   .&Apache::loncommon::end_scrollbox();
        'text'=>'<font size="+1">'.      }
    $name.'</font>',      my $tid = 1;
        'no_mt'=>1,      if ($supplementalflag) {
        });          $tid = 2;
  $plain.=$name.' &gt; ';      }
     }      if ($allowed) {
     $plain=~s/\&gt\;\s*$//;          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,$jumpto,
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);                                         $readfile));
 }          &print_paste_buffer($r,$container);
       } else {
 sub log_docs {          if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
     return &Apache::lonnet::instructor_log('docslog',@_);              #Function Box for Supplemental Content for users with mdc priv.
 }              my $funcname = &mt('Folder Editor');
               $r->print(
 {                  &Apache::loncommon::head_subbox(
     my @oldresources=();                      &Apache::lonhtmlcommon::start_funclist().
     my @oldorder=();                      &Apache::lonhtmlcommon::add_item_funclist(
     my $parmidx;                          '<a href="/adm/coursedocs?command=direct&forcesupplement=1&'.
     my %parmaction=();                          'supppath='.&HTML::Entities::encode($env{'form.folderpath'}).'">'.
     my %parmvalue=();                          '<img src="/res/adm/pages/docs.png" alt="'.$funcname.'" class="LC_icon" />'.
     my $changedflag;                          '<span class="LC_menubuttons_inline_text">'.$funcname.'</span></a>').
                             &Apache::lonhtmlcommon::end_funclist()));
     sub snapshotbefore {          }
         @oldresources=@LONCAPA::map::resources;          $r->print($to_show);
         @oldorder=@LONCAPA::map::order;      }
         $parmidx=undef;      return;
         %parmaction=();  }
         %parmvalue=();  
         $changedflag=0;  sub process_file_upload {
     }      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
   # upload a file, if present
     sub remember_parms {      my ($parseaction,$showupload,$nextphase,$mimetype);
         my ($idx,$parameter,$action,$value)=@_;      if ($env{'form.parserflag'}) {
         $parmidx=$idx;          $parseaction = 'parse';
         $parmaction{$parameter}=$action;      }
         $parmvalue{$parameter}=$value;      my $folder=$env{'form.folder'};
         $changedflag=1;      if ($folder eq '') {
     }          $folder='default';
       }
     sub log_differences {      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
         my ($plain)=@_;          my $errtext='';
         my %storehash=('folder' => $plain,          my $fatal=0;
                        'currentfolder' => $env{'form.folder'});          my $container='sequence';
         if ($parmidx) {          if ($env{'form.pagepath'}) {
            $storehash{'parameter_res'}=$oldresources[$parmidx];              $container='page';
            foreach my $parm (keys(%parmaction)) {          }
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};          ($errtext,$fatal)=
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};                &mapread($coursenum,$coursedom,$folder.'.'.$container);
            }          if ($#LONCAPA::map::order<1) {
         }              $LONCAPA::map::order[0]=1;
         my $maxidx=$#oldresources;              $LONCAPA::map::resources[1]='';
         if ($#LONCAPA::map::resources>$#oldresources) {          }
            $maxidx=$#LONCAPA::map::resources;          if ($fatal) {
         }              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('The uploaded file has not been stored as an error occurred reading the contents of the current folder.').'</div>';
         for (my $idx=0; $idx<=$maxidx; $idx++) {              return;
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {          }
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];          my $destination = 'docs/';
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];          if ($folder =~ /^supplemental/) {
               $changedflag=1;              $destination = 'supplemental/';
            }          }
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {          if (($folder eq 'default') || ($folder eq 'supplemental')) {
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];              $destination .= 'default/';
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
               $changedflag=1;              $destination .=  $2.'/';
            }          }
         }  # this is for a course, not a user, so set context to coursedoc.
  $storehash{'maxidx'}=$maxidx;          my $newidx=&LONCAPA::map::getresidx();
         if ($changedflag) { &log_docs(\%storehash); }          $destination .= $newidx;
     }          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
 }   $parseaction,$allfiles,
    $codebase,undef,undef,undef,undef,
                                                   undef,undef,\$mimetype);
           if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
               my $stored = $1;
               $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 sub docs_change_log {                            $stored.'</span>').'</p>';
     my ($r)=@_;          } else {
     my $folder=$env{'form.folder'};              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));              
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
     my %docslog=&Apache::lonnet::dump('nohist_docslog',              return;
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},          }
                                       $env{'course.'.$env{'request.course.id'}.'.num'});          my $ext='false';
           if ($url=~m{^http://}) { $ext='true'; }
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }   $url     = &LONCAPA::map::qtunescape($url);
           my $comment=$env{'form.comment'};
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.   $comment = &LONCAPA::map::qtunescape($comment);
               '<input type="hidden" name="docslog" value="1" />');          if ($folder=~/^supplemental/) {
                 $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     my %saveable_parameters = ('show' => 'scalar',);                    $env{'user.domain'}.'___&&&___'.$comment;
     &Apache::loncommon::store_course_settings('docs_log',          }
                                               \%saveable_parameters);  
     &Apache::loncommon::restore_course_settings('docs_log',          $LONCAPA::map::resources[$newidx]=
                                                 \%saveable_parameters);      $comment.':'.$url.':'.$ext.':normal:res';
     if (!$env{'form.show'}) { $env{'form.show'}=10; }          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     my %lt=('hiddenresource' => 'Resources hidden',          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     'encrypturl'     => 'URL hidden',      $folder.'.'.$container);
     'randompick'     => 'Randomly pick',          if ($fatal) {
     'randomorder'    => 'Randomly ordered',              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
     'set'            => 'set to',              return;
     'del'            => 'deleted');          } else {
     $r->print(&Apache::loncommon::display_filter().              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
               '<input type="hidden" name="folder" value="'.$folder.'" />'.                  $$upload_output = $showupload;
               '<input type="submit" value="'.&mt('Display').'" /></form>');                  my $total_embedded = scalar(keys(%{$allfiles}));
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().                  if ($total_embedded > 0) {
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.                      my $uploadphase = 'upload_embedded';
               &mt('After').'</th>'.                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
               &Apache::loncommon::end_data_table_header_row());      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
     my $shown=0;                      my ($embedded,$num) = 
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {                          &Apache::loncommon::ask_for_embedded_content(
  if ($env{'form.displayfilter'} eq 'currentfolder') {                              '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }                      if ($embedded) {
  }                          if ($num) {
         my @changes=keys(%{$docslog{$id}{'logentry'}});                              $$upload_output .=
         if ($env{'form.displayfilter'} eq 'containing') {           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.                              $nextphase = $uploadphase;
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});                          } else {
     foreach my $key (@changes) {                              $$upload_output .= $embedded;
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};                          }
     }                      } else {
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }                                  $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
  }                      }
         my $count = 0;                  } else {
         my $time =                      $$upload_output .= &mt('No embedded items identified').'<br />';
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});                  }
         my $plainname =                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
                                           $docslog{$id}{'exe_udom'});                  $nextphase = 'decompress_uploaded';
         my $about_me_link =                  my $position = scalar(@LONCAPA::map::order)-1;
             &Apache::loncommon::aboutmewrapper($plainname,                  my $noextract = &return_to_editor();
                                                $docslog{$id}{'exe_uname'},                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
                                                $docslog{$id}{'exe_udom'});                  my %archiveitems = (
         my $send_msg_link='';                      folderpath => $env{'form.folderpath'},
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})                      pagepath   => $env{'form.pagepath'},
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {                      cmd        => $nextphase,
             $send_msg_link ='<br />'.                      newidx     => $newidx,
                 &Apache::loncommon::messagewrapper(&mt('Send message'),                      position   => $position,
                                                    $docslog{$id}{'exe_uname'},                      phase      => $nextphase,
                                                    $docslog{$id}{'exe_udom'});                      comment    => $comment,
         }                  );
         $r->print(&Apache::loncommon::start_data_table_row());                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
         $r->print('<td>'.$time.'</td>                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
                        <td>'.$about_me_link.                  $$upload_output = $showupload.
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.                                    &Apache::loncommon::decompress_form($mimetype,
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.                                        $archiveurl,'/adm/coursedocs',$noextract,
                   $send_msg_link.'</td><td>'.                                        \%archiveitems,\@current);
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');              }
 # Before          }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {      }
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];      return $nextphase;
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];  }
     if ($oldname ne $newname) {  
  $r->print(&LONCAPA::map::qtescape($oldname));  sub get_dir_list {
     }      my ($url,$coursenum,$coursedom,$newidx) = @_;
  }      my ($destination,$dir_root) = &embedded_destination();
  $r->print('<ul>');      my ($dirlistref,$listerror) =  
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {      my @dir_lines;
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');      my $dirptr=16384;
     }      if (ref($dirlistref) eq 'ARRAY') {
  }          foreach my $dir_line (sort
  $r->print('</ul>');                            {
 # After                                my ($afile)=split('&',$a,2);
         $r->print('</td><td>');                                my ($bfile)=split('&',$b,2);
                                 return (lc($afile) cmp lc($bfile));
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                            } (@{$dirlistref})) {
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];              $filename =~ s/\s+$//;
     if ($oldname ne '' && $oldname ne $newname) {              next if ($filename =~ /^\.\.?$/); 
  $r->print(&LONCAPA::map::qtescape($newname));              my $isdir = 0;
     }              if ($dirptr&$testdir) {
  }                          $isdir = 1;
  $r->print('<ul>');              }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {          }
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');      }
     }      return @dir_lines;
  }  }
  $r->print('</ul>');  
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {  sub is_supplemental_title {
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');      my ($title) = @_;
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {  }
     $r->print('<li>'.  
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',  sub parse_supplemental_title {
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})      my ($title) = @_;
       .'</li>');  
  }      my ($foldertitle,$renametitle);
     }      if ($title =~ /&amp;&amp;&amp;/) {
     $r->print('</ul>');   $title = &HTML::Entites::decode($title);
  }      }
 # End   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());   $renametitle=$4;
         $shown++;   my ($time,$uname,$udom) = ($1,$2,$3);
         if (!($env{'form.show'} eq &mt('all')   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
               || $shown<=$env{'form.show'})) { last; }   my $name =  &Apache::loncommon::plainname($uname,$udom);
     }   $name = &HTML::Entities::encode($name,'"<>&\'');
     $r->print(&Apache::loncommon::end_data_table());          $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
 }   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
       $name.': <br />'.$foldertitle;
 sub update_paste_buffer {      }
     my ($coursenum,$coursedom) = @_;      if (wantarray) {
    return ($title,$foldertitle,$renametitle);
     return if (!defined($env{'form.markcopy'}));      }
     return if (!defined($env{'form.copyfolder'}));      return $title;
     return if ($env{'form.markcopy'} < 0);  }
   
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,  # --------------------------------------------------------------- An entry line
     $env{'form.copyfolder'});  
      sub entryline {
     return if ($fatal);      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$crstype)=@_;
       my ($foldertitle,$pagetitle,$renametitle);
 # Mark for copying      if (&is_supplemental_title($title)) {
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
     if (&is_supplemental_title($title)) {   $pagetitle = $foldertitle;
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});      } else {
  ($title) = &parse_supplemental_title($title);   $title=&HTML::Entities::encode($title,'"<>&\'');
     } elsif ($env{'docs.markedcopy_supplemental'}) {   $renametitle=$title;
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');   $foldertitle=$title;
     }   $pagetitle=$title;
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};      }
   
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,      my $orderidx=$LONCAPA::map::order[$index];
     'docs.markedcopy_url'   => $url});  
     delete($env{'form.markcopy'});  
 }      $renametitle=~s/\\/\\\\/g;
       $renametitle=~s/\&quot\;/\\\"/g;
 sub print_paste_buffer {      $renametitle=~s/ /%20/g;
     my ($r,$container) = @_;      my $line=&Apache::loncommon::start_data_table_row();
     return if (!defined($env{'docs.markedcopy_url'}));      my ($form_start,$form_end,$form_common);
   # Edit commands
     $r->print(<<ENDPASTE);      my ($container, $type, $esc_path, $path, $symb);
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>      if ($env{'form.folderpath'}) {
 ENDPASTE   $type = 'folder';
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');          $container = 'sequence';
    $esc_path=&escape($env{'form.folderpath'});
     my $type;   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
  $type = &mt('External Resource');      }
  $r->print($type.': '.      if ($env{'form.pagepath'}) {
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.          $type = $container = 'page';
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');          $esc_path=&escape($env{'form.pagepath'});
     }  else {   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];          $symb=&escape($env{'form.pagesymb'});
  my $icon = &Apache::loncommon::icon($extension);      }
  if ($extension eq 'sequence' &&      my $cpinfo='';
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {      if ($allowed) {
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));   my $incindex=$index+1;
     $icon .= '/folder_closed.gif';   my $selectbox='';
  }   if (($#LONCAPA::map::order>0) &&
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';      ((split(/\:/,
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
     }       ne '') &&
     if ($container eq 'page') {      ((split(/\:/,
  $r->print('       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />       ne '')) {
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />      $selectbox=
 ');   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
     } else {   '<select name="newpos" onchange="this.form.submit()">';
  $r->print('      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />   if ($i==$incindex) {
 ');      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
     }   } else {
     $r->print('</p></form>');      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
 }   }
       }
 sub do_paste_from_buffer {      $selectbox.='</select>';
     my ($coursenum,$coursedom,$folder) = @_;   }
    my %lt=&Apache::lonlocal::texthash(
     if (!$env{'form.pastemarked'}) {                  'up' => 'Move Up',
         return;   'dw' => 'Move Down',
     }   'rm' => 'Remove',
                   'ct' => 'Cut',
 # paste resource to end of list   'rn' => 'Rename',
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});   'cp' => 'Copy');
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});   my $nocopy=0;
 # Maps need to be copied first          my $nocut=0;
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {          if ($url=~/\.(page|sequence)$/) {
  $title=&mt('Copy of').' '.$title;      if ($url =~ m{/res/}) {
  my $newid=$$.int(rand(100)).time;   # no copy for published maps
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);   $nocopy = 1;
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {      } else {
             my $path = $1;   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
             my $prefix = $2;      my ($title,$url,$ext,$type)=split(/\:/,$item);
             my $ancestor = $3;      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
             if (length($ancestor) > 10) {   $nocopy=1;
                 $ancestor = substr($ancestor,-10,10);   last;
             }      }
             $oldid = $path.$prefix.$ancestor;   }
         }      }
         my $counter = 0;   }
         my $newurl=$oldid.$newid.'.'.$ext;          if ($url=~/^\/res\/lib\/templates\//) {
         my $is_unique = &uniqueness_check($newurl);             $nocopy=1;
         while (!$is_unique && $counter < 100) {             $nocut=1;
             $counter ++;          }
             $newid ++;          my $copylink='&nbsp;';
             $newurl = $oldid.$newid;          my $cutlink='&nbsp;';
             $is_unique = &uniqueness_check($newurl);  
         }   my $skip_confirm = 0;
         if (!$is_unique) {   if ( $folder =~ /^supplemental/
             if ($url=~/\.page$/) {       || ($url =~ m{( /smppg$
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');      |/syllabus$
             } else {      |/aboutme$
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');      |/navmaps$
             }      |/bulletinboard$
         }      |\.html$
  my $storefn=$newurl;      |^/adm/wrapper/ext)}x)) {
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};      $skip_confirm = 1;
  my $paste_map_result =   }
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,  
        &Apache::lonnet::getfile($url));   if (!$nocopy) {
         if ($paste_map_result eq '/adm/notfound.html') {      $copylink=(<<ENDCOPY);
             if ($url=~/\.page$/) {  <a href="javascript:markcopy('$esc_path','$index','$renametitle','$container','$symb','$folder');" class="LC_docs_copy">$lt{'cp'}</a>
                 return &mt('Paste failed: an error occurred saving the composite page');  ENDCOPY
             } else {          }
                 return &mt('Paste failed: an error occurred saving the folder');   if (!$nocut) {
             }      $cutlink=(<<ENDCUT);
         }  <a href="javascript:cutres('$esc_path','$index','$renametitle','$container','$symb','$folder',$skip_confirm);" class="LC_docs_cut">$lt{'ct'}</a>
  $url = $newurl;  ENDCUT
     }          }
 # published maps can only exists once, so remove it from paste buffer when done   $form_start = '
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {     <form action="/adm/coursedocs" method="post">
  &Apache::lonnet::delenv('docs\\.markedcopy');  ';
     }          $form_common=(<<END);
     if ($url=~ m{/smppg$}) {     <input type="hidden" name="${type}path" value="$path" />
  my $db_name = &Apache::lonsimplepage::get_db_name($url);     <input type="hidden" name="${type}symb" value="$symb" />
  if ($db_name =~ /^smppage_/) {     <input type="hidden" name="setparms" value="$orderidx" />
     #simple pages, need to copy the db contents to a new one.     <input type="hidden" name="changeparms" value="0" />
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);  END
     my $now = time();          $form_end = '</form>';
     $db_name =~ s{_\d*$ }{_$now}x;   $line.=(<<END);
     my $result=&Apache::lonnet::put($db_name,\%contents,  <td>
     $coursedom,$coursenum);  <div class="LC_docs_entry_move">
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;    <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'>
     $title=&mt('Copy of').' '.$title;      <img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" />
  }    </a>
     }  </div>
     $title = &LONCAPA::map::qtunescape($title);  <div class="LC_docs_entry_move">
     my $ext='false';    <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'>
     if ($url=~m{^http(|s)://}) { $ext='true'; }      <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" />
     $url       = &LONCAPA::map::qtunescape($url);    </a>
 # Now insert the URL at the bottom  </div>
     my $newidx = &LONCAPA::map::getresidx($url);  </td>
     if ($env{'docs.markedcopy_supplemental'}) {  <td>
         if ($folder =~ /^supplemental/) {     $form_start
             $title = $env{'docs.markedcopy_supplemental'};     $form_common
         } else {     $selectbox
             (undef,undef,$title) =     $form_end
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});  </td>
         }  <td class="LC_docs_entry_commands">
     } else {     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
         if ($folder=~/^supplemental/) {  $cutlink
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
                   $env{'user.domain'}.'___&&&___'.$title;  $copylink
         }  </td>
     }  END
   
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';      }
     push(@LONCAPA::map::order, $newidx);  # Figure out what kind of a resource this is
     return 'ok';      my ($extension)=($url=~/\.(\w+)$/);
 # Store the result      my $uploaded=($url=~/^\/*uploaded\//);
 }      my $icon=&Apache::loncommon::icon($url);
       my $isfolder=0;
 sub uniqueness_check {      my $ispage=0;
     my ($newurl) = @_;      my $folderarg;
     my $unique = 1;      my $pagearg;
     foreach my $res (@LONCAPA::map::order) {      my $pagefile;
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);      if ($uploaded) {
         $url=&LONCAPA::map::qtescape($url);          if (($extension eq 'sequence') || ($extension eq 'page')) {
         if ($newurl eq $url) {              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
             $unique = 0;              my $containerarg = $1;
             last;          if ($extension eq 'sequence') {
         }          $icon=$iconpath.'navmap.folder.closed.gif';
     }                  $folderarg=$containerarg;
     return $unique;                  $isfolder=1;
 }              } else {
                   $icon=$iconpath.'page.gif';
 my %parameter_type = ( 'randompick'     => 'int_pos',                  $pagearg=$containerarg;
        'hiddenresource' => 'string_yesno',                  $ispage=1;
        'encrypturl'     => 'string_yesno',              }
        'randomorder'    => 'string_yesno',);              if ($allowed) {
 my $valid_parameters_re = join('|',keys(%parameter_type));                  $url='/adm/coursedocs?';
 # set parameters              } else {
 sub update_parameter {                  $url='/adm/supplemental?';
               }
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);   } else {
       &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
     my $which = $env{'form.changeparms'};   }
     my $idx = $env{'form.setparms'};      }
     if ($env{'form.'.$which.'_'.$idx}) {  
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}      my $orig_url = $url;
                                      : 'yes';      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
       $parameter_type{$which});      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
  &remember_parms($idx,$which,'set',$value);   my $symb=&Apache::lonnet::symbclean(
     } else {            &Apache::lonnet::declutter('uploaded/'.
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
              $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
  &remember_parms($idx,$which,'del');             '.sequence').
     }             '___'.$residx.'___'.
     return 1;     &Apache::lonnet::declutter($url));
 }   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
    $url=&Apache::lonnet::clutter($url);
    if ($url=~/^\/*uploaded\//) {
 sub handle_edit_cmd {      $url=~/\.(\w+)$/;
     my ($coursenum,$coursedom) =@_;      my $embstyle=&Apache::loncommon::fileembstyle($1);
       if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
     my ($cmd,$idx)=split('_',$env{'form.cmd'});   $url='/adm/wrapper'.$url;
       } elsif ($embstyle eq 'ssi') {
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];   #do nothing with these
     my ($title, $url, @rrest) = split(':', $ratstr);      } elsif ($url!~/\.(sequence|page)$/) {
    $url='/adm/coursedocs/showdoc'.$url;
     if ($cmd eq 'del') {      }
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&   } elsif ($url=~m|^/ext/|) {
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {      $url='/adm/wrapper'.$url;
     &Apache::lonnet::removeuploadedurl($url);      $external = 1;
  } else {   }
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);          if (&Apache::lonnet::symbverify($symb,$url)) {
  }      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  splice(@LONCAPA::map::order, $idx, 1);          } else {
               $url='';
     } elsif ($cmd eq 'cut') {          }
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);   if ($container eq 'page') {
  splice(@LONCAPA::map::order, $idx, 1);      my $symb=$env{'form.pagesymb'};
   
     } elsif ($cmd eq 'up'      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];   }
       }
     } elsif ($cmd eq 'down'      my ($rand_pick_text,$rand_order_text);
      && defined($LONCAPA::map::order[$idx+1])) {      if ($isfolder || $extension eq 'sequence') {
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];   my $foldername=&escape($foldertitle);
    my $folderpath=$env{'form.folderpath'};
     } elsif ($cmd eq 'rename') {   if ($folderpath) { $folderpath.='&' };
   # Append randompick number, hidden, and encrypted with ":" to foldername,
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});  # so it gets transferred between levels
  if ($comment=~/\S/) {   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=                                                'parameter_randompick'))[0]
  $comment.':'.join(':', $url, @rrest);                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  }                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
 # Devalidate title cache                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  my $renamed_url=&LONCAPA::map::qtescape($url);                                                'parameter_encrypturl'))[0]=~/^yes$/i)
  &Apache::lonnet::devalidate_title_cache($renamed_url);                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     } else {                                                'parameter_randomorder'))[0]=~/^yes$/i);
  return 0;   $url.='folderpath='.&escape($folderpath).$cpinfo;
     }          my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
     return 1;                                                     'parameter_randompick'))[0];
 }          my $rpckchk;
           if ($rpicknum) {
 sub editor {              $rpckchk = ' checked="checked"';
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;          }
           my $formname = 'edit_rpick_'.$orderidx;
     my $container= ($env{'form.pagepath'}) ? 'page'   $rand_pick_text = 
                            : 'sequence';  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
   $form_common."\n".
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,  '<span class="LC_nobreak"><label><input type="checkbox" name="randpickon_'.$orderidx.'" id="rpick_'.$orderidx.'" onclick="'."updatePick(this.form,'$orderidx','check');".'"'.$rpckchk.' /> '.&mt('Randomly Pick').'</label><input type="hidden" name="randompick_'.$orderidx.'" id="rpicknum_'.$orderidx.'" value="'.$rpicknum.'" />';
     $folder.'.'.$container);          if ($rpicknum ne '') {
     return $errtext if ($fatal);              $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
           }
     if ($#LONCAPA::map::order<1) {          $rand_pick_text .= '</span></form>';
  my $idx=&LONCAPA::map::getresidx();      my $ro_set=
  if ($idx<=0) { $idx=1; }      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
         $LONCAPA::map::order[0]=$idx;   $rand_order_text = 
         $LONCAPA::map::resources[$idx]='';  $form_start.
     }  $form_common.'
      <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></form>';
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=      }
  &breadcrumbs($folder,$allowed,$type);      if ($ispage) {
     $r->print($breadcrumbtrail);          my $pagename=&escape($pagetitle);
              my $pagepath;
 # ------------------------------------------------------------ Process commands          my $folderpath=$env{'form.folderpath'};
           if ($folderpath) { $pagepath = $folderpath.'&' };
 # ---------------- if they are for this folder and user allowed to make changes          $pagepath.=$pagearg.'&'.$pagename;
     if (($allowed) && ($env{'form.folder'} eq $folder)) {   my $symb=$env{'form.pagesymb'};
 # set parameters and change order   if (!$symb) {
  &snapshotbefore();      my $path='uploaded/'.
    $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
  if (&update_parameter()) {   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
     return $errtext if ($fatal);         $residx,
  }         $path.$pagearg.'.page');
    }
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {   $url.='pagepath='.&escape($pagepath).
 # change order      '&amp;pagesymb='.&escape($symb).$cpinfo;
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);      }
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);      if (($external) && ($allowed)) {
    my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
     return $errtext if ($fatal);      } else {
  }   undef($external);
           }
  if ($env{'form.pastemarked'}) {      my $reinit;
             my $paste_res =      if ($crstype eq 'Community') {
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);          $reinit = &mt('(re-initialize community to access)');
             if ($paste_res eq 'ok') {      } else {
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);          $reinit = &mt('(re-initialize course to access)');
                 return $errtext if ($fatal);      }  
             } elsif ($paste_res ne '') {      $line.='<td>';
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
             }         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
  }      } elsif ($url) {
          $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
  $r->print($upload_output);                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
       } else {
  if (&handle_edit_cmd()) {         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);      }
     return $errtext if ($fatal);      $line.='</td><td>';
  }      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
 # Group import/search         $line.='<a href="'.$url.'">'.$title.'</a>';
  if ($env{'form.importdetail'}) {      } elsif ($url) {
     my @imports;         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {                                               $title,600,500);
  if (defined($item)) {      } else {
     my ($name,$url,$residx)=         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
  map {&unescape($_)} split(/\=/,$item);      }
     push(@imports, [$name, $url, $residx]);      $line.=$external."</td>";
  }      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
     }      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,      if (($allowed) && ($folder!~/^supplemental/)) {
     $container,'londocs',@imports);    my %lt=&Apache::lonlocal::texthash(
     return $errtext if ($fatal);         'hd' => 'Hidden',
  }         'ec' => 'URL hidden');
 # Loading a complete map   my $enctext=
  if ($env{'form.loadmap'}) {      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
     if ($env{'form.importmap'}=~/\w/) {   my $hidtext=
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
     my ($title,$url,$ext,$type)=split(/\:/,$res);   $line.=(<<ENDPARMS);
     my $idx=&LONCAPA::map::getresidx($url);    <td class="LC_docs_entry_parameter">
     $LONCAPA::map::resources[$idx]=$res;      $form_start
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;      $form_common
  }      <label><input type="checkbox" name="hiddenresource_$orderidx" onclick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,      $form_end
     $folder.'.'.$container);      <br />
  return $errtext if ($fatal);      $form_start
     } else {      $form_common
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');      <label><input type="checkbox" name="encrypturl_$orderidx" onclick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
       $form_end
     }    </td>
  }    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
  &log_differences($plain);                                        $rand_order_text</td>
     }  ENDPARMS
 # ---------------------------------------------------------------- End commands      }
 # ---------------------------------------------------------------- Print screen      $line.=&Apache::loncommon::end_data_table_row();
     my $idx=0;      return $line;
     my $shown=0;  }
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {  
  $r->print('<p>'.&mt('Parameters').':<ul>'.  =pod
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').  
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').  =item tiehash()
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').  
   '</ul></p>');  tie the hash
     }                                                                                                      
     if ($randompick>=0) {  =cut
  $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>');  
     }  sub tiehash {
     if ($is_random_order) {      my ($mode)=@_;
  $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>');      $hashtied=0;
     }      if ($env{'request.course.fn'}) {
     $r->print('<table class="LC_docs_editor">');   if ($mode eq 'write') {
     foreach my $res (@LONCAPA::map::order) {      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);      &GDBM_WRCREAT(),0640)) {
  $name=&LONCAPA::map::qtescape($name);                  $hashtied=2;
  $url=&LONCAPA::map::qtescape($url);      }
  unless ($name) {  $name=(split(/\//,$url))[-1]; }   } else {
  unless ($name) { $idx++; next; }      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,      &GDBM_READER(),0640)) {
      $coursenum));                  $hashtied=1;
  $idx++;      }
  $shown++;   }
     }      }
     unless ($shown) {  }
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');  
     }  sub untiehash {
     $r->print("\n</table>\n");      if ($hashtied) { untie %hash; }
     if ($allowed) {      $hashtied=0;
         &print_paste_buffer($r,$container);      return OK;
     }  }
     return;  
 }  
   
 sub process_file_upload {  
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;  sub checkonthis {
 # upload a file, if present      my ($r,$url,$level,$title)=@_;
     my $parseaction;      $url=&unescape($url);
    if ($env{'form.parserflag'}) {      $alreadyseen{$url}=1;
         $parseaction = 'parse';      $r->rflush();
     }      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
     my $phase_status;         $r->print("\n<br />");
     my $folder=$env{'form.folder'};         if ($level==0) {
     if ($folder eq '') {             $r->print("<br />");
         $folder='default';         }
     }         for (my $i=0;$i<=$level*5;$i++) {
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {             $r->print('&nbsp;');
         my $errtext='';         }
         my $fatal=0;         $r->print('<a href="'.$url.'" target="cat">'.
         my $container='sequence';   ($title?$title:$url).'</a> ');
         if ($env{'form.pagepath'}) {         if ($url=~/^\/res\//) {
             $container='page';    my $result=&Apache::lonnet::repcopy(
         }                                &Apache::lonnet::filelocation('',$url));
         ($errtext,$fatal)=            if ($result eq 'ok') {
               &mapread($coursenum,$coursedom,$folder.'.'.$container);               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
         if ($#LONCAPA::map::order<1) {               $r->rflush();
             $LONCAPA::map::order[0]=1;               &Apache::lonnet::countacc($url);
             $LONCAPA::map::resources[1]='';               $url=~/\.(\w+)$/;
         }               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
         if ($fatal) {   $r->print('<br />');
             return 'failed';                   $r->rflush();
         }                   for (my $i=0;$i<=$level*5;$i++) {
         my $destination = 'docs/';                       $r->print('&nbsp;');
         if ($folder =~ /^supplemental/) {                   }
             $destination = 'supplemental/';                   $r->print('- '.&mt('Rendering:').' ');
         }   my ($errorcount,$warningcount)=split(/:/,
         if (($folder eq 'default') || ($folder eq 'supplemental')) {         &Apache::lonnet::ssi_body($url,
             $destination .= 'default/';         ('grade_target'=>'web',
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {   'return_only_error_and_warning_counts' => 1)));
             $destination .=  $2.'/';                   if (($errorcount) ||
         }                       ($warningcount)) {
 # this is for a course, not a user, so set coursedoc flag       if ($errorcount) {
 # probably the only place in the system where this should be "1"                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
         my $newidx=&LONCAPA::map::getresidx();                            &mt('[quant,_1,error]',$errorcount).'</span>');
         $destination .= $newidx;                       }
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,       if ($warningcount) {
  $parseaction,$allfiles,                          $r->print('<span class="LC_warning">'.
  $codebase);                            &mt('[quant,_1,warning]',$warningcount).'</span>');
         my $ext='false';                       }
         if ($url=~m{^http://}) { $ext='true'; }                   } else {
  $url     = &LONCAPA::map::qtunescape($url);                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
         my $comment=$env{'form.comment'};                   }
  $comment = &LONCAPA::map::qtunescape($comment);                   $r->rflush();
         if ($folder=~/^supplemental/) {               }
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.       my $dependencies=
                   $env{'user.domain'}.'___&&&___'.$comment;                  &Apache::lonnet::metadata($url,'dependencies');
         }               foreach my $dep (split(/\,/,$dependencies)) {
    if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
         $LONCAPA::map::resources[$newidx]=                      &checkonthis($r,$dep,$level+1);
     $comment.':'.$url.':'.$ext.':normal:res';                   }
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;               }
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,            } elsif ($result eq 'unavailable') {
     $folder.'.'.$container);               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
         if ($fatal) {            } elsif ($result eq 'not_found') {
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';        unless ($url=~/\$/) {
             return 'failed';    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
         } else {        } else {
             if ($parseaction eq 'parse') {    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
                 my $total_embedded = keys(%{$allfiles});        }
                 if ($total_embedded > 0) {            } else {
                     my $num = 0;               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
     my $state = '            }
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />         }
    <input type="hidden" name="cmd" value="upload_embedded" />      }
    <input type="hidden" name="newidx" value="'.$newidx.'" />  }
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />  
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';  
     $phase_status = 'phasetwo';  
   =pod
                     $$upload_output .=  
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.  =item list_symbs()
  &Apache::loncommon::ask_for_embedded_content(  
                             '/adm/coursedocs',$state,$allfiles,$codebase);  List Content Identifiers
                 } else {  
                     $$upload_output .= 'No embedded items identified<br />';  =cut
                 }  
             }  sub list_symbs {
         }      my ($r) = @_;
     }  
     return $phase_status;      my $crstype = &Apache::loncommon::course_type();
 }      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
 sub process_secondary_uploads {      $r->print(&startContentScreen('tools'));
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;      my $navmap = Apache::lonnavmaps::navmap->new();
     my $folder=$env{'form.folder'};      if (!defined($navmap)) {
     my $destination = 'docs/';          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
     if ($folder =~ /^supplemental/) {                    '<div class="LC_error">'.
         $destination = 'supplemental/';                    &mt('Unable to retrieve information about course contents').
     }                    '</div>');
     if (($folder eq 'default') || ($folder eq 'supplemental')) {          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
         $destination .= 'default/';      } else {
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {          $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
         $destination .=  $2.'/';                    &Apache::loncommon::start_data_table().
     }                    &Apache::loncommon::start_data_table_header_row().
     $destination .= $newidx;                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
     my ($url,$filename);                    &Apache::loncommon::end_data_table_header_row()."\n");
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);          my $count;
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});          foreach my $res ($navmap->retrieveResources()) {
     return $filename;              $r->print(&Apache::loncommon::start_data_table_row().
 }                        '<td>'.$res->compTitle().'</td>'.
                         '<td>'.$res->symb().'</td>'.
 sub is_supplemental_title {                        &Apache::loncommon::start_data_table_row());
     my ($title) = @_;              $count ++;
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);          }
 }          if (!$count) {
               $r->print(&Apache::loncommon::start_data_table_row().
 sub parse_supplemental_title {                        '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
     my ($title) = @_;                        &Apache::loncommon::end_data_table_row()); 
           }
     my ($foldertitle,$renametitle);          $r->print(&Apache::loncommon::end_data_table());
     if ($title =~ /&amp;&amp;&amp;/) {      }
  $title = &HTML::Entites::decode($title);  }
     }  
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {  
  $renametitle=$4;  sub verifycontent {
  my ($time,$uname,$udom) = ($1,$2,$3);      my ($r) = @_;
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);      my $crstype = &Apache::loncommon::course_type();
  my $name =  &Apache::loncommon::plainname($uname,$udom);      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
  $name = &HTML::Entities::encode($name,'"<>&\'');      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.      $r->print(&startContentScreen('tools'));
     $name.': <br />'.$foldertitle;      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
     }     $hashtied=0;
     if (wantarray) {     undef %alreadyseen;
  return ($title,$foldertitle,$renametitle);     %alreadyseen=();
     }     &tiehash();
     return $title;     
 }     foreach my $key (keys(%hash)) {
          if ($hash{$key}=~/\.(page|sequence)$/) {
 # --------------------------------------------------------------- An entry line     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
          $r->print('<hr /><span class="LC_error">'.
 sub entryline {   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;   &unescape($hash{$key}).'</span><br />'.
    &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
     my ($foldertitle,$pagetitle,$renametitle);     }
     if (&is_supplemental_title($title)) {         }
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
  $pagetitle = $foldertitle;             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
     } else {         }
  $title=&HTML::Entities::encode($title,'"<>&\'');     }
  $renametitle=$title;     &untiehash();
  $foldertitle=$title;     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
  $pagetitle=$title;  }
     }  
   
     my $orderidx=$LONCAPA::map::order[$index];  sub devalidateversioncache {
          my $src=shift;
       &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
     $renametitle=~s/\\/\\\\/g;    &Apache::lonnet::clutter($src));
     $renametitle=~s/\&quot\;/\\\"/g;  }
     $renametitle=~s/ /%20/g;  
     my $line='<tr>';  sub checkversions {
     my ($form_start,$form_end);      my ($r) = @_;
 # Edit commands      my $crstype = &Apache::loncommon::course_type();
     my ($container, $type, $esc_path, $path, $symb);      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
     if ($env{'form.folderpath'}) {      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
  $type = 'folder';      $r->print(&startContentScreen('tools'));
         $container = 'sequence';  
  $esc_path=&escape($env{'form.folderpath'});      my $header='';
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      my $startsel='';
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');      my $monthsel='';
     }      my $weeksel='';
     if ($env{'form.pagepath'}) {      my $daysel='';
         $type = $container = 'page';      my $allsel='';
         $esc_path=&escape($path = $env{'form.pagepath'});      my %changes=();
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');      my $starttime=0;
         $symb=&escape($env{'form.pagesymb'});      my $haschanged=0;
     }      my %setversions=&Apache::lonnet::dump('resourceversions',
     my $cpinfo='';    $env{'course.'.$env{'request.course.id'}.'.domain'},
     if ($allowed) {    $env{'course.'.$env{'request.course.id'}.'.num'});
  my $incindex=$index+1;  
  my $selectbox='';      $hashtied=0;
  if (($folder!~/^supplemental/) &&      &tiehash();
     ($#LONCAPA::map::order>0) &&      my %newsetversions=();
     ((split(/\:/,      if ($env{'form.setmostrecent'}) {
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]   $haschanged=1;
      ne '') &&   foreach my $key (keys(%hash)) {
     ((split(/\:/,      if ($key=~/^ids\_(\/res\/.+)$/) {
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]   $newsetversions{$1}='mostrecent';
      ne '')) {                  &devalidateversioncache($1);
     $selectbox=      }
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.   }
  '<select name="newpos" onChange="this.form.submit()">';      } elsif ($env{'form.setcurrent'}) {
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {   $haschanged=1;
  if ($i==$incindex) {   foreach my $key (keys(%hash)) {
     $selectbox.='<option value="" selected="1">('.$i.')</option>';      if ($key=~/^ids\_(\/res\/.+)$/) {
  } else {   my $getvers=&Apache::lonnet::getversion($1);
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';   if ($getvers>0) {
  }      $newsetversions{$1}=$getvers;
     }      &devalidateversioncache($1);
     $selectbox.='</select>';   }
  }      }
  my %lt=&Apache::lonlocal::texthash(   }
                 'up' => 'Move Up',      } elsif ($env{'form.setversions'}) {
  'dw' => 'Move Down',   $haschanged=1;
  'rm' => 'Remove',   foreach my $key (keys(%env)) {
                 'ct' => 'Cut',      if ($key=~/^form\.set_version_(.+)$/) {
  'rn' => 'Rename',   my $src=$1;
  'cp' => 'Copy');   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
  my $nocopy=0;      $newsetversions{$src}=$env{$key};
         my $nocut=0;      &devalidateversioncache($src);
         if ($url=~/\.(page|sequence)$/) {   }
     if ($url =~ m{/res/}) {      }
  # no copy for published maps   }
  $nocopy = 1;      }
     } else {      if ($haschanged) {
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
     my ($title,$url,$ext,$type)=split(/\:/,$item);    $env{'course.'.$env{'request.course.id'}.'.domain'},
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
  $nocopy=1;      $r->print(&Apache::loncommon::confirmwrapper(
  last;                  &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
     }   } else {
  }      $r->print(&Apache::loncommon::confirmwrapper(
     }                  &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
  }   }
         if ($url=~/^\/res\/lib\/templates\//) {   &mark_hash_old();
            $nocopy=1;      }
            $nocut=1;      &changewarning($r,'');
         }      if ($env{'form.timerange'} eq 'all') {
         my $copylink='&nbsp;';  # show all documents
         my $cutlink='&nbsp;';   $header=&mt('All Documents in '.$crstype);
    $allsel=1;
  my $skip_confirm = 0;   foreach my $key (keys(%hash)) {
  if ( $folder =~ /^supplemental/      if ($key=~/^ids\_(\/res\/.+)$/) {
      || ($url =~ m{( /smppg$   my $src=$1;
     |/syllabus$   $changes{$src}=1;
     |/aboutme$      }
     |/navmaps$   }
     |/bulletinboard$      } else {
     |\.html$  # show documents which changed
     |^/adm/wrapper/ext)}x)) {   %changes=&Apache::lonnet::dump
     $skip_confirm = 1;   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
  }                       $env{'course.'.$env{'request.course.id'}.'.num'});
    my $firstkey=(keys(%changes))[0];
  if (!$nocopy) {   unless ($firstkey=~/^error\:/) {
     $copylink=(<<ENDCOPY);      unless ($env{'form.timerange'}) {
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>   $env{'form.timerange'}=604800;
 ENDCOPY      }
         }      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
  if (!$nocut) {   .&mt('seconds');
     $cutlink=(<<ENDCUT);      if ($env{'form.timerange'}==-1) {
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>   $seltext='since start of course';
 ENDCUT   $startsel='selected';
         }   $env{'form.timerange'}=time;
  $form_start = (<<END);      }
    <form  action="/adm/coursedocs" method="post">      $starttime=time-$env{'form.timerange'};
    <input type="hidden" name="${type}path" value="$path" />      if ($env{'form.timerange'}==2592000) {
    <input type="hidden" name="${type}symb" value="$symb" />   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    <input type="hidden" name="setparms" value="$orderidx" />   $monthsel='selected';
    <input type="hidden" name="changeparms" value="0" />      } elsif ($env{'form.timerange'}==604800) {
 END   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
         $form_end = '</form>';   $weeksel='selected';
  $line.=(<<END);      } elsif ($env{'form.timerange'}==86400) {
 <td>   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    <table class="LC_docs_entry_move">   $daysel='selected';
       <tr>      }
          <td>      $header=&mt('Content changed').' '.$seltext;
             <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>   } else {
          </td>      $header=&mt('No content modifications yet.');
       </tr>   }
       <tr>      }
         <td>      %setversions=&Apache::lonnet::dump('resourceversions',
            <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'}.'.domain'},
         </td>    $env{'course.'.$env{'request.course.id'}.'.num'});
       </tr>      my %lt=&Apache::lonlocal::texthash
     </table>        ('st' => 'Version changes since start of '.$crstype,
 </td>         'lm' => 'Version changes since last Month',
 <td>         'lw' => 'Version changes since last Week',
    $form_start         'sy' => 'Version changes since Yesterday',
    $selectbox                 'al' => 'All Resources (possibly large output)',
    $form_end                 'cd' => 'Change display', 
 </td>         'sd' => 'Display',
 <td class="LC_docs_entry_commands">         'fi' => 'File',
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>         'md' => 'Modification Date',
 $cutlink                 'mr' => 'Most recently published Version',
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>         've' => 'Version used in '.$crstype,
 $copylink                 'vu' => 'Set Version to be used in '.$crstype,
 </td>  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
 END  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
   'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
     }         'di' => 'Differences',
 # Figure out what kind of a resource this is         'save' => 'Save changes',
     my ($extension)=($url=~/\.(\w+)$/);                 'vers' => 'Version choice(s) for specific resources', 
     my $uploaded=($url=~/^\/*uploaded\//);         'act' => 'Actions');
     my $icon=&Apache::loncommon::icon($url);      $r->print(<<ENDHEADERS);
     my $isfolder=0;  <h4 class="LC_info">$header</h4>
     my $ispage=0;  <form action="/adm/coursedocs" method="post">
     my $folderarg;  <input type="hidden" name="versions" value="1" />
     my $pagearg;  <div class="LC_left_float">
     my $pagefile;  <fieldset>
     if ($uploaded) {  <legend>$lt{'cd'}</legend>
  if ($extension eq 'sequence') {  <select name="timerange">
     $icon=$iconpath.'/folder_closed.gif';  <option value='all' $allsel>$lt{'al'}</option>
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;  <option value="-1" $startsel>$lt{'st'}</option>
     $url='/adm/coursedocs?';  <option value="2592000" $monthsel>$lt{'lm'}</option>
     $folderarg=$1;  <option value="604800" $weeksel>$lt{'lw'}</option>
     $isfolder=1;  <option value="86400" $daysel>$lt{'sy'}</option>
         } elsif ($extension eq 'page') {  </select>
             $icon=$iconpath.'/page.gif';  <input type="submit" name="display" value="$lt{'sd'}" />
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;  </fieldset>
             $pagearg=$1;  </div>
             $url='/adm/coursedocs?';  <div class="LC_left_float">
             $ispage=1;  <fieldset>
  } else {  <legend>$lt{'act'}</legend>
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);  $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
  }  $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
     }  </fieldset>
      </div>
     my $orig_url = $url;  <br clear="all" />
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});  <hr />
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {  <h4>$lt{'vers'}</h4>
  my $symb=&Apache::lonnet::symbclean(  <input type="submit" name="setversions" value="$lt{'save'}" />
           &Apache::lonnet::declutter('uploaded/'.  <table border="0">
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.  ENDHEADERS
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.      #number of columns for version history
            '.sequence').      my $num_ver_col = 1;
            '___'.$residx.'___'.      $r->print(
    &Apache::lonnet::declutter($url));      &Apache::loncommon::start_data_table().
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);      &Apache::loncommon::start_data_table_header_row().
  $url=&Apache::lonnet::clutter($url);      '<th>'.&mt('Resources').'</th>'.
  if ($url=~/^\/*uploaded\//) {      "<th>$lt{'mr'}</th>".
     $url=~/\.(\w+)$/;      "<th>$lt{'ve'}</th>".
     my $embstyle=&Apache::loncommon::fileembstyle($1);      "<th>$lt{'vu'}</th>".
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {      '<th colspan="'.$num_ver_col.'">'.&mt('History').'</th>'.
  $url='/adm/wrapper'.$url;      '</b>');
     } elsif ($embstyle eq 'ssi') {      foreach my $key (sort(keys(%changes))) {
  #do nothing with these   if ($changes{$key}>$starttime) {
     } elsif ($url!~/\.(sequence|page)$/) {      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
  $url='/adm/coursedocs/showdoc'.$url;      my $currentversion=&Apache::lonnet::getversion($key);
     }      if ($currentversion<0) {
  } elsif ($url=~m|^/ext/|) {                  $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
     $url='/adm/wrapper'.$url;      }
     $external = 1;      my $linkurl=&Apache::lonnet::clutter($key);
  }          $r->print(
         if (&Apache::lonnet::symbverify($symb,$url)) {              &Apache::loncommon::end_data_table_header_row().
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);              &Apache::loncommon::start_data_table_row().
         } else {              '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br>'.
             $url='';              '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
         }              '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br>('.
  if ($container eq 'page') {              &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
     my $symb=$env{'form.pagesymb'};              '<td align="right">');
           # Used in course
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);      my $usedversion=$hash{'version_'.$linkurl};
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);      if (($usedversion) && ($usedversion ne 'mostrecent')) {
  }                  if($usedversion != $currentversion){
     }                      $r->print('<span class="LC_warning">'.$usedversion.'</span>');
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');                  }else{
     if ($isfolder || $extension eq 'sequence') {                      $r->print($usedversion);
  my $foldername=&escape($foldertitle);                  }
  my $folderpath=$env{'form.folderpath'};      } else {
  if ($folderpath) { $folderpath.='&' };   $r->print($currentversion);
 # Append randompick number, hidden, and encrypted with ":" to foldername,      }
 # so it gets transferred between levels      $r->print('</td><td title="'.$lt{'vu'}.'">');
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,  # Set version
                                               'parameter_randompick'))[0]      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
                                                .':'.((&LONCAPA::map::getparameter($orderidx,        'set_version_'.$linkurl,
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)        {'select_form_order' =>
                                                .':'.((&LONCAPA::map::getparameter($orderidx,         ['',1..$currentversion,'mostrecent'],
                                               'parameter_encrypturl'))[0]=~/^yes$/i)         '' => '',
                                                .':'.((&LONCAPA::map::getparameter($orderidx,         'mostrecent' => &mt('most recent'),
                                               'parameter_randomorder'))[0]=~/^yes$/i);         map {$_,$_} (1..$currentversion)}));
  $url.='folderpath='.&escape($folderpath).$cpinfo;      my $lastold=1;
  $parameterset='<label>'.&mt('Randomly Pick: ').      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.   my $url=$root.'.'.$prevvers.'.'.$extension;
     (&LONCAPA::map::getparameter($orderidx,   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
                                               'parameter_randompick'))[0].      $starttime) {
                                               '" />'.      $lastold=$prevvers;
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';   }
     my $ro_set=      }
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');              #
  $rand_order_text ='              # Code to figure out how many version entries should go in
 <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>';                # each of the four columns
     }              my $entries_per_col = 0;
     if ($ispage) {              my $num_entries = ($currentversion-$lastold);
         my $pagename=&escape($pagetitle);              if ($num_entries % $num_ver_col == 0) {
         my $pagepath;                  $entries_per_col = $num_entries/$num_ver_col;
         my $folderpath=$env{'form.folderpath'};              } else {
         if ($folderpath) { $pagepath = $folderpath.'&' };                  $entries_per_col = $num_entries/$num_ver_col + 1;
         $pagepath.=$pagearg.'&'.$pagename;              }
  my $symb=$env{'form.pagesymb'};              my $entries_count = 0;
  if (!$symb) {              $r->print('<td valign="top"><span class="LC_fontsize_medium">');
     my $path='uploaded/'.              my $cols_output = 1;
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.              for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';   my $url=$root.'.'.$prevvers.'.'.$extension;
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
        $residx,    '">'.&mt('Version').' '.$prevvers.'</a> ('.
        $path.$pagearg.'.page');    &Apache::lonlocal::locallocaltime(
  }                                  &Apache::lonnet::metadata($url,
  $url.='pagepath='.&escape($pagepath).                                                            'lastrevisiondate')
     '&amp;pagesymb='.&escape($symb).$cpinfo;                                                              ).
     }    ')');
     if ($external) {   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';                      $r->print(' <a href="/adm/diff?filename='.
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';        &Apache::lonnet::clutter($root.'.'.$extension).
     } else {        '&versionone='.$prevvers.
  undef($external);        '" target="diffs">'.&mt('Diffs').'</a>');
     }   }
     $line.='   $r->print('</span><br />');
   <td class="LC_docs_entry_icon">                  if (++$entries_count % $entries_per_col == 0) {
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'                      $r->print('</span></td>');
   </td>                      if ($cols_output != $num_ver_col) {
   <td class="LC_docs_entry_title">                          $r->print('<td valign="top"><span class="LC_fontsize_medium">');
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."                          $cols_output++;
   </td>";                      }
     if (($allowed) && ($folder!~/^supplemental/)) {                  }
   my %lt=&Apache::lonlocal::texthash(      }
        'hd' => 'Hidden',              while($cols_output++ < $num_ver_col) {
        'ec' => 'URL hidden');                  $r->print('</span></td><td>');
  my $enctext=              }
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');   }
  my $hidtext=      }
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');      $r->print('</td>'.&Apache::loncommon::end_data_table_row().
  $line.=(<<ENDPARMS);              &Apache::loncommon::end_data_table().
   <td class="LC_docs_entry_parameter">              '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />');
     $form_start  
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>      &untiehash();
     $form_end  }
   </td>  
   <td class="LC_docs_entry_parameter">  sub mark_hash_old {
     $form_start      my $retie_hash=0;
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>      if ($hashtied) {
     $form_end   $retie_hash=1;
   </td>   &untiehash();
   <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>      &tiehash('write');
 ENDPARMS      $hash{'old'}=1;
     }      &untiehash();
     $line.="</tr>";      if ($retie_hash) { &tiehash(); }
     return $line;  }
 }  
   sub is_hash_old {
 =pod      my $untie_hash=0;
       if (!$hashtied) {
 =item tiehash()   $untie_hash=1;
    &tiehash();
 tie the hash      }
       my $return=$hash{'old'};
 =cut      if ($untie_hash) { &untiehash(); }
       return $return;
 sub tiehash {  }
     my ($mode)=@_;  
     $hashtied=0;  sub changewarning {
     if ($env{'request.course.fn'}) {      my ($r,$postexec,$message,$url)=@_;
  if ($mode eq 'write') {      if (!&is_hash_old()) { return; }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      my $pathvar='folderpath';
     &GDBM_WRCREAT(),0640)) {      my $path=&escape($env{'form.folderpath'});
                 $hashtied=2;      if (!defined($url)) {
     }   if (defined($env{'form.pagepath'})) {
  } else {      $pathvar='pagepath';
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      $path=&escape($env{'form.pagepath'});
     &GDBM_READER(),0640)) {      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
                 $hashtied=1;   }
     }   $url='/adm/coursedocs?'.$pathvar.'='.$path;
  }      }
     }          my $course_type = &Apache::loncommon::course_type();
 }      if (!defined($message)) {
    $message='Changes will become active for your current session after [_1], or the next time you log in.';
 sub untiehash {      }
     if ($hashtied) { untie %hash; }      $r->print("\n\n".
     $hashtied=0;  '<script type="text/javascript">'."\n".
     return OK;  '// <![CDATA['."\n".
 }  'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
   '// ]]>'."\n".
   '</script>'."\n".
   '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
   '<input type="hidden" name="orgurl" value="'.$url.
 sub checkonthis {  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
     my ($r,$url,$level,$title)=@_;  &mt($message,' <input type="hidden" name="'.
     $url=&unescape($url);      $env{'request.role'}.'" value="1" /><input type="button" value="'.
     $alreadyseen{$url}=1;      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
     $r->rflush();  $help{'Caching'}.'</p></form>'."\n\n");
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {  }
        $r->print("\n<br />");  
        if ($level==0) {  
            $r->print("<br />");  sub init_breadcrumbs {
        }      my ($form,$text)=@_;
        for (my $i=0;$i<=$level*5;$i++) {      &Apache::lonhtmlcommon::clear_breadcrumbs();
            $r->print('&nbsp;');      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
        }      text=>&Apache::loncommon::course_type().' Editor',
        $r->print('<a href="'.$url.'" target="cat">'.      faq=>273,
  ($title?$title:$url).'</a> ');      bug=>'Instructor Interface',
        if ($url=~/^\/res\//) {                                              help => 'Docs_Adding_Course_Doc'});
   my $result=&Apache::lonnet::repcopy(      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
                               &Apache::lonnet::filelocation('',$url));      text=>$text,
           if ($result eq 'ok') {      faq=>273,
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');      bug=>'Instructor Interface'});
              $r->rflush();  }
              &Apache::lonnet::countacc($url);  
              $url=~/\.(\w+)$/;  # subroutine to list form elements
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {  sub create_list_elements {
  $r->print('<br />');     my @formarr = @_;
                  $r->rflush();     my $list = '';
                  for (my $i=0;$i<=$level*5;$i++) {     for my $button (@formarr){
                      $r->print('&nbsp;');          for my $picture(keys %$button) {
                  }              $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text'});
                  $r->print('- '.&mt('Rendering:').' ');          }
  my ($errorcount,$warningcount)=split(/:/,     }
        &Apache::lonnet::ssi_body($url,     return $list;
        ('grade_target'=>'web',  }
  'return_only_error_and_warning_counts' => 1)));  
                  if (($errorcount) ||  # subroutine to create ul from list elements
                      ($warningcount)) {  sub create_form_ul {
      if ($errorcount) {     my $list = shift;
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.     my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
                           &mt('[quant,_1,error]',$errorcount).'</span>');     return $ul;
                      }  }
      if ($warningcount) {  
                         $r->print('<span class="LC_warning">'.  #
                           &mt('[quant,_1,warning]',$warningcount).'</span>');  # Start tabs
                      }  #
                  } else {  
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');  sub startContentScreen {
                  }      my ($mode) = @_;
                  $r->rflush();      my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
              }      if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
      my $dependencies=          $output .= '<li'.(($mode eq 'navmaps')?' class="active"':'').'><a href="/adm/navmaps"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Overview').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
                 &Apache::lonnet::metadata($url,'dependencies');          $output .= '<li'.(($mode eq 'coursesearch')?' class="active"':'').'><a href="/adm/searchcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Search').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
              foreach my $dep (split(/\,/,$dependencies)) {          $output .= '<li'.(($mode eq 'courseindex')?' class="active"':'').'><a href="/adm/indexcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Index').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
                     &checkonthis($r,$dep,$level+1);      } else {
                  }          $output .= '<li '.(($mode eq 'docs')?' class="active"':'').' id="tabbededitor"><a href="/adm/coursedocs?forcestandard=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Editor').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
              }          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
           } elsif ($result eq 'unavailable') {          $output .= '<li '.(($mode eq 'tools')?' class="active"':'').'><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');                     '><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>';
           } elsif ($result eq 'not_found') {      }
       unless ($url=~/\$/) {      $output .= "\n".'</ul>'."\n";
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');      $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
       } else {                 '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');                 '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
       }      return $output;
           } else {  }
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');  
           }  #
        }  # End tabs
     }  #
 }  
   sub endContentScreen {
       return '</div></div></div>';
   }
 =pod  
   sub supplemental_base {
 =item list_symbs()      return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
   }
 List Symbs  
   sub handler {
 =cut      my $r = shift;
       &Apache::loncommon::content_type($r,'text/html');
 sub list_symbs {      $r->send_http_header;
     my ($r) = @_;      return OK if $r->header_only;
   
     my $type = &Apache::loncommon::course_type();  # get course data
     $r->print(&Apache::loncommon::start_page('Symb List'));      my $crstype = &Apache::loncommon::course_type();
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
     my $navmap = Apache::lonnavmaps::navmap->new();      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
     if (!defined($navmap)) {  
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.  # graphics settings
                   '<div class="LC_error">'.      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
                   &mt('Unable to retrieve information about course contents').  
                   '</div>');  #
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});  # --------------------------------------------- Initialize help topics for this
     } else {      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
         $r->print("<pre>\n");                 'Adding_External_Resource','Navigate_Content',
         foreach my $res ($navmap->retrieveResources()) {                 'Adding_Folders','Docs_Overview', 'Load_Map',
     $r->print($res->compTitle()."\t".$res->symb()."\n");                 'Supplemental','Score_Upload_Form','Adding_Pages',
         }                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
         $r->print("\n</pre>\n");                 'Check_Resource_Versions','Verify_Content') {
     }   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');      }
 }      # Composite help files
       $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 sub verifycontent {      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
     my ($r) = @_;      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
     my $type = &Apache::loncommon::course_type();      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
    my $loaderror=&Apache::lonnet::overloaderror($r);      'Option_Response_Simple');
    if ($loaderror) { return $loaderror; }      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
    $hashtied=0;    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
    undef %alreadyseen;      $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
    %alreadyseen=();      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
    &tiehash();  
    foreach my $key (keys(%hash)) {      
        if ($hash{$key}=~/\.(page|sequence)$/) {      my $allowed;
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {  # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
        $r->print('<hr /><span class="LC_error">'.      unless ($r->uri eq '/adm/supplemental') {
  &mt('The following sequence or page is included more than once in your '.$type.': ').          # does this user have privileges to modify content.  
  &unescape($hash{$key}).'</span><br />'.          $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));      }
    }  
        }      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {                                              'inhibitmenu']);
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});    if ($allowed && $env{'form.chooseserver'}) {
        }        &choose_dump_server($r);
    }        return OK;
    &untiehash();    } elsif ($allowed && $env{'form.verify'}) {
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.        &init_breadcrumbs('verify','Verify Content');
      &mt('Return to DOCS').'</a>');        &verifycontent($r);
 }    } elsif ($allowed && $env{'form.listsymbs'}) {
         &init_breadcrumbs('listsymbs','List Content IDs');
         &list_symbs($r);
 sub devalidateversioncache {    } elsif ($allowed && $env{'form.docslog'}) {
     my $src=shift;        &init_breadcrumbs('docslog','Show Log');
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.        my $folder = $env{'form.folder'};
   &Apache::lonnet::clutter($src));        if ($folder eq '') {
 }            $folder='default';
         }
 sub checkversions {        &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
     my ($r) = @_;    } elsif ($allowed && $env{'form.versions'}) {
     my $type = &Apache::loncommon::course_type();        &init_breadcrumbs('versions','Check/Set Resource Versions');
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));        &checkversions($r);
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));    } elsif ($allowed && $env{'form.dumpcourse'}) {
     my $header='';        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
     my $startsel='';        &dumpcourse($r);
     my $monthsel='';    } elsif ($allowed && $env{'form.exportcourse'}) {
     my $weeksel='';        &init_breadcrumbs('exportcourse','IMS Export');
     my $daysel='';        &Apache::imsexport::exportcourse($r);
     my $allsel='';    } else {
     my %changes=();  #
     my $starttime=0;  # Done catching special calls
     my $haschanged=0;  # The whole rest is for course and supplemental documents and utilities menu
     my %setversions=&Apache::lonnet::dump('resourceversions',  # Get the parameters that may be needed
   $env{'course.'.$env{'request.course.id'}.'.domain'},  #
   $env{'course.'.$env{'request.course.id'}.'.num'});      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                               ['folderpath','pagepath',
     $hashtied=0;                                               'pagesymb','forcesupplement','forcestandard',
     &tiehash();                                               'tools','symb','command']);
     my %newsetversions=();  
     if ($env{'form.setmostrecent'}) {  # standard=1: this is a "new-style" course with an uploaded map as top level
  $haschanged=1;  # standard=2: this is a "old-style" course, and there is nothing we can do
  foreach my $key (keys(%hash)) {  
     if ($key=~/^ids\_(\/res\/.+)$/) {      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
  $newsetversions{$1}='mostrecent';  
                 &devalidateversioncache($1);  # Decide whether this should display supplemental or main content or utilities
     }  # supplementalflag=1: show supplemental documents
  }  # supplementalflag=0: show standard documents
     } elsif ($env{'form.setcurrent'}) {  # toolsflag=1: show utilities
  $haschanged=1;  
  foreach my $key (keys(%hash)) {  
     if ($key=~/^ids\_(\/res\/.+)$/) {      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
  my $getvers=&Apache::lonnet::getversion($1);      if (($env{'form.folderpath'}=~/^default/) || $env{'form.folderpath'} eq "" || ($env{'form.pagepath'})) {
  if ($getvers>0) {         $supplementalflag=0;
     $newsetversions{$1}=$getvers;      }
     &devalidateversioncache($1);      if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
  }      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
     }      unless ($allowed) { $supplementalflag=1; }
  }      unless ($standard) { $supplementalflag=1; }
     } elsif ($env{'form.setversions'}) {      my $toolsflag=0;
  $haschanged=1;      if ($env{'form.tools'}) { $toolsflag=1; }
  foreach my $key (keys(%env)) {  
     if ($key=~/^form\.set_version_(.+)$/) {      my $script='';
  my $src=$1;      my $showdoc=0;
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {      my $addentries = {};
     $newsetversions{$src}=$env{$key};      my $container;
     &devalidateversioncache($src);      my $containertag;
  }      my $uploadtag;
     }  
  }  # Do we directly jump somewhere?
     }  
     if ($haschanged) {     if ($env{'form.command'} eq 'direct') {
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,         my ($mapurl,$id,$resurl);
   $env{'course.'.$env{'request.course.id'}.'.domain'},         if ($env{'form.symb'} ne '') {
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {             ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($env{'form.symb'});
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');             if ($resurl=~/\.(sequence|page)$/) {
  } else {                 $mapurl=$resurl;
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');             } elsif ($resurl eq 'adm/navmaps') {
  }                 $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
  &mark_hash_old();             }
     }             my $mapresobj;
     &changewarning($r,'');             my $navmap = Apache::lonnavmaps::navmap->new();
     if ($env{'form.timerange'} eq 'all') {             if (ref($navmap)) {
 # show all documents                 $mapresobj = $navmap->getResourceByUrl($mapurl);
  $header=&mt('All Documents in '.$type);             }
  $allsel=1;             $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
  foreach my $key (keys(%hash)) {             my $type=$2;
     if ($key=~/^ids\_(\/res\/.+)$/) {             my $path;
  my $src=$1;             if (ref($mapresobj)) {
  $changes{$src}=1;                 my $pcslist = $mapresobj->map_hierarchy();
     }                 if ($pcslist ne '') {
  }                     foreach my $pc (split(/,/,$pcslist)) {
     } else {                         next if ($pc <= 1);
 # show documents which changed                         my $res = $navmap->getByMapPc($pc);
  %changes=&Apache::lonnet::dump                         if (ref($res)) {
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},                             my $thisurl = $res->src();
                      $env{'course.'.$env{'request.course.id'}.'.num'});                             $thisurl=~s{^.*/([^/]+)\.\w+$}{$1}; 
  my $firstkey=(keys(%changes))[0];                             my $thistitle = $res->title();
  unless ($firstkey=~/^error\:/) {                             $path .= '&'.
     unless ($env{'form.timerange'}) {                                      &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
  $env{'form.timerange'}=604800;                                      &Apache::lonhtmlcommon::entity_encode($thistitle).
     }                                      ':'.$res->randompick().
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '                                      ':'.$res->randomout().
  .&mt('seconds');                                      ':'.$res->encrypted().
     if ($env{'form.timerange'}==-1) {                                      ':'.$res->randomorder();
  $seltext='since start of course';                         }
  $startsel='selected';                     }
  $env{'form.timerange'}=time;                 }
     }                 $path .= '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
     $starttime=time-$env{'form.timerange'};                      &Apache::lonhtmlcommon::entity_encode($mapresobj->title()).
     if ($env{'form.timerange'}==2592000) {                      ':'.$mapresobj->randompick().
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                      ':'.$mapresobj->randomout().
  $monthsel='selected';                      ':'.$mapresobj->encrypted().
     } elsif ($env{'form.timerange'}==604800) {                      ':'.$mapresobj->randomorder();
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';             } else {
  $weeksel='selected';                 my $maptitle = &Apache::lonnet::gettitle($mapurl);
     } elsif ($env{'form.timerange'}==86400) {                 $path = '&default&...::::'.
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                     '&'.&Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
  $daysel='selected';                     &Apache::lonhtmlcommon::entity_encode($maptitle).'::::';
     }             }
     $header=&mt('Content changed').' '.$seltext;             $path = 'default&'.
  } else {                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
     $header=&mt('No content modifications yet.');                     $path;
  }             if ($type eq 'sequence') {
     }                 $env{'form.folderpath'}=$path;
     %setversions=&Apache::lonnet::dump('resourceversions',                 $env{'form.pagepath'}='';
   $env{'course.'.$env{'request.course.id'}.'.domain'},             } else {
   $env{'course.'.$env{'request.course.id'}.'.num'});                 $env{'form.pagepath'}=$path;
     my %lt=&Apache::lonlocal::texthash                 $env{'form.folderpath'}='';
       ('st' => 'Version changes since start of '.$type,             }
        'lm' => 'Version changes since last Month',         } elsif ($env{'form.supppath'} ne '') {
        'lw' => 'Version changes since last Week',             $env{'form.folderpath'}=$env{'form.supppath'};
        'sy' => 'Version changes since Yesterday',         }
                'al' => 'All Resources (possibly large output)',     } elsif ($env{'form.command'} eq 'editdocs') {
        'sd' => 'Display',          $env{'form.folderpath'} = 'default&'.
        'fi' => 'File',                                    &Apache::lonhtmlcommon::entity_encode('Main Course Content');
        'md' => 'Modification Date',          $env{'form.pagepath'}='';
                'mr' => 'Most recently published Version',     } elsif ($env{'form.command'} eq 'editsupp') {
        've' => 'Version used in '.$type,          $env{'form.folderpath'} = 'default&'.
                'vu' => 'Set Version to be used in '.$type,                                    &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',          $env{'form.pagepath'}='';
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',     }
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',  
        'di' => 'Differences');  # Where do we store these for when we come back?
     $r->print(<<ENDHEADERS);      my $stored_folderpath='docs_folderpath';
 <form action="/adm/coursedocs" method="post">      if ($supplementalflag) {
 <input type="hidden" name="versions" value="1" />         $stored_folderpath='docs_sup_folderpath';
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />      }
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />  
 <select name="timerange">  # No folderpath, no pagepath, see if we have something stored
 <option value='all' $allsel>$lt{'al'}</option>      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
 <option value="-1" $startsel>$lt{'st'}</option>          &Apache::loncommon::restore_course_settings($stored_folderpath,
 <option value="2592000" $monthsel>$lt{'lm'}</option>                                                {'folderpath' => 'scalar'});
 <option value="604800" $weeksel>$lt{'lw'}</option>      }
 <option value="86400" $daysel>$lt{'sy'}</option>     
 </select>  # If we are not allowed to make changes, all we can see are supplemental docs
 <input type="submit" name="display" value="$lt{'sd'}" />      if (!$allowed) {
 <h3>$header</h3>          $env{'form.pagepath'}='';
 <input type="submit" name="setversions" value="$lt{'sv'}" />          unless ($env{'form.folderpath'} =~ /^supplemental/) {
 <table border="0">              $env{'form.folderpath'} = &supplemental_base();
 ENDHEADERS          }
     foreach my $key (sort(keys(%changes))) {      }
  if ($changes{$key}>$starttime) {  # If we still not have a folderpath, see if we can resurrect at pagepath
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);      if (!$env{'form.folderpath'} && $allowed) {
     my $currentversion=&Apache::lonnet::getversion($key);          &Apache::loncommon::restore_course_settings($stored_folderpath,
     if ($currentversion<0) {                                                {'pagepath' => 'scalar'});
  $currentversion=&mt('Could not be determined.');      }
     }  # Make the zeroth entry in supplemental docs page paths, so we can get to top level
     my $linkurl=&Apache::lonnet::clutter($key);      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
     $r->print(          $env{'form.folderpath'} = &supplemental_base()
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.                                    .'&'.
       &Apache::lonnet::gettitle($linkurl).                                    $env{'form.folderpath'};
                       '</b></font></td></tr>'.      }
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.  # If after all of this, we still don't have any paths, make them
                       '<td colspan="4">'.      unless (($env{'form.pagepath'}) || ($env{'form.folderpath'})) {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.         if ($supplementalflag) {
       '</a></td></tr>'.            $env{'form.folderpath'}=&supplemental_base();
                       '<tr><td></td>'.         } else {
                       '<td title="'.$lt{'md'}.'">'.            $env{'form.folderpath'}='default';
       &Apache::lonlocal::locallocaltime(         }
                            &Apache::lonnet::metadata($root.'.'.$extension,      }
                                                      'lastrevisiondate')  
                                                         ).  # Store this
                       '</td>'.      unless ($toolsflag) {
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.          &Apache::loncommon::store_course_settings($stored_folderpath,
                       '<font size="+1">'.$currentversion.'</font>'.                                                    {'pagepath' => 'scalar',
                       '</span></td>'.                                                     'folderpath' => 'scalar'});
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.          if ($env{'form.folderpath'}) {
                       '<font size="+1">');      my (@folderpath)=split('&',$env{'form.folderpath'});
 # Used in course      $env{'form.foldername'}=&unescape(pop(@folderpath));
     my $usedversion=$hash{'version_'.$linkurl};      $env{'form.folder'}=pop(@folderpath);
     if (($usedversion) && ($usedversion ne 'mostrecent')) {              $container='sequence';
  $r->print($usedversion);          }
     } else {          if ($env{'form.pagepath'}) {
  $r->print($currentversion);              my (@pagepath)=split('&',$env{'form.pagepath'});
     }              $env{'form.pagename'}=&unescape(pop(@pagepath));
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.              $env{'form.folder'}=pop(@pagepath);
                       '<span class="LC_nobreak">Use: ');              $container='page';
 # Set version              $containertag = '<input type="hidden" name="pagepath" value="" />'.
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},                      '<input type="hidden" name="pagesymb" value="" />';
       'set_version_'.$linkurl,              $uploadtag = 
       ('select_form_order' =>                  '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
        ['',1..$currentversion,'mostrecent'],          '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />'.
        '' => '',                  '<input type="hidden" name="folderpath" value="" />';
        'mostrecent' => 'most recent',          } else {
        map {$_,$_} (1..$currentversion))));              my $folderpath=$env{'form.folderpath'};
     $r->print('</span></td></tr><tr><td></td>');              if (!$folderpath) {
     my $lastold=1;                  if ($env{'form.folder'} eq '' ||
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {                      $env{'form.folder'} eq 'supplemental') {
  my $url=$root.'.'.$prevvers.'.'.$extension;                      $folderpath='default&'.
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                          &escape(&mt('Main '.$crstype.' Documents'));
     $starttime) {                  }
     $lastold=$prevvers;              }
  }              $containertag = '<input type="hidden" name="folderpath" value="" />';
     }              $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
             #          }
             # Code to figure out how many version entries should go in          if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
             # each of the four columns             $showdoc='/'.$1;
             my $entries_per_col = 0;          }
             my $num_entries = ($currentversion-$lastold);          if ($showdoc) { # got called in sequence from course
             if ($num_entries % 4 == 0) {      $allowed=0; 
                 $entries_per_col = $num_entries/4;          } else {
             } else {              if ($allowed) {
                 $entries_per_col = $num_entries/4 + 1;                  &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
             }                  $script=&Apache::lonratedt::editscript('simple');
             my $entries_count = 0;              }
             $r->print('<td valign="top"><font size="-2">');          }
             my $cols_output = 1;      }
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {  
  my $url=$root.'.'.$prevvers.'.'.$extension;  # get personal data
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).      my $uname=$env{'user.name'};
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      my $udom=$env{'user.domain'};
   &Apache::lonlocal::locallocaltime(      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
                                 &Apache::lonnet::metadata($url,  
                                                           'lastrevisiondate')      if ($allowed) {
                                                             ).          if ($toolsflag) {
   ')');              $script .= &inject_data_js();
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {              my ($home,$other,%outhash)=&authorhosts();
                     $r->print(' <a href="/adm/diff?filename='.              if (!$home && $other) {
       &Apache::lonnet::clutter($root.'.'.$extension).                  my @hosts;
       '&versionone='.$prevvers.                  foreach my $aurole (keys(%outhash)) {
       '">'.&mt('Diffs').'</a>');                      unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
  }                          push(@hosts,$outhash{$aurole});
  $r->print('</span><br />');                      }
                 if (++$entries_count % $entries_per_col == 0) {                  }
                     $r->print('</font></td>');                  $script .= &dump_switchserver_js(@hosts); 
                     if ($cols_output != 4) {              }
                         $r->print('<td valign="top"><font size="-2">');          } else {
                         $cols_output++;              my @tabids;
                     }              if ($supplementalflag) {
                 }                  @tabids = ('002','ee2','ff2');
     }              } else {
             while($cols_output++ < 4) {                  @tabids = ('aa1','bb1','cc1','ff1');
                 $r->print('</font></td><td><font>')                  unless ($env{'form.pagepath'}) {
             }                      unshift(@tabids,'001');
     $r->print('</font></td></tr>'."\n");                      push(@tabids,('dd1','ee1'));
  }                  }
     }              }
     $r->print('</table></form>');              my $tabidstr = join("','",@tabids);
     $r->print('<h1>'.&mt('Done').'.</h1>');      $script .= &editing_js($udom,$uname,$supplementalflag).
                          &history_tab_js().
     &untiehash();                         &inject_data_js().
 }                         &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr);
               $addentries = {
 sub mark_hash_old {                              onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
     my $retie_hash=0;                            };
     if ($hashtied) {          }
  $retie_hash=1;      }
  &untiehash();  # -------------------------------------------------------------------- Body tag
     }      $script = '<script type="text/javascript">'."\n"
     &tiehash('write');                .'// <![CDATA['."\n"
     $hash{'old'}=1;                .$script."\n"
     &untiehash();                .'// ]]>'."\n"
     if ($retie_hash) { &tiehash(); }                .'</script>'."\n";
 }  
       # Breadcrumbs
 sub is_hash_old {      &Apache::lonhtmlcommon::clear_breadcrumbs();
     my $untie_hash=0;      unless ($showdoc) {
     if (!$hashtied) {          &Apache::lonhtmlcommon::add_breadcrumb({
  $untie_hash=1;              href=>"/adm/coursedocs",text=>"$crstype Contents"});
  &tiehash();  
     }          $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
     my $return=$hash{'old'};                                                   {'force_register' => $showdoc,
     if ($untie_hash) { &untiehash(); }                                                    'add_entries'    => $addentries,
     return $return;                                                   })
 }                   .&Apache::loncommon::help_open_menu('','',273,'RAT')
                    .&Apache::lonhtmlcommon::breadcrumbs(
 sub changewarning {                       'Editing '.$crstype.' Contents',
     my ($r,$postexec,$message,$url)=@_;                       'Docs_Adding_Course_Doc')
     if (!&is_hash_old()) { return; }          );
     my $pathvar='folderpath';      } else {
     my $path=&escape($env{'form.folderpath'});          $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
     if (!defined($url)) {                                                  {'force_register' => $showdoc,}));
  if (defined($env{'form.pagepath'})) {      }
     $pathvar='pagepath';  
     $path=&escape($env{'form.pagepath'});    my %allfiles = ();
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});    my %codebase = ();
  }    my ($upload_result,$upload_output,$uploadphase);
  $url='/adm/coursedocs?'.$pathvar.'='.$path;    if ($allowed) {
     }        if (($env{'form.uploaddoc.filename'}) &&
     my $course_type = &Apache::loncommon::course_type();    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
     if (!defined($message)) {            my $context = $1; 
  $message='Changes will become active for your current session after [_1], or the next time you log in.';            # Process file upload - phase one - upload and parse primary file.
     }    undef($hadchanges);
     $r->print("\n\n".            $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".                                                \%allfiles,\%codebase,$context);
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.    if ($hadchanges) {
 '<input type="hidden" name="orgurl" value="'.$url.        &mark_hash_old();
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.    }
 &mt($message,' <input type="hidden" name="'.            $r->print($upload_output);
     $env{'request.role'}.'" value="1" /><input type="button" value="'.        } elsif ($env{'form.phase'} eq 'upload_embedded') {
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').            # Process file upload - phase two - upload embedded objects 
 $help{'Caching'}.'</span></h3></form>'."\n\n");            $uploadphase = 'check_embedded';
 }            my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
             my $state = &embedded_form_elems($uploadphase,$primaryurl,
                                              $env{'form.newidx'});
 sub init_breadcrumbs {            my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
     my ($form,$text)=@_;            my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
     &Apache::lonhtmlcommon::clear_breadcrumbs();            my ($destination,$dir_root) = &embedded_destination();
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",            my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
     text=>"Edit ".&Apache::loncommon::course_type(),            my $actionurl = '/adm/coursedocs';
     faq=>273,            my ($result,$flag) = 
     bug=>'Instructor Interface',                &Apache::loncommon::upload_embedded('coursedoc',$destination,
                                             help => 'Docs_Adding_Course_Doc'});                    $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',                    $actionurl);
     text=>$text,            $r->print($result.&return_to_editor());
     faq=>273,        } elsif ($env{'form.phase'} eq 'check_embedded') {
     bug=>'Instructor Interface'});            # Process file upload - phase three - modify references in HTML file
 }            $uploadphase = 'modified_orightml';
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $result = 
 sub handler {                &Apache::loncommon::modify_html_refs('coursedoc',$destination,
     my $r = shift;                                                     $docuname,$docudom,undef,
     &Apache::loncommon::content_type($r,'text/html');                                                     $dir_root);
     $r->send_http_header;            $r->print($result.&return_to_editor());   
     return OK if $r->header_only;        } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
     my $type = &Apache::loncommon::course_type();            $uploadphase = 'decompress_phase_one';
             $r->print(&decompression_phase_one().
                       &return_to_editor());
 # --------------------------------------------- Initialize help topics for this        } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',            $uploadphase = 'decompress_phase_two';
                'Adding_External_Resource','Navigate_Content',            $r->print(&decompression_phase_two().
                'Adding_Folders','Docs_Overview', 'Load_Map',                      &return_to_editor());
                'Supplemental','Score_Upload_Form','Adding_Pages',        }
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',    }
                'Check_Resource_Versions','Verify_Content') {  
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);    if ($allowed && $toolsflag) {
     }        $r->print(&startContentScreen('tools'));
     # Composite help files        $r->print(&generate_admin_menu($crstype));
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(        $r->print(&endContentScreen());
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');    } elsif ((!$showdoc) && (!$uploadphase)) {
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(  # -----------------------------------------------------------------------------
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');         my %lt=&Apache::lonlocal::texthash(
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(                  'uplm' => 'Upload a new main '.lc($crstype).' document',
     'Option_Response_Simple');                  'upls' => 'Upload a new supplemental '.lc($crstype).' document',
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(                  'impp' => 'Import a document',
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');   'copm' => 'All documents out of a published map into this folder',
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(                  'upld' => 'Import Document',
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');                  'srch' => 'Search',
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');                  'impo' => 'Import',
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');   'wish' => 'Import from Wishlist',
                   'selm' => 'Select Map',
 # does this user have privileges to modify docs                  'load' => 'Load Map',
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});                  'reco' => 'Recover Deleted Documents',
   if ($allowed && $env{'form.verify'}) {                  'newf' => 'New Folder',
       &init_breadcrumbs('verify','Verify Content');                  'newp' => 'New Composite Page',
       &verifycontent($r);                  'extr' => 'External Resource',
   } elsif ($allowed && $env{'form.listsymbs'}) {                  'syll' => 'Syllabus',
       &init_breadcrumbs('listsymbs','List Symbs');                  'navc' => 'Table of Contents',
       &list_symbs($r);                  'sipa' => 'Simple Course Page',
   } elsif ($allowed && $env{'form.docslog'}) {                  'sipr' => 'Simple Problem',
       &init_breadcrumbs('docslog','Show Log');                  'drbx' => 'Drop Box',
       &docs_change_log($r);                  'scuf' => 'External Scores (handgrade, upload, clicker)',
   } elsif ($allowed && $env{'form.versions'}) {                  'bull' => 'Discussion Board',
       &init_breadcrumbs('versions','Check/Set Resource Versions');                  'mypi' => 'My Personal Information Page',
       &checkversions($r);                  'grpo' => 'Group Portfolio',
   } elsif ($allowed && $env{'form.dumpcourse'}) {                  'rost' => 'Course Roster',
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');   'abou' => 'Personal Information Page for a User',
       &dumpcourse($r);                  'imsf' => 'IMS Import',
   } elsif ($allowed && $env{'form.exportcourse'}) {                  'imsl' => 'Import IMS package',
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');                  'file' =>  'File',
       &exportcourse($r);                  'title' => 'Title',
   } else {                  'comment' => 'Comment',
 # is this a standard course?                  'parse' => 'Upload embedded images/multimedia files if HTML file',
    'nd' => 'Upload Document',
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);   'pm' => 'Published Map',
     my $forcestandard = 0;   'sd' => 'Special Document',
     my $forcesupplement;   'mo' => 'More Options',
     my $script='';    );
     my $showdoc=0;  # -----------------------------------------------------------------------------
     my $containertag;   my $fileupload=(<<FIUP);
     my $uploadtag;   $lt{'file'}:<br />
    <input type="file" name="uploaddoc" size="40" />
   FIUP
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  
     ['folderpath','pagepath',   my $checkbox=(<<CHBO);
      'pagesymb']);   <!-- <label>$lt{'parse'}?
 # No folderpath, no pagepath, see if we have something stored   <input type="checkbox" name="parserflag" />
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {   </label> -->
         &Apache::loncommon::restore_course_settings('docs_folderpath',   <label>
                                               {'folderpath' => 'scalar'});   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
     }   </label>
     if (!$env{'form.folderpath'}) {  CHBO
         &Apache::loncommon::restore_course_settings('docs_folderpath',  
                                               {'pagepath' => 'scalar'});      my $fileuploada = "<br clear='all' /><input type='submit' value='".$lt{'upld'}."' /> $help{'Uploading_From_Harddrive'}";
     }   my $fileuploadform=(<<FUFORM);
     if ($env{'form.pagepath'}) {   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
        $env{'form.folderpath'}='';   <input type="hidden" name="active" value="aa" />
     }   $fileupload
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {   <br />
         $env{'form.folderpath'} = 'supplemental&'.   $lt{'title'}:<br />
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.   <input type="text" size="60" name="comment" />
                                   $env{'form.folderpath'};   $uploadtag
     }   <input type="hidden" name="cmd" value="upload_default" />
     &Apache::loncommon::store_course_settings('docs_folderpath',   <br />
                                                 {'pagepath' => 'scalar',   <span class="LC_nobreak" style="float:left">
                                                  'folderpath' => 'scalar'});   $checkbox
     if ($env{'form.folderpath'}) {   </span>
  my (@folderpath)=split('&',$env{'form.folderpath'});  FUFORM
  $env{'form.foldername'}=&unescape(pop(@folderpath));      $fileuploadform .= $fileuploada.'</form>';
  $env{'form.folder'}=pop(@folderpath);  
     }   my $simpleeditdefaultform=(<<SEDFFORM);
     if ($env{'form.pagepath'}) {   <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
         my (@pagepath)=split('&',$env{'form.pagepath'});   <input type="hidden" name="active" value="bb" />
         $env{'form.pagename'}=&unescape(pop(@pagepath));  SEDFFORM
         $env{'form.folder'}=pop(@pagepath);   my @simpleeditdefaultforma = ( 
         $containertag = '<input type="hidden" name="pagepath" value="" />'.   { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => "$uploadtag<a class='LC_menubuttons_link' href='javascript:groupsearch()'>$lt{'srch'}</a>" },
     '<input type="hidden" name="pagesymb" value="" />';   { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{impo}.'"  onclick="javascript:groupimport();"/>' => "<a class='LC_menubuttons_link' href='javascript:groupimport();'>$lt{'impo'}</a>$help{'Importing_LON-CAPA_Resource'}" },
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.   { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{wish}.'" onclick="javascript:open_Wishlist_Import();" />' => "<a class='LC_menubuttons_link' href='javascript:open_Wishlist_Import();'>$lt{'wish'}</a>" },
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';   );
     }   $simpleeditdefaultform .= &create_form_ul(&create_list_elements(@simpleeditdefaultforma));
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {   $simpleeditdefaultform .=(<<SEDFFORM);
        $showdoc='/'.$1;   <hr id="bb_hrule" style="width:0px;text-align:left;margin-left:0" />
     }   $lt{'copm'}<br />
     unless ($showdoc) { # got called from remote   <input type="text" size="40" name="importmap" /><br />
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||   <span class="LC_nobreak" style="float:left"><input type="button"
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {   onclick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
            $forcestandard = 1;   value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
        }   $help{'Load_Map'}</span>
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);   </form>
   SEDFFORM
        if ($allowed) {  
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);        my $extresourcesform=(<<ERFORM);
          $script=&Apache::lonratedt::editscript('simple');        <form action="/adm/coursedocs" method="post" name="newext">
        }        $uploadtag
     } else { # got called in sequence from course        <input type="hidden" name="importdetail" value="" />
        $allowed=0;        <a class="LC_menubuttons_link" href="javascript:makenewext('newext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
     }        </form>
   ERFORM
 # get course data  
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};  
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};      if ($allowed) {
    &update_paste_buffer($coursenum,$coursedom);
 # get personal data   $r->print(<<HIDDENFORM);
     my $uname=$env{'user.name'};   <form name="renameform" method="post" action="/adm/coursedocs">
     my $udom=$env{'user.domain'};     <input type="hidden" name="title" />
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));     <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
 # graphics settings     <input type="hidden" name="copyfolder" />
      $containertag
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");   </form>
   
     if ($allowed) {  HIDDENFORM
  $script .= &editing_js($udom,$uname);          $r->print(&makesimpleeditform($uploadtag)."\n".
     }                    &makedocslogform($uploadtag."\n".
 # -------------------------------------------------------------------- Body tag                                     '<input type="hidden" name="folder" value="'.
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';                                     $env{'form.folder'}.'" />'."\n"));
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];      }
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,  
     {'force_register' => $showdoc,  # Generate the tabs
                                      'bread_crumbs' => $brcrum}).      my $mode;
       &Apache::loncommon::help_open_menu('','',273,'RAT'));      if (($supplementalflag) && (!$allowed)) {
            &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
   my %allfiles = ();      } else {
   my %codebase = ();          $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
   my ($upload_result,$upload_output);      }
   if ($allowed) {  
       if (($env{'form.uploaddoc.filename'}) &&  #
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {  
 # Process file upload - phase one - upload and parse primary file.        my $savefolderpath;
   undef($hadchanges);  
           $upload_result = &process_file_upload(\$upload_output,$coursenum,      if ($allowed) {
  $coursedom,\%allfiles,         my $folder=$env{'form.folder'};
  \%codebase,$1);         if ($folder eq '' || $supplementalflag) {
   if ($hadchanges) {             $folder='default';
       &mark_hash_old();     $savefolderpath = $env{'form.folderpath'};
   }     $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
           if ($upload_result eq 'phasetwo') {             $uploadtag = '<input type="hidden" name="folderpath" value="'.
               $r->print($upload_output);         &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
           }         }
       } elsif ($env{'form.phasetwo'}) {         my $postexec='';
           my %newname = ();         if ($folder eq 'default') {
           my %origname = ();             $r->print('<script type="text/javascript">'."\n"
           my %attribs = ();                      .'// <![CDATA['."\n"
           my $updateflag = 0;                      .'this.window.name="loncapaclient";'."\n"
           my $residx = $env{'form.newidx'};                      .'// ]]>'."\n"
           my $primary_url = &unescape($env{'form.primaryurl'});                      .'</script>'."\n"
 # Process file upload - phase two - gather secondary files.         );
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {         } else {
               if ($env{'form.embedded_item_'.$i.'.filename'}) {             #$postexec='self.close();';
                   my $javacodebase;         }
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);         my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});                       '.sequence';
                   if (exists($env{'form.embedded_codebase_'.$i})) {         my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});                         '.page';
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;   my $container='sequence';
                   }   if ($env{'form.pagepath'}) {
                   my @attributes = ();      $container='page';
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {   }
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});   my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
                   } else {  
                       @attributes = ($env{'form.embedded_attrib_'.$i});   my $imspform=(<<IMSPFORM);
                   }   <form action="/adm/imsimportdocs" method="post" name="ims">
                   foreach my $attr (@attributes) {   <input type="hidden" name="folder" value="$folder" />
                       push(@{$attribs{$i}},&unescape($attr));   <a class="LC_menubuttons_link" href="javascript:makeims();">$lt{'imsf'}</a>
                   }   </form>
                   if ($javacodebase) {  IMSPFORM
                       $codebase{$i} = $javacodebase;  
                       $codebase{$i} =~ s#/$##;   my $newnavform=(<<NNFORM);
                       $updateflag = 1;   <form action="/adm/coursedocs" method="post" name="newnav">
                   }   <input type="hidden" name="active" value="cc" />
               }   $uploadtag
               unless ($newname{$i} eq $origname{$i}) {   <input type="hidden" name="importdetail" 
                   $updateflag = 1;   value="$lt{'navc'}=/adm/navmaps" />
               }   <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
           }   $help{'Navigate_Content'}
 # Process file upload - phase three - modify primary file   </form>
           if ($updateflag) {  NNFORM
               my ($content,$rtncode);   my $newsmppageform=(<<NSPFORM);
               my $updateflag = 0;   <form action="/adm/coursedocs" method="post" name="newsmppg">
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);   <input type="hidden" name="active" value="cc" />
               if ($getstatus eq 'ok') {   $uploadtag
                   foreach my $item (keys(%newname)) {   <input type="hidden" name="importdetail" value="" />
                       if ($newname{$item} ne $origname{$item}) {   <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
                           my $attrib_regexp = '';   $help{'Simple Page'}
                           if (@{$attribs{$item}} > 1) {   </form>
                               $attrib_regexp = join('|',@{$attribs{$item}});  NSPFORM
                           } else {  
                               $attrib_regexp = $attribs{$item}[0];   my $newsmpproblemform=(<<NSPROBFORM);
                           }   <form action="/adm/coursedocs" method="post" name="newsmpproblem">
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {   <input type="hidden" name="active" value="cc" />
                           }   $uploadtag
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;   <input type="hidden" name="importdetail" value="" />
                       }   <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
                       if (exists($codebase{$item})) {   $help{'Simple Problem'}
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs   </form>
                       }  
                   }  NSPROBFORM
 # Save edited file.  
                   my $saveresult;   my $newdropboxform=(<<NDBFORM);
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};   <form action="/adm/coursedocs" method="post" name="newdropbox">
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};   <input type="hidden" name="active" value="cc" />
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);   $uploadtag
               } else {   <input type="hidden" name="importdetail" value="" />
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);   <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
               }   </form>
           }  NDBFORM
       }  
   }   my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
   unless ($showdoc ||  $upload_result eq 'phasetwo') {   <input type="hidden" name="active" value="cc" />
 # -----------------------------------------------------------------------------   $uploadtag
        my %lt=&Apache::lonlocal::texthash(   <input type="hidden" name="importdetail" value="" />
                 'uplm' => 'Upload a new main '.lc($type).' document',   <a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
                 'upls' => 'Upload a new supplemental '.lc($type).' document',   $help{'Score_Upload_Form'}
                 'impp' => 'Import a document',   </form>
                 'pubd' => 'Published Documents',  NEXUFORM
  'copm' => 'All documents out of a published map into this folder',  
                 'upld' => 'Upload Document',   my $newbulform=(<<NBFORM);
                 'srch' => 'Search',   <form action="/adm/coursedocs" method="post" name="newbul">
                 'impo' => 'Import',   <input type="hidden" name="active" value="cc" />
  'book' => 'Import Bookmarks',   $uploadtag
                 'selm' => 'Select Map',   <input type="hidden" name="importdetail" value="" />
                 'load' => 'Load Map',   <a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
                 'reco' => 'Recover Deleted Resources',   $help{'Bulletin Board'}
                 'newf' => 'New Folder',   </form>
                 'newp' => 'New Composite Page',  NBFORM
                 'extr' => 'External Resource',  
                 'syll' => 'Syllabus',   my $newaboutmeform=(<<NAMFORM);
                 'navc' => 'Navigate Contents',   <form action="/adm/coursedocs" method="post" name="newaboutme">
                 'sipa' => 'Simple Page',   <input type="hidden" name="active" value="cc" />
                 'sipr' => 'Simple Problem',   $uploadtag
                 'drbx' => 'Drop Box',   <input type="hidden" name="importdetail" 
                 'scuf' => 'Score Upload Form',   value="$plainname=/adm/$udom/$uname/aboutme" />
                 'bull' => 'Bulletin Board',   <a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
                 'mypi' => 'My Personal Info',   $help{'My Personal Information Page'}
                 'grpo' => 'Group Files',   </form>
                 'rost' => 'Course Roster',  NAMFORM
  'abou' => 'About User',  
                 'imsf' => 'Import IMS package',   my $newaboutsomeoneform=(<<NASOFORM);
                 'file' =>  'File',   <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
                 'title' => 'Title',   <input type="hidden" name="active" value="cc" />
                 'comment' => 'Comment',   $uploadtag
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',   <input type="hidden" name="importdetail" value="" />
  'nd' => 'New Document',   <a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
  'pm' => 'Published Map',   </form>
  'sd' => 'Special Document',  NASOFORM
  'mo' => 'More Options',  
  'hao' => 'Hide all Options'  
   );   my $newrosterform=(<<NROSTFORM);
 # -----------------------------------------------------------------------------   <form action="/adm/coursedocs" method="post" name="newroster">
  my $fileupload=(<<FIUP);   <input type="hidden" name="active" value="cc" />
  $lt{'file'}:<br />   $uploadtag
  <input type="file" name="uploaddoc" size="40" />   <input type="hidden" name="importdetail" 
 FIUP   value="$lt{'rost'}=/adm/viewclasslist" />
    <a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
  my $checkbox=(<<CHBO);   $help{'Course Roster'}
  <!-- <label>$lt{'parse'}?   </form>
  <input type="checkbox" name="parserflag" />  NROSTFORM
  </label> -->  
  <label>  my $specialdocumentsform;
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}  my @specialdocumentsforma;
  </label>  my $gradingform;
 CHBO  my @gradingforma;
   my $communityform;
  my $fileuploadform=(<<FUFORM);  my @communityforma;
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">  my $newfolderform;
  $fileupload  my $newfolderb;
  <br />  
  $lt{'title'}:<br />   my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  <input type="text" size="50" name="comment" />  
  $uploadtag   my $newpageform=(<<NPFORM);
  <input type="hidden" name="cmd" value="upload_default" />   <form action="/adm/coursedocs" method="post" name="newpage">
  <br />   <input type="hidden" name="folderpath" value="$path" />
  <span class="LC_nobreak">   <input type="hidden" name="importdetail" value="" />
  $checkbox   <input type="hidden" name="active" value="cc" />
  </span>   <a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
  <br />   $help{'Adding_Pages'}
  <br />   </form>
  <span class="LC_nobreak">  NPFORM
  <input type="submit" value="$lt{'upld'}" />  
  $help{'Uploading_From_Harddrive'}  
  </span>   $newfolderform=(<<NFFORM);
  </form>   <form action="/adm/coursedocs" method="post" name="newfolder">
 FUFORM   <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
  my $simpleeditdefaultform=(<<SEDFFORM);   <input type="hidden" name="active" value="aa" />
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">   <a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
  $lt{'pubd'}<br />   </form>
  $uploadtag  NFFORM
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />  
  <br />   my $newsylform=(<<NSYLFORM);
  <span class="LC_nobreak">   <form action="/adm/coursedocs" method="post" name="newsyl">
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />   <input type="hidden" name="active" value="cc" />
  $help{'Importing_LON-CAPA_Resource'}   $uploadtag
  </span>   <input type="hidden" name="importdetail" 
  <br />   value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />   <a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
  <hr />   $help{'Syllabus'}
  <p>  
  $lt{'copm'}<br />   </form>
  <input type="text" size="40" name="importmap" /><br />  NSYLFORM
  <span class="LC_nobreak"><input type="button"  
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"   my $newgroupfileform=(<<NGFFORM);
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />   <form action="/adm/coursedocs" method="post" name="newgroupfiles">
  $help{'Load_Map'}</span>   <input type="hidden" name="active" value="cc" />
  </p>   $uploadtag
  </form>   <input type="hidden" name="importdetail"
 SEDFFORM   value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
  my $extresourcesform=(<<ERFORM);   $help{'Group Portfolio'}
  <form action="/adm/coursedocs" method="post" name="newext">   </form>
  $uploadtag  NGFFORM
  <input type="hidden" name="importdetail" value="" />   @specialdocumentsforma=(
  <span class="LC_nobreak">   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
  </span>          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
  </form>          );
 ERFORM          $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
   
     if ($allowed) {  
  &update_paste_buffer($coursenum,$coursedom);          my @importdoc = (
        my $dumpbut=&dumpbutton();          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'newext\');" />'=>$extresourcesform},
        my $exportbut=&exportbutton();          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:makeims();" />'=>$imspform},);
        my %lt=&Apache::lonlocal::texthash(          $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc)) . '<hr id="cc_hrule" style="width:0px;text-align:left;margin-left:0" />' . $fileuploadform;
  'vc' => 'Verify Content',  
  'cv' => 'Check/Set Resource Versions',          @gradingforma=(
  'ls' => 'List Symbs',          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
                                          'sl' => 'Show Log'          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
   );          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
   
        my $folderpath=$env{'form.folderpath'};          );
        if (!$folderpath) {          $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
    if ($env{'form.folder'} eq '' ||  
        $env{'form.folder'} eq 'supplemental') {          @communityforma=(
        $folderpath='default&'.         {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
    &escape(&mt('Main '.$type.' Documents'));          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
    }          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
        }          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
        unless ($env{'form.pagepath'}) {          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
            $containertag = '<input type="hidden" name="folderpath" value="" />';          );
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';          $communityform = &create_form_ul(&create_list_elements(@communityforma));
        }  
   my %orderhash = (
        $r->print(<<ENDCOURSEVERIFY);                  'aa' => ['Import Documents',$fileuploadform],
 <form name="renameform" method="post" action="/adm/coursedocs">                  'bb' => ['Published Resources',$simpleeditdefaultform],
   <input type="hidden" name="title" />                  'cc' => ['Grading Resources',$gradingform],
   <input type="hidden" name="cmd" />                  );
   <input type="hidden" name="markcopy" />  unless ($env{'form.pagepath'}) {
   <input type="hidden" name="copyfolder" />      $orderhash{'00'} = ['Newfolder',$newfolderform];
   $containertag      $orderhash{'dd'} = ['Collaboration',$communityform];
 </form>      $orderhash{'ee'} = ['Special Documents',$specialdocumentsform];
 <form name="simpleedit" method="post" action="/adm/coursedocs">  }
   <input type="hidden" name="importdetail" value="" />  
   $uploadtag   $hadchanges=0;
 </form>         unless (($supplementalflag || $toolsflag)) {
 <form action="/adm/coursedocs" method="post" name="courseverify">            my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
   <div class="LC_docs_course_commands">                                $supplementalflag,\%orderhash,$iconpath);
             if ($error) {
       <div>               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
         <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}            }
       </div>            if ($hadchanges) {
       <div>               &mark_hash_old();
         <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}            }
       </div>  
         $dumpbut            &changewarning($r,'');
         $exportbut          }
       <div>      }
         <input type="submit" name="listsymbs" value="$lt{'ls'}" />  
       </div>  # Supplemental documents start here
       <div>  
         <input type="hidden" name="folder" value="$env{'form.folder'}" />         my $folder=$env{'form.folder'};
         <input type="submit" name="docslog" value="$lt{'sl'}" />         unless ($supplementalflag) {
       </div>     $folder='supplemental';
   </div>         }
 </form>         if ($folder =~ /^supplemental$/ &&
 <div style="clear: both; height: 0px;">&nbsp;</div>     (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
 ENDCOURSEVERIFY            $env{'form.folderpath'} = &supplemental_base();
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',         } elsif ($allowed) {
      &mt('Editing the Table of Contents for your '.$type)));    $env{'form.folderpath'} = $savefolderpath;
     }         }
 # --------------------------------------------------------- Standard documents         $env{'form.pagepath'} = '';
     $r->print('<table class="LC_docs_documents">');         if ($allowed) {
      my $folderseq=
     if (($standard) && ($allowed) && (!$forcesupplement)) {         '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
  $r->print('<tr><td class="LC_docs_document">');         '.sequence';
 #  '<h2>'.&mt('Main Course Documents').  
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');     my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
        my $folder=$env{'form.folder'};  
        if ($folder eq '' || $folder eq 'supplemental') {   my $supupdocformbtn = "<input type='submit' value='".$lt{'upld'}."' />$help{'Uploading_From_Harddrive'}";
            $folder='default';   my $supupdocform=(<<SUPDOCFORM);
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));   <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
            $uploadtag = '<input type="hidden" name="folderpath" value="'.   <input type="hidden" name="active" value="ee" />
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';   $fileupload
        }   <br />
        my $postexec='';   <br />
        if ($folder eq 'default') {   <span class="LC_nobreak">
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');   $checkbox
        } else {   </span>
            #$postexec='self.close();';   <br /><br />
        }   $lt{'comment'}:<br />
        $hadchanges=0;   <textarea cols="50" rows="4" name="comment"></textarea>
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,   <br />
    $upload_output,$type);   <input type="hidden" name="folderpath" value="$path" />
        if ($error) {   <input type="hidden" name="cmd" value="upload_supplemental" />
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');  SUPDOCFORM
        }   $supupdocform .=  &create_form_ul(&Apache::lonhtmlcommon::htmltag('li',$supupdocformbtn,{class => 'LC_menubuttons_inline_text'}))."</form>";
        if ($hadchanges) {  
    &mark_hash_old();   my $supnewfolderform=(<<SNFFORM);
        }   <form action="/adm/coursedocs" method="post" name="supnewfolder">
        &changewarning($r,$postexec);   <input type="hidden" name="active" value="ee" />
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.   <input type="hidden" name="folderpath" value="$path" />
                      '.sequence';   <input type="hidden" name="importdetail" value="" />
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.   <a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
                      '.page';   $help{'Adding_Folders'}
  my $container='sequence';   </form>
  if ($env{'form.pagepath'}) {  SNFFORM
     $container='page';  
  }  
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;   my $supnewextform=(<<SNEFORM);
    <form action="/adm/coursedocs" method="post" name="supnewext">
    <input type="hidden" name="active" value="ff" />
    <input type="hidden" name="folderpath" value="$path" />
  my $recoverform=(<<RFORM);   <input type="hidden" name="importdetail" value="" />
  <form action="/adm/groupsort" method="post" name="recover">   <a class="LC_menubuttons_link" href="javascript:makenewext('supnewext');">$lt{'extr'}</a> $help{'Adding_External_Resource'}
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />   </form>
  </form>  SNEFORM
 RFORM  
    my $supnewsylform=(<<SNSFORM);
  my $imspform=(<<IMSPFORM);   <form action="/adm/coursedocs" method="post" name="supnewsyl">
  <form action="/adm/imsimportdocs" method="post" name="ims">   <input type="hidden" name="active" value="ff" />
  <input type="hidden" name="folder" value="$folder" />   <input type="hidden" name="folderpath" value="$path" />
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />   <input type="hidden" name="importdetail" 
  </form>   value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
 IMSPFORM   <a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
  my $newnavform=(<<NNFORM);   </form>
  <form action="/adm/coursedocs" method="post" name="newnav">  SNSFORM
  $uploadtag  
  <input type="hidden" name="importdetail"   my $supnewaboutmeform=(<<SNAMFORM);
  value="$lt{'navc'}=/adm/navmaps" />   <form action="/adm/coursedocs" method="post" name="supnewaboutme">
  <span class="LC_nobreak">   <input type="hidden" name="active" value="ff" />
  <input name="newnav" type="submit" value="$lt{'navc'}" />   <input type="hidden" name="folderpath" value="$path" />
  $help{'Navigate_Content'}   <input type="hidden" name="importdetail" 
  </span>   value="$plainname=/adm/$udom/$uname/aboutme" />
  </form>   <a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
 NNFORM   $help{'My Personal Information Page'}
  my $newsmppageform=(<<NSPFORM);   </form>
  <form action="/adm/coursedocs" method="post" name="newsmppg">  SNAMFORM
  $uploadtag  
  <input type="hidden" name="importdetail" value="" />  
  <span class="LC_nobreak">  my @specialdocs = (
  <input name="newsmppg" type="button" value="$lt{'sipa'}"   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.supnewsyl.submit()" />'
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}              =>$supnewsylform},
  </span>   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
  </form>              =>$supnewaboutmeform},
 NSPFORM   );
   my @supimportdoc = (
  my $newsmpproblemform=(<<NSPROBFORM);   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'supnewext\');" />'
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">              =>$supnewextform},
  $uploadtag          );
  <input type="hidden" name="importdetail" value="" />  $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc)) . '<hr id="ee_hrule" style="width:0px;text-align:left;margin-left:0" />' . $supupdocform;
  <span class="LC_nobreak">  my %suporderhash = (
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"   '00' => ['Supnewfolder', $supnewfolderform],
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}                  'ee' => ['Import Documents',$supupdocform],
  </span>                  'ff' => ['Special Documents',&create_form_ul(&create_list_elements(@specialdocs))]
  </form>                  );
           if ($supplementalflag) {
 NSPROBFORM             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                  $supplementalflag,\%suporderhash,$iconpath);
  my $newdropboxform=(<<NDBFORM);             if ($error) {
  <form action="/adm/coursedocs" method="post" name="newdropbox">                $r->print('<p><span class="LC_error">'.$error.'</span></p>');
  $uploadtag                   }
  <input type="hidden" name="importdetail" value="" />          }
  <span class="LC_nobreak">                } elsif ($supplementalflag) {
  <input name="newdropbox" type="button" value="$lt{'drbx'}"          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
  onClick="javascript:makedropbox();" />                              $supplementalflag,'',$iconpath);
  </span>                  if ($error) {
  </form>              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 NDBFORM          }
       }
  my $newexuploadform=(<<NEXUFORM);  
  <form action="/adm/coursedocs" method="post" name="newexamupload">      $r->print(&endContentScreen());
  $uploadtag  
  <input type="hidden" name="importdetail" value="" />      if ($allowed) {
  <span class="LC_nobreak">   $r->print('
  <input name="newexamupload" type="button" value="$lt{'scuf'}"  <form method="post" name="extimport" action="/adm/coursedocs">
  onClick="javascript:makeexamupload();" />    <input type="hidden" name="title" />
  $help{'Score_Upload_Form'}    <input type="hidden" name="url" />
  </span>    <input type="hidden" name="useform" />
  </form>    <input type="hidden" name="residx" />
 NEXUFORM  </form>');
       }
  my $newbulform=(<<NBFORM);    } elsif ($showdoc) {
  <form action="/adm/coursedocs" method="post" name="newbul">  # -------------------------------------------------------- This is showdoc mode
  $uploadtag        $r->print("<h1>".&mt('Uploaded Document').' - '.
  <input type="hidden" name="importdetail" value="" />   &Apache::lonnet::gettitle($r->uri).'</h1><p>'.
  <span class="LC_nobreak">  &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
  <input name="newbulletin" type="button" value="$lt{'bull'}"                  &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
  onClick="javascript:makebulboard();" />    }
  $help{'Bulletin Board'}   }
  </span>   $r->print(&Apache::loncommon::end_page());
  </form>   return OK;
 NBFORM  }
   
  my $newaboutmeform=(<<NAMFORM);  sub embedded_form_elems {
  <form action="/adm/coursedocs" method="post" name="newaboutme">      my ($phase,$primaryurl,$newidx) = @_;
  $uploadtag      my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  <input type="hidden" name="importdetail"      return <<STATE;
  value="$plainname=/adm/$udom/$uname/aboutme" />      <input type="hidden" name="folderpath" value="$folderpath" />
  <span class="LC_nobreak">      <input type="hidden" name="cmd" value="upload_embedded" />
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      <input type="hidden" name="newidx" value="$newidx" />
  $help{'My Personal Info'}      <input type="hidden" name="phase" value="$phase" />
  </span>      <input type="hidden" name="primaryurl" value="$primaryurl" />
  </form>  STATE
 NAMFORM  }
   
  my $newaboutsomeoneform=(<<NASOFORM);  sub embedded_destination {
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">      my $folder=$env{'form.folder'};
  $uploadtag      my $destination = 'docs/';
  <input type="hidden" name="importdetail" value="" />      if ($folder =~ /^supplemental/) {
  <span class="LC_nobreak">          $destination = 'supplemental/';
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"      }
  onClick="javascript:makeabout();" />      if (($folder eq 'default') || ($folder eq 'supplemental')) {
  </span>          $destination .= 'default/';
  </form>      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 NASOFORM          $destination .=  $2.'/';
       }
       $destination .= $env{'form.newidx'};
  my $newrosterform=(<<NROSTFORM);      my $dir_root = '/userfiles';
  <form action="/adm/coursedocs" method="post" name="newroster">      return ($destination,$dir_root);
  $uploadtag  }
  <input type="hidden" name="importdetail"  
  value="$lt{'rost'}=/adm/viewclasslist" />  sub return_to_editor {
  <span class="LC_nobreak">      my $actionurl = '/adm/coursedocs';
  <input name="newroster" type="submit" value="$lt{'rost'}" />      return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
  $help{'Course Roster'}             '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
  </span>             '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
  </form>             '</a></p>';
 NROSTFORM  }
   
        $r->print(<<ENDFORM);  sub decompression_info {
       my ($destination,$dir_root) = &embedded_destination();
 <ul class="LC_TabContent">      my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 <li>$lt{'nd'}</li>      my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 <li>$lt{'pm'}</li>      my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 <li>$lt{'pubd'}</li>      my $container='sequence';
 <li>$lt{'sd'}</li>      my ($pathitem,$hiddenelem);
 <li>$lt{'mo'}</li>      my @hiddens = ('newidx','comment','position');
 <li>$lt{'hao'}</li>      if ($env{'form.pagepath'}) {
 </ul>          $container='page';
           $pathitem = 'pagepath';
 <table class="LC_docs_adddocs">      } else {
 <!-- <tr>          $pathitem = 'folderpath';
 <th>$lt{'uplm'}</th>      }
 <th>$lt{'impp'}</th>      unshift(@hiddens,$pathitem);
 <th>$lt{'spec'}</th>      foreach my $item (@hiddens) {
 </tr> -->          if ($env{'form.'.$item}) {
 <tr>              $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
 <td>                             $env{'form.'.$item}.'" />'."\n";
 $fileuploadform          }
 </td>      }
 <td>      return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
 $simpleeditdefaultform              $hiddenelem);
 <hr />  }
 $recoverform  
 ENDFORM  sub decompression_phase_one {
        unless ($env{'form.pagepath'}) {      my ($dir,$file,$warning,$error,$output);
    $r->print(<<ENDFORM);      my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
 <hr />          &decompression_info();
 $extresourcesform      if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/docs/\E(?:default|supplemental|\d+).*/([^/]+)$}) {
  <br />          $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
 $imspform      } else {
 ENDFORM          my $file = $1;
        }          $output = 
        $r->print('</td><td>');              &Apache::loncommon::process_decompression($docudom,$docuname,$file,
        unless ($env{'form.pagepath'}) {                                                        $destination,$dir_root,
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                                                        $hiddenelem);
           if ($env{'form.autoextract_camtasia'}) {
               $output .= &remove_archive($docudom,$docuname,$container);
           }
  my $newpageform=(<<NPFORM);      }
  <form action="/adm/coursedocs" method="post" name="newpage">      if ($error) {
  <input type="hidden" name="folderpath" value="$path" />          $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
  <input type="hidden" name="importdetail" value="" />                     $error.'</p>'."\n";
  <span class="LC_nobreak">      }
  <input name="newpage" type="button"      if ($warning) {
  onClick="javascript:makenewpage(this.form,'$pageseq');"          $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
  value="$lt{'newp'}" />$help{'Adding_Pages'}      }
  </span>      return $output;
  </form>  }
 NPFORM  
   sub decompression_phase_two {
  my $newfolderform=(<<NFFORM);      my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
  <form action="/adm/coursedocs" method="post" name="newfolder">          &decompression_info();
  <input type="hidden" name="folderpath" value="$path" />      my $output;
  <input type="hidden" name="importdetail" value="" />      if ($env{'form.archivedelete'}) {
  <span class="LC_nobreak">          $output = &remove_archive($docudom,$docuname,$container);
  <input name="newfolder" type="button"      }
  onClick="javascript:makenewfolder(this.form,'$folderseq');"      $output .= 
  value="$lt{'newf'}" />$help{'Adding_Folders'}          &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
  </span>                                                      $destination,$dir_root,$hiddenelem);
  </form>      return $output;
 NFFORM  }
   
  my $newsylform=(<<NSYLFORM);  sub remove_archive {
  <form action="/adm/coursedocs" method="post" name="newsyl">      my ($docudom,$docuname,$container) = @_;
  $uploadtag      my $map = $env{'form.folder'}.'.'.$container;
  <input type="hidden" name="importdetail"      my ($output,$delwarning,$delresult,$url);
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />      my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
  <span class="LC_nobreak">      if ($fatal) {
  <input name="newsyl" type="submit" value="$lt{'syll'}" />          if ($container eq 'page') {
  $help{'Syllabus'}              $delwarning = &mt('An error occurred retrieving the contents of the current page.');
  </span>          } else {
  </form>              $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
 NSYLFORM          }
           $delwarning .= &mt('As a result the archive file has not been removed.');
  my $newgroupfileform=(<<NGFFORM);      } else {
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">          my $currcmd = $env{'form.cmd'};
  $uploadtag          my $position = $env{'form.position'};
  <input type="hidden" name="importdetail"          if ($position > 0) { 
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />              $env{'form.cmd'} = 'del_'.$position;
  <span class="LC_nobreak">              my ($title,$url,@rrest) = 
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />                  split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$position]]);
  $help{'Group Files'}              if (&handle_edit_cmd($docuname,$docudom)) {
  </span>                  ($errtext,$fatal) = &storemap($docuname,$docudom,$map);
  </form>                  if ($fatal) {
 NGFFORM                      if ($container eq 'page') {
                           $delwarning = &mt('An error occurred updating the contents of the current page.');
                       } else {
            $r->print(<<ENDFORM);                          $delwarning = &mt('An error occurred updating the contents of the current folder.');
 <br />                      }
 $newfolderform                  } else {
 <br />                      $delresult = &mt('Archive file removed.');
 $newpageform                  }
 <br />              }
 $newsylform          }
 <br />          $env{'form.cmd'} = $currcmd;
 $newnavform      }
 <br />      if ($delwarning) {
 $newsmppageform          $output = '<p class="LC_warning">'.
 <br />                     $delwarning.
 $newsmpproblemform                     '</p>';
 <br />      }
 $newdropboxform      if ($delresult) {
 <br />          $output .= '<p class="LC_info">'.
 $newexuploadform                     $delresult.
 <br />                     '</p>';
 $newbulform      }
 <br />      return $output;
 $newaboutmeform  }
 <br />  
 $newaboutsomeoneform  sub generate_admin_menu {
 <br />      my ($crstype) = @_;
 $newgroupfileform      my $lc_crstype = lc($crstype);
 <br />      my ($home,$other,%outhash)=&authorhosts();
 $newrosterform      my %lt=&Apache::lonlocal::texthash (
 ENDFORM                                           'vc'   => 'Verify Content',
        }                                           'cv'   => 'Check/Set Resource Versions',
        if ($env{'form.pagepath'}) {                                           'ls'   => 'List Resource Identifiers',
            $r->print(<<ENDBLOCK);                                           'imse' => 'Export contents to IMS Archive',
 $newsmpproblemform                                           'dcd'  => "Dump $crstype Content to Authoring Space",
 <br />                                         );
 $newexuploadform      my ($candump,$dumpurl);
 ENDBLOCK      if ($home + $other > 0) {
        }          $candump = 'F';
        $r->print('</td></tr>'."\n".          if ($home) {
 '</table>');              $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
        $r->print('</td></tr>');          } else {
     }              my @hosts;
 # ----------------------------------------------------- Supplemental documents              foreach my $aurole (keys(%outhash)) {
     if (!$forcestandard) {                  unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
        $r->print('<tr><td class="LC_docs_document">');                      push(@hosts,$outhash{$aurole});
 # '<h2>'.&mt('Supplemental Course Documents').                  }  
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');              }
        my $folder=$env{'form.folder'};              if (@hosts == 1) {
        unless ($folder=~/^supplemental/) {                  my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
    $folder='supplemental';                                 '&amp;role='.
        }                                 &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
        if ($folder =~ /^supplemental$/ &&                                 &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {                  $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
           $env{'form.folderpath'} = 'supplemental&'.              } else {
                                     &escape(&mt('Supplemental '.$type.' Documents'));                  $dumpurl = "javascript:choose_switchserver_window()";
        }              }
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);          }
        if ($error) {      }
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');      my @menu=
        }          ({  categorytitle=>'Administration',
        if ($allowed) {              items =>[
    my $folderseq=                  {   linktext   => $lt{'vc'},
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.                      url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
        '.sequence';                      permission => 'F',
                       help       => 'Verify_Content',
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                      icon       => 'verify.png',
                       linktitle  => 'Verify contents can be retrieved/rendered',
  my $supupdocform=(<<SUPDOCFORM);                  },
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">                  {   linktext => $lt{'cv'},
  $fileupload                      url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
  <br />                      permission => 'F',
  <br />                      help       => 'Check_Resource_Versions',
  <span class="LC_nobreak">                      icon       => 'resversion.png',
  $checkbox                      linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
  </span>                  },
  <br /><br />                  {   linktext   => $lt{'ls'},
  $lt{'comment'}:<br />                      url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
  <textarea cols=50 rows=4 name='comment'>                      permission => 'F',
  </textarea>                      #help => '',
  <br />                      icon       => 'symbs.png',
  <input type="hidden" name="folderpath" value="$path" />                      linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
  <input type="hidden" name="cmd" value="upload_supplemental" />                  },
  <span class="LC_nobreak">                  ]
  <input type="submit" value="$lt{'upld'}" />          },
  $help{'Uploading_From_Harddrive'}          {   categorytitle=>'Export',
  </span>              items =>[
  </form>                  {   linktext   => $lt{'imse'},
 SUPDOCFORM                      url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
                       permission => 'F',
  my $supnewfolderform=(<<SNFFORM);                      help       => 'Docs_Export_Course_Docs',
  <form action="/adm/coursedocs" method="post" name="supnewfolder">                      icon       => 'imsexport.png',
  <input type="hidden" name="folderpath" value="$path" />                      linktitle  => $lt{'imse'},
  <input type="hidden" name="importdetail" value="" />                  },
  <span class="LC_nobreak">                  {   linktext   => $lt{'dcd'},
  <input name="newfolder" type="button"                      url        => $dumpurl,
  onClick="javascript:makenewfolder(this.form,'$folderseq');"                      permission => $candump,
  value="$lt{'newf'}" /> $help{'Adding_Folders'}                      #help => '',
  </span>                      icon       => 'dump.png',
  </form>                      linktitle  => $lt{'dcd'},
 SNFFORM                  },
                   ]
           });
  my $supnewextform=(<<SNEFORM);      return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
  <form action="/adm/coursedocs" method="post" name="supnewext">             '<input type="hidden" id="dummy" />'."\n".
  <input type="hidden" name="folderpath" value="$path" />             &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
  <input type="hidden" name="importdetail" value="" />             '</form>';
  <span class="LC_nobreak">  }
  <input name="newext" type="button"  
  onClick="javascript:makenewext('supnewext');"  sub generate_edit_table {
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile) = @_;
  </span>      return unless(ref($orderhash_ref) eq 'HASH');
  </form>      my %orderhash = %{$orderhash_ref};
 SNEFORM      my $form;
       my $activetab;
  my $supnewsylform=(<<SNSFORM);      my $active;
  <form action="/adm/coursedocs" method="post" name="supnewsyl">      if($env{'form.active'} ne ''){
  <input type="hidden" name="folderpath" value="$path" />          $activetab = $env{'form.active'};
  <input type="hidden" name="importdetail"      }
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />      my $backicon = $iconpath.'clickhere.gif';
  <span class="LC_nobreak">      my $backtext = &mt('To Overview');
  <input name="newsyl" type="submit" value="$lt{'syll'}" />      $form = '<div class="LC_Box" style="margin:0;">'.
  $help{'Syllabus'}               '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
  </span>               '<li class="goback">'.
  </form>               '<a href="javascript:toContents('."'$jumpto'".');">'.
 SNSFORM               '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
                '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n";
  my $supnewaboutmeform=(<<SNAMFORM);      if ($tid == 1) {
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">          $form .= '<li>'.
  <input type="hidden" name="folderpath" value="$path" />                   '<a href="javascript:groupopen('."'$readfile'".',1);">'.
  <input type="hidden" name="importdetail"                   &mt('Undo Delete').'</a></li>'."\n";
  value="$plainname=/adm/$udom/$uname/aboutme" />          if ($env{'form.docslog'}) {
  <span class="LC_nobreak">              $form .= '<li class="active">';
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />          } else {
  $help{'My Personal Info'}              $form .= '<li>';
  </span>          }
  </form>          $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
 SNAMFORM                    &mt('History').'</a></li>'."\n";
           if ($env{'form.docslog'}) {
    $r->print(<<ENDSUPFORM);              $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
 <ul class="LC_TabContent">                    &mt('Edit').'</a></li>'."\n";
 <li>$lt{'nd'}</li>          }
 <li>$lt{'sd'}</li>      }
 <li>$lt{'hao'}</li>      foreach my $name (reverse(sort(keys(%orderhash)))) {
 </ul>          if($name ne '00'){
 <table class="LC_docs_adddocs">              if($activetab eq '' || $activetab ne $name){
 <tr><td>                 $active = '';
 $supupdocform              }elsif($activetab eq $name){
 </td>                 $active = 'class="active"';
 <td>              }
 $supnewfolderform              $form .= '<li style="float:right" '.$active
 <br />                  .' onmouseover="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"'
 $supnewextform                  .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
 <br />          } else {
 $supnewsylform      $form .= '<li '.$active.' style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
 <br />  
 $supnewaboutmeform   }
 </td></tr>      }
 </table></td></tr>      $form .= '</ul>'."\n";
 ENDSUPFORM      $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
        }  
     }      if ($to_show ne '') {
     $r->print('</table>');          $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'."\n";
     if ($allowed) {      }
  $r->print('      foreach my $field (keys(%orderhash)){
 <form method="post" name="extimport" action="/adm/coursedocs">   if($field ne '00'){
   <input type="hidden" name="title" />              if($activetab eq '' || $activetab ne $field){
   <input type="hidden" name="url" />                  $active = 'style="display: none;float:left"';
   <input type="hidden" name="useform" />              }elsif($activetab eq $field){
   <input type="hidden" name="residx" />                  $active = 'style="display:block;float:left"';
 </form>');              }
     }              $form .= '<div id="'.$field.$tid.'"'
   } else {                      .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
       unless ($upload_result eq 'phasetwo') {                      .'</div>'."\n";
 # -------------------------------------------------------- This is showdoc mode          }
           $r->print("<h1>".&mt('Uploaded Document').' - '.      }
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.      unless ($env{'form.docslog'}) {
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".          $form .= '</div></div>'."\n";
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');      }
       }      return $form;
   }  }
  }  
  $r->print(&Apache::loncommon::end_page());  sub editing_js {
  return OK;      my ($udom,$uname,$supplementalflag) = @_;
 }      my $now = time();
       my %lt = &Apache::lonlocal::texthash(
                                             p_mnf => 'Name of New Folder',
 sub editing_js {                                            t_mnf => 'New Folder',
     my ($udom,$uname) = @_;                                            p_mnp => 'Name of New Page',
     my $now = time();                                            t_mnp => 'New Page',
     my %lt = &Apache::lonlocal::texthash(                                            p_mxu => 'Title for the External Score',
                                           p_mnf => 'Name of New Folder',                                            p_msp => 'Name of Simple Course Page',
                                           t_mnf => 'New Folder',                                            p_msb => 'Title for the Problem',
                                           p_mnp => 'Name of New Page',                                            p_mdb => 'Title for the Drop Box',
                                           t_mnp => 'New Page',                                            p_mbb => 'Title for the Discussion Board',
                                           p_mxu => 'Title for the Uploaded Score',                                            p_mab => "Enter user:domain for User's Personal Information Page",
                                           p_msp => 'Title for the Page',                                            p_mab2 => 'Personal Information Page of ',
                                           p_msb => 'Title for the Problem',                                            p_mab_alrt1 => 'Not a valid user:domain',
                                           p_mdb => 'Title for the Drop Box',                                            p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                           p_mbb => 'Title for the Bulletin Board',                                            p_chn => 'New Title',
                                           p_mab => "Enter user:domain for User's 'About Me' Page",                                            p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
                                           p_mab2 => "About [_99]",                                            p_rmr2a => 'Remove[_99]',
                                           p_mab_alrt1 => 'Not a valid user:domain',                                            p_rmr2b => '?[_99]',
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',                                            p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                           p_chn => 'New Title',                                            p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',                                            p_ctr2a => 'Cut[_98]',
                                           p_rmr2a => 'Remove[_99]',                                            p_ctr2b => '?[_98]',
                                           p_rmr2b => '?[_99]',                                            rpck    => 'Enter number to pick (e.g., 3)',
                                           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]',      my $crstype = &Apache::loncommon::course_type();
                                           p_ctr2b => '?[_98]'      my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
                                         );      my $docs_pagepath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.pagepath'},'<>&"');
       my $main_container_page;
     return <<ENDNEWSCRIPT;      if ($docs_folderpath eq '') {
 function makenewfolder(targetform,folderseq) {          if ($docs_pagepath ne '') {
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');              $main_container_page = 1;
     if (foldername) {          }
        targetform.importdetail.value=escape(foldername)+"="+folderseq;      }
         targetform.submit();      my $toplevelmain = 'default&Main%20'.$crstype.'%20Documents';
     }      my $toplevelsupp = &supplemental_base();
 }  
       my $backtourl = '/adm/navmaps';
 function makenewpage(targetform,folderseq) {      if ($supplementalflag) {
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');          $backtourl = '/adm/supplemental';
     if (pagename) {      }
         targetform.importdetail.value=escape(pagename)+"="+folderseq;  
         targetform.submit();      return <<ENDNEWSCRIPT;
     }  function makenewfolder(targetform,folderseq) {
 }      var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
       if (foldername) {
 function makenewext(targetname) {         targetform.importdetail.value=escape(foldername)+"="+folderseq;
     this.document.forms.extimport.useform.value=targetname;          targetform.submit();
     this.document.forms.extimport.title.value='';      }
     this.document.forms.extimport.url.value='';  }
     this.document.forms.extimport.residx.value='';  
     window.open('/adm/rat/extpickframe.html');  function makenewpage(targetform,folderseq) {
 }      var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
       if (pagename) {
 function edittext(targetname,residx,title,url) {          targetform.importdetail.value=escape(pagename)+"="+folderseq;
     this.document.forms.extimport.useform.value=targetname;          targetform.submit();
     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 makenewext(targetname) {
 }      this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.title.value='';
 function makeexamupload() {      this.document.forms.extimport.url.value='';
    var title=prompt('$lt{"p_mxu"}');      this.document.forms.extimport.residx.value='';
    if (title) {      window.open('/adm/rat/extpickframe.html');
     this.document.forms.newexamupload.importdetail.value=  }
  escape(title)+'=/res/lib/templates/examupload.problem';  
     this.document.forms.newexamupload.submit();  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;
 function makesmppage() {      this.document.forms.extimport.title.value=title;
    var title=prompt('$lt{"p_msp"}');      window.open('/adm/rat/extpickframe.html');
    if (title) {  }
     this.document.forms.newsmppg.importdetail.value=  
  escape(title)+'=/adm/$udom/$uname/$now/smppg';  function makeexamupload() {
     this.document.forms.newsmppg.submit();     var title=prompt('$lt{"p_mxu"}');
    }     if (title) {
 }      this.document.forms.newexamupload.importdetail.value=
    escape(title)+'=/res/lib/templates/examupload.problem';
 function makesmpproblem() {      this.document.forms.newexamupload.submit();
    var title=prompt('$lt{"p_msb"}');     }
    if (title) {  }
     this.document.forms.newsmpproblem.importdetail.value=  
  escape(title)+'=/res/lib/templates/simpleproblem.problem';  function makesmppage() {
     this.document.forms.newsmpproblem.submit();     var title=prompt('$lt{"p_msp"}');
    }     if (title) {
 }      this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/smppg';
 function makedropbox() {      this.document.forms.newsmppg.submit();
    var title=prompt('$lt{"p_mdb"}');     }
    if (title) {  }
     this.document.forms.newdropbox.importdetail.value=  
         escape(title)+'=/res/lib/templates/DropBox.problem';  function makesmpproblem() {
     this.document.forms.newdropbox.submit();     var title=prompt('$lt{"p_msb"}');
    }     if (title) {
 }      this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
 function makebulboard() {      this.document.forms.newsmpproblem.submit();
    var title=prompt('$lt{"p_mbb"}');     }
    if (title) {  }
     this.document.forms.newbul.importdetail.value=  
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';  function makedropbox() {
     this.document.forms.newbul.submit();     var title=prompt('$lt{"p_mdb"}');
    }     if (title) {
 }      this.document.forms.newdropbox.importdetail.value=
           escape(title)+'=/res/lib/templates/DropBox.problem';
 function makeabout() {      this.document.forms.newdropbox.submit();
    var user=prompt("$lt{'p_mab'}");     }
    if (user) {  }
        var comp=new Array();  
        comp=user.split(':');  function makebulboard() {
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {     var title=prompt('$lt{"p_mbb"}');
    if ((comp[0]) && (comp[1])) {     if (title) {
        this.document.forms.newaboutsomeone.importdetail.value=      this.document.forms.newbul.importdetail.value=
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';   escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
        this.document.forms.newaboutsomeone.submit();      this.document.forms.newbul.submit();
    } else {     }
                alert("$lt{'p_mab_alrt1'}");  }
            }  
        } else {  function makeabout() {
            alert("$lt{'p_mab_alrt2'}");     var user=prompt("$lt{'p_mab'}");
        }     if (user) {
    }         var comp=new Array();
 }         comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
 function makeims() {     if ((comp[0]) && (comp[1])) {
     var caller = document.forms.ims.folder.value;         this.document.forms.newaboutsomeone.importdetail.value=
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";     '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");         this.document.forms.newaboutsomeone.submit();
     newWindow.location.href = newlocation;     } else {
 }         alert("$lt{'p_mab_alrt1'}");
      }
   } else {
 function finishpick() {     alert("$lt{'p_mab_alrt2'}");
     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 makeims() {
 }  var caller = document.forms.ims.folder.value;
   var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
 function changename(folderpath,index,oldtitle,container,pagesymb) {  newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");
     var title=prompt('$lt{"p_chn"}',oldtitle);  newWindow.location.href = newlocation;
     if (title) {  }
  this.document.forms.renameform.markcopy.value=-1;  
  this.document.forms.renameform.title.value=title;  function finishpick() {
  this.document.forms.renameform.cmd.value='rename_'+index;  var title=this.document.forms.extimport.title.value;
         if (container == 'sequence') {  var url=this.document.forms.extimport.url.value;
     this.document.forms.renameform.folderpath.value=folderpath;  var form=this.document.forms.extimport.useform.value;
         }  var residx=this.document.forms.extimport.residx.value;
         if (container == 'page') {  eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');
             this.document.forms.renameform.pagepath.value=folderpath;  }
             this.document.forms.renameform.pagesymb.value=pagesymb;  
         }  function changename(folderpath,index,oldtitle,container,pagesymb) {
         this.document.forms.renameform.submit();  var title=prompt('$lt{"p_chn"}',oldtitle);
     }  if (title) {
 }  this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.title.value=title;
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {  this.document.forms.renameform.cmd.value='rename_'+index;
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {  if (container == 'sequence') {
  this.document.forms.renameform.markcopy.value=-1;      this.document.forms.renameform.folderpath.value=folderpath;
  this.document.forms.renameform.cmd.value='del_'+index;  }
         if (container == 'sequence') {  if (container == 'page') {
             this.document.forms.renameform.folderpath.value=folderpath;      this.document.forms.renameform.pagepath.value=folderpath;
         }      this.document.forms.renameform.pagesymb.value=pagesymb;
         if (container == 'page') {  }
             this.document.forms.renameform.pagepath.value=folderpath;  this.document.forms.renameform.submit();
             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;
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {  this.document.forms.renameform.cmd.value='del_'+index;
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {  if (container == 'sequence') {
  this.document.forms.renameform.cmd.value='cut_'+index;      this.document.forms.renameform.folderpath.value=folderpath;
  this.document.forms.renameform.markcopy.value=index;  }
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;  if (container == 'page') {
         if (container == 'sequence') {      this.document.forms.renameform.pagepath.value=folderpath;
             this.document.forms.renameform.folderpath.value=folderpath;      this.document.forms.renameform.pagesymb.value=pagesymb;
         }  }
         if (container == 'page') {  this.document.forms.renameform.submit();
             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;
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {  this.document.forms.renameform.copyfolder.value=folder+'.'+container;
     this.document.forms.renameform.markcopy.value=index;  if (container == 'sequence') {
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;      this.document.forms.renameform.folderpath.value=folderpath;
     if (container == 'sequence') {  }
  this.document.forms.renameform.folderpath.value=folderpath;  if (container == 'page') {
     }      this.document.forms.renameform.pagepath.value=folderpath;
     if (container == 'page') {      this.document.forms.renameform.pagesymb.value=pagesymb;
  this.document.forms.renameform.pagepath.value=folderpath;  }
  this.document.forms.renameform.pagesymb.value=pagesymb;  this.document.forms.renameform.submit();
     }  }
     this.document.forms.renameform.submit();  }
 }  
   function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
   this.document.forms.renameform.markcopy.value=index;
 ENDNEWSCRIPT  this.document.forms.renameform.copyfolder.value=folder+'.'+container;
 }  if (container == 'sequence') {
 1;  this.document.forms.renameform.folderpath.value=folderpath;
 __END__  }
   if (container == 'page') {
   this.document.forms.renameform.pagepath.value=folderpath;
 =head1 NAME  this.document.forms.renameform.pagesymb.value=pagesymb;
   }
 Apache::londocs.pm  this.document.forms.renameform.submit();
   }
 =head1 SYNOPSIS  
   function updatePick(targetform,index,caller) {
 This is part of the LearningOnline Network with CAPA project      var pickitem = document.getElementById('rpick_'+index);
 described at http://www.lon-capa.org.      var picknumitem = document.getElementById('rpicknum_'+index);
       if (pickitem.checked) {
 =head1 SUBROUTINES          var picknum=prompt('$lt{"rpck"}',picknumitem.value);
           if (picknum == '' || picknum == null) {
 =over              if (caller == 'check') {
                   pickitem.checked=false;
 =item %help=()                  return;
               }
 Available help topics          } else {
               picknum.toString();
 =item mapread()              var regexdigit=/^\\d+\$/;
               if (regexdigit.test(picknum)) {
 Mapread read maps into LONCAPA::map:: global arrays                  picknumitem.value = picknum;
 @order and @resources, determines status                  targetform.changeparms.value='randompick';
 sets @order - pointer to resources in right order                  targetform.submit();
 sets @resources - array with the resources with correct idx              } else {
                   if (caller == 'check') {
 =item authorhosts()                      pickitem.checked=false;
                   }
 Return hash with valid author names                  return;
               }
 =item dumpbutton()          }
       } else {
 Generate "dump" button          picknumitem.value = 0;
           targetform.changeparms.value='randompick';
 =item clean()          targetform.submit();
       }
 =item dumpcourse()  }
   
     Actually dump course  function unselectInactive(nav) {
   currentNav = document.getElementById(nav);
   currentLis = currentNav.getElementsByTagName('LI');
 =item exportbutton()  for (i = 0; i < currentLis.length; i++) {
           if (currentLis[i].className == 'goback') {
     Generate "export" button              currentLis[i].className = 'goback';
           } else {
 =item exportcourse()      if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
    currentLis[i].className = 'right';
 =item create_ims_store()      } else {
    currentLis[i].className = 'i';
 =item build_package()      }
           }
 =item get_dependencies()  }
   }
 =item process_content()  
   function hideAll(current, nav, data) {
 =item replicate_content()  unselectInactive(nav);
   if(current.className == 'right'){
 =item extract_media()   current.className = 'right active'
    }else{
 =item store_template()   current.className = 'active';
   }
 =item group_import()  currentData = document.getElementById(data);
   currentDivs = currentData.getElementsByTagName('DIV');
     Imports the given (name, url) resources into the course  for (i = 0; i < currentDivs.length; i++) {
     coursenum, coursedom, and folder must precede the list   if(currentDivs[i].className == 'LC_ContentBox'){
    currentDivs[i].style.display = 'none';
 =item breadcrumbs()   }
   }
 =item log_docs()  }
   
 =item docs_change_log()  function openTabs(pageId) {
    tabnav = document.getElementById(pageId).getElementsByTagName('UL');
 =item update_paste_buffer()   if(tabnav.length > 2 ){
    currentNav = document.getElementById(tabnav[1].id);
 =item print_paste_buffer()   currentLis = currentNav.getElementsByTagName('LI');
    for(i = 0; i< currentLis.length; i++){
 =item do_paste_from_buffer()   if(currentLis[i].className == 'active') {
    funcString = currentLis[i].onclick.toString();
 =item update_parameter()   tab = funcString.split('"');
                                   if(tab.length < 2) {
 =item handle_edit_cmd()                                     tab = funcString.split("'");
                                   }
 =item editor()   currentData = document.getElementById(tab[1]);
           currentData.style.display = 'block';
 =item process_file_upload()   }
    }
 =item process_secondary_uploads()   }
   }
 =item is_supplemental_title()  
   function showPage(current, pageId, nav, data) {
 =item parse_supplemental_title()   hideAll(current, nav, data);
    openTabs(pageId);
 =item entryline()   unselectInactive(nav);
    current.className = 'active';
 =item tiehash()   currentData = document.getElementById(pageId);
    currentData.style.display = 'block';
 =item untiehash()          activeTab = pageId;
           if (nav == 'mainnav') {
 =item checkonthis()              var storedpath = "$docs_folderpath";
               if (storedpath == '') {
 check on this                  storedpath = "$docs_pagepath";
               }
 =item verifycontent()              var storedpage = "$main_container_page";
               var reg = new RegExp("^supplemental");
 Verify Content              if (pageId == 'mainCourseDocuments') {
                   if (storedpage == 1) {
 =item devalidateversioncache() & checkversions()                      document.simpleedit.folderpath.value = '';
                       document.uploaddocument.folderpath.value = '';
 Check Versions                  } else {
                       if (reg.test(storedpath)) {
 =item mark_hash_old()                          document.simpleedit.folderpath.value = '$toplevelmain';
                           document.uploaddocument.folderpath.value = '$toplevelmain';
 =item is_hash_old()                          document.newext.folderpath.value = '$toplevelmain';
                       } else {
 =item changewarning()                          document.simpleedit.folderpath.value = storedpath;
                           document.uploaddocument.folderpath.value = storedpath;
 =item init_breadcrumbs()                          document.newext.folderpath.value = storedpath;
                       }
 Breadcrumbs for special functions                  }
               } else {
 =back                  if (reg.test(storedpath)) {
                       document.simpleedit.folderpath.value = storedpath;
 =cut                      document.supuploaddocument.folderpath.value = storedpath;
                       document.supnewext.folderpath.value = storedpath;
                   } else {
                       document.simpleedit.folderpath.value = '$toplevelsupp';
                       document.supuploaddocument.folderpath.value = '$toplevelsupp';
                       document.supnewext.folderpath.value = '$toplevelsupp';
                   }
               }
           }
           resize_scrollbox('contentscroll','1','0');
    return false;
   }
   
   function toContents(jumpto) {
       var newurl = '$backtourl';
       if (jumpto != '') {
           newurl = newurl+'?postdata='+jumpto;
   ;
       }
       location.href=newurl;
   }
   
   ENDNEWSCRIPT
   }
   
   sub history_tab_js {
       return <<"ENDHIST";
   function toggleHistoryDisp(choice) {
       document.docslogform.docslog.value = choice;
       document.docslogform.submit();
       return;
   }
   
   ENDHIST
   }
   
   sub inject_data_js {
       return <<ENDINJECT;
   
   function injectData(current, hiddenField, name, value) {
           currentElement = document.getElementById(hiddenField);
           currentElement.name = name;
           currentElement.value = value;
           current.submit();
   }
   
   ENDINJECT
   }
   
   sub dump_switchserver_js {
       my @hosts = @_;
       my %lt = &Apache::lonlocal::texthash(
           dump => 'Dumping to Authoring Space requires switching server.',
           swit => 'Switch server?',
           duco => 'Dump content to Authoring Space',
           yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
           chos => 'Choose server',
       );
       my $role = $env{'request.role'};
       my $js = <<"ENDSWJS";
   <script type="text/javascript">
   function write_switchserver() {
       var server;
       if (document.setserver.posshosts.length > 0) {
           for (var i=0; i<document.setserver.posshosts.length; i++) {
               if (document.setserver.posshosts[i].checked) {
                   server = document.setserver.posshosts[i].value;
               }
          }
          opener.document.location.href="/adm/switchserver?otherserver="+server+"&role=$role&origurl=/adm/coursedocs";
       }
       window.close();
   }
   </script>
   
   ENDSWJS
   
       my $startpage = &Apache::loncommon::start_page('Choose server',$js,
                                                      {'only_body' => 1,
                                                       'js_ready'  => 1,});
       my $endpage = &Apache::loncommon::end_page({'js_ready'  => 1});
   
       my $hostpicker;
       my $count = 0;
       foreach my $host (sort(@hosts)) {
           my $checked;
           if ($count == 0) {
               $checked = ' checked="checked"';
           }
           $hostpicker .= '<label><input type="radio" name="posshosts" value="'.
                          $host.'"'.$checked.' />'.$host.'</label>&nbsp;&nbsp;';
           $count++;
       }
       
       return <<"ENDSWITCHJS";
   
   function dump_needs_switchserver(url) {
       if (url!='' && url!= null) {
           if (confirm("$lt{'dump'}\\n$lt{'swit'}")) {
               go(url);
           }
       }
       return;
   }
   
   function choose_switchserver_window() {
       newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
       newWindow.document.open();
       newWindow.document.writeln('$startpage');
       newWindow.document.write('<h3>$lt{'duco'}<\\/h3>\\n'+
          '<p>$lt{'yone'}<\\/p>\\n'+
          '<div class="LC_left_float"><fieldset><legend>$lt{'chos'}<\\/legend>\\n'+
          '<form name="setserver" method="post" action="" \\/>\\n'+
          '$hostpicker\\n'+
          '<br \\/><br \\/>\\n'+
          '<input type="button" name="makeswitch" value="$lt{'swit'}" '+
          'onclick="write_switchserver();" \\/>\\n'+
          '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
       newWindow.document.writeln('$endpage');
       newWindow.document.close();
       newWindow.focus();
   }
   
   ENDSWITCHJS
   }
   
   sub makedocslogform {
       my ($formelems,$docslog) = @_;
       return <<"LOGSFORM";
    <form action="/adm/coursedocs" method="post" name="docslogform">
      <input type="hidden" name="docslog" value="$docslog" />
      $formelems
    </form>
   LOGSFORM
   }
   
   sub makesimpleeditform {
       my ($formelems) = @_;
       return <<"SIMPFORM";
    <form name="simpleedit" method="post" action="/adm/coursedocs">
      <input type="hidden" name="importdetail" value="" />
      $formelems
    </form>
   SIMPFORM
   }
   
   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 clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   =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
   
   =item create_list_elements()
   
   =item create_form_ul()
   
   =item startContentScreen() 
   
   =item endContentScreen()
   
   =item supplemental_base()
   
   =item embedded_form_elems()
   
   =item embedded_destination()
   
   =item return_to_editor()
   
   =item decompression_info()
   
   =item decompression_phase_one()
   
   =item decompression_phase_two()
   
   =item remove_archive()
   
   =item generate_admin_menu()
   
   =item generate_edit_table()
   
   =item editing_js()
   
   =item history_tab_js()
   
   =item inject_data_js()
   
   =item dump_switchserver_js()
   
   =item resize_scrollbox_js()
   
   =item makedocslogform()
   
   =item makesimpleeditform()
   
   =back
   
   =cut

Removed from v.1.326  
changed lines
  Added in v.1.486


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