File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.256: download - view: text, annotated - select for diffs
Tue Jul 30 19:59:32 2002 UTC (21 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- need to put () after the &GDBM_* calls BUG#574

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

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