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

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

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


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