File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.351: download - view: text, annotated - select for diffs
Tue Mar 25 19:18:40 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
First use of reverse role association

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

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