File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.257: download - view: text, annotated - select for diffs
Tue Jul 30 21:20:27 2002 UTC (22 years ago) by www
Branches: MAIN
CVS tags: HEAD
Start of routine to load user file into userfile space, which will later
have token-security.

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

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