File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.292: download - view: text, annotated - select for diffs
Mon Oct 7 13:50:36 2002 UTC (21 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Toward bug 531.

Can address most recent version.
Can find out with lonnet::getversion what the most recent version is
Shows versions in lonmeta

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.292 2002/10/07 13:50:36 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   30: # 11/8,11/16,11/18,11/22,11/23,12/22,
   31: # 01/06,01/13,02/24,02/28,02/29,
   32: # 03/01,03/02,03/06,03/07,03/13,
   33: # 04/05,05/29,05/31,06/01,
   34: # 06/05,06/26 Gerd Kortemeyer
   35: # 06/26 Ben Tyszka
   36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   37: # 08/14 Ben Tyszka
   38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   39: # 10/04 Gerd Kortemeyer
   40: # 10/04 Guy Albertelli
   41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   42: # 10/30,10/31,
   43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
   44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
   45: # 05/01/01 Guy Albertelli
   46: # 05/01,06/01,09/01 Gerd Kortemeyer
   47: # 09/01 Guy Albertelli
   48: # 09/01,10/01,11/01 Gerd Kortemeyer
   49: # YEAR=2001
   50: # 02/27/01 Scott Harrison
   51: # 3/2 Gerd Kortemeyer
   52: # 3/15,3/19 Scott Harrison
   53: # 3/19,3/20 Gerd Kortemeyer
   54: # 3/22,3/27,4/2,4/16,4/17 Scott Harrison
   55: # 5/26,5/28 Gerd Kortemeyer
   56: # 5/30 H. K. Ng
   57: # 6/1 Gerd Kortemeyer
   58: # July Guy Albertelli
   59: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
   60: # 10/2 Gerd Kortemeyer
   61: # 10/5,10/10,11/13,11/15 Scott Harrison
   62: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
   63: # 12/5 Matthew Hall
   64: # 12/5 Guy Albertelli
   65: # 12/6,12/7,12/12 Gerd Kortemeyer
   66: # 12/18 Scott Harrison
   67: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
   68: # YEAR=2002
   69: # 1/4,2/4,2/7 Gerd Kortemeyer
   70: #
   71: ###
   72: 
   73: package Apache::lonnet;
   74: 
   75: use strict;
   76: use Apache::File;
   77: use LWP::UserAgent();
   78: use HTTP::Headers;
   79: use vars 
   80: qw(%perlvar %hostname %homecache %badServerCache %hostip %spareid %hostdom 
   81:    %libserv %pr %prp %metacache %packagetab 
   82:    %courselogs %accesshash $processmarker $dumpcount 
   83:    %coursedombuf %coursehombuf %courseresdatacache %domaindescription);
   84: use IO::Socket;
   85: use GDBM_File;
   86: use Apache::Constants qw(:common :http);
   87: use HTML::LCParser;
   88: use Fcntl qw(:flock);
   89: my $readit;
   90: 
   91: # --------------------------------------------------------------------- Logging
   92: 
   93: sub logtouch {
   94:     my $execdir=$perlvar{'lonDaemons'};
   95:     unless (-e "$execdir/logs/lonnet.log") {
   96: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
   97: 	close $fh;
   98:     }
   99:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  100:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  101: }
  102: 
  103: sub logthis {
  104:     my $message=shift;
  105:     my $execdir=$perlvar{'lonDaemons'};
  106:     my $now=time;
  107:     my $local=localtime($now);
  108:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
  109:     print $fh "$local ($$): $message\n";
  110:     return 1;
  111: }
  112: 
  113: sub logperm {
  114:     my $message=shift;
  115:     my $execdir=$perlvar{'lonDaemons'};
  116:     my $now=time;
  117:     my $local=localtime($now);
  118:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
  119:     print $fh "$now:$message:$local\n";
  120:     return 1;
  121: }
  122: 
  123: # -------------------------------------------------- Non-critical communication
  124: sub subreply {
  125:     my ($cmd,$server)=@_;
  126:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  127:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  128:                                      Type    => SOCK_STREAM,
  129:                                      Timeout => 10)
  130:        or return "con_lost";
  131:     print $client "$cmd\n";
  132:     my $answer=<$client>;
  133:     if (!$answer) { $answer="con_lost"; }
  134:     chomp($answer);
  135:     return $answer;
  136: }
  137: 
  138: sub reply {
  139:     my ($cmd,$server)=@_;
  140:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  141:     my $answer=subreply($cmd,$server);
  142:     if ($answer eq 'con_lost') {
  143:        #sleep 5; 
  144:        #$answer=subreply($cmd,$server);
  145:        #if ($answer eq 'con_lost') {
  146: 	#   &logthis("Second attempt con_lost on $server");
  147:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
  148:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  149:         #                                    Type    => SOCK_STREAM,
  150:         #                                    Timeout => 10)
  151:         #              or return "con_lost";
  152:         #   &logthis("Killing socket");
  153:         #   print $client "close_connection_exit\n";
  154:            #sleep 5;
  155:         #   $answer=subreply($cmd,$server);       
  156:        #}   
  157:     }
  158:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  159:        &logthis("<font color=blue>WARNING:".
  160:                 " $cmd to $server returned $answer</font>");
  161:     }
  162:     return $answer;
  163: }
  164: 
  165: # ----------------------------------------------------------- Send USR1 to lonc
  166: 
  167: sub reconlonc {
  168:     my $peerfile=shift;
  169:     &logthis("Trying to reconnect for $peerfile");
  170:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  171:     if (my $fh=Apache::File->new("$loncfile")) {
  172: 	my $loncpid=<$fh>;
  173:         chomp($loncpid);
  174:         if (kill 0 => $loncpid) {
  175: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  176:             kill USR1 => $loncpid;
  177:             sleep 1;
  178:             if (-e "$peerfile") { return; }
  179:             &logthis("$peerfile still not there, give it another try");
  180:             sleep 5;
  181:             if (-e "$peerfile") { return; }
  182:             &logthis(
  183:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  184:         } else {
  185: 	    &logthis(
  186:                "<font color=blue>WARNING:".
  187:                " lonc at pid $loncpid not responding, giving up</font>");
  188:         }
  189:     } else {
  190:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  191:     }
  192: }
  193: 
  194: # ------------------------------------------------------ Critical communication
  195: 
  196: sub critical {
  197:     my ($cmd,$server)=@_;
  198:     unless ($hostname{$server}) {
  199:         &logthis("<font color=blue>WARNING:".
  200:                " Critical message to unknown server ($server)</font>");
  201:         return 'no_such_host';
  202:     }
  203:     my $answer=reply($cmd,$server);
  204:     if ($answer eq 'con_lost') {
  205:         my $pingreply=reply('ping',$server);
  206: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  207:         my $pongreply=reply('pong',$server);
  208:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
  209:         $answer=reply($cmd,$server);
  210:         if ($answer eq 'con_lost') {
  211:             my $now=time;
  212:             my $middlename=$cmd;
  213:             $middlename=substr($middlename,0,16);
  214:             $middlename=~s/\W//g;
  215:             my $dfilename=
  216:              "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
  217:             {
  218:              my $dfh;
  219:              if ($dfh=Apache::File->new(">$dfilename")) {
  220:                 print $dfh "$cmd\n";
  221: 	     }
  222:             }
  223:             sleep 2;
  224:             my $wcmd='';
  225:             {
  226: 	     my $dfh;
  227:              if ($dfh=Apache::File->new("$dfilename")) {
  228:                 $wcmd=<$dfh>;
  229: 	     }
  230:             }
  231:             chomp($wcmd);
  232:             if ($wcmd eq $cmd) {
  233: 		&logthis("<font color=blue>WARNING: ".
  234:                          "Connection buffer $dfilename: $cmd</font>");
  235:                 &logperm("D:$server:$cmd");
  236: 	        return 'con_delayed';
  237:             } else {
  238:                 &logthis("<font color=red>CRITICAL:"
  239:                         ." Critical connection failed: $server $cmd</font>");
  240:                 &logperm("F:$server:$cmd");
  241:                 return 'con_failed';
  242:             }
  243:         }
  244:     }
  245:     return $answer;
  246: }
  247: 
  248: # ---------------------------------------------------------- Append Environment
  249: 
  250: sub appenv {
  251:     my %newenv=@_;
  252:     foreach (keys %newenv) {
  253: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  254:             &logthis("<font color=blue>WARNING: ".
  255:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  256:                 .'</font>');
  257: 	    delete($newenv{$_});
  258:         } else {
  259:             $ENV{$_}=$newenv{$_};
  260:         }
  261:     }
  262: 
  263:     my $lockfh;
  264:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
  265:        return 'error: '.$!;
  266:     }
  267:     unless (flock($lockfh,LOCK_EX)) {
  268:          &logthis("<font color=blue>WARNING: ".
  269:                   'Could not obtain exclusive lock in appenv: '.$!);
  270:          $lockfh->close();
  271:          return 'error: '.$!;
  272:     }
  273: 
  274:     my @oldenv;
  275:     {
  276:      my $fh;
  277:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  278: 	return 'error: '.$!;
  279:      }
  280:      @oldenv=<$fh>;
  281:      $fh->close();
  282:     }
  283:     for (my $i=0; $i<=$#oldenv; $i++) {
  284:         chomp($oldenv[$i]);
  285:         if ($oldenv[$i] ne '') {
  286:            my ($name,$value)=split(/=/,$oldenv[$i]);
  287:            unless (defined($newenv{$name})) {
  288: 	      $newenv{$name}=$value;
  289: 	   }
  290:         }
  291:     }
  292:     {
  293:      my $fh;
  294:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  295: 	return 'error';
  296:      }
  297:      my $newname;
  298:      foreach $newname (keys %newenv) {
  299: 	 print $fh "$newname=$newenv{$newname}\n";
  300:      }
  301:      $fh->close();
  302:     }
  303: 
  304:     $lockfh->close();
  305:     return 'ok';
  306: }
  307: # ----------------------------------------------------- Delete from Environment
  308: 
  309: sub delenv {
  310:     my $delthis=shift;
  311:     my %newenv=();
  312:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  313:         &logthis("<font color=blue>WARNING: ".
  314:                 "Attempt to delete from environment ".$delthis);
  315:         return 'error';
  316:     }
  317:     my @oldenv;
  318:     {
  319:      my $fh;
  320:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  321: 	return 'error';
  322:      }
  323:      unless (flock($fh,LOCK_SH)) {
  324:          &logthis("<font color=blue>WARNING: ".
  325:                   'Could not obtain shared lock in delenv: '.$!);
  326:          $fh->close();
  327:          return 'error: '.$!;
  328:      }
  329:      @oldenv=<$fh>;
  330:      $fh->close();
  331:     }
  332:     {
  333:      my $fh;
  334:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  335: 	return 'error';
  336:      }
  337:      unless (flock($fh,LOCK_EX)) {
  338:          &logthis("<font color=blue>WARNING: ".
  339:                   'Could not obtain exclusive lock in delenv: '.$!);
  340:          $fh->close();
  341:          return 'error: '.$!;
  342:      }
  343:      foreach (@oldenv) {
  344: 	 unless ($_=~/^$delthis/) { print $fh $_; }
  345:      }
  346:      $fh->close();
  347:     }
  348:     return 'ok';
  349: }
  350: 
  351: # ------------------------------------------ Fight off request when overloaded
  352: 
  353: sub overloaderror {
  354:     my ($r,$checkserver)=@_;
  355:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  356:     my $loadavg;
  357:     if ($checkserver eq $perlvar{'lonHostID'}) {
  358:        my $loadfile=Apache::File->new('/proc/loadavg');
  359:        $loadavg=<$loadfile>;
  360:        $loadavg =~ s/\s.*//g;
  361:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  362:     } else {
  363:        $loadavg=&reply('load',$checkserver);
  364:     }
  365:     my $overload=$loadavg-100;
  366:     if ($overload>0) {
  367: 	$r->err_headers_out->{'Retry-After'}=$overload;
  368:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  369:         return 413;
  370:     }    
  371:     return '';
  372: }
  373: 
  374: # ------------------------------ Find server with least workload from spare.tab
  375: 
  376: sub spareserver {
  377:     my $loadpercent = shift;
  378:     my $tryserver;
  379:     my $spareserver='';
  380:     my $lowestserver=$loadpercent; 
  381:     foreach $tryserver (keys %spareid) {
  382:        my $answer=reply('load',$tryserver);
  383:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  384: 	   $spareserver="http://$hostname{$tryserver}";
  385:            $lowestserver=$answer;
  386:        }
  387:     }    
  388:     return $spareserver;
  389: }
  390: 
  391: # --------------------------------------------- Try to change a user's password
  392: 
  393: sub changepass {
  394:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  395:     $currentpass = &escape($currentpass);
  396:     $newpass     = &escape($newpass);
  397:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  398: 		       $server);
  399:     if (! $answer) {
  400: 	&logthis("No reply on password change request to $server ".
  401: 		 "by $uname in domain $udom.");
  402:     } elsif ($answer =~ "^ok") {
  403:         &logthis("$uname in $udom successfully changed their password ".
  404: 		 "on $server.");
  405:     } elsif ($answer =~ "^pwchange_failure") {
  406: 	&logthis("$uname in $udom was unable to change their password ".
  407: 		 "on $server.  The action was blocked by either lcpasswd ".
  408: 		 "or pwchange");
  409:     } elsif ($answer =~ "^non_authorized") {
  410:         &logthis("$uname in $udom did not get their password correct when ".
  411: 		 "attempting to change it on $server.");
  412:     } elsif ($answer =~ "^auth_mode_error") {
  413:         &logthis("$uname in $udom attempted to change their password despite ".
  414: 		 "not being locally or internally authenticated on $server.");
  415:     } elsif ($answer =~ "^unknown_user") {
  416:         &logthis("$uname in $udom attempted to change their password ".
  417: 		 "on $server but were unable to because $server is not ".
  418: 		 "their home server.");
  419:     } elsif ($answer =~ "^refused") {
  420: 	&logthis("$server refused to change $uname in $udom password because ".
  421: 		 "it was sent an unencrypted request to change the password.");
  422:     }
  423:     return $answer;
  424: }
  425: 
  426: # ----------------------- Try to determine user's current authentication scheme
  427: 
  428: sub queryauthenticate {
  429:     my ($uname,$udom)=@_;
  430:     if (($perlvar{'lonRole'} eq 'library') && 
  431:         ($udom eq $perlvar{'lonDefDomain'})) {
  432: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
  433: 			 $perlvar{'lonHostID'});
  434: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  435: 	    if (length($answer)) {
  436: 		return $answer;
  437: 	    }
  438: 	    else {
  439: 	&logthis("User $uname at $udom lacks an authentication mechanism");
  440: 		return 'no_host';
  441: 	    }
  442: 	}
  443:     }
  444: 
  445:     my $tryserver;
  446:     foreach $tryserver (keys %libserv) {
  447: 	if ($hostdom{$tryserver} eq $udom) {
  448:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
  449: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  450: 	       if (length($answer)) {
  451: 		   return $answer;
  452: 	       }
  453: 	       else {
  454: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
  455: 		   return 'no_host';
  456: 	       }
  457: 	   }
  458:        }
  459:     }
  460:     &logthis("User $uname at $udom lacks an authentication mechanism");    
  461:     return 'no_host';
  462: }
  463: 
  464: # --------- Try to authenticate user from domain's lib servers (first this one)
  465: 
  466: sub authenticate {
  467:     my ($uname,$upass,$udom)=@_;
  468:     $upass=escape($upass);
  469:     $uname=~s/\W//g;
  470:     if (($perlvar{'lonRole'} eq 'library') && 
  471:         ($udom eq $perlvar{'lonDefDomain'})) {
  472:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
  473:         if ($answer =~ /authorized/) {
  474:               if ($answer eq 'authorized') {
  475:                  &logthis("User $uname at $udom authorized by local server"); 
  476:                  return $perlvar{'lonHostID'}; 
  477:               }
  478:               if ($answer eq 'non_authorized') {
  479:                  &logthis("User $uname at $udom rejected by local server"); 
  480:                  return 'no_host'; 
  481:               }
  482: 	}
  483:     }
  484: 
  485:     my $tryserver;
  486:     foreach $tryserver (keys %libserv) {
  487: 	if ($hostdom{$tryserver} eq $udom) {
  488:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
  489:            if ($answer =~ /authorized/) {
  490:               if ($answer eq 'authorized') {
  491:                  &logthis("User $uname at $udom authorized by $tryserver"); 
  492:                  return $tryserver; 
  493:               }
  494:               if ($answer eq 'non_authorized') {
  495:                  &logthis("User $uname at $udom rejected by $tryserver");
  496:                  return 'no_host';
  497:               } 
  498: 	   }
  499:        }
  500:     }
  501:     &logthis("User $uname at $udom could not be authenticated");    
  502:     return 'no_host';
  503: }
  504: 
  505: # ---------------------- Find the homebase for a user from domain's lib servers
  506: 
  507: sub homeserver {
  508:     my ($uname,$udom,$ignoreBadCache)=@_;
  509:     my $index="$uname:$udom";
  510:     if ($homecache{$index}) { 
  511:         return "$homecache{$index}"; 
  512:     }
  513:     my $tryserver;
  514:     foreach $tryserver (keys %libserv) {
  515:         next if ($ignoreBadCache ne 'true' && 
  516: 		 exists($badServerCache{$tryserver}));
  517: 	if ($hostdom{$tryserver} eq $udom) {
  518:            my $answer=reply("home:$udom:$uname",$tryserver);
  519:            if ($answer eq 'found') { 
  520:               $homecache{$index}=$tryserver;
  521:               return $tryserver; 
  522:            } elsif ($answer eq 'no_host') {
  523: 	       $badServerCache{$tryserver}=1;
  524:            }
  525:        }
  526:     }    
  527:     return 'no_host';
  528: }
  529: 
  530: # ------------------------------------- Find the usernames behind a list of IDs
  531: 
  532: sub idget {
  533:     my ($udom,@ids)=@_;
  534:     my %returnhash=();
  535:     
  536:     my $tryserver;
  537:     foreach $tryserver (keys %libserv) {
  538:        if ($hostdom{$tryserver} eq $udom) {
  539: 	  my $idlist=join('&',@ids);
  540:           $idlist=~tr/A-Z/a-z/; 
  541: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  542:           my @answer=();
  543:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  544: 	      @answer=split(/\&/,$reply);
  545:           }                    ;
  546:           my $i;
  547:           for ($i=0;$i<=$#ids;$i++) {
  548:               if ($answer[$i]) {
  549: 		  $returnhash{$ids[$i]}=$answer[$i];
  550:               } 
  551:           }
  552:        }
  553:     }    
  554:     return %returnhash;
  555: }
  556: 
  557: # ------------------------------------- Find the IDs behind a list of usernames
  558: 
  559: sub idrget {
  560:     my ($udom,@unames)=@_;
  561:     my %returnhash=();
  562:     foreach (@unames) {
  563:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  564:     }
  565:     return %returnhash;
  566: }
  567: 
  568: # ------------------------------- Store away a list of names and associated IDs
  569: 
  570: sub idput {
  571:     my ($udom,%ids)=@_;
  572:     my %servers=();
  573:     foreach (keys %ids) {
  574:         my $uhom=&homeserver($_,$udom);
  575:         if ($uhom ne 'no_host') {
  576:             my $id=&escape($ids{$_});
  577:             $id=~tr/A-Z/a-z/;
  578:             my $unam=&escape($_);
  579: 	    if ($servers{$uhom}) {
  580: 		$servers{$uhom}.='&'.$id.'='.$unam;
  581:             } else {
  582:                 $servers{$uhom}=$id.'='.$unam;
  583:             }
  584:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
  585:         }
  586:     }
  587:     foreach (keys %servers) {
  588:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  589:     }
  590: }
  591: 
  592: # ------------------------------------- Find the section of student in a course
  593: 
  594: sub usection {
  595:     my ($udom,$unam,$courseid)=@_;
  596:     $courseid=~s/\_/\//g;
  597:     $courseid=~s/^(\w)/\/$1/;
  598:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  599:                         &homeserver($unam,$udom)))) {
  600:         my ($key,$value)=split(/\=/,$_);
  601:         $key=&unescape($key);
  602:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
  603:             my $section=$1;
  604:             if ($key eq $courseid.'_st') { $section=''; }
  605: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  606:             my $now=time;
  607:             my $notactive=0;
  608:             if ($start) {
  609: 		if ($now<$start) { $notactive=1; }
  610:             }
  611:             if ($end) {
  612:                 if ($now>$end) { $notactive=1; }
  613:             } 
  614:             unless ($notactive) { return $section; }
  615:         }
  616:     }
  617:     return '-1';
  618: }
  619: 
  620: # ------------------------------------- Read an entry from a user's environment
  621: 
  622: sub userenvironment {
  623:     my ($udom,$unam,@what)=@_;
  624:     my %returnhash=();
  625:     my @answer=split(/\&/,
  626:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  627:                       &homeserver($unam,$udom)));
  628:     my $i;
  629:     for ($i=0;$i<=$#what;$i++) {
  630: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  631:     }
  632:     return %returnhash;
  633: }
  634: 
  635: # -------------------------------------------------------------------- New chat
  636: 
  637: sub chatsend {
  638:     my ($newentry,$anon)=@_;
  639:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  640:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  641:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
  642:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
  643: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
  644: 		   &escape($newentry)),$chome);
  645: }
  646: 
  647: # ------------------------------------------ Find current version of a resource
  648: 
  649: sub getversion {
  650:     my $fname=&clutter(shift);
  651:     unless ($fname=~/^\/res\//) { return -1; }
  652:     return &currentversion(&filelocation('',$fname));
  653: }
  654: 
  655: sub currentversion {
  656:     my $fname=shift;
  657:     my $author=$fname;
  658:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  659:     my ($udom,$uname)=split(/\//,$author);
  660:     my $home=homeserver($uname,$udom);
  661:     if ($home eq 'no_host') { 
  662:         return -1; 
  663:     }
  664:     my $answer=reply("currentversion:$fname",$home);
  665:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  666: 	return -1;
  667:     }
  668:     return $answer;
  669: }
  670: 
  671: # ----------------------------- Subscribe to a resource, return URL if possible
  672: 
  673: sub subscribe {
  674:     my $fname=shift;
  675:     my $author=$fname;
  676:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  677:     my ($udom,$uname)=split(/\//,$author);
  678:     my $home=homeserver($uname,$udom);
  679:     if ($home eq 'no_host') { 
  680:         return 'not_found'; 
  681:     }
  682:     my $answer=reply("sub:$fname",$home);
  683:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  684: 	$answer.=' by '.$home;
  685:     }
  686:     return $answer;
  687: }
  688:     
  689: # -------------------------------------------------------------- Replicate file
  690: 
  691: sub repcopy {
  692:     my $filename=shift;
  693:     $filename=~s/\/+/\//g;
  694:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
  695:     my $transname="$filename.in.transfer";
  696:     if ((-e $filename) || (-e $transname)) { return OK; }
  697:     my $remoteurl=subscribe($filename);
  698:     if ($remoteurl =~ /^con_lost by/) {
  699: 	   &logthis("Subscribe returned $remoteurl: $filename");
  700:            return HTTP_SERVICE_UNAVAILABLE;
  701:     } elsif ($remoteurl eq 'not_found') {
  702: 	   &logthis("Subscribe returned not_found: $filename");
  703: 	   return HTTP_NOT_FOUND;
  704:     } elsif ($remoteurl =~ /^rejected by/) {
  705: 	   &logthis("Subscribe returned $remoteurl: $filename");
  706:            return FORBIDDEN;
  707:     } elsif ($remoteurl eq 'directory') {
  708:            return OK;
  709:     } else {
  710:         my $author=$filename;
  711:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  712:         my ($udom,$uname)=split(/\//,$author);
  713:         my $home=homeserver($uname,$udom);
  714:         unless ($home eq $perlvar{'lonHostID'}) {
  715:            my @parts=split(/\//,$filename);
  716:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  717:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
  718:                &logthis("Malconfiguration for replication: $filename");
  719: 	       return HTTP_BAD_REQUEST;
  720:            }
  721:            my $count;
  722:            for ($count=5;$count<$#parts;$count++) {
  723:                $path.="/$parts[$count]";
  724:                if ((-e $path)!=1) {
  725: 		   mkdir($path,0777);
  726:                }
  727:            }
  728:            my $ua=new LWP::UserAgent;
  729:            my $request=new HTTP::Request('GET',"$remoteurl");
  730:            my $response=$ua->request($request,$transname);
  731:            if ($response->is_error()) {
  732: 	       unlink($transname);
  733:                my $message=$response->status_line;
  734:                &logthis("<font color=blue>WARNING:"
  735:                        ." LWP get: $message: $filename</font>");
  736:                return HTTP_SERVICE_UNAVAILABLE;
  737:            } else {
  738: 	       if ($remoteurl!~/\.meta$/) {
  739:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
  740:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
  741:                   if ($mresponse->is_error()) {
  742: 		      unlink($filename.'.meta');
  743:                       &logthis(
  744:                      "<font color=yellow>INFO: No metadata: $filename</font>");
  745:                   }
  746: 	       }
  747:                rename($transname,$filename);
  748:                return OK;
  749:            }
  750:        }
  751:     }
  752: }
  753: 
  754: # --------------------------------------------------------- Server Side Include
  755: 
  756: sub ssi {
  757: 
  758:     my ($fn,%form)=@_;
  759: 
  760:     my $ua=new LWP::UserAgent;
  761:     
  762:     my $request;
  763:     
  764:     if (%form) {
  765:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
  766:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
  767:     } else {
  768:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
  769:     }
  770: 
  771:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
  772:     my $response=$ua->request($request);
  773: 
  774:     return $response->content;
  775: }
  776: 
  777: # ------- Add a token to a remote URI's query string to vouch for access rights
  778: 
  779: sub tokenwrapper {
  780:     my $uri=shift;
  781:     $uri=~s/^http\:\/\/([^\/]+)//;
  782:     $uri=~s/^\///;
  783:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
  784:     my $token=$1;
  785:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
  786: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
  787:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
  788:                (($uri=~/\?/)?'&':'?').'token='.$token;
  789:     } else {
  790: 	return '/adm/notfound.html';
  791:     }
  792: }
  793:     
  794: # --------------- Take an uploaded file and put it into the userfiles directory
  795: # input: name of form element, coursedoc=1 means this is for the course
  796: # output: url of file in userspace
  797: 
  798: sub userfileupload {
  799:     my ($formname,$coursedoc)=@_;
  800:     my $fname=$ENV{'form.'.$formname.'.filename'};
  801:     $fname=~s/\\/\//g;
  802:     $fname=~s/^.*\/([^\/]+)$/$1/;
  803:     unless ($fname) { return 'error: no uploaded file'; }
  804:     chop($ENV{'form.'.$formname});
  805: # Create the directory if not present
  806:     my $docuname='';
  807:     my $docudom='';
  808:     my $docuhome='';
  809:     if ($coursedoc) {
  810: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  811: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  812: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
  813:     } else {
  814:         $docuname=$ENV{'user.name'};
  815:         $docudom=$ENV{'user.domain'};
  816:         $docuhome=$ENV{'user.home'};
  817:     }
  818:     return 
  819:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
  820: }
  821: 
  822: sub finishuserfileupload {
  823:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
  824:     my $path=$docudom.'/'.$docuname.'/';
  825:     my $filepath=$perlvar{'lonDocRoot'};
  826:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
  827:     my $count;
  828:     for ($count=4;$count<=$#parts;$count++) {
  829:         $filepath.="/$parts[$count]";
  830:         if ((-e $filepath)!=1) {
  831: 	    mkdir($filepath,0777);
  832:         }
  833:     }
  834: # Save the file
  835:     {
  836:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
  837:        print $fh $ENV{'form.'.$formname};
  838:     }
  839: # Notify homeserver to grep it
  840: #
  841:     if 
  842: (&reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome) eq 'ok') 
  843:     {
  844: #
  845: # Return the URL to it
  846:         return '/uploaded/'.$path.$fname;
  847:     } else {
  848:         return '/adm/notfound.html';
  849:     }    
  850: }
  851: 
  852: # ------------------------------------------------------------------------- Log
  853: 
  854: sub log {
  855:     my ($dom,$nam,$hom,$what)=@_;
  856:     return critical("log:$dom:$nam:$what",$hom);
  857: }
  858: 
  859: # ------------------------------------------------------------------ Course Log
  860: 
  861: sub flushcourselogs {
  862:     &logthis('Flushing course log buffers');
  863:     foreach (keys %courselogs) {
  864:         my $crsid=$_;
  865:         if (&reply('log:'.$coursedombuf{$crsid}.':'.
  866: 		          &escape($courselogs{$crsid}),
  867: 		          $coursehombuf{$crsid}) eq 'ok') {
  868: 	    delete $courselogs{$crsid};
  869:         } else {
  870:             &logthis('Failed to flush log buffer for '.$crsid);
  871:             if (length($courselogs{$crsid})>40000) {
  872:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
  873:                         " exceeded maximum size, deleting.</font>");
  874:                delete $courselogs{$crsid};
  875:             }
  876:         }        
  877:     }
  878:     &logthis('Flushing access logs');
  879:     foreach (keys %accesshash) {
  880:         my $entry=$_;
  881:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
  882:         my %temphash=($entry => $accesshash{$entry});
  883:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
  884: 	    delete $accesshash{$entry};
  885:         }
  886:     }
  887:     $dumpcount++;
  888: }
  889: 
  890: sub courselog {
  891:     my $what=shift;
  892:     $what=time.':'.$what;
  893:     unless ($ENV{'request.course.id'}) { return ''; }
  894:     $coursedombuf{$ENV{'request.course.id'}}=
  895:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
  896:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  897:     $coursehombuf{$ENV{'request.course.id'}}=
  898:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
  899:     if (defined $courselogs{$ENV{'request.course.id'}}) {
  900: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
  901:     } else {
  902: 	$courselogs{$ENV{'request.course.id'}}.=$what;
  903:     }
  904:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
  905: 	&flushcourselogs();
  906:     }
  907: }
  908: 
  909: sub courseacclog {
  910:     my $fnsymb=shift;
  911:     unless ($ENV{'request.course.id'}) { return ''; }
  912:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
  913:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
  914:         $what.=':POST';
  915: 	foreach (keys %ENV) {
  916:             if ($_=~/^form\.(.*)/) {
  917: 		$what.=':'.$1.'='.$ENV{$_};
  918:             }
  919:         }
  920:     }
  921:     &courselog($what);
  922: }
  923: 
  924: sub countacc {
  925:     my $url=&declutter(shift);
  926:     unless ($ENV{'request.course.id'}) { return ''; }
  927:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
  928:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
  929:     if (defined($accesshash{$key})) {
  930: 	$accesshash{$key}++;
  931:     } else {
  932:         $accesshash{$key}=1;
  933:     }
  934: }
  935:     
  936: # ----------------------------------------------------------- Check out an item
  937: 
  938: sub checkout {
  939:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  940:     my $now=time;
  941:     my $lonhost=$perlvar{'lonHostID'};
  942:     my $infostr=&escape(
  943:                  'CHECKOUTTOKEN&'.
  944:                  $tuname.'&'.
  945:                  $tudom.'&'.
  946:                  $tcrsid.'&'.
  947:                  $symb.'&'.
  948: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
  949:     my $token=&reply('tmpput:'.$infostr,$lonhost);
  950:     if ($token=~/^error\:/) { 
  951:         &logthis("<font color=blue>WARNING: ".
  952:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
  953:                  "</font>");
  954:         return ''; 
  955:     }
  956: 
  957:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
  958:     $token=~tr/a-z/A-Z/;
  959: 
  960:     my %infohash=('resource.0.outtoken' => $token,
  961:                   'resource.0.checkouttime' => $now,
  962:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
  963: 
  964:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
  965:        return '';
  966:     } else {
  967:         &logthis("<font color=blue>WARNING: ".
  968:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
  969:                  "</font>");
  970:     }    
  971: 
  972:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
  973:                          &escape('Checkout '.$infostr.' - '.
  974:                                                  $token)) ne 'ok') {
  975: 	return '';
  976:     } else {
  977:         &logthis("<font color=blue>WARNING: ".
  978:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
  979:                  "</font>");
  980:     }
  981:     return $token;
  982: }
  983: 
  984: # ------------------------------------------------------------ Check in an item
  985: 
  986: sub checkin {
  987:     my $token=shift;
  988:     my $now=time;
  989:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
  990:     $lonhost=~tr/A-Z/a-z/;
  991:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
  992:     $dtoken=~s/\W/\_/g;
  993:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
  994:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
  995: 
  996:     unless (($tuname) && ($tudom)) {
  997:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
  998:         return '';
  999:     }
 1000:     
 1001:     unless (&allowed('mgr',$tcrsid)) {
 1002:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 1003:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
 1004:         return '';
 1005:     }
 1006: 
 1007:     my %infohash=('resource.0.intoken' => $token,
 1008:                   'resource.0.checkintime' => $now,
 1009:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 1010: 
 1011:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1012:        return '';
 1013:     }    
 1014: 
 1015:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1016:                          &escape('Checkin - '.$token)) ne 'ok') {
 1017: 	return '';
 1018:     }
 1019: 
 1020:     return ($symb,$tuname,$tudom,$tcrsid);    
 1021: }
 1022: 
 1023: # --------------------------------------------- Set Expire Date for Spreadsheet
 1024: 
 1025: sub expirespread {
 1026:     my ($uname,$udom,$stype,$usymb)=@_;
 1027:     my $cid=$ENV{'request.course.id'}; 
 1028:     if ($cid) {
 1029:        my $now=time;
 1030:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1031:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1032:                             $ENV{'course.'.$cid.'.num'}.
 1033: 	        	    ':nohist_expirationdates:'.
 1034:                             &escape($key).'='.$now,
 1035:                             $ENV{'course.'.$cid.'.home'})
 1036:     }
 1037:     return 'ok';
 1038: }
 1039: 
 1040: # ----------------------------------------------------- Devalidate Spreadsheets
 1041: 
 1042: sub devalidate {
 1043:     my $symb=shift;
 1044:     my $cid=$ENV{'request.course.id'}; 
 1045:     if ($cid) {
 1046: 	my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
 1047:         my $status=
 1048: 	    &del('nohist_calculatedsheet',
 1049: 		 [$key.'studentcalc'],
 1050: 		 $ENV{'course.'.$cid.'.domain'},
 1051: 		 $ENV{'course.'.$cid.'.num'})
 1052: 		.' '.
 1053: 	    &del('nohist_calculatedsheets_'.$cid,
 1054: 		 [$key.'assesscalc:'.$symb]);
 1055:         unless ($status eq 'ok ok') {
 1056:            &logthis('Could not devalidate spreadsheet '.
 1057:                     $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
 1058: 		    $symb.': '.$status);
 1059:         }
 1060:     }
 1061: }
 1062: 
 1063: sub get_scalar {
 1064:     my ($string,$end) = @_;
 1065:     my $value;
 1066:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 1067: 	$value = $1;
 1068:     } elsif ($$string =~ s/^([^&]*?)&//) {
 1069: 	$value = $1;
 1070:     }
 1071:     return &unescape($value);
 1072: }
 1073: 
 1074: sub array2str {
 1075:   my (@array) = @_;
 1076:   my $result=&arrayref2str(\@array);
 1077:   $result=~s/^__ARRAY_REF__//;
 1078:   $result=~s/__END_ARRAY_REF__$//;
 1079:   return $result;
 1080: }
 1081: 
 1082: sub arrayref2str {
 1083:   my ($arrayref) = @_;
 1084:   my $result='__ARRAY_REF__';
 1085:   foreach my $elem (@$arrayref) {
 1086:     if(ref($elem) eq 'ARRAY') {
 1087:       $result.=&arrayref2str($elem).'&';
 1088:     } elsif(ref($elem) eq 'HASH') {
 1089:       $result.=&hashref2str($elem).'&';
 1090:     } elsif(ref($elem)) {
 1091:       #print("Got a ref of ".(ref($elem))." skipping.");
 1092:     } else {
 1093:       $result.=&escape($elem).'&';
 1094:     }
 1095:   }
 1096:   $result=~s/\&$//;
 1097:   $result .= '__END_ARRAY_REF__';
 1098:   return $result;
 1099: }
 1100: 
 1101: sub hash2str {
 1102:   my (%hash) = @_;
 1103:   my $result=&hashref2str(\%hash);
 1104:   $result=~s/^__HASH_REF__//;
 1105:   $result=~s/__END_HASH_REF__$//;
 1106:   return $result;
 1107: }
 1108: 
 1109: sub hashref2str {
 1110:   my ($hashref)=@_;
 1111:   my $result='__HASH_REF__';
 1112:   foreach (keys(%$hashref)) {
 1113:     if (ref($_) eq 'ARRAY') {
 1114:       $result.=&arrayref2str($_).'=';
 1115:     } elsif (ref($_) eq 'HASH') {
 1116:       $result.=&hashref2str($_).'=';
 1117:     } elsif (ref($_)) {
 1118:       $result.='=';
 1119:       #print("Got a ref of ".(ref($_))." skipping.");
 1120:     } else {
 1121: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 1122:     }
 1123: 
 1124:     if(ref($hashref->{$_}) eq 'ARRAY') {
 1125:       $result.=&arrayref2str($hashref->{$_}).'&';
 1126:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 1127:       $result.=&hashref2str($hashref->{$_}).'&';
 1128:     } elsif(ref($hashref->{$_})) {
 1129:        $result.='&';
 1130:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 1131:     } else {
 1132:       $result.=&escape($hashref->{$_}).'&';
 1133:     }
 1134:   }
 1135:   $result=~s/\&$//;
 1136:   $result .= '__END_HASH_REF__';
 1137:   return $result;
 1138: }
 1139: 
 1140: sub str2hash {
 1141:     my ($string)=@_;
 1142:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 1143:     return %$hash;
 1144: }
 1145: 
 1146: sub str2hashref {
 1147:   my ($string) = @_;
 1148: 
 1149:   my %hash;
 1150: 
 1151:   if($string !~ /^__HASH_REF__/) {
 1152:       if (! ($string eq '' || !defined($string))) {
 1153: 	  $hash{'error'}='Not hash reference';
 1154:       }
 1155:       return (\%hash, $string);
 1156:   }
 1157: 
 1158:   $string =~ s/^__HASH_REF__//;
 1159: 
 1160:   while($string !~ /^__END_HASH_REF__/) {
 1161:       #key
 1162:       my $key='';
 1163:       if($string =~ /^__HASH_REF__/) {
 1164:           ($key, $string)=&str2hashref($string);
 1165:           if(defined($key->{'error'})) {
 1166:               $hash{'error'}='Bad data';
 1167:               return (\%hash, $string);
 1168:           }
 1169:       } elsif($string =~ /^__ARRAY_REF__/) {
 1170:           ($key, $string)=&str2arrayref($string);
 1171:           if($key->[0] eq 'Array reference error') {
 1172:               $hash{'error'}='Bad data';
 1173:               return (\%hash, $string);
 1174:           }
 1175:       } else {
 1176:           $string =~ s/^(.*?)=//;
 1177: 	  $key=&unescape($1);
 1178:       }
 1179:       $string =~ s/^=//;
 1180: 
 1181:       #value
 1182:       my $value='';
 1183:       if($string =~ /^__HASH_REF__/) {
 1184:           ($value, $string)=&str2hashref($string);
 1185:           if(defined($value->{'error'})) {
 1186:               $hash{'error'}='Bad data';
 1187:               return (\%hash, $string);
 1188:           }
 1189:       } elsif($string =~ /^__ARRAY_REF__/) {
 1190:           ($value, $string)=&str2arrayref($string);
 1191:           if($value->[0] eq 'Array reference error') {
 1192:               $hash{'error'}='Bad data';
 1193:               return (\%hash, $string);
 1194:           }
 1195:       } else {
 1196: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 1197:       }
 1198:       $string =~ s/^&//;
 1199: 
 1200:       $hash{$key}=$value;
 1201:   }
 1202: 
 1203:   $string =~ s/^__END_HASH_REF__//;
 1204: 
 1205:   return (\%hash, $string);
 1206: }
 1207: 
 1208: sub str2array {
 1209:     my ($string)=@_;
 1210:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 1211:     return @$array;
 1212: }
 1213: 
 1214: sub str2arrayref {
 1215:   my ($string) = @_;
 1216:   my @array;
 1217: 
 1218:   if($string !~ /^__ARRAY_REF__/) {
 1219:       if (! ($string eq '' || !defined($string))) {
 1220: 	  $array[0]='Array reference error';
 1221:       }
 1222:       return (\@array, $string);
 1223:   }
 1224: 
 1225:   $string =~ s/^__ARRAY_REF__//;
 1226: 
 1227:   while($string !~ /^__END_ARRAY_REF__/) {
 1228:       my $value='';
 1229:       if($string =~ /^__HASH_REF__/) {
 1230:           ($value, $string)=&str2hashref($string);
 1231:           if(defined($value->{'error'})) {
 1232:               $array[0] ='Array reference error';
 1233:               return (\@array, $string);
 1234:           }
 1235:       } elsif($string =~ /^__ARRAY_REF__/) {
 1236:           ($value, $string)=&str2arrayref($string);
 1237:           if($value->[0] eq 'Array reference error') {
 1238:               $array[0] ='Array reference error';
 1239:               return (\@array, $string);
 1240:           }
 1241:       } else {
 1242: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 1243:       }
 1244:       $string =~ s/^&//;
 1245: 
 1246:       push(@array, $value);
 1247:   }
 1248: 
 1249:   $string =~ s/^__END_ARRAY_REF__//;
 1250: 
 1251:   return (\@array, $string);
 1252: }
 1253: 
 1254: # -------------------------------------------------------------------Temp Store
 1255: 
 1256: sub tmpreset {
 1257:   my ($symb,$namespace,$domain,$stuname) = @_;
 1258:   if (!$symb) {
 1259:     $symb=&symbread();
 1260:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
 1261:   }
 1262:   $symb=escape($symb);
 1263: 
 1264:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1265:   $namespace=~s/\//\_/g;
 1266:   $namespace=~s/\W//g;
 1267: 
 1268:   #FIXME needs to do something for /pub resources
 1269:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1270:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1271:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1272:   my %hash;
 1273:   if (tie(%hash,'GDBM_File',
 1274: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1275: 	  &GDBM_WRCREAT(),0640)) {
 1276:     foreach my $key (keys %hash) {
 1277:       if ($key=~ /:$symb/) {
 1278: 	delete($hash{$key});
 1279:       }
 1280:     }
 1281:   }
 1282: }
 1283: 
 1284: sub tmpstore {
 1285:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1286: 
 1287:   if (!$symb) {
 1288:     $symb=&symbread();
 1289:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1290:   }
 1291:   $symb=escape($symb);
 1292: 
 1293:   if (!$namespace) {
 1294:     # I don't think we would ever want to store this for a course.
 1295:     # it seems this will only be used if we don't have a course.
 1296:     #$namespace=$ENV{'request.course.id'};
 1297:     #if (!$namespace) {
 1298:       $namespace=$ENV{'request.state'};
 1299:     #}
 1300:   }
 1301:   $namespace=~s/\//\_/g;
 1302:   $namespace=~s/\W//g;
 1303: #FIXME needs to do something for /pub resources
 1304:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1305:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1306:   my $now=time;
 1307:   my %hash;
 1308:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1309:   if (tie(%hash,'GDBM_File',
 1310: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1311: 	  &GDBM_WRCREAT(),0640)) {
 1312:     $hash{"version:$symb"}++;
 1313:     my $version=$hash{"version:$symb"};
 1314:     my $allkeys=''; 
 1315:     foreach my $key (keys(%$storehash)) {
 1316:       $allkeys.=$key.':';
 1317:       $hash{"$version:$symb:$key"}=$$storehash{$key};
 1318:     }
 1319:     $hash{"$version:$symb:timestamp"}=$now;
 1320:     $allkeys.='timestamp';
 1321:     $hash{"$version:keys:$symb"}=$allkeys;
 1322:     if (untie(%hash)) {
 1323:       return 'ok';
 1324:     } else {
 1325:       return "error:$!";
 1326:     }
 1327:   } else {
 1328:     return "error:$!";
 1329:   }
 1330: }
 1331: 
 1332: # -----------------------------------------------------------------Temp Restore
 1333: 
 1334: sub tmprestore {
 1335:   my ($symb,$namespace,$domain,$stuname) = @_;
 1336: 
 1337:   if (!$symb) {
 1338:     $symb=&symbread();
 1339:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1340:   }
 1341:   $symb=escape($symb);
 1342: 
 1343:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1344:   #FIXME needs to do something for /pub resources
 1345:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1346:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1347: 
 1348:   my %returnhash;
 1349:   $namespace=~s/\//\_/g;
 1350:   $namespace=~s/\W//g;
 1351:   my %hash;
 1352:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1353:   if (tie(%hash,'GDBM_File',
 1354: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1355: 	  &GDBM_READER(),0640)) {
 1356:     my $version=$hash{"version:$symb"};
 1357:     $returnhash{'version'}=$version;
 1358:     my $scope;
 1359:     for ($scope=1;$scope<=$version;$scope++) {
 1360:       my $vkeys=$hash{"$scope:keys:$symb"};
 1361:       my @keys=split(/:/,$vkeys);
 1362:       my $key;
 1363:       $returnhash{"$scope:keys"}=$vkeys;
 1364:       foreach $key (@keys) {
 1365: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
 1366: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
 1367:       }
 1368:     }
 1369:     if (!(untie(%hash))) {
 1370:       return "error:$!";
 1371:     }
 1372:   } else {
 1373:     return "error:$!";
 1374:   }
 1375:   return %returnhash;
 1376: }
 1377: 
 1378: # ----------------------------------------------------------------------- Store
 1379: 
 1380: sub store {
 1381:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1382:     my $home='';
 1383: 
 1384:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1385: 
 1386:     $symb=&symbclean($symb);
 1387:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1388: 
 1389:     &devalidate($symb);
 1390: 
 1391:     $symb=escape($symb);
 1392:     if (!$namespace) { 
 1393:        unless ($namespace=$ENV{'request.course.id'}) { 
 1394:           return ''; 
 1395:        } 
 1396:     }
 1397:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1398:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1399:     if (!$home) { $home=$ENV{'user.home'}; }
 1400:     my $namevalue='';
 1401:     foreach (keys %$storehash) {
 1402:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1403:     }
 1404:     $namevalue=~s/\&$//;
 1405:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 1406:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1407: }
 1408: 
 1409: # -------------------------------------------------------------- Critical Store
 1410: 
 1411: sub cstore {
 1412:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1413:     my $home='';
 1414: 
 1415:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1416: 
 1417:     $symb=&symbclean($symb);
 1418:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1419: 
 1420:     &devalidate($symb);
 1421: 
 1422:     $symb=escape($symb);
 1423:     if (!$namespace) { 
 1424:        unless ($namespace=$ENV{'request.course.id'}) { 
 1425:           return ''; 
 1426:        } 
 1427:     }
 1428:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1429:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1430:     if (!$home) { $home=$ENV{'user.home'}; }
 1431: 
 1432:     my $namevalue='';
 1433:     foreach (keys %$storehash) {
 1434:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1435:     }
 1436:     $namevalue=~s/\&$//;
 1437:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 1438:     return critical
 1439:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1440: }
 1441: 
 1442: # --------------------------------------------------------------------- Restore
 1443: 
 1444: sub restore {
 1445:     my ($symb,$namespace,$domain,$stuname) = @_;
 1446:     my $home='';
 1447: 
 1448:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1449: 
 1450:     if (!$symb) {
 1451:       unless ($symb=escape(&symbread())) { return ''; }
 1452:     } else {
 1453:       $symb=&escape(&symbclean($symb));
 1454:     }
 1455:     if (!$namespace) { 
 1456:        unless ($namespace=$ENV{'request.course.id'}) { 
 1457:           return ''; 
 1458:        } 
 1459:     }
 1460:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1461:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1462:     if (!$home) { $home=$ENV{'user.home'}; }
 1463:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 1464: 
 1465:     my %returnhash=();
 1466:     foreach (split(/\&/,$answer)) {
 1467: 	my ($name,$value)=split(/\=/,$_);
 1468:         $returnhash{&unescape($name)}=&unescape($value);
 1469:     }
 1470:     my $version;
 1471:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1472:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 1473:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1474:        }
 1475:     }
 1476:     return %returnhash;
 1477: }
 1478: 
 1479: # ---------------------------------------------------------- Course Description
 1480: 
 1481: sub coursedescription {
 1482:     my $courseid=shift;
 1483:     $courseid=~s/^\///;
 1484:     $courseid=~s/\_/\//g;
 1485:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1486:     my $chome=&homeserver($cnum,$cdomain);
 1487:     if ($chome ne 'no_host') {
 1488:        my %returnhash=&dump('environment',$cdomain,$cnum);
 1489:        if (!exists($returnhash{'con_lost'})) {
 1490:            my $normalid=$cdomain.'_'.$cnum;
 1491:            my %envhash=();
 1492:            $returnhash{'home'}= $chome;
 1493: 	   $returnhash{'domain'} = $cdomain;
 1494: 	   $returnhash{'num'} = $cnum;
 1495:            while (my ($name,$value) = each %returnhash) {
 1496:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 1497:            }
 1498:            $returnhash{'url'}=&clutter($returnhash{'url'});
 1499:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 1500: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 1501:            $envhash{'course.'.$normalid.'.last_cache'}=time;
 1502:            $envhash{'course.'.$normalid.'.home'}=$chome;
 1503:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 1504:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 1505:            &appenv(%envhash);
 1506:            return %returnhash;
 1507:        }
 1508:     }
 1509:     return ();
 1510: }
 1511: 
 1512: # -------------------------------------------------------- Get user privileges
 1513: 
 1514: sub rolesinit {
 1515:     my ($domain,$username,$authhost)=@_;
 1516:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 1517:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 1518:     my %allroles=();
 1519:     my %thesepriv=();
 1520:     my $now=time;
 1521:     my $userroles="user.login.time=$now\n";
 1522:     my $thesestr;
 1523: 
 1524:     if ($rolesdump ne '') {
 1525:         foreach (split(/&/,$rolesdump)) {
 1526: 	  if ($_!~/^rolesdef\&/) {
 1527:             my ($area,$role)=split(/=/,$_);
 1528:             $area=~s/\_\w\w$//;
 1529:             my ($trole,$tend,$tstart)=split(/_/,$role);
 1530:             $userroles.='user.role.'.$trole.'.'.$area.'='.
 1531:                         $tstart.'.'.$tend."\n";
 1532:             if ($tend!=0) {
 1533: 	        if ($tend<$now) {
 1534: 	            $trole='';
 1535:                 } 
 1536:             }
 1537:             if ($tstart!=0) {
 1538:                 if ($tstart>$now) {
 1539:                    $trole='';        
 1540:                 }
 1541:             }
 1542:             if (($area ne '') && ($trole ne '')) {
 1543: 	       my $spec=$trole.'.'.$area;
 1544:                my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 1545:                if ($trole =~ /^cr\//) {
 1546: 		   my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 1547:                    my $homsvr=homeserver($rauthor,$rdomain);
 1548:                    if ($hostname{$homsvr} ne '') {
 1549:                       my $roledef=
 1550: 			  reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
 1551:                                 $homsvr);
 1552:                       if (($roledef ne 'con_lost') && ($roledef ne '')) {
 1553:                          my ($syspriv,$dompriv,$coursepriv)=
 1554: 			     split(/\_/,unescape($roledef));
 1555:  	                 $allroles{'cm./'}.=':'.$syspriv;
 1556:                          $allroles{$spec.'./'}.=':'.$syspriv;
 1557:                          if ($tdomain ne '') {
 1558:                              $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 1559:                              $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 1560:                              if ($trest ne '') {
 1561: 		                $allroles{'cm.'.$area}.=':'.$coursepriv;
 1562: 		                $allroles{$spec.'.'.$area}.=':'.$coursepriv;
 1563:                              }
 1564: 	                 }
 1565:                       }
 1566:                    }
 1567:                } else {
 1568: 	           $allroles{'cm./'}.=':'.$pr{$trole.':s'};
 1569: 	           $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 1570:                    if ($tdomain ne '') {
 1571:                      $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1572:                      $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1573:                       if ($trest ne '') {
 1574: 		          $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 1575: 		          $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 1576:                       }
 1577: 	           }
 1578: 	       }
 1579:             }
 1580:           } 
 1581:         }
 1582:         my $adv=0;
 1583:         my $author=0;
 1584:         foreach (keys %allroles) {
 1585:             %thesepriv=();
 1586:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
 1587:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 1588:             foreach (split(/:/,$allroles{$_})) {
 1589:                 if ($_ ne '') {
 1590: 		    my ($privilege,$restrictions)=split(/&/,$_);
 1591:                     if ($restrictions eq '') {
 1592: 			$thesepriv{$privilege}='F';
 1593:                     } else {
 1594:                         if ($thesepriv{$privilege} ne 'F') {
 1595: 			    $thesepriv{$privilege}.=$restrictions;
 1596:                         }
 1597:                     }
 1598:                 }
 1599:             }
 1600:             $thesestr='';
 1601:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 1602:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
 1603:         }
 1604:         $userroles.='user.adv='.$adv."\n".
 1605: 	            'user.author='.$author."\n";
 1606:         $ENV{'user.adv'}=$adv;
 1607:     }
 1608:     return $userroles;  
 1609: }
 1610: 
 1611: # --------------------------------------------------------------- get interface
 1612: 
 1613: sub get {
 1614:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1615:    my $items='';
 1616:    foreach (@$storearr) {
 1617:        $items.=escape($_).'&';
 1618:    }
 1619:    $items=~s/\&$//;
 1620:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1621:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1622:    my $uhome=&homeserver($uname,$udomain);
 1623: 
 1624:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 1625:    my @pairs=split(/\&/,$rep);
 1626:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1627:      return @pairs;
 1628:    }
 1629:    my %returnhash=();
 1630:    my $i=0;
 1631:    foreach (@$storearr) {
 1632:       $returnhash{$_}=unescape($pairs[$i]);
 1633:       $i++;
 1634:    }
 1635:    return %returnhash;
 1636: }
 1637: 
 1638: # --------------------------------------------------------------- del interface
 1639: 
 1640: sub del {
 1641:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1642:    my $items='';
 1643:    foreach (@$storearr) {
 1644:        $items.=escape($_).'&';
 1645:    }
 1646:    $items=~s/\&$//;
 1647:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1648:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1649:    my $uhome=&homeserver($uname,$udomain);
 1650: 
 1651:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 1652: }
 1653: 
 1654: # -------------------------------------------------------------- dump interface
 1655: 
 1656: sub dump {
 1657:    my ($namespace,$udomain,$uname,$regexp)=@_;
 1658:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1659:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1660:    my $uhome=&homeserver($uname,$udomain);
 1661:    if ($regexp) {
 1662:        $regexp=&escape($regexp);
 1663:    } else {
 1664:        $regexp='.';
 1665:    }
 1666:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 1667:    my @pairs=split(/\&/,$rep);
 1668:    my %returnhash=();
 1669:    foreach (@pairs) {
 1670:       my ($key,$value)=split(/=/,$_);
 1671:       $returnhash{unescape($key)}=unescape($value);
 1672:    }
 1673:    return %returnhash;
 1674: }
 1675: 
 1676: # --------------------------------------------------------------- put interface
 1677: 
 1678: sub put {
 1679:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1680:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1681:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1682:    my $uhome=&homeserver($uname,$udomain);
 1683:    my $items='';
 1684:    foreach (keys %$storehash) {
 1685:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 1686:    }
 1687:    $items=~s/\&$//;
 1688:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 1689: }
 1690: 
 1691: # ------------------------------------------------------ critical put interface
 1692: 
 1693: sub cput {
 1694:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1695:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1696:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1697:    my $uhome=&homeserver($uname,$udomain);
 1698:    my $items='';
 1699:    foreach (keys %$storehash) {
 1700:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 1701:    }
 1702:    $items=~s/\&$//;
 1703:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 1704: }
 1705: 
 1706: # -------------------------------------------------------------- eget interface
 1707: 
 1708: sub eget {
 1709:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1710:    my $items='';
 1711:    foreach (@$storearr) {
 1712:        $items.=escape($_).'&';
 1713:    }
 1714:    $items=~s/\&$//;
 1715:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1716:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1717:    my $uhome=&homeserver($uname,$udomain);
 1718:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 1719:    my @pairs=split(/\&/,$rep);
 1720:    my %returnhash=();
 1721:    my $i=0;
 1722:    foreach (@$storearr) {
 1723:       $returnhash{$_}=unescape($pairs[$i]);
 1724:       $i++;
 1725:    }
 1726:    return %returnhash;
 1727: }
 1728: 
 1729: # ------------------------------------------------- Check for a user privilege
 1730: 
 1731: sub allowed {
 1732:     my ($priv,$uri)=@_;
 1733: 
 1734:     my $orguri=$uri;
 1735:     $uri=&declutter($uri);
 1736: 
 1737: # Free bre access to adm and meta resources
 1738: 
 1739:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 1740: 	return 'F';
 1741:     }
 1742: 
 1743: # Free bre to public access
 1744: 
 1745:     if ($priv eq 'bre') {
 1746:         my $copyright=&metadata($uri,'copyright');
 1747: 	if ($copyright eq 'public') { return 'F'; }
 1748:         if ($copyright eq 'priv') {
 1749:             $uri=~/([^\/]+)\/([^\/]+)\//;
 1750: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
 1751: 		return '';
 1752:             }
 1753:         }
 1754:         if ($copyright eq 'domain') {
 1755:             $uri=~/([^\/]+)\/([^\/]+)\//;
 1756: 	    unless (($ENV{'user.domain'} eq $1) ||
 1757:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
 1758: 		return '';
 1759:             }
 1760:         }
 1761:         if ($ENV{'request.role'}=~ /li\.\//) {
 1762:             # Library role, so allow browsing of resources in this domain.
 1763:             return 'F';
 1764:         }
 1765:     }
 1766:     # Domain coordinator is trying to create a course
 1767:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
 1768:         # uri is the requested domain in this case.
 1769:         # comparison to 'request.role.domain' shows if the user has selected
 1770:         # a role of dc for the domain in question. 
 1771:         return 'F' if ($uri eq $ENV{'request.role.domain'});
 1772:     }
 1773: 
 1774:     my $thisallowed='';
 1775:     my $statecond=0;
 1776:     my $courseprivid='';
 1777: 
 1778: # Course
 1779: 
 1780:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 1781:        $thisallowed.=$1;
 1782:     }
 1783: 
 1784: # Domain
 1785: 
 1786:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 1787:        =~/$priv\&([^\:]*)/) {
 1788:        $thisallowed.=$1;
 1789:     }
 1790: 
 1791: # Course: uri itself is a course
 1792:     my $courseuri=$uri;
 1793:     $courseuri=~s/\_(\d)/\/$1/;
 1794:     $courseuri=~s/^([^\/])/\/$1/;
 1795: 
 1796:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 1797:        =~/$priv\&([^\:]*)/) {
 1798:        $thisallowed.=$1;
 1799:     }
 1800: 
 1801: # Full access at system, domain or course-wide level? Exit.
 1802: 
 1803:     if ($thisallowed=~/F/) {
 1804: 	return 'F';
 1805:     }
 1806: 
 1807: # If this is generating or modifying users, exit with special codes
 1808: 
 1809:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 1810: 	return $thisallowed;
 1811:     }
 1812: #
 1813: # Gathered so far: system, domain and course wide privileges
 1814: #
 1815: # Course: See if uri or referer is an individual resource that is part of 
 1816: # the course
 1817: 
 1818:     if ($ENV{'request.course.id'}) {
 1819: 
 1820:        $courseprivid=$ENV{'request.course.id'};
 1821:        if ($ENV{'request.course.sec'}) {
 1822:           $courseprivid.='/'.$ENV{'request.course.sec'};
 1823:        }
 1824:        $courseprivid=~s/\_/\//;
 1825:        my $checkreferer=1;
 1826:        my ($match,$cond)=&is_on_map($uri);
 1827:        if ($match) {
 1828:            $statecond=$cond;
 1829:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1830:                =~/$priv\&([^\:]*)/) {
 1831:                $thisallowed.=$1;
 1832:                $checkreferer=0;
 1833:            }
 1834:        }
 1835:        
 1836:        if ($checkreferer) {
 1837: 	  my $refuri=$ENV{'httpref.'.$orguri};
 1838:             unless ($refuri) {
 1839:                 foreach (keys %ENV) {
 1840: 		    if ($_=~/^httpref\..*\*/) {
 1841: 			my $pattern=$_;
 1842:                         $pattern=~s/^httpref\.\/res\///;
 1843:                         $pattern=~s/\*/\[\^\/\]\+/g;
 1844:                         $pattern=~s/\//\\\//g;
 1845:                         if ($orguri=~/$pattern/) {
 1846: 			    $refuri=$ENV{$_};
 1847:                         }
 1848:                     }
 1849:                 }
 1850:             }
 1851: 
 1852:          if ($refuri) { 
 1853: 	  $refuri=&declutter($refuri);
 1854:           my ($match,$cond)=&is_on_map($refuri);
 1855:             if ($match) {
 1856:               my $refstatecond=$cond;
 1857:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1858:                   =~/$priv\&([^\:]*)/) {
 1859:                   $thisallowed.=$1;
 1860:                   $uri=$refuri;
 1861:                   $statecond=$refstatecond;
 1862:               }
 1863:           }
 1864:         }
 1865:        }
 1866:    }
 1867: 
 1868: #
 1869: # Gathered now: all privileges that could apply, and condition number
 1870: # 
 1871: #
 1872: # Full or no access?
 1873: #
 1874: 
 1875:     if ($thisallowed=~/F/) {
 1876: 	return 'F';
 1877:     }
 1878: 
 1879:     unless ($thisallowed) {
 1880:         return '';
 1881:     }
 1882: 
 1883: # Restrictions exist, deal with them
 1884: #
 1885: #   C:according to course preferences
 1886: #   R:according to resource settings
 1887: #   L:unless locked
 1888: #   X:according to user session state
 1889: #
 1890: 
 1891: # Possibly locked functionality, check all courses
 1892: # Locks might take effect only after 10 minutes cache expiration for other
 1893: # courses, and 2 minutes for current course
 1894: 
 1895:     my $envkey;
 1896:     if ($thisallowed=~/L/) {
 1897:         foreach $envkey (keys %ENV) {
 1898:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 1899:                my $courseid=$2;
 1900:                my $roleid=$1.'.'.$2;
 1901:                $courseid=~s/^\///;
 1902:                my $expiretime=600;
 1903:                if ($ENV{'request.role'} eq $roleid) {
 1904: 		  $expiretime=120;
 1905:                }
 1906: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 1907:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 1908:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 1909: 		   &coursedescription($courseid);
 1910:                }
 1911:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 1912:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 1913: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 1914:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1915:                             $ENV{'user.home'},
 1916:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 1917:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1918:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1919: 		       return '';
 1920:                    }
 1921:                }
 1922:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 1923:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 1924: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 1925:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1926:                             $ENV{'user.home'},
 1927:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 1928:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1929:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1930: 		       return '';
 1931:                    }
 1932:                }
 1933: 	   }
 1934:        }
 1935:     }
 1936:    
 1937: #
 1938: # Rest of the restrictions depend on selected course
 1939: #
 1940: 
 1941:     unless ($ENV{'request.course.id'}) {
 1942:        return '1';
 1943:     }
 1944: 
 1945: #
 1946: # Now user is definitely in a course
 1947: #
 1948: 
 1949: 
 1950: # Course preferences
 1951: 
 1952:    if ($thisallowed=~/C/) {
 1953:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1954:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
 1955:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 1956: 	   =~/$rolecode/) {
 1957:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1958:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 1959:                 $ENV{'request.course.id'});
 1960:            return '';
 1961:        }
 1962: 
 1963:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
 1964: 	   =~/$unamedom/) {
 1965:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1966:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 1967:                 $ENV{'request.course.id'});
 1968:            return '';
 1969:        }
 1970:    }
 1971: 
 1972: # Resource preferences
 1973: 
 1974:    if ($thisallowed=~/R/) {
 1975:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1976:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
 1977:        if (-e $filename) {
 1978:            my @content;
 1979:            {
 1980: 	     my $fh=Apache::File->new($filename);
 1981:              @content=<$fh>;
 1982: 	   }
 1983:            if (join('',@content)=~
 1984:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
 1985: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1986:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 1987:            return '';
 1988: 
 1989:            }
 1990:        }
 1991:    }
 1992: 
 1993: # Restricted by state or randomout?
 1994: 
 1995:    if ($thisallowed=~/X/) {
 1996:       if ($ENV{'acc.randomout'}) {
 1997:          my $symb=&symbread($uri,1);
 1998:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
 1999:             return ''; 
 2000:          }
 2001:       }
 2002:       if (&condval($statecond)) {
 2003: 	 return '2';
 2004:       } else {
 2005:          return '';
 2006:       }
 2007:    }
 2008: 
 2009:    return 'F';
 2010: }
 2011: 
 2012: # --------------------------------------------------- Is a resource on the map?
 2013: 
 2014: sub is_on_map {
 2015:     my $uri=&declutter(shift);
 2016:     my @uriparts=split(/\//,$uri);
 2017:     my $filename=$uriparts[$#uriparts];
 2018:     my $pathname=$uri;
 2019:     $pathname=~s|/\Q$filename\E$||;
 2020:     #Trying to find the conditional for the file
 2021:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 2022: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 2023:     if ($match) {
 2024: 	return (1,$1);
 2025:     } else {
 2026: 	return (0,0);
 2027:     }
 2028: }
 2029: 
 2030: # ----------------------------------------------------------------- Define Role
 2031: 
 2032: sub definerole {
 2033:   if (allowed('mcr','/')) {
 2034:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 2035:     foreach (split('/',$sysrole)) {
 2036: 	my ($crole,$cqual)=split(/\&/,$_);
 2037:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 2038:         if ($pr{'cr:s'}=~/$crole\&/) {
 2039: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 2040:                return "refused:s:$crole&$cqual"; 
 2041:             }
 2042:         }
 2043:     }
 2044:     foreach (split('/',$domrole)) {
 2045: 	my ($crole,$cqual)=split(/\&/,$_);
 2046:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 2047:         if ($pr{'cr:d'}=~/$crole\&/) {
 2048: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 2049:                return "refused:d:$crole&$cqual"; 
 2050:             }
 2051:         }
 2052:     }
 2053:     foreach (split('/',$courole)) {
 2054: 	my ($crole,$cqual)=split(/\&/,$_);
 2055:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 2056:         if ($pr{'cr:c'}=~/$crole\&/) {
 2057: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 2058:                return "refused:c:$crole&$cqual"; 
 2059:             }
 2060:         }
 2061:     }
 2062:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2063:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 2064: 	        "rolesdef_$rolename=".
 2065:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 2066:     return reply($command,$ENV{'user.home'});
 2067:   } else {
 2068:     return 'refused';
 2069:   }
 2070: }
 2071: 
 2072: # ---------------- Make a metadata query against the network of library servers
 2073: 
 2074: sub metadata_query {
 2075:     my ($query,$custom,$customshow,$server_array)=@_;
 2076:     my %rhash;
 2077:     my @server_list = (defined($server_array) ? @$server_array
 2078:                                               : keys(%libserv) );
 2079:     for my $server (@server_list) {
 2080: 	unless ($custom or $customshow) {
 2081: 	    my $reply=&reply("querysend:".&escape($query),$server);
 2082: 	    $rhash{$server}=$reply;
 2083: 	}
 2084: 	else {
 2085: 	    my $reply=&reply("querysend:".&escape($query).':'.
 2086: 			     &escape($custom).':'.&escape($customshow),
 2087: 			     $server);
 2088: 	    $rhash{$server}=$reply;
 2089: 	}
 2090:     }
 2091:     return \%rhash;
 2092: }
 2093: 
 2094: # ----------------------------------------- Send log queries and wait for reply
 2095: 
 2096: sub log_query {
 2097:     my ($uname,$udom,$query,%filters)=@_;
 2098:     my $uhome=&homeserver($uname,$udom);
 2099:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 2100:     my $uhost=$hostname{$uhome};
 2101:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 2102:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 2103:                        $uhome);
 2104:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
 2105:     return get_query_reply($queryid);
 2106: }
 2107: 
 2108: sub get_query_reply {
 2109:     my $queryid=shift;
 2110:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 2111:     my $reply='';
 2112:     for (1..100) {
 2113: 	sleep 2;
 2114:         if (-e $replyfile.'.end') {
 2115: 	    if (my $fh=Apache::File->new($replyfile)) {
 2116:                $reply.=<$fh>;
 2117:                $fh->close;
 2118: 	   } else { return 'error: reply_file_error'; }
 2119:            return &unescape($reply);
 2120: 	}
 2121:     }
 2122:     return 'timeout:'.$queryid;
 2123: }
 2124: 
 2125: sub courselog_query {
 2126: #
 2127: # possible filters:
 2128: # url: url or symb
 2129: # username
 2130: # domain
 2131: # action: view, submit, grade
 2132: # start: timestamp
 2133: # end: timestamp
 2134: #
 2135:     my (%filters)=@_;
 2136:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
 2137:     if ($filters{'url'}) {
 2138: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 2139:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 2140:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 2141:     }
 2142:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 2143:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 2144:     return &log_query($cname,$cdom,'courselog',%filters);
 2145: }
 2146: 
 2147: sub userlog_query {
 2148:     my ($uname,$udom,%filters)=@_;
 2149:     return &log_query($uname,$udom,'userlog',%filters);
 2150: }
 2151: 
 2152: # ------------------------------------------------------------------ Plain Text
 2153: 
 2154: sub plaintext {
 2155:     my $short=shift;
 2156:     return $prp{$short};
 2157: }
 2158: 
 2159: # ----------------------------------------------------------------- Assign Role
 2160: 
 2161: sub assignrole {
 2162:     my ($udom,$uname,$url,$role,$end,$start)=@_;
 2163:     my $mrole;
 2164:     if ($role =~ /^cr\//) {
 2165: 	unless (&allowed('ccr',$url)) {
 2166:            &logthis('Refused custom assignrole: '.
 2167:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2168: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2169:            return 'refused'; 
 2170:         }
 2171:         $mrole='cr';
 2172:     } else {
 2173:         my $cwosec=$url;
 2174:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 2175:         unless (&allowed('c'.$role,$cwosec)) { 
 2176:            &logthis('Refused assignrole: '.
 2177:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2178: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2179:            return 'refused'; 
 2180:         }
 2181:         $mrole=$role;
 2182:     }
 2183:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2184:                 "$udom:$uname:$url".'_'."$mrole=$role";
 2185:     if ($end) { $command.='_'.$end; }
 2186:     if ($start) {
 2187: 	if ($end) { 
 2188:            $command.='_'.$start; 
 2189:         } else {
 2190:            $command.='_0_'.$start;
 2191:         }
 2192:     }
 2193:     return &reply($command,&homeserver($uname,$udom));
 2194: }
 2195: 
 2196: # -------------------------------------------------- Modify user authentication
 2197: # Overrides without validation
 2198: 
 2199: sub modifyuserauth {
 2200:     my ($udom,$uname,$umode,$upass)=@_;
 2201:     my $uhome=&homeserver($uname,$udom);
 2202:     unless (&allowed('mau',$udom)) { return 'refused'; }
 2203:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 2204:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2205:              ' in domain '.$ENV{'request.role.domain'});  
 2206:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 2207: 		     &escape($upass),$uhome);
 2208:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
 2209:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 2210:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2211:     &log($udom,,$uname,$uhome,
 2212:         'Authentication changed by '.$ENV{'user.domain'}.', '.
 2213:                                      $ENV{'user.name'}.', '.$umode.
 2214:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2215:     unless ($reply eq 'ok') {
 2216:         &logthis('Authentication mode error: '.$reply);
 2217: 	return 'error: '.$reply;
 2218:     }   
 2219:     return 'ok';
 2220: }
 2221: 
 2222: # --------------------------------------------------------------- Modify a user
 2223: 
 2224: sub modifyuser {
 2225:     my ($udom,    $uname, $uid,
 2226:         $umode,   $upass, $first,
 2227:         $middle,  $last,  $gene,
 2228:         $forceid, $desiredhome)=@_;
 2229:     $udom=~s/\W//g;
 2230:     $uname=~s/\W//g;
 2231:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 2232:              $umode.', '.$first.', '.$middle.', '.
 2233: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 2234:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 2235:                                      ' desiredhome not specified'). 
 2236:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2237:              ' in domain '.$ENV{'request.role.domain'});
 2238:     my $uhome=&homeserver($uname,$udom,'true');
 2239: # ----------------------------------------------------------------- Create User
 2240:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 2241:         my $unhome='';
 2242:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 2243:             $unhome = $desiredhome;
 2244: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 2245: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 2246:         } else { # load balancing routine for determining $unhome
 2247:             my $tryserver;
 2248:             my $loadm=10000000;
 2249:             foreach $tryserver (keys %libserv) {
 2250: 	       if ($hostdom{$tryserver} eq $udom) {
 2251:                   my $answer=reply('load',$tryserver);
 2252:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 2253: 		      $loadm=$answer;
 2254:                       $unhome=$tryserver;
 2255:                   }
 2256: 	       }
 2257: 	    }
 2258:         }
 2259:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 2260: 	    return 'error: unable to find a home server for '.$uname.
 2261:                    ' in domain '.$udom;
 2262:         }
 2263:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 2264:                          &escape($upass),$unhome);
 2265: 	unless ($reply eq 'ok') {
 2266:             return 'error: '.$reply;
 2267:         }   
 2268:         $uhome=&homeserver($uname,$udom,'true');
 2269:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 2270: 	    return 'error: verify home';
 2271:         }
 2272:     }   # End of creation of new user
 2273: # ---------------------------------------------------------------------- Add ID
 2274:     if ($uid) {
 2275:        $uid=~tr/A-Z/a-z/;
 2276:        my %uidhash=&idrget($udom,$uname);
 2277:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 2278:          && (!$forceid)) {
 2279: 	  unless ($uid eq $uidhash{$uname}) {
 2280: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 2281:           }
 2282:        } else {
 2283: 	  &idput($udom,($uname => $uid));
 2284:        }
 2285:     }
 2286: # -------------------------------------------------------------- Add names, etc
 2287:     my %names=&get('environment',
 2288: 		   ['firstname','middlename','lastname','generation'],
 2289: 		   $udom,$uname);
 2290:     if ($names{'firstname'} =~ m/^error:.*/) { %names=(); }
 2291:     if ($first)  { $names{'firstname'}  = $first; }
 2292:     if ($middle) { $names{'middlename'} = $middle; }
 2293:     if ($last)   { $names{'lastname'}   = $last; }
 2294:     if ($gene)   { $names{'generation'} = $gene; }
 2295:     my $reply = &put('environment', \%names, $udom,$uname);
 2296:     if ($reply ne 'ok') { return 'error: '.$reply; }
 2297:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 2298:              $umode.', '.$first.', '.$middle.', '.
 2299: 	     $last.', '.$gene.' by '.
 2300:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2301:     return 'ok';
 2302: }
 2303: 
 2304: # -------------------------------------------------------------- Modify student
 2305: 
 2306: sub modifystudent {
 2307:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 2308:         $end,$start,$forceid,$desiredhome)=@_;
 2309:     my $cid='';
 2310:     unless ($cid=$ENV{'request.course.id'}) {
 2311: 	return 'not_in_class';
 2312:     }
 2313: # --------------------------------------------------------------- Make the user
 2314:     my $reply=&modifyuser
 2315: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 2316:          $desiredhome);
 2317:     unless ($reply eq 'ok') { return $reply; }
 2318:     my $uhome=&homeserver($uname,$udom);
 2319:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2320: 	return 'error: no such user';
 2321:     }
 2322: # -------------------------------------------------- Add student to course list
 2323:     $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 2324: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 2325:                       &escape($uname.':'.$udom).'='.
 2326:                       &escape($end.':'.$start),
 2327: 	              $ENV{'course.'.$cid.'.home'});
 2328:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 2329: 	return 'error: '.$reply;
 2330:     }
 2331: # ---------------------------------------------------- Add student role to user
 2332:     my $uurl='/'.$cid;
 2333:     $uurl=~s/\_/\//g;
 2334:     if ($usec) {
 2335: 	$uurl.='/'.$usec;
 2336:     }
 2337:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 2338: }
 2339: 
 2340: # ------------------------------------------------- Write to course preferences
 2341: 
 2342: sub writecoursepref {
 2343:     my ($courseid,%prefs)=@_;
 2344:     $courseid=~s/^\///;
 2345:     $courseid=~s/\_/\//g;
 2346:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2347:     my $chome=homeserver($cnum,$cdomain);
 2348:     if (($chome eq '') || ($chome eq 'no_host')) { 
 2349: 	return 'error: no such course';
 2350:     }
 2351:     my $cstring='';
 2352:     foreach (keys %prefs) {
 2353: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 2354:     }
 2355:     $cstring=~s/\&$//;
 2356:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 2357: }
 2358: 
 2359: # ---------------------------------------------------------- Make/modify course
 2360: 
 2361: sub createcourse {
 2362:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
 2363:     $url=&declutter($url);
 2364:     my $cid='';
 2365:     unless (&allowed('ccc',$udom)) {
 2366:         return 'refused';
 2367:     }
 2368: # ------------------------------------------------------------------- Create ID
 2369:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2370:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2371: # ----------------------------------------------- Make sure that does not exist
 2372:    my $uhome=&homeserver($uname,$udom,'true');
 2373:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2374:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2375:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2376:        $uhome=&homeserver($uname,$udom,'true');       
 2377:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2378:            return 'error: unable to generate unique course-ID';
 2379:        } 
 2380:    }
 2381: # ------------------------------------------------ Check supplied server name
 2382:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
 2383:     if (! exists($libserv{$course_server})) {
 2384:         return 'error:bad server name '.$course_server;
 2385:     }
 2386: # ------------------------------------------------------------- Make the course
 2387:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 2388:                       $course_server);
 2389:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 2390:     $uhome=&homeserver($uname,$udom,'true');
 2391:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2392: 	return 'error: no such course';
 2393:     }
 2394: # ----------------------------------------------------------------- Course made
 2395:     my $topurl=$url;
 2396:     unless ($nonstandard) {
 2397: # ------------------------------------------ For standard courses, make top url
 2398:         my $mapurl=&clutter($url);
 2399:         if ($mapurl eq '/res/') { $mapurl=''; }
 2400:         $ENV{'form.initmap'}=(<<ENDINITMAP);
 2401: <map>
 2402: <resource id="1" type="start"></resource>
 2403: <resource id="2" src="$mapurl"></resource>
 2404: <resource id="3" type="finish"></resource>
 2405: <link index="1" from="1" to="2"></link>
 2406: <link index="2" from="2" to="3"></link>
 2407: </map>
 2408: ENDINITMAP
 2409:         $topurl=&declutter(
 2410:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
 2411:                           );
 2412:     }
 2413: # ----------------------------------------------------------- Write preferences
 2414:     &writecoursepref($udom.'_'.$uname,
 2415:                      ('description' => $description,
 2416:                       'url'         => $topurl));
 2417:     return '/'.$udom.'/'.$uname;
 2418: }
 2419: 
 2420: # ---------------------------------------------------------- Assign Custom Role
 2421: 
 2422: sub assigncustomrole {
 2423:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
 2424:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 2425:                        $end,$start);
 2426: }
 2427: 
 2428: # ----------------------------------------------------------------- Revoke Role
 2429: 
 2430: sub revokerole {
 2431:     my ($udom,$uname,$url,$role)=@_;
 2432:     my $now=time;
 2433:     return &assignrole($udom,$uname,$url,$role,$now);
 2434: }
 2435: 
 2436: # ---------------------------------------------------------- Revoke Custom Role
 2437: 
 2438: sub revokecustomrole {
 2439:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
 2440:     my $now=time;
 2441:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
 2442: }
 2443: 
 2444: # ------------------------------------------------------------ Directory lister
 2445: 
 2446: sub dirlist {
 2447:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 2448: 
 2449:     $uri=~s/^\///;
 2450:     $uri=~s/\/$//;
 2451:     my ($udom, $uname);
 2452:     (undef,$udom,$uname)=split(/\//,$uri);
 2453:     if(defined($userdomain)) {
 2454:         $udom = $userdomain;
 2455:     }
 2456:     if(defined($username)) {
 2457:         $uname = $username;
 2458:     }
 2459: 
 2460:     my $dirRoot = $perlvar{'lonDocRoot'};
 2461:     if(defined($alternateDirectoryRoot)) {
 2462:         $dirRoot = $alternateDirectoryRoot;
 2463:         $dirRoot =~ s/\/$//;
 2464:     }
 2465: 
 2466:     if($udom) {
 2467:         if($uname) {
 2468:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
 2469:                               homeserver($uname,$udom));
 2470:             return split(/:/,$listing);
 2471:         } elsif(!defined($alternateDirectoryRoot)) {
 2472:             my $tryserver;
 2473:             my %allusers=();
 2474:             foreach $tryserver (keys %libserv) {
 2475:                 if($hostdom{$tryserver} eq $udom) {
 2476:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 2477:                                       $udom, $tryserver);
 2478:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 2479:                         && ($listing ne 'con_lost')) {
 2480:                         foreach (split(/:/,$listing)) {
 2481:                             my ($entry,@stat)=split(/&/,$_);
 2482:                             $allusers{$entry}=1;
 2483:                         }
 2484:                     }
 2485:                 }
 2486:             }
 2487:             my $alluserstr='';
 2488:             foreach (sort keys %allusers) {
 2489:                 $alluserstr.=$_.'&user:';
 2490:             }
 2491:             $alluserstr=~s/:$//;
 2492:             return split(/:/,$alluserstr);
 2493:         } else {
 2494:             my @emptyResults = ();
 2495:             push(@emptyResults, 'missing user name');
 2496:             return split(':',@emptyResults);
 2497:         }
 2498:     } elsif(!defined($alternateDirectoryRoot)) {
 2499:         my $tryserver;
 2500:         my %alldom=();
 2501:         foreach $tryserver (keys %libserv) {
 2502:             $alldom{$hostdom{$tryserver}}=1;
 2503:         }
 2504:         my $alldomstr='';
 2505:         foreach (sort keys %alldom) {
 2506:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 2507:         }
 2508:         $alldomstr=~s/:$//;
 2509:         return split(/:/,$alldomstr);       
 2510:     } else {
 2511:         my @emptyResults = ();
 2512:         push(@emptyResults, 'missing domain');
 2513:         return split(':',@emptyResults);
 2514:     }
 2515: }
 2516: 
 2517: # --------------------------------------------- GetFileTimestamp
 2518: # This function utilizes dirlist and returns the date stamp for
 2519: # when it was last modified.  It will also return an error of -1
 2520: # if an error occurs
 2521: 
 2522: sub GetFileTimestamp {
 2523:     my ($studentDomain,$studentName,$filename,$root)=@_;
 2524:     $studentDomain=~s/\W//g;
 2525:     $studentName=~s/\W//g;
 2526:     my $subdir=$studentName.'__';
 2527:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 2528:     my $proname="$studentDomain/$subdir/$studentName";
 2529:     $proname .= '/'.$filename;
 2530:     my @dir = &Apache::lonnet::dirlist($proname, $studentDomain, $studentName,
 2531:                                        $root);
 2532:     my $fileStat = $dir[0];
 2533:     my @stats = split('&', $fileStat);
 2534:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 2535:         return $stats[9];
 2536:     } else {
 2537:         return -1;
 2538:     }
 2539: }
 2540: 
 2541: # -------------------------------------------------------- Value of a Condition
 2542: 
 2543: sub directcondval {
 2544:     my $number=shift;
 2545:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 2546:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 2547:     } else {
 2548:        return 2;
 2549:     }
 2550: }
 2551: 
 2552: sub condval {
 2553:     my $condidx=shift;
 2554:     my $result=0;
 2555:     my $allpathcond='';
 2556:     foreach (split(/\|/,$condidx)) {
 2557:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 2558: 	   $allpathcond.=
 2559:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 2560:        }
 2561:     }
 2562:     $allpathcond=~s/\|$//;
 2563:     if ($ENV{'request.course.id'}) {
 2564:        if ($allpathcond) {
 2565:           my $operand='|';
 2566: 	  my @stack;
 2567:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 2568:               if ($_ eq '(') {
 2569:                  push @stack,($operand,$result)
 2570:               } elsif ($_ eq ')') {
 2571:                   my $before=pop @stack;
 2572: 		  if (pop @stack eq '&') {
 2573: 		      $result=$result>$before?$before:$result;
 2574:                   } else {
 2575:                       $result=$result>$before?$result:$before;
 2576:                   }
 2577:               } elsif (($_ eq '&') || ($_ eq '|')) {
 2578:                   $operand=$_;
 2579:               } else {
 2580:                   my $new=directcondval($_);
 2581:                   if ($operand eq '&') {
 2582:                      $result=$result>$new?$new:$result;
 2583:                   } else {
 2584:                      $result=$result>$new?$result:$new;
 2585:                   }
 2586:               }
 2587:           }
 2588:        }
 2589:     }
 2590:     return $result;
 2591: }
 2592: 
 2593: # ---------------------------------------------------- Devalidate courseresdata
 2594: 
 2595: sub devalidatecourseresdata {
 2596:     my ($coursenum,$coursedomain)=@_;
 2597:     my $hashid=$coursenum.':'.$coursedomain;
 2598:     delete $courseresdatacache{$hashid.'.time'};
 2599: }
 2600: 
 2601: # --------------------------------------------------- Course Resourcedata Query
 2602: 
 2603: sub courseresdata {
 2604:     my ($coursenum,$coursedomain,@which)=@_;
 2605:     my $coursehom=&homeserver($coursenum,$coursedomain);
 2606:     my $hashid=$coursenum.':'.$coursedomain;
 2607:     my $dodump=0;
 2608:     if (!defined($courseresdatacache{$hashid.'.time'})) {
 2609: 	$dodump=1;
 2610:     } else {
 2611: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
 2612:     }
 2613:     if ($dodump) {
 2614: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 2615: 	my ($tmp) = keys(%dumpreply);
 2616: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 2617: 	    $courseresdatacache{$hashid.'.time'}=time;
 2618: 	    $courseresdatacache{$hashid}=\%dumpreply;
 2619: 	}
 2620:     }
 2621:     foreach my $item (@which) {
 2622: 	if (defined($courseresdatacache{$hashid}->{$item})) {
 2623: 	    return $courseresdatacache{$hashid}->{$item};
 2624: 	}
 2625:     }
 2626:     return undef;
 2627: }
 2628: 
 2629: # --------------------------------------------------------- Value of a Variable
 2630: 
 2631: sub EXT {
 2632:     my ($varname,$symbparm,$udom,$uname,)=@_;
 2633: 
 2634:     unless ($varname) { return ''; }
 2635: 
 2636:     #get real user name/domain, courseid and symb
 2637:     my $courseid;
 2638:     if (!($uname && $udom)) {
 2639:       (my $cursymb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2640:       if (!$symbparm) {	$symbparm=$cursymb; }
 2641:     } else {
 2642: 	$courseid=$ENV{'request.course.id'};
 2643:     }
 2644: 
 2645:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 2646:     my $rest;
 2647:     if ($therest[0]) {
 2648:        $rest=join('.',@therest);
 2649:     } else {
 2650:        $rest='';
 2651:     }
 2652:     my $qualifierrest=$qualifier;
 2653:     if ($rest) { $qualifierrest.='.'.$rest; }
 2654:     my $spacequalifierrest=$space;
 2655:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 2656:     if ($realm eq 'user') {
 2657: # --------------------------------------------------------------- user.resource
 2658: 	if ($space eq 'resource') {
 2659: 	    my %restored=&restore(undef,undef,$udom,$uname);
 2660:             return $restored{$qualifierrest};
 2661: # ----------------------------------------------------------------- user.access
 2662:         } elsif ($space eq 'access') {
 2663: 	    # FIXME - not supporting calls for a specific user
 2664:             return &allowed($qualifier,$rest);
 2665: # ------------------------------------------ user.preferences, user.environment
 2666:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 2667: 	    if (($uname eq $ENV{'user.name'}) &&
 2668: 		($udom eq $ENV{'user.domain'})) {
 2669: 		return $ENV{join('.',('environment',$qualifierrest))};
 2670: 	    } else {
 2671: 		my %returnhash=&userenvironment($udom,$uname,$qualifierrest);
 2672: 		return $returnhash{$qualifierrest};
 2673: 	    }
 2674: # ----------------------------------------------------------------- user.course
 2675:         } elsif ($space eq 'course') {
 2676: 	    # FIXME - not supporting calls for a specific user
 2677:             return $ENV{join('.',('request.course',$qualifier))};
 2678: # ------------------------------------------------------------------- user.role
 2679:         } elsif ($space eq 'role') {
 2680: 	    # FIXME - not supporting calls for a specific user
 2681:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 2682:             if ($qualifier eq 'value') {
 2683: 		return $role;
 2684:             } elsif ($qualifier eq 'extent') {
 2685:                 return $where;
 2686:             }
 2687: # ----------------------------------------------------------------- user.domain
 2688:         } elsif ($space eq 'domain') {
 2689:             return $udom;
 2690: # ------------------------------------------------------------------- user.name
 2691:         } elsif ($space eq 'name') {
 2692:             return $uname;
 2693: # ---------------------------------------------------- Any other user namespace
 2694:         } else {
 2695:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
 2696:             my %reply=&get($space,[$item]);
 2697:             return $reply{$item};
 2698:         }
 2699:     } elsif ($realm eq 'query') {
 2700: # ---------------------------------------------- pull stuff out of query string
 2701:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
 2702: 	return $ENV{'form.'.$space}; 
 2703:    } elsif ($realm eq 'request') {
 2704: # ------------------------------------------------------------- request.browser
 2705:         if ($space eq 'browser') {
 2706: 	    return $ENV{'browser.'.$qualifier};
 2707: # ------------------------------------------------------------ request.filename
 2708:         } else {
 2709:             return $ENV{'request.'.$spacequalifierrest};
 2710:         }
 2711:     } elsif ($realm eq 'course') {
 2712: # ---------------------------------------------------------- course.description
 2713:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
 2714:     } elsif ($realm eq 'resource') {
 2715: 
 2716: 	if ($courseid eq $ENV{'request.course.id'}) {
 2717: 
 2718: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 2719: 
 2720: # ----------------------------------------------------- Cascading lookup scheme
 2721: 	    if (!$symbparm) { $symbparm=&symbread(); }
 2722: 	    my $symbp=$symbparm;
 2723: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
 2724: 
 2725: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 2726: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 2727: 
 2728: 	    my $section;
 2729: 	    if (($ENV{'user.name'} eq $uname) &&
 2730: 		($ENV{'user.domain'} eq $udom)) {
 2731: 		$section=$ENV{'request.course.sec'};
 2732: 	    } else {
 2733: 		$section=&usection($udom,$uname,$courseid);
 2734: 	    }
 2735: 
 2736: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 2737: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 2738: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 2739: 
 2740: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
 2741: 	    my $courselevelr=$courseid.'.'.$symbparm;
 2742: 	    my $courselevelm=$courseid.'.'.$mapparm;
 2743: 
 2744: # ----------------------------------------------------------- first, check user
 2745: 	    my %resourcedata=&get('resourcedata',
 2746: 				  [$courselevelr,$courselevelm,$courselevel],
 2747: 				 $udom,$uname);
 2748: 	    if (($resourcedata{$courselevelr}!~/^error\:/) &&
 2749: 		($resourcedata{$courselevelr}!~/^con_lost/)) {
 2750: 
 2751: 		if ($resourcedata{$courselevelr}) {
 2752: 		    return $resourcedata{$courselevelr}; }
 2753: 		if ($resourcedata{$courselevelm}) {
 2754: 		    return $resourcedata{$courselevelm}; }
 2755: 		if ($resourcedata{$courselevel}) {
 2756: 		    return $resourcedata{$courselevel}; }
 2757: 	    } else {
 2758: 		if ($resourcedata{$courselevelr}!~/No such file/) {
 2759: 		    &logthis("<font color=blue>WARNING:".
 2760: 			     " Trying to get resource data for ".
 2761: 			     $uname." at ".$udom.": ".
 2762: 			     $resourcedata{$courselevelr}."</font>");
 2763: 		}
 2764: 	    }
 2765: 
 2766: # -------------------------------------------------------- second, check course
 2767: 
 2768: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
 2769: 					  $ENV{'course.'.$courseid.'.domain'},
 2770: 					  ($seclevelr,$seclevelm,$seclevel,
 2771: 					   $courselevelr,$courselevelm,
 2772: 					   $courselevel));
 2773: 	    if (defined($coursereply)) { return $coursereply; }
 2774: 
 2775: # ------------------------------------------------------ third, check map parms
 2776: 	    my %parmhash=();
 2777: 	    my $thisparm='';
 2778: 	    if (tie(%parmhash,'GDBM_File',
 2779: 		    $ENV{'request.course.fn'}.'_parms.db',
 2780: 		    &GDBM_READER(),0640)) {
 2781: 		$thisparm=$parmhash{$symbparm};
 2782: 		untie(%parmhash);
 2783: 	    }
 2784: 	    if ($thisparm) { return $thisparm; }
 2785: 	}
 2786: # --------------------------------------------- last, look in resource metadata
 2787: 
 2788: 	$spacequalifierrest=~s/\./\_/;
 2789: 	my $filename;
 2790: 	if (!$symbparm) { $symbparm=&symbread(); }
 2791: 	if ($symbparm) {
 2792: 	    $filename=(split(/\_\_\_/,$symbparm))[2];
 2793: 	} else {
 2794: 	    $filename=$ENV{'request.filename'};
 2795: 	}
 2796: 	my $metadata=&metadata($filename,$spacequalifierrest);
 2797: 	if (defined($metadata)) { return $metadata; }
 2798: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 2799: 	if (defined($metadata)) { return $metadata; }
 2800: 
 2801: # ------------------------------------------------------------------ Cascade up
 2802: 	unless ($space eq '0') {
 2803: 	    my ($part,$id)=split(/\_/,$space);
 2804: 	    if ($id) {
 2805: 		my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 2806: 				     $symbparm,$udom,$uname);
 2807: 		if (defined($partgeneral)) { return $partgeneral; }
 2808: 	    } else {
 2809: 		my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
 2810: 					 $symbparm,$udom,$uname);
 2811: 		if (defined($resourcegeneral)) { return $resourcegeneral; }
 2812: 	    }
 2813: 	}
 2814: 
 2815: # ---------------------------------------------------- Any other user namespace
 2816:     } elsif ($realm eq 'environment') {
 2817: # ----------------------------------------------------------------- environment
 2818: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
 2819: 	    return $ENV{'environment.'.$spacequalifierrest};
 2820: 	} else {
 2821: 	    my %returnhash=&userenvironment($udom,$uname,
 2822: 					    $spacequalifierrest);
 2823: 	    return $returnhash{$spacequalifierrest};
 2824: 	}
 2825:     } elsif ($realm eq 'system') {
 2826: # ----------------------------------------------------------------- system.time
 2827: 	if ($space eq 'time') {
 2828: 	    return time;
 2829:         }
 2830:     }
 2831:     return '';
 2832: }
 2833: 
 2834: # ---------------------------------------------------------------- Get metadata
 2835: 
 2836: sub metadata {
 2837:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 2838: 
 2839:     $uri=&declutter($uri);
 2840:     # if it is a non metadata possible uri return quickly
 2841:     if (($uri eq '') || ($uri =~ m|^/*adm/|) || ($uri =~ m|/$|) ||
 2842: 	($uri =~ m|/.meta$|)) {
 2843: 	return '';
 2844:     }
 2845:     my $filename=$uri;
 2846:     $uri=~s/\.meta$//;
 2847: #
 2848: # Is the metadata already cached?
 2849: # Look at timestamp of caching
 2850: # Everything is cached by the main uri, libraries are never directly cached
 2851: #
 2852:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
 2853: #
 2854: # Is this a recursive call for a library?
 2855: #
 2856:         if ($liburi) {
 2857: 	    $liburi=&declutter($liburi);
 2858:             $filename=$liburi;
 2859:         }
 2860:         my %metathesekeys=();
 2861:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 2862: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
 2863:         my $parser=HTML::LCParser->new(\$metastring);
 2864:         my $token;
 2865:         undef %metathesekeys;
 2866:         while ($token=$parser->get_token) {
 2867:            if ($token->[0] eq 'S') {
 2868: 	     if (defined($token->[2]->{'package'})) {
 2869: #
 2870: # This is a package - get package info
 2871: #
 2872: 	      my $package=$token->[2]->{'package'};
 2873: 	      my $keyroot='';
 2874:               if ($prefix) {
 2875: 		  $keyroot.=$prefix;
 2876:               } else {
 2877:                 if (defined($token->[2]->{'part'})) { 
 2878:                    $keyroot.='_'.$token->[2]->{'part'}; 
 2879: 	        }
 2880: 	      }
 2881:               if (defined($token->[2]->{'id'})) { 
 2882:                  $keyroot.='_'.$token->[2]->{'id'}; 
 2883: 	      }
 2884:               if ($metacache{$uri.':packages'}) {
 2885:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
 2886:               } else {
 2887:                  $metacache{$uri.':packages'}=$package.$keyroot;
 2888: 	      }
 2889:               foreach (keys %packagetab) {
 2890: 		  if ($_=~/^$package\&/) {
 2891: 		      my ($pack,$name,$subp)=split(/\&/,$_);
 2892:                       my $value=$packagetab{$_};
 2893: 		      my $part=$keyroot;
 2894:                       $part=~s/^\_//;
 2895:                       if ($subp eq 'display') {
 2896: 			  $value.=' [Part: '.$part.']';
 2897:                       }
 2898:                       my $unikey='parameter'.$keyroot.'_'.$name;
 2899:                       $metathesekeys{$unikey}=1;
 2900:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
 2901:                       unless 
 2902:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 2903:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 2904: 		      }
 2905:                   }
 2906:               }
 2907:              } else {
 2908: #
 2909: # This is not a package - some other kind of start tag
 2910: # 
 2911:               my $entry=$token->[1];
 2912:               my $unikey;
 2913:               if ($entry eq 'import') {
 2914:                  $unikey='';
 2915:               } else {
 2916:                  $unikey=$entry;
 2917: 	      }
 2918:               if ($prefix) {
 2919: 		  $unikey.=$prefix;
 2920:               } else {
 2921:                 if (defined($token->[2]->{'part'})) { 
 2922:                    $unikey.='_'.$token->[2]->{'part'}; 
 2923: 	        }
 2924: 	      }
 2925:               if (defined($token->[2]->{'id'})) { 
 2926:                  $unikey.='_'.$token->[2]->{'id'}; 
 2927: 	      }
 2928: 
 2929:              if ($entry eq 'import') {
 2930: #
 2931: # Importing a library here
 2932: #                
 2933:                  if ($depthcount<20) {
 2934: 		     my $location=$parser->get_text('/import');
 2935: 		     my $dir=$filename;
 2936: 		     $dir=~s|[^/]*$||;
 2937: 		     $location=&filelocation($dir,$location);
 2938: 		     foreach (sort(split(/\,/,&metadata($uri,'keys',
 2939: 							$location,$unikey,
 2940: 							$depthcount+1)))) {
 2941:                          $metathesekeys{$_}=1;
 2942: 		     }
 2943: 		 }
 2944:              } else { 
 2945: 
 2946:               if (defined($token->[2]->{'name'})) { 
 2947:                  $unikey.='_'.$token->[2]->{'name'}; 
 2948: 	      }
 2949:               $metathesekeys{$unikey}=1;
 2950:               foreach (@{$token->[3]}) {
 2951: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 2952:               }
 2953:               unless (
 2954:                  $metacache{$uri.':'.$unikey}=&HTML::Entities::decode($parser->get_text('/'.$entry))
 2955: 		      ) { $metacache{$uri.':'.$unikey}=
 2956: 			      $metacache{$uri.':'.$unikey.'.default'};
 2957: 		      }
 2958: # end of not-a-package not-a-library import
 2959: 	   }
 2960: # end of not-a-package start tag
 2961: 	  }
 2962: # the next is the end of "start tag"
 2963: 	 }
 2964:        }
 2965:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 2966: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
 2967:        $metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
 2968:        $metacache{$uri.':cachedtimestamp'}=time;
 2969: # this is the end of "was not already recently cached
 2970:     }
 2971:     return $metacache{$uri.':'.$what};
 2972: }
 2973: 
 2974: sub metadata_generate_part0 {
 2975:     my ($metadata,$metacache,$uri) = @_;
 2976:     my %allnames;
 2977:     foreach my $metakey (sort keys %$metadata) {
 2978: 	if ($metakey=~/^parameter\_(.*)/) {
 2979: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
 2980: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
 2981: 	  if (! exists($$metadata{'parameter_0_'.$name})) {
 2982: 	    $allnames{$name}=$part;
 2983: 	  }
 2984: 	}
 2985:     }
 2986:     foreach my $name (keys(%allnames)) {
 2987:       $$metadata{"parameter_0_$name"}=1;
 2988:       my $key="$uri:parameter_0_$name";
 2989:       $$metacache{"$key.part"}='0';
 2990:       $$metacache{"$key.name"}=$name;
 2991:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
 2992: 					   $allnames{$name}.'_'.$name.
 2993: 					   '.type'};
 2994:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
 2995: 			     '.display'};
 2996:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 2997:       $olddis=~s/$expr/\[Part: 0\]/;
 2998:       $$metacache{"$key.display"}=$olddis;
 2999:     }
 3000: }
 3001: 
 3002: # ------------------------------------------------- Update symbolic store links
 3003: 
 3004: sub symblist {
 3005:     my ($mapname,%newhash)=@_;
 3006:     $mapname=declutter($mapname);
 3007:     my %hash;
 3008:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 3009:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3010:                       &GDBM_WRCREAT(),0640)) {
 3011: 	    foreach (keys %newhash) {
 3012:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 3013:             }
 3014:             if (untie(%hash)) {
 3015: 		return 'ok';
 3016:             }
 3017:         }
 3018:     }
 3019:     return 'error';
 3020: }
 3021: 
 3022: # --------------------------------------------------------------- Verify a symb
 3023: 
 3024: sub symbverify {
 3025:     my ($symb,$thisfn)=@_;
 3026:     $thisfn=&declutter($thisfn);
 3027: # direct jump to resource in page or to a sequence - will construct own symbs
 3028:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 3029: # check URL part
 3030:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3031:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
 3032: 
 3033:     $symb=&symbclean($symb);
 3034: 
 3035:     my %bighash;
 3036:     my $okay=0;
 3037:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3038:                             &GDBM_READER(),0640)) {
 3039:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3040:         unless ($ids) { 
 3041:            $ids=$bighash{'ids_/'.$thisfn};
 3042:         }
 3043:         if ($ids) {
 3044: # ------------------------------------------------------------------- Has ID(s)
 3045: 	    foreach (split(/\,/,$ids)) {
 3046:                my ($mapid,$resid)=split(/\./,$_);
 3047:                if (
 3048:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 3049:    eq $symb) { 
 3050:                   $okay=1; 
 3051:                }
 3052: 	   }
 3053:         }
 3054: 	untie(%bighash);
 3055:     }
 3056:     return $okay;
 3057: }
 3058: 
 3059: # --------------------------------------------------------------- Clean-up symb
 3060: 
 3061: sub symbclean {
 3062:     my $symb=shift;
 3063: 
 3064: # remove version from map
 3065:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 3066: 
 3067: # remove version from URL
 3068:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 3069: 
 3070:     return $symb;
 3071: }
 3072: 
 3073: # ------------------------------------------------------ Return symb list entry
 3074: 
 3075: sub symbread {
 3076:     my ($thisfn,$donotrecurse)=@_;
 3077: # no filename provided? try from environment
 3078:     unless ($thisfn) {
 3079:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
 3080: 	$thisfn=$ENV{'request.filename'};
 3081:     }
 3082: # is that filename actually a symb? Verify, clean, and return
 3083:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 3084: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
 3085:     }
 3086:     $thisfn=declutter($thisfn);
 3087:     my %hash;
 3088:     my %bighash;
 3089:     my $syval='';
 3090:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 3091:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3092:                       &GDBM_READER(),0640)) {
 3093: 	    $syval=$hash{$thisfn};
 3094:             untie(%hash);
 3095:         }
 3096: # ---------------------------------------------------------- There was an entry
 3097:         if ($syval) {
 3098:            unless ($syval=~/\_\d+$/) {
 3099: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 3100:                   &appenv('request.ambiguous' => $thisfn);
 3101:                   return '';
 3102:                }    
 3103:                $syval.=$1;
 3104: 	   }
 3105:         } else {
 3106: # ------------------------------------------------------- Was not in symb table
 3107:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3108:                             &GDBM_READER(),0640)) {
 3109: # ---------------------------------------------- Get ID(s) for current resource
 3110:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3111:               unless ($ids) { 
 3112:                  $ids=$bighash{'ids_/'.$thisfn};
 3113:               }
 3114:               unless ($ids) {
 3115: # alias?
 3116: 		  $ids=$bighash{'mapalias_'.$thisfn};
 3117:               }
 3118:               if ($ids) {
 3119: # ------------------------------------------------------------------- Has ID(s)
 3120:                  my @possibilities=split(/\,/,$ids);
 3121:                  if ($#possibilities==0) {
 3122: # ----------------------------------------------- There is only one possibility
 3123: 		     my ($mapid,$resid)=split(/\./,$ids);
 3124:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 3125:                  } elsif (!$donotrecurse) {
 3126: # ------------------------------------------ There is more than one possibility
 3127:                      my $realpossible=0;
 3128:                      foreach (@possibilities) {
 3129: 			 my $file=$bighash{'src_'.$_};
 3130:                          if (&allowed('bre',$file)) {
 3131:          		    my ($mapid,$resid)=split(/\./,$_);
 3132:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 3133: 				$realpossible++;
 3134:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 3135:                                        '___'.$resid;
 3136:                             }
 3137: 			 }
 3138:                      }
 3139: 		     if ($realpossible!=1) { $syval=''; }
 3140:                  } else {
 3141:                      $syval='';
 3142:                  }
 3143: 	      }
 3144:               untie(%bighash)
 3145:            } 
 3146:         }
 3147:         if ($syval) {
 3148:            return &symbclean($syval.'___'.$thisfn); 
 3149:         }
 3150:     }
 3151:     &appenv('request.ambiguous' => $thisfn);
 3152:     return '';
 3153: }
 3154: 
 3155: # ---------------------------------------------------------- Return random seed
 3156: 
 3157: sub numval {
 3158:     my $txt=shift;
 3159:     $txt=~tr/A-J/0-9/;
 3160:     $txt=~tr/a-j/0-9/;
 3161:     $txt=~tr/K-T/0-9/;
 3162:     $txt=~tr/k-t/0-9/;
 3163:     $txt=~tr/U-Z/0-5/;
 3164:     $txt=~tr/u-z/0-5/;
 3165:     $txt=~s/\D//g;
 3166:     return int($txt);
 3167: }    
 3168: 
 3169: sub rndseed {
 3170:     my ($symb,$courseid,$domain,$username)=@_;
 3171:     if (!$symb) {
 3172:       unless ($symb=&symbread()) { return time; }
 3173:     }
 3174:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
 3175:     if (!$domain) {$domain=$ENV{'user.domain'};}
 3176:     if (!$username) {$username=$ENV{'user.name'};}
 3177:     {
 3178:       use integer;
 3179:       my $symbchck=unpack("%32C*",$symb) << 27;
 3180:       my $symbseed=numval($symb) << 22;
 3181:       my $namechck=unpack("%32C*",$username) << 17;
 3182:       my $nameseed=numval($username) << 12;
 3183:       my $domainseed=unpack("%32C*",$domain) << 7;
 3184:       my $courseseed=unpack("%32C*",$courseid);
 3185:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 3186:       #uncommenting these lines can break things!
 3187:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3188:       #&Apache::lonxml::debug("rndseed :$num:$symb");
 3189:       return $num;
 3190:     }
 3191: }
 3192: 
 3193: sub ireceipt {
 3194:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 3195:     my $cuname=unpack("%32C*",$funame);
 3196:     my $cudom=unpack("%32C*",$fudom);
 3197:     my $cucourseid=unpack("%32C*",$fucourseid);
 3198:     my $cusymb=unpack("%32C*",$fusymb);
 3199:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 3200:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 3201:            ($cunique%$cuname+
 3202:             $cunique%$cudom+
 3203:             $cusymb%$cuname+
 3204:             $cusymb%$cudom+
 3205:             $cucourseid%$cuname+
 3206:             $cucourseid%$cudom);
 3207: }
 3208: 
 3209: sub receipt {
 3210:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 3211:   return &ireceipt($name,$domain,$courseid,$symb);
 3212: }
 3213: 
 3214: # ------------------------------------------------------------ Serves up a file
 3215: # returns either the contents of the file or a -1
 3216: sub getfile {
 3217:  my $file=shift;
 3218:  if ($file=~/^\/*uploaded\//) { # user file
 3219:     my $ua=new LWP::UserAgent;
 3220:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
 3221:     my $response=$ua->request($request);
 3222:     if ($response->is_success()) {
 3223:        return $response->content;
 3224:     } else { 
 3225:        return -1; 
 3226:     }
 3227:  } else { # normal file from res space
 3228:   &repcopy($file);
 3229:   if (! -e $file ) { return -1; };
 3230:   my $fh=Apache::File->new($file);
 3231:   my $a='';
 3232:   while (<$fh>) { $a .=$_; }
 3233:   return $a;
 3234:  }
 3235: }
 3236: 
 3237: sub filelocation {
 3238:   my ($dir,$file) = @_;
 3239:   my $location;
 3240:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 3241:   if ($file=~m:^/~:) { # is a contruction space reference
 3242:     $location = $file;
 3243:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 3244:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 3245:     $location=$file;
 3246:   } else {
 3247:     $file=~s/^$perlvar{'lonDocRoot'}//;
 3248:     $file=~s:^/*res::;
 3249:     if ( !( $file =~ m:^/:) ) {
 3250:       $location = $dir. '/'.$file;
 3251:     } else {
 3252:       $location = '/home/httpd/html/res'.$file;
 3253:     }
 3254:   }
 3255:   $location=~s://+:/:g; # remove duplicate /
 3256:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 3257:   return $location;
 3258: }
 3259: 
 3260: sub hreflocation {
 3261:     my ($dir,$file)=@_;
 3262:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 3263:        my $finalpath=filelocation($dir,$file);
 3264:        $finalpath=~s/^\/home\/httpd\/html//;
 3265:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
 3266:        return $finalpath;
 3267:     } else {
 3268:        return $file;
 3269:     }
 3270: }
 3271: 
 3272: # ------------------------------------------------------------- Declutters URLs
 3273: 
 3274: sub declutter {
 3275:     my $thisfn=shift;
 3276:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 3277:     $thisfn=~s/^\///;
 3278:     $thisfn=~s/^res\///;
 3279:     $thisfn=~s/\?.+$//;
 3280:     return $thisfn;
 3281: }
 3282: 
 3283: # ------------------------------------------------------------- Clutter up URLs
 3284: 
 3285: sub clutter {
 3286:     my $thisfn='/'.&declutter(shift);
 3287:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
 3288:        $thisfn='/res'.$thisfn; 
 3289:     }
 3290:     return $thisfn;
 3291: }
 3292: 
 3293: # -------------------------------------------------------- Escape Special Chars
 3294: 
 3295: sub escape {
 3296:     my $str=shift;
 3297:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 3298:     return $str;
 3299: }
 3300: 
 3301: # ----------------------------------------------------- Un-Escape Special Chars
 3302: 
 3303: sub unescape {
 3304:     my $str=shift;
 3305:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 3306:     return $str;
 3307: }
 3308: 
 3309: # ================================================================ Main Program
 3310: 
 3311: sub goodbye {
 3312:    &logthis("Starting Shut down");
 3313:    &flushcourselogs();
 3314:    &logthis("Shutting down");
 3315: }
 3316: 
 3317: BEGIN {
 3318: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 3319:     unless ($readit) {
 3320: {
 3321:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
 3322: 
 3323:     while (my $configline=<$config>) {
 3324:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 3325: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 3326:            chomp($varvalue);
 3327:            $perlvar{$varname}=$varvalue;
 3328:         }
 3329:     }
 3330: }
 3331: {
 3332:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
 3333: 
 3334:     while (my $configline=<$config>) {
 3335:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 3336: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 3337:            chomp($varvalue);
 3338:            $perlvar{$varname}=$varvalue;
 3339:         }
 3340:     }
 3341: }
 3342: 
 3343: # ------------------------------------------------------------- Read hosts file
 3344: {
 3345:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 3346: 
 3347:     while (my $configline=<$config>) {
 3348:        chomp($configline);
 3349:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 3350:        if ($id && $domain && $role && $name && $ip) {
 3351: 	 $hostname{$id}=$name;
 3352: 	 $hostdom{$id}=$domain;
 3353: 	 $hostip{$id}=$ip;
 3354: 	 if ($domdescr) { $domaindescription{$domain}=$domdescr; }
 3355: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 3356:        } else {
 3357: 	 if ($configline) {
 3358: 	   &logthis("Skipping hosts.tab line -$configline-");
 3359: 	 }
 3360:        }
 3361:     }
 3362: }
 3363: 
 3364: # ------------------------------------------------------ Read spare server file
 3365: {
 3366:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 3367: 
 3368:     while (my $configline=<$config>) {
 3369:        chomp($configline);
 3370:        if ($configline) {
 3371:           $spareid{$configline}=1;
 3372:        }
 3373:     }
 3374: }
 3375: # ------------------------------------------------------------ Read permissions
 3376: {
 3377:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 3378: 
 3379:     while (my $configline=<$config>) {
 3380:        chomp($configline);
 3381:       if ($configline) {
 3382:        my ($role,$perm)=split(/ /,$configline);
 3383:        if ($perm ne '') { $pr{$role}=$perm; }
 3384:       }
 3385:     }
 3386: }
 3387: 
 3388: # -------------------------------------------- Read plain texts for permissions
 3389: {
 3390:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 3391: 
 3392:     while (my $configline=<$config>) {
 3393:        chomp($configline);
 3394:       if ($configline) {
 3395:        my ($short,$plain)=split(/:/,$configline);
 3396:        if ($plain ne '') { $prp{$short}=$plain; }
 3397:       }
 3398:     }
 3399: }
 3400: 
 3401: # ---------------------------------------------------------- Read package table
 3402: {
 3403:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 3404: 
 3405:     while (my $configline=<$config>) {
 3406:        chomp($configline);
 3407:        my ($short,$plain)=split(/:/,$configline);
 3408:        my ($pack,$name)=split(/\&/,$short);
 3409:        if ($plain ne '') {
 3410:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 3411:           $packagetab{$short}=$plain; 
 3412:        }
 3413:     }
 3414: }
 3415: 
 3416: %metacache=();
 3417: 
 3418: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 3419: $dumpcount=0;
 3420: 
 3421: &logtouch();
 3422: &logthis('<font color=yellow>INFO: Read configuration</font>');
 3423: $readit=1;
 3424: }
 3425: }
 3426: 
 3427: 1;
 3428: __END__
 3429: 
 3430: =pod
 3431: 
 3432: =head1 NAME
 3433: 
 3434: Apache::lonnet - Subroutines to ask questions about things in the network.
 3435: 
 3436: =head1 SYNOPSIS
 3437: 
 3438: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 3439: 
 3440:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 3441: 
 3442: Common parameters:
 3443: 
 3444: =over 4
 3445: 
 3446: =item *
 3447: 
 3448: $uname : an internal username (if $cname expecting a course Id specifically)
 3449: 
 3450: =item *
 3451: 
 3452: $udom : a domain (if $cdom expecting a course's domain specifically)
 3453: 
 3454: =item *
 3455: 
 3456: $symb : a resource instance identifier
 3457: 
 3458: =item *
 3459: 
 3460: $namespace : the name of a .db file that contains the data needed or
 3461: being set.
 3462: 
 3463: =back
 3464: 
 3465: =head1 INTRODUCTION
 3466: 
 3467: This module provides subroutines which interact with the
 3468: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
 3469: - classes
 3470: - users 
 3471: - resources
 3472: 
 3473: For many of these objects you can also use this to store data about
 3474: them or modify them in various ways.
 3475: 
 3476: This is part of the LearningOnline Network with CAPA project
 3477: described at http://www.lon-capa.org.
 3478: 
 3479: =head1 RETURN MESSAGES
 3480: 
 3481: =over 4
 3482: 
 3483: =item *
 3484: 
 3485: con_lost : unable to contact remote host
 3486: 
 3487: =item *
 3488: 
 3489: con_delayed : unable to contact remote host, message will be delivered
 3490: when the connection is brought back up
 3491: 
 3492: =item *
 3493: 
 3494: con_failed : unable to contact remote host and unable to save message
 3495: for later delivery
 3496: 
 3497: =item *
 3498: 
 3499: error: : an error a occured, a description of the error follows the :
 3500: 
 3501: =item *
 3502: 
 3503: no_such_host : unable to fund a host associated with the user/domain
 3504: that was requested
 3505: 
 3506: =back
 3507: 
 3508: =head1 PUBLIC SUBROUTINES
 3509: 
 3510: =head2 Session Environment Functions
 3511: 
 3512: =over 4
 3513: 
 3514: =item *
 3515: 
 3516: appenv(%hash) : the value of %hash is written to the user envirnoment
 3517: file, and will be restored for each access this user makes during this
 3518: session, also modifies the %ENV for the current process
 3519: 
 3520: =item *
 3521: 
 3522: delenv($regexp) : removes all items from the session environment file that matches the regular expression in $regexp. The values are also delted from the current processes %ENV.
 3523: 
 3524: =back
 3525: 
 3526: =head2 User Information
 3527: 
 3528: =over 4
 3529: 
 3530: =item *
 3531: 
 3532: queryauthenticate($uname,$udom) : try to determine user's current
 3533: authentication scheme
 3534: 
 3535: =item *
 3536: 
 3537: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
 3538: servers (first use the current one), $upass should be the users password
 3539: 
 3540: =item *
 3541: 
 3542: homeserver($uname,$udom) : find the server which has the user's
 3543: directory and files (there must be only one), this caches the answer,
 3544: and also caches if there is a borken connection.
 3545: 
 3546: =item *
 3547: 
 3548: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
 3549: unique resource in a domain, there must be only 1 ID per username, and
 3550: only 1 username per ID in a specific domain) (returns hash:
 3551: id=>name,id=>name)
 3552: 
 3553: =item *
 3554: 
 3555: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
 3556: name=>id,name=>id)
 3557: 
 3558: =item *
 3559: 
 3560: idput($udom,%ids) : store away a list of names and associated IDs
 3561: 
 3562: =item *
 3563: 
 3564: rolesinit($udom,$username,$authhost) : get user privileges
 3565: 
 3566: =item *
 3567: 
 3568: usection($udom,$uname,$cname) : finds the section of student in the
 3569: course $cname, return section name/number or '' for "not in course"
 3570: and '-1' for "no section"
 3571: 
 3572: =item *
 3573: 
 3574: userenvironment($udom,$uname,@what) : gets the values of the keys
 3575: passed in @what from the requested user's environment, returns a hash
 3576: 
 3577: =back
 3578: 
 3579: =head2 User Roles
 3580: 
 3581: =over 4
 3582: 
 3583: =item *
 3584: 
 3585: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 3586: actions
 3587:  F: full access
 3588:  U,I,K: authentication modes (cxx only)
 3589:  '': forbidden
 3590:  1: user needs to choose course
 3591:  2: browse allowed
 3592: 
 3593: =item *
 3594: 
 3595: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 3596: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 3597: and course level
 3598: 
 3599: =item *
 3600: 
 3601: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 3602: explanation of a user role term
 3603: 
 3604: =back
 3605: 
 3606: =head2 User Modification
 3607: 
 3608: =over 4
 3609: 
 3610: =item *
 3611: 
 3612: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 3613: user for the level given by URL.  Optional start and end dates (leave empty
 3614: string or zero for "no date")
 3615: 
 3616: =item *
 3617: 
 3618: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 3619: change a users, password, possible return values are: ok,
 3620: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 3621: refused
 3622: 
 3623: =item *
 3624: 
 3625: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 3626: 
 3627: =item *
 3628: 
 3629: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 3630: modify user
 3631: 
 3632: =item *
 3633: 
 3634: modifystudent
 3635: 
 3636: modify a students enrollment and identification information.
 3637: The course id is resolved based on the current users environment.  
 3638: This means the envoking user must be a course coordinator or otherwise
 3639: associated with a course.
 3640: 
 3641: This call is essentially a wrapper for lonnet::modifyuser
 3642: 
 3643: Inputs: 
 3644: 
 3645: =over 4
 3646: 
 3647: =item B<$udom> Students loncapa domain
 3648: 
 3649: =item B<$uname> Students loncapa login name
 3650: 
 3651: =item B<$uid> Students id/student number
 3652: 
 3653: =item B<$umode> Students authentication mode
 3654: 
 3655: =item B<$upass> Students password
 3656: 
 3657: =item B<$first> Students first name
 3658: 
 3659: =item B<$middle> Students middle name
 3660: 
 3661: =item B<$last> Students last name
 3662: 
 3663: =item B<$gene> Students generation
 3664: 
 3665: =item B<$usec> Students section in course
 3666: 
 3667: =item B<$end> Unix time of the roles expiration
 3668: 
 3669: =item B<$start> Unix time of the roles start date
 3670: 
 3671: =item B<$forceid> If defined, allow $uid to be changed
 3672: 
 3673: =item B<$desiredhome> server to use as home server for student
 3674: 
 3675: =back
 3676: 
 3677: =item *
 3678: 
 3679: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 3680: custom role; give a custom role to a user for the level given by URL.  Specify
 3681: name and domain of role author, and role name
 3682: 
 3683: =item *
 3684: 
 3685: revokerole($udom,$uname,$url,$role) : revoke a role for url
 3686: 
 3687: =item *
 3688: 
 3689: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 3690: 
 3691: =back
 3692: 
 3693: =head2 Course Infomation
 3694: 
 3695: =over 4
 3696: 
 3697: =item *
 3698: 
 3699: coursedescription($courseid) : course description
 3700: 
 3701: =item *
 3702: 
 3703: courseresdata($coursenum,$coursedomain,@which) : request for current
 3704: parameter setting for a specific course, @what should be a list of
 3705: parameters to ask about. This routine caches answers for 5 minutes.
 3706: 
 3707: =back
 3708: 
 3709: =head2 Course Modification
 3710: 
 3711: =over 4
 3712: 
 3713: =item *
 3714: 
 3715: writecoursepref($courseid,%prefs) : write preferences (environment
 3716: database) for a course
 3717: 
 3718: =item *
 3719: 
 3720: createcourse($udom,$description,$url) : make/modify course
 3721: 
 3722: =back
 3723: 
 3724: =head2 Resource Subroutines
 3725: 
 3726: =over 4
 3727: 
 3728: =item *
 3729: 
 3730: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 3731: 
 3732: =item *
 3733: 
 3734: repcopy($filename) : subscribes to the requested file, and attempts to
 3735: replicate from the owning library server, Might return
 3736: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 3737: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 3738: resource. Expects the local filesystem pathname
 3739: (/home/httpd/html/res/....)
 3740: 
 3741: =back
 3742: 
 3743: =head2 Resource Information
 3744: 
 3745: =over 4
 3746: 
 3747: =item *
 3748: 
 3749: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 3750: a vairety of different possible values, $varname should be a request
 3751: string, and the other parameters can be used to specify who and what
 3752: one is asking about.
 3753: 
 3754: Possible values for $varname are environment.lastname (or other item
 3755: from the envirnment hash), user.name (or someother aspect about the
 3756: user), resource.0.maxtries (or some other part and parameter of a
 3757: resource)
 3758: 
 3759: =item *
 3760: 
 3761: directcondval($number) : get current value of a condition; reads from a state
 3762: string
 3763: 
 3764: =item *
 3765: 
 3766: condval($condidx) : value of condition index based on state
 3767: 
 3768: =item *
 3769: 
 3770: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 3771: resource's metadata, $what should be either a specific key, or either
 3772: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 3773: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 3774: 
 3775: this function automatically caches all requests
 3776: 
 3777: =item *
 3778: 
 3779: metadata_query($query,$custom,$customshow) : make a metadata query against the
 3780: network of library servers; returns file handle of where SQL and regex results
 3781: will be stored for query
 3782: 
 3783: =item *
 3784: 
 3785: symbread($filename) : return symbolic list entry (filename argument optional);
 3786: returns the data handle
 3787: 
 3788: =item *
 3789: 
 3790: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 3791: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
 3792: failure, user must be in a course, as it assumes the existance of the
 3793: course initi hash, and uses $ENV('request.course.id'}
 3794: 
 3795: 
 3796: =item *
 3797: 
 3798: symbclean($symb) : removes versions numbers from a symb, returns the
 3799: cleaned symb
 3800: 
 3801: =item *
 3802: 
 3803: is_on_map($uri) : checks if the $uri is somewhere on the current
 3804: course map, user must be in a course for it to work.
 3805: 
 3806: =item *
 3807: 
 3808: numval($salt) : return random seed value (addend for rndseed)
 3809: 
 3810: =item *
 3811: 
 3812: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 3813: a random seed, all arguments are optional, if they aren't sent it uses the
 3814: environment to derive them. Note: if symb isn't sent and it can't get one
 3815: from &symbread it will use the current time as its return value
 3816: 
 3817: =item *
 3818: 
 3819: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 3820: unfakeable, receipt
 3821: 
 3822: =item *
 3823: 
 3824: receipt() : API to ireceipt working off of ENV values; given out to users
 3825: 
 3826: =item *
 3827: 
 3828: countacc($url) : count the number of accesses to a given URL
 3829: 
 3830: =item *
 3831: 
 3832: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
 3833: 
 3834: =item *
 3835: 
 3836: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
 3837: 
 3838: =item *
 3839: 
 3840: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 3841: 
 3842: =item *
 3843: 
 3844: devalidate($symb) : devalidate temporary spreadsheet calculations,
 3845: forcing spreadsheet to reevaluate the resource scores next time.
 3846: 
 3847: =back
 3848: 
 3849: =head2 Storing/Retreiving Data
 3850: 
 3851: =over 4
 3852: 
 3853: =item *
 3854: 
 3855: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 3856: for this url; hashref needs to be given and should be a \%hashname; the
 3857: remaining args aren't required and if they aren't passed or are '' they will
 3858: be derived from the ENV
 3859: 
 3860: =item *
 3861: 
 3862: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 3863: uses critical subroutine
 3864: 
 3865: =item *
 3866: 
 3867: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 3868: all args are optional
 3869: 
 3870: =item *
 3871: 
 3872: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 3873: works very similar to store/cstore, but all data is stored in a
 3874: temporary location and can be reset using tmpreset, $storehash should
 3875: be a hash reference, returns nothing on success
 3876: 
 3877: =item *
 3878: 
 3879: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 3880: similar to restore, but all data is stored in a temporary location and
 3881: can be reset using tmpreset. Returns a hash of values on success,
 3882: error string otherwise.
 3883: 
 3884: =item *
 3885: 
 3886: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 3887: deltes all keys for $symb form the temporary storage hash.
 3888: 
 3889: =item *
 3890: 
 3891: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 3892: reference filled in from namesp ($udom and $uname are optional)
 3893: 
 3894: =item *
 3895: 
 3896: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 3897: namesp ($udom and $uname are optional)
 3898: 
 3899: =item *
 3900: 
 3901: dump($namespace,$udom,$uname,$regexp) : 
 3902: dumps the complete (or key matching regexp) namespace into a hash
 3903: ($udom, $uname and $regexp are optional)
 3904: 
 3905: =item *
 3906: 
 3907: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 3908: ($udom and $uname are optional)
 3909: 
 3910: =item *
 3911: 
 3912: cput($namespace,$storehash,$udom,$uname) : critical put
 3913: ($udom and $uname are optional)
 3914: 
 3915: =item *
 3916: 
 3917: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 3918: reference filled in from namesp (encrypts the return communication)
 3919: ($udom and $uname are optional)
 3920: 
 3921: =item *
 3922: 
 3923: log($udom,$name,$home,$message) : write to permanent log for user; use
 3924: critical subroutine
 3925: 
 3926: =back
 3927: 
 3928: =head2 Network Status Functions
 3929: 
 3930: =over 4
 3931: 
 3932: =item *
 3933: 
 3934: dirlist($uri) : return directory list based on URI
 3935: 
 3936: =item *
 3937: 
 3938: spareserver() : find server with least workload from spare.tab
 3939: 
 3940: =back
 3941: 
 3942: =head2 Apache Request
 3943: 
 3944: =over 4
 3945: 
 3946: =item *
 3947: 
 3948: ssi($url,%hash) : server side include, does a complete request cycle on url to
 3949: localhost, posts hash
 3950: 
 3951: =back
 3952: 
 3953: =head2 Data to String to Data
 3954: 
 3955: =over 4
 3956: 
 3957: =item *
 3958: 
 3959: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 3960: and '&' separators, supports elements that are arrayrefs and hashrefs
 3961: 
 3962: =item *
 3963: 
 3964: hashref2str($hashref) : convert a hashref into a string complete with
 3965: escaping and '=' and '&' separators, supports elements that are
 3966: arrayrefs and hashrefs
 3967: 
 3968: =item *
 3969: 
 3970: arrayref2str($arrayref) : convert an arrayref into a string complete
 3971: with escaping and '&' separators, supports elements that are arrayrefs
 3972: and hashrefs
 3973: 
 3974: =item *
 3975: 
 3976: str2hash($string) : convert string to hash using unescaping and
 3977: splitting on '=' and '&', supports elements that are arrayrefs and
 3978: hashrefs
 3979: 
 3980: =item *
 3981: 
 3982: str2array($string) : convert string to hash using unescaping and
 3983: splitting on '&', supports elements that are arrayrefs and hashrefs
 3984: 
 3985: =back
 3986: 
 3987: =head2 Logging Routines
 3988: 
 3989: =over 4
 3990: 
 3991: These routines allow one to make log messages in the lonnet.log and
 3992: lonnet.perm logfiles.
 3993: 
 3994: =item *
 3995: 
 3996: logtouch() : make sure the logfile, lonnet.log, exists
 3997: 
 3998: =item *
 3999: 
 4000: logthis() : append message to the normal lonnet.log file, it gets
 4001: preiodically rolled over and deleted.
 4002: 
 4003: =item *
 4004: 
 4005: logperm() : append a permanent message to lonnet.perm.log, this log
 4006: file never gets deleted by any automated portion of the system, only
 4007: messages of critical importance should go in here.
 4008: 
 4009: =back
 4010: 
 4011: =head2 General File Helper Routines
 4012: 
 4013: =over 4
 4014: 
 4015: =item *
 4016: 
 4017: getfile($file) : returns the entire contents of a file or -1; it
 4018: properly subscribes to and replicates the file if neccessary.
 4019: 
 4020: =item *
 4021: 
 4022: filelocation($dir,$file) : returns file system location of a file
 4023: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 4024: directory that relative $file lookups are to looked in ($dir of /a/dir
 4025: and a file of ../bob will become /a/bob)
 4026: 
 4027: =item *
 4028: 
 4029: hreflocation($dir,$file) : returns file system location or a URL; same as
 4030: filelocation except for hrefs
 4031: 
 4032: =item *
 4033: 
 4034: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 4035: 
 4036: =back
 4037: 
 4038: =head2 HTTP Helper Routines
 4039: 
 4040: =over 4
 4041: 
 4042: =item *
 4043: 
 4044: escape() : unpack non-word characters into CGI-compatible hex codes
 4045: 
 4046: =item *
 4047: 
 4048: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 4049: 
 4050: =back
 4051: 
 4052: =head1 PRIVATE SUBROUTINES
 4053: 
 4054: =head2 Underlying communication routines (Shouldn't call)
 4055: 
 4056: =over 4
 4057: 
 4058: =item *
 4059: 
 4060: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 4061: 
 4062: =item *
 4063: 
 4064: reply() : uses subreply to send a message to remote machine, logs all failures
 4065: 
 4066: =item *
 4067: 
 4068: critical() : passes a critical message to another server; if cannot
 4069: get through then place message in connection buffer directory and
 4070: returns con_delayed, if incapable of saving message, returns
 4071: con_failed
 4072: 
 4073: =item *
 4074: 
 4075: reconlonc() : tries to reconnect lonc client processes.
 4076: 
 4077: =back
 4078: 
 4079: =head2 Resource Access Logging
 4080: 
 4081: =over 4
 4082: 
 4083: =item *
 4084: 
 4085: flushcourselogs() : flush (save) buffer logs and access logs
 4086: 
 4087: =item *
 4088: 
 4089: courselog($what) : save message for course in hash
 4090: 
 4091: =item *
 4092: 
 4093: courseacclog($what) : save message for course using &courselog().  Perform
 4094: special processing for specific resource types (problems, exams, quizzes, etc).
 4095: 
 4096: =item *
 4097: 
 4098: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 4099: as a PerlChildExitHandler
 4100: 
 4101: =back
 4102: 
 4103: =head2 Other
 4104: 
 4105: =over 4
 4106: 
 4107: =item *
 4108: 
 4109: symblist($mapname,%newhash) : update symbolic storage links
 4110: 
 4111: =back
 4112: 
 4113: =cut

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