File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.264: download - view: text, annotated - select for diffs
Thu Aug 8 20:33:50 2002 UTC (21 years, 11 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bug 263.  Modified &allowed to deal properly with domain coordinator
domains.  Modified &createcourse to take another parameter to specify
the server to create a course on.  Was using $ENV{'user.home'} for the
course home server.

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

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