File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.230: download - view: text, annotated - select for diffs
Tue May 21 15:00:05 2002 UTC (22 years, 1 month ago) by stredwic
Branches: MAIN
CVS tags: HEAD
See bug report 458.  Reversed default for homeserver to using caching of negative results.

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

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