File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.231: download - view: text, annotated - select for diffs
Wed May 22 13:56:43 2002 UTC (22 years, 2 months ago) by stredwic
Branches: MAIN
CVS tags: HEAD
Changed caching of negative results such that it marks which servers don't respond.  This was done in lonnet::homerserve.

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

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