File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.369: download - view: text, annotated - select for diffs
Thu May 8 21:35:48 2003 UTC (21 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- more user load balancing, BUG#958

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.369 2003/05/08 21:35:48 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   30: # 11/8,11/16,11/18,11/22,11/23,12/22,
   31: # 01/06,01/13,02/24,02/28,02/29,
   32: # 03/01,03/02,03/06,03/07,03/13,
   33: # 04/05,05/29,05/31,06/01,
   34: # 06/05,06/26 Gerd Kortemeyer
   35: # 06/26 Ben Tyszka
   36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   37: # 08/14 Ben Tyszka
   38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   39: # 10/04 Gerd Kortemeyer
   40: # 10/04 Guy Albertelli
   41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   42: # 10/30,10/31,
   43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
   44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
   45: # 05/01/01 Guy Albertelli
   46: # 05/01,06/01,09/01 Gerd Kortemeyer
   47: # 09/01 Guy Albertelli
   48: # 09/01,10/01,11/01 Gerd Kortemeyer
   49: # YEAR=2001
   50: # 3/2 Gerd Kortemeyer
   51: # 3/19,3/20 Gerd Kortemeyer
   52: # 5/26,5/28 Gerd Kortemeyer
   53: # 5/30 H. K. Ng
   54: # 6/1 Gerd Kortemeyer
   55: # July Guy Albertelli
   56: # 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,
   57: # 10/2 Gerd Kortemeyer
   58: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
   59: # 12/5 Matthew Hall
   60: # 12/5 Guy Albertelli
   61: # 12/6,12/7,12/12 Gerd Kortemeyer
   62: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
   63: # YEAR=2002
   64: # 1/4,2/4,2/7 Gerd Kortemeyer
   65: #
   66: ###
   67: 
   68: package Apache::lonnet;
   69: 
   70: use strict;
   71: use Apache::File;
   72: use LWP::UserAgent();
   73: use HTTP::Headers;
   74: use vars 
   75: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
   76:    %libserv %pr %prp %metacache %packagetab %titlecache 
   77:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
   78:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache 
   79:    %domaindescription %domain_auth_def %domain_auth_arg_def $tmpdir);
   80: use IO::Socket;
   81: use GDBM_File;
   82: use Apache::Constants qw(:common :http);
   83: use HTML::LCParser;
   84: use Fcntl qw(:flock);
   85: use Apache::loncoursedata;
   86: 
   87: my $readit;
   88: 
   89: # --------------------------------------------------------------------- Logging
   90: 
   91: sub logtouch {
   92:     my $execdir=$perlvar{'lonDaemons'};
   93:     unless (-e "$execdir/logs/lonnet.log") {
   94: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
   95: 	close $fh;
   96:     }
   97:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
   98:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
   99: }
  100: 
  101: sub logthis {
  102:     my $message=shift;
  103:     my $execdir=$perlvar{'lonDaemons'};
  104:     my $now=time;
  105:     my $local=localtime($now);
  106:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
  107:     print $fh "$local ($$): $message\n";
  108:     return 1;
  109: }
  110: 
  111: sub logperm {
  112:     my $message=shift;
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     my $now=time;
  115:     my $local=localtime($now);
  116:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
  117:     print $fh "$now:$message:$local\n";
  118:     return 1;
  119: }
  120: 
  121: # -------------------------------------------------- Non-critical communication
  122: sub subreply {
  123:     my ($cmd,$server)=@_;
  124:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  125:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  126:                                      Type    => SOCK_STREAM,
  127:                                      Timeout => 10)
  128:        or return "con_lost";
  129:     print $client "$cmd\n";
  130:     my $answer=<$client>;
  131:     if (!$answer) { $answer="con_lost"; }
  132:     chomp($answer);
  133:     return $answer;
  134: }
  135: 
  136: sub reply {
  137:     my ($cmd,$server)=@_;
  138:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  139:     my $answer=subreply($cmd,$server);
  140:     if ($answer eq 'con_lost') {
  141:         #sleep 5; 
  142:         #$answer=subreply($cmd,$server);
  143:         #if ($answer eq 'con_lost') {
  144: 	#   &logthis("Second attempt con_lost on $server");
  145:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
  146:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  147:         #                                    Type    => SOCK_STREAM,
  148:         #                                    Timeout => 10)
  149:         #              or return "con_lost";
  150:         #   &logthis("Killing socket");
  151:         #   print $client "close_connection_exit\n";
  152:            #sleep 5;
  153:         #   $answer=subreply($cmd,$server);       
  154:        #}   
  155:     }
  156:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  157:        &logthis("<font color=blue>WARNING:".
  158:                 " $cmd to $server returned $answer</font>");
  159:     }
  160:     return $answer;
  161: }
  162: 
  163: # ----------------------------------------------------------- Send USR1 to lonc
  164: 
  165: sub reconlonc {
  166:     my $peerfile=shift;
  167:     &logthis("Trying to reconnect for $peerfile");
  168:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  169:     if (my $fh=Apache::File->new("$loncfile")) {
  170: 	my $loncpid=<$fh>;
  171:         chomp($loncpid);
  172:         if (kill 0 => $loncpid) {
  173: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  174:             kill USR1 => $loncpid;
  175:             sleep 1;
  176:             if (-e "$peerfile") { return; }
  177:             &logthis("$peerfile still not there, give it another try");
  178:             sleep 5;
  179:             if (-e "$peerfile") { return; }
  180:             &logthis(
  181:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  182:         } else {
  183: 	    &logthis(
  184:                "<font color=blue>WARNING:".
  185:                " lonc at pid $loncpid not responding, giving up</font>");
  186:         }
  187:     } else {
  188:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  189:     }
  190: }
  191: 
  192: # ------------------------------------------------------ Critical communication
  193: 
  194: sub critical {
  195:     my ($cmd,$server)=@_;
  196:     unless ($hostname{$server}) {
  197:         &logthis("<font color=blue>WARNING:".
  198:                " Critical message to unknown server ($server)</font>");
  199:         return 'no_such_host';
  200:     }
  201:     my $answer=reply($cmd,$server);
  202:     if ($answer eq 'con_lost') {
  203:         my $pingreply=reply('ping',$server);
  204: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  205:         my $pongreply=reply('pong',$server);
  206:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
  207:         $answer=reply($cmd,$server);
  208:         if ($answer eq 'con_lost') {
  209:             my $now=time;
  210:             my $middlename=$cmd;
  211:             $middlename=substr($middlename,0,16);
  212:             $middlename=~s/\W//g;
  213:             my $dfilename=
  214:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  215:             $dumpcount++;
  216:             {
  217:              my $dfh;
  218:              if ($dfh=Apache::File->new(">$dfilename")) {
  219:                 print $dfh "$cmd\n";
  220: 	     }
  221:             }
  222:             sleep 2;
  223:             my $wcmd='';
  224:             {
  225: 	     my $dfh;
  226:              if ($dfh=Apache::File->new("$dfilename")) {
  227:                 $wcmd=<$dfh>;
  228: 	     }
  229:             }
  230:             chomp($wcmd);
  231:             if ($wcmd eq $cmd) {
  232: 		&logthis("<font color=blue>WARNING: ".
  233:                          "Connection buffer $dfilename: $cmd</font>");
  234:                 &logperm("D:$server:$cmd");
  235: 	        return 'con_delayed';
  236:             } else {
  237:                 &logthis("<font color=red>CRITICAL:"
  238:                         ." Critical connection failed: $server $cmd</font>");
  239:                 &logperm("F:$server:$cmd");
  240:                 return 'con_failed';
  241:             }
  242:         }
  243:     }
  244:     return $answer;
  245: }
  246: 
  247: # ---------------------------------------------------------- Append Environment
  248: 
  249: sub appenv {
  250:     my %newenv=@_;
  251:     foreach (keys %newenv) {
  252: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  253:             &logthis("<font color=blue>WARNING: ".
  254:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  255:                 .'</font>');
  256: 	    delete($newenv{$_});
  257:         } else {
  258:             $ENV{$_}=$newenv{$_};
  259:         }
  260:     }
  261: 
  262:     my $lockfh;
  263:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
  264:        return 'error: '.$!;
  265:     }
  266:     unless (flock($lockfh,LOCK_EX)) {
  267:          &logthis("<font color=blue>WARNING: ".
  268:                   'Could not obtain exclusive lock in appenv: '.$!);
  269:          $lockfh->close();
  270:          return 'error: '.$!;
  271:     }
  272: 
  273:     my @oldenv;
  274:     {
  275:      my $fh;
  276:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  277: 	return 'error: '.$!;
  278:      }
  279:      @oldenv=<$fh>;
  280:      $fh->close();
  281:     }
  282:     for (my $i=0; $i<=$#oldenv; $i++) {
  283:         chomp($oldenv[$i]);
  284:         if ($oldenv[$i] ne '') {
  285:            my ($name,$value)=split(/=/,$oldenv[$i]);
  286:            unless (defined($newenv{$name})) {
  287: 	      $newenv{$name}=$value;
  288: 	   }
  289:         }
  290:     }
  291:     {
  292:      my $fh;
  293:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  294: 	return 'error';
  295:      }
  296:      my $newname;
  297:      foreach $newname (keys %newenv) {
  298: 	 print $fh "$newname=$newenv{$newname}\n";
  299:      }
  300:      $fh->close();
  301:     }
  302: 
  303:     $lockfh->close();
  304:     return 'ok';
  305: }
  306: # ----------------------------------------------------- Delete from Environment
  307: 
  308: sub delenv {
  309:     my $delthis=shift;
  310:     my %newenv=();
  311:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  312:         &logthis("<font color=blue>WARNING: ".
  313:                 "Attempt to delete from environment ".$delthis);
  314:         return 'error';
  315:     }
  316:     my @oldenv;
  317:     {
  318:      my $fh;
  319:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  320: 	return 'error';
  321:      }
  322:      unless (flock($fh,LOCK_SH)) {
  323:          &logthis("<font color=blue>WARNING: ".
  324:                   'Could not obtain shared lock in delenv: '.$!);
  325:          $fh->close();
  326:          return 'error: '.$!;
  327:      }
  328:      @oldenv=<$fh>;
  329:      $fh->close();
  330:     }
  331:     {
  332:      my $fh;
  333:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  334: 	return 'error';
  335:      }
  336:      unless (flock($fh,LOCK_EX)) {
  337:          &logthis("<font color=blue>WARNING: ".
  338:                   'Could not obtain exclusive lock in delenv: '.$!);
  339:          $fh->close();
  340:          return 'error: '.$!;
  341:      }
  342:      foreach (@oldenv) {
  343: 	 unless ($_=~/^$delthis/) { print $fh $_; }
  344:      }
  345:      $fh->close();
  346:     }
  347:     return 'ok';
  348: }
  349: 
  350: # ------------------------------------------ Find out current server userload
  351: # there is a copy in lond
  352: sub userload {
  353:     my $numusers=0;
  354:     {
  355: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  356: 	my $filename;
  357: 	my $curtime=time;
  358: 	while ($filename=readdir(LONIDS)) {
  359: 	    if ($filename eq '.' || $filename eq '..') {next;}
  360: 	    my ($atime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[8];
  361: 	    if ($curtime-$atime < 3600) { $num_users++; }
  362: 	}
  363: 	closedir(LONIDS);
  364:     }
  365:     my $userloadpercent=0;
  366:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  367:     if ($maxuserload) {
  368: 	$userloadpercent=100*$num_users/$maxuserload;
  369:     }
  370:     return $userloadpercent;
  371: }
  372: 
  373: # ------------------------------------------ Fight off request when overloaded
  374: 
  375: sub overloaderror {
  376:     my ($r,$checkserver)=@_;
  377:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  378:     my $loadavg;
  379:     if ($checkserver eq $perlvar{'lonHostID'}) {
  380:        my $loadfile=Apache::File->new('/proc/loadavg');
  381:        $loadavg=<$loadfile>;
  382:        $loadavg =~ s/\s.*//g;
  383:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  384:     } else {
  385:        $loadavg=&reply('load',$checkserver);
  386:     }
  387:     my $overload=$loadavg-100;
  388:     if ($overload>0) {
  389: 	$r->err_headers_out->{'Retry-After'}=$overload;
  390:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  391:         return 413;
  392:     }    
  393:     return '';
  394: }
  395: 
  396: # ------------------------------ Find server with least workload from spare.tab
  397: 
  398: sub spareserver {
  399:     my $loadpercent = shift;
  400:     my $tryserver;
  401:     my $spareserver='';
  402:     my $lowestserver=$loadpercent; 
  403:     foreach $tryserver (keys %spareid) {
  404:        my $answer=reply('load',$tryserver);
  405:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  406: 	   $spareserver="http://$hostname{$tryserver}";
  407:            $lowestserver=$answer;
  408:        }
  409:     }    
  410:     return $spareserver;
  411: }
  412: 
  413: # --------------------------------------------- Try to change a user's password
  414: 
  415: sub changepass {
  416:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  417:     $currentpass = &escape($currentpass);
  418:     $newpass     = &escape($newpass);
  419:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  420: 		       $server);
  421:     if (! $answer) {
  422: 	&logthis("No reply on password change request to $server ".
  423: 		 "by $uname in domain $udom.");
  424:     } elsif ($answer =~ "^ok") {
  425:         &logthis("$uname in $udom successfully changed their password ".
  426: 		 "on $server.");
  427:     } elsif ($answer =~ "^pwchange_failure") {
  428: 	&logthis("$uname in $udom was unable to change their password ".
  429: 		 "on $server.  The action was blocked by either lcpasswd ".
  430: 		 "or pwchange");
  431:     } elsif ($answer =~ "^non_authorized") {
  432:         &logthis("$uname in $udom did not get their password correct when ".
  433: 		 "attempting to change it on $server.");
  434:     } elsif ($answer =~ "^auth_mode_error") {
  435:         &logthis("$uname in $udom attempted to change their password despite ".
  436: 		 "not being locally or internally authenticated on $server.");
  437:     } elsif ($answer =~ "^unknown_user") {
  438:         &logthis("$uname in $udom attempted to change their password ".
  439: 		 "on $server but were unable to because $server is not ".
  440: 		 "their home server.");
  441:     } elsif ($answer =~ "^refused") {
  442: 	&logthis("$server refused to change $uname in $udom password because ".
  443: 		 "it was sent an unencrypted request to change the password.");
  444:     }
  445:     return $answer;
  446: }
  447: 
  448: # ----------------------- Try to determine user's current authentication scheme
  449: 
  450: sub queryauthenticate {
  451:     my ($uname,$udom)=@_;
  452:     if (($perlvar{'lonRole'} eq 'library') && 
  453:         ($udom eq $perlvar{'lonDefDomain'})) {
  454: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
  455: 			 $perlvar{'lonHostID'});
  456: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  457: 	    if (length($answer)) {
  458: 		return $answer;
  459: 	    }
  460: 	    else {
  461: 	&logthis("User $uname at $udom lacks an authentication mechanism");
  462: 		return 'no_host';
  463: 	    }
  464: 	}
  465:     }
  466: 
  467:     my $tryserver;
  468:     foreach $tryserver (keys %libserv) {
  469: 	if ($hostdom{$tryserver} eq $udom) {
  470:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
  471: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  472: 	       if (length($answer)) {
  473: 		   return $answer;
  474: 	       }
  475: 	       else {
  476: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
  477: 		   return 'no_host';
  478: 	       }
  479: 	   }
  480:        }
  481:     }
  482:     &logthis("User $uname at $udom lacks an authentication mechanism");    
  483:     return 'no_host';
  484: }
  485: 
  486: # --------- Try to authenticate user from domain's lib servers (first this one)
  487: 
  488: sub authenticate {
  489:     my ($uname,$upass,$udom)=@_;
  490:     $upass=escape($upass);
  491:     $uname=~s/\W//g;
  492:     if (($perlvar{'lonRole'} eq 'library') && 
  493:         ($udom eq $perlvar{'lonDefDomain'})) {
  494:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
  495:         if ($answer =~ /authorized/) {
  496:               if ($answer eq 'authorized') {
  497:                  &logthis("User $uname at $udom authorized by local server"); 
  498:                  return $perlvar{'lonHostID'}; 
  499:               }
  500:               if ($answer eq 'non_authorized') {
  501:                  &logthis("User $uname at $udom rejected by local server"); 
  502:                  return 'no_host'; 
  503:               }
  504: 	}
  505:     }
  506: 
  507:     my $tryserver;
  508:     foreach $tryserver (keys %libserv) {
  509: 	if ($hostdom{$tryserver} eq $udom) {
  510:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
  511:            if ($answer =~ /authorized/) {
  512:               if ($answer eq 'authorized') {
  513:                  &logthis("User $uname at $udom authorized by $tryserver"); 
  514:                  return $tryserver; 
  515:               }
  516:               if ($answer eq 'non_authorized') {
  517:                  &logthis("User $uname at $udom rejected by $tryserver");
  518:                  return 'no_host';
  519:               } 
  520: 	   }
  521:        }
  522:     }
  523:     &logthis("User $uname at $udom could not be authenticated");    
  524:     return 'no_host';
  525: }
  526: 
  527: # ---------------------- Find the homebase for a user from domain's lib servers
  528: 
  529: sub homeserver {
  530:     my ($uname,$udom,$ignoreBadCache)=@_;
  531:     my $index="$uname:$udom";
  532:     if ($homecache{$index}) { 
  533:         return "$homecache{$index}"; 
  534:     }
  535:     my $tryserver;
  536:     foreach $tryserver (keys %libserv) {
  537:         next if ($ignoreBadCache ne 'true' && 
  538: 		 exists($badServerCache{$tryserver}));
  539: 	if ($hostdom{$tryserver} eq $udom) {
  540:            my $answer=reply("home:$udom:$uname",$tryserver);
  541:            if ($answer eq 'found') { 
  542:               $homecache{$index}=$tryserver;
  543:               return $tryserver; 
  544:            } elsif ($answer eq 'no_host') {
  545: 	       $badServerCache{$tryserver}=1;
  546:            }
  547:        }
  548:     }    
  549:     return 'no_host';
  550: }
  551: 
  552: # ------------------------------------- Find the usernames behind a list of IDs
  553: 
  554: sub idget {
  555:     my ($udom,@ids)=@_;
  556:     my %returnhash=();
  557:     
  558:     my $tryserver;
  559:     foreach $tryserver (keys %libserv) {
  560:        if ($hostdom{$tryserver} eq $udom) {
  561: 	  my $idlist=join('&',@ids);
  562:           $idlist=~tr/A-Z/a-z/; 
  563: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  564:           my @answer=();
  565:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  566: 	      @answer=split(/\&/,$reply);
  567:           }                    ;
  568:           my $i;
  569:           for ($i=0;$i<=$#ids;$i++) {
  570:               if ($answer[$i]) {
  571: 		  $returnhash{$ids[$i]}=$answer[$i];
  572:               } 
  573:           }
  574:        }
  575:     }    
  576:     return %returnhash;
  577: }
  578: 
  579: # ------------------------------------- Find the IDs behind a list of usernames
  580: 
  581: sub idrget {
  582:     my ($udom,@unames)=@_;
  583:     my %returnhash=();
  584:     foreach (@unames) {
  585:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  586:     }
  587:     return %returnhash;
  588: }
  589: 
  590: # ------------------------------- Store away a list of names and associated IDs
  591: 
  592: sub idput {
  593:     my ($udom,%ids)=@_;
  594:     my %servers=();
  595:     foreach (keys %ids) {
  596:         my $uhom=&homeserver($_,$udom);
  597:         if ($uhom ne 'no_host') {
  598:             my $id=&escape($ids{$_});
  599:             $id=~tr/A-Z/a-z/;
  600:             my $unam=&escape($_);
  601: 	    if ($servers{$uhom}) {
  602: 		$servers{$uhom}.='&'.$id.'='.$unam;
  603:             } else {
  604:                 $servers{$uhom}=$id.'='.$unam;
  605:             }
  606:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
  607:         }
  608:     }
  609:     foreach (keys %servers) {
  610:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  611:     }
  612: }
  613: 
  614: # --------------------------------------------------- Assign a key to a student
  615: 
  616: sub assign_access_key {
  617: #
  618: # a valid key looks like uname:udom#comments
  619: # comments are being appended
  620: #
  621:     my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  622:     $cdom=
  623:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  624:     $cnum=
  625:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  626:     $udom=$ENV{'user.name'} unless (defined($udom));
  627:     $uname=$ENV{'user.domain'} unless (defined($uname));
  628:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  629:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  630:         ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) { 
  631:                                                   # assigned to this person
  632:                                                   # - this should not happen,
  633:                                                   # unless something went wrong
  634:                                                   # the first time around
  635: # ready to assign
  636:         $logentry=$1.'; '.$logentry;
  637:         if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  638:                                                  $cdom,$cnum) eq 'ok') {
  639: # key now belongs to user
  640: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  641:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  642:                 &appenv('environment.'.$envkey => $ckey);
  643:                 return 'ok';
  644:             } else {
  645:                 return 
  646:   'error: Count not permanently assign key, will need to be re-entered later.';
  647: 	    }
  648:         } else {
  649:             return 'error: Could not assign key, try again later.';
  650:         }
  651:     } elsif (!$existing{$ckey}) {
  652: # the key does not exist
  653: 	return 'error: The key does not exist';
  654:     } else {
  655: # the key is somebody else's
  656: 	return 'error: The key is already in use';
  657:     }
  658: }
  659: 
  660: # ------------------------------------------ put an additional comment on a key
  661: 
  662: sub comment_access_key {
  663: #
  664: # a valid key looks like uname:udom#comments
  665: # comments are being appended
  666: #
  667:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  668:     $cdom=
  669:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  670:     $cnum=
  671:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  672:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  673:     if ($existing{$ckey}) {
  674:         $existing{$ckey}.='; '.$logentry;
  675: # ready to assign
  676:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  677:                                                  $cdom,$cnum) eq 'ok') {
  678: 	    return 'ok';
  679:         } else {
  680: 	    return 'error: Count not store comment.';
  681:         }
  682:     } else {
  683: # the key does not exist
  684: 	return 'error: The key does not exist';
  685:     }
  686: }
  687: 
  688: # ------------------------------------------------------ Generate a set of keys
  689: 
  690: sub generate_access_keys {
  691:     my ($number,$cdom,$cnum,$logentry)=@_;
  692:     $cdom=
  693:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  694:     $cnum=
  695:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  696:     unless (&allowed('mky',$cdom)) { return 0; }
  697:     unless (($cdom) && ($cnum)) { return 0; }
  698:     if ($number>10000) { return 0; }
  699:     sleep(2); # make sure don't get same seed twice
  700:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  701:     my $total=0;
  702:     for (my $i=1;$i<=$number;$i++) {
  703:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  704:                   sprintf("%lx",int(100000*rand)).'-'.
  705:                   sprintf("%lx",int(100000*rand));
  706:        $newkey=~s/1/g/g; # folks mix up 1 and l
  707:        $newkey=~s/0/h/g; # and also 0 and O
  708:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  709:        if ($existing{$newkey}) {
  710:            $i--;
  711:        } else {
  712: 	  if (&put('accesskeys',
  713:               { $newkey => '# generated '.localtime().
  714:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
  715:                            '; '.$logentry },
  716: 		   $cdom,$cnum) eq 'ok') {
  717:               $total++;
  718: 	  }
  719:        }
  720:     }
  721:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
  722:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  723:     return $total;
  724: }
  725: 
  726: # ------------------------------------------------------- Validate an accesskey
  727: 
  728: sub validate_access_key {
  729:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  730:     $cdom=
  731:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  732:     $cnum=
  733:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  734:     $udom=$ENV{'user.name'} unless (defined($udom));
  735:     $uname=$ENV{'user.domain'} unless (defined($uname));
  736:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  737:     return ($existing{$ckey}=~/^$uname\:$udom\#/);
  738: }
  739: 
  740: # ------------------------------------- Find the section of student in a course
  741: 
  742: sub getsection {
  743:     my ($udom,$unam,$courseid)=@_;
  744:     $courseid=~s/\_/\//g;
  745:     $courseid=~s/^(\w)/\/$1/;
  746:     my %Pending; 
  747:     my %Expired;
  748:     #
  749:     # Each role can either have not started yet (pending), be active, 
  750:     #    or have expired.
  751:     #
  752:     # If there is an active role, we are done.
  753:     #
  754:     # If there is more than one role which has not started yet, 
  755:     #     choose the one which will start sooner
  756:     # If there is one role which has not started yet, return it.
  757:     #
  758:     # If there is more than one expired role, choose the one which ended last.
  759:     # If there is a role which has expired, return it.
  760:     #
  761:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  762:                         &homeserver($unam,$udom)))) {
  763:         my ($key,$value)=split(/\=/,$_);
  764:         $key=&unescape($key);
  765:         next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
  766:         my $section=$1;
  767:         if ($key eq $courseid.'_st') { $section=''; }
  768:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  769:         my $now=time;
  770:         if (defined($end) && ($now > $end)) {
  771:             $Expired{$end}=$section;
  772:             next;
  773:         }
  774:         if (defined($start) && ($now < $start)) {
  775:             $Pending{$start}=$section;
  776:             next;
  777:         }
  778:         return $section;
  779:     }
  780:     #
  781:     # Presumedly there will be few matching roles from the above
  782:     # loop and the sorting time will be negligible.
  783:     if (scalar(keys(%Pending))) {
  784:         my ($time) = sort {$a <=> $b} keys(%Pending);
  785:         return $Pending{$time};
  786:     } 
  787:     if (scalar(keys(%Expired))) {
  788:         my @sorted = sort {$a <=> $b} keys(%Expired);
  789:         my $time = pop(@sorted);
  790:         return $Expired{$time};
  791:     }
  792:     return '-1';
  793: }
  794: 
  795: sub usection {
  796:     my ($udom,$unam,$courseid)=@_;
  797:     $courseid=~s/\_/\//g;
  798:     $courseid=~s/^(\w)/\/$1/;
  799:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  800:                         &homeserver($unam,$udom)))) {
  801:         my ($key,$value)=split(/\=/,$_);
  802:         $key=&unescape($key);
  803:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
  804:             my $section=$1;
  805:             if ($key eq $courseid.'_st') { $section=''; }
  806: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  807:             my $now=time;
  808:             my $notactive=0;
  809:             if ($start) {
  810: 		if ($now<$start) { $notactive=1; }
  811:             }
  812:             if ($end) {
  813:                 if ($now>$end) { $notactive=1; }
  814:             } 
  815:             unless ($notactive) { return $section; }
  816:         }
  817:     }
  818:     return '-1';
  819: }
  820: 
  821: # ------------------------------------- Read an entry from a user's environment
  822: 
  823: sub userenvironment {
  824:     my ($udom,$unam,@what)=@_;
  825:     my %returnhash=();
  826:     my @answer=split(/\&/,
  827:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  828:                       &homeserver($unam,$udom)));
  829:     my $i;
  830:     for ($i=0;$i<=$#what;$i++) {
  831: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  832:     }
  833:     return %returnhash;
  834: }
  835: 
  836: # -------------------------------------------------------------------- New chat
  837: 
  838: sub chatsend {
  839:     my ($newentry,$anon)=@_;
  840:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  841:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  842:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
  843:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
  844: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
  845: 		   &escape($newentry)),$chome);
  846: }
  847: 
  848: # ------------------------------------------ Find current version of a resource
  849: 
  850: sub getversion {
  851:     my $fname=&clutter(shift);
  852:     unless ($fname=~/^\/res\//) { return -1; }
  853:     return &currentversion(&filelocation('',$fname));
  854: }
  855: 
  856: sub currentversion {
  857:     my $fname=shift;
  858:     my $author=$fname;
  859:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  860:     my ($udom,$uname)=split(/\//,$author);
  861:     my $home=homeserver($uname,$udom);
  862:     if ($home eq 'no_host') { 
  863:         return -1; 
  864:     }
  865:     my $answer=reply("currentversion:$fname",$home);
  866:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  867: 	return -1;
  868:     }
  869:     return $answer;
  870: }
  871: 
  872: # ----------------------------- Subscribe to a resource, return URL if possible
  873: 
  874: sub subscribe {
  875:     my $fname=shift;
  876:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
  877:     my $author=$fname;
  878:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  879:     my ($udom,$uname)=split(/\//,$author);
  880:     my $home=homeserver($uname,$udom);
  881:     if ($home eq 'no_host') {
  882:         return 'not_found';
  883:     }
  884:     my $answer=reply("sub:$fname",$home);
  885:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  886: 	$answer.=' by '.$home;
  887:     }
  888:     return $answer;
  889: }
  890:     
  891: # -------------------------------------------------------------- Replicate file
  892: 
  893: sub repcopy {
  894:     my $filename=shift;
  895:     $filename=~s/\/+/\//g;
  896:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
  897:     my $transname="$filename.in.transfer";
  898:     if ((-e $filename) || (-e $transname)) { return OK; }
  899:     my $remoteurl=subscribe($filename);
  900:     if ($remoteurl =~ /^con_lost by/) {
  901: 	   &logthis("Subscribe returned $remoteurl: $filename");
  902:            return HTTP_SERVICE_UNAVAILABLE;
  903:     } elsif ($remoteurl eq 'not_found') {
  904: 	   &logthis("Subscribe returned not_found: $filename");
  905: 	   return HTTP_NOT_FOUND;
  906:     } elsif ($remoteurl =~ /^rejected by/) {
  907: 	   &logthis("Subscribe returned $remoteurl: $filename");
  908:            return FORBIDDEN;
  909:     } elsif ($remoteurl eq 'directory') {
  910:            return OK;
  911:     } else {
  912:         my $author=$filename;
  913:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  914:         my ($udom,$uname)=split(/\//,$author);
  915:         my $home=homeserver($uname,$udom);
  916:         unless ($home eq $perlvar{'lonHostID'}) {
  917:            my @parts=split(/\//,$filename);
  918:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  919:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
  920:                &logthis("Malconfiguration for replication: $filename");
  921: 	       return HTTP_BAD_REQUEST;
  922:            }
  923:            my $count;
  924:            for ($count=5;$count<$#parts;$count++) {
  925:                $path.="/$parts[$count]";
  926:                if ((-e $path)!=1) {
  927: 		   mkdir($path,0777);
  928:                }
  929:            }
  930:            my $ua=new LWP::UserAgent;
  931:            my $request=new HTTP::Request('GET',"$remoteurl");
  932:            my $response=$ua->request($request,$transname);
  933:            if ($response->is_error()) {
  934: 	       unlink($transname);
  935:                my $message=$response->status_line;
  936:                &logthis("<font color=blue>WARNING:"
  937:                        ." LWP get: $message: $filename</font>");
  938:                return HTTP_SERVICE_UNAVAILABLE;
  939:            } else {
  940: 	       if ($remoteurl!~/\.meta$/) {
  941:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
  942:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
  943:                   if ($mresponse->is_error()) {
  944: 		      unlink($filename.'.meta');
  945:                       &logthis(
  946:                      "<font color=yellow>INFO: No metadata: $filename</font>");
  947:                   }
  948: 	       }
  949:                rename($transname,$filename);
  950:                return OK;
  951:            }
  952:        }
  953:     }
  954: }
  955: 
  956: # ------------------------------------------------ Get server side include body
  957: sub ssi_body {
  958:     my $filelink=shift;
  959:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
  960:                                      &ssi($filelink));
  961:     $output=~s/^.*\<body[^\>]*\>//si;
  962:     $output=~s/\<\/body\s*\>.*$//si;
  963:     $output=~
  964:             s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
  965:     return $output;
  966: }
  967: 
  968: # --------------------------------------------------------- Server Side Include
  969: 
  970: sub ssi {
  971: 
  972:     my ($fn,%form)=@_;
  973: 
  974:     my $ua=new LWP::UserAgent;
  975:     
  976:     my $request;
  977:     
  978:     if (%form) {
  979:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
  980:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
  981:     } else {
  982:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
  983:     }
  984: 
  985:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
  986:     my $response=$ua->request($request);
  987: 
  988:     return $response->content;
  989: }
  990: 
  991: sub externalssi {
  992:     my ($url)=@_;
  993:     my $ua=new LWP::UserAgent;
  994:     my $request=new HTTP::Request('GET',$url);
  995:     my $response=$ua->request($request);
  996:     return $response->content;
  997: }
  998: 
  999: # ------- Add a token to a remote URI's query string to vouch for access rights
 1000: 
 1001: sub tokenwrapper {
 1002:     my $uri=shift;
 1003:     $uri=~s/^http\:\/\/([^\/]+)//;
 1004:     $uri=~s/^\///;
 1005:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
 1006:     my $token=$1;
 1007:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
 1008: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
 1009:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
 1010:                (($uri=~/\?/)?'&':'?').'token='.$token.
 1011:                                '&tokenissued='.$perlvar{'lonHostID'};
 1012:     } else {
 1013: 	return '/adm/notfound.html';
 1014:     }
 1015: }
 1016:     
 1017: # --------------- Take an uploaded file and put it into the userfiles directory
 1018: # input: name of form element, coursedoc=1 means this is for the course
 1019: # output: url of file in userspace
 1020: 
 1021: sub userfileupload {
 1022:     my ($formname,$coursedoc)=@_;
 1023:     my $fname=$ENV{'form.'.$formname.'.filename'};
 1024: # Replace Windows backslashes by forward slashes
 1025:     $fname=~s/\\/\//g;
 1026: # Get rid of everything but the actual filename
 1027:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1028: # Replace spaces by underscores
 1029:     $fname=~s/\s+/\_/g;
 1030: # Replace all other weird characters by nothing
 1031:     $fname=~s/[^\w\.\-]//g;
 1032: # See if there is anything left
 1033:     unless ($fname) { return 'error: no uploaded file'; }
 1034:     chop($ENV{'form.'.$formname});
 1035: # Create the directory if not present
 1036:     my $docuname='';
 1037:     my $docudom='';
 1038:     my $docuhome='';
 1039:     if ($coursedoc) {
 1040: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1041: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1042: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1043:     } else {
 1044:         $docuname=$ENV{'user.name'};
 1045:         $docudom=$ENV{'user.domain'};
 1046:         $docuhome=$ENV{'user.home'};
 1047:     }
 1048:     return 
 1049:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
 1050: }
 1051: 
 1052: sub finishuserfileupload {
 1053:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
 1054:     my $path=$docudom.'/'.$docuname.'/';
 1055:     my $filepath=$perlvar{'lonDocRoot'};
 1056:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1057:     my $count;
 1058:     for ($count=4;$count<=$#parts;$count++) {
 1059:         $filepath.="/$parts[$count]";
 1060:         if ((-e $filepath)!=1) {
 1061: 	    mkdir($filepath,0777);
 1062:         }
 1063:     }
 1064: # Save the file
 1065:     {
 1066:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
 1067:        print $fh $ENV{'form.'.$formname};
 1068:     }
 1069: # Notify homeserver to grep it
 1070: #
 1071:     
 1072:     my $fetchresult= 
 1073:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
 1074:     if ($fetchresult eq 'ok') {
 1075: #
 1076: # Return the URL to it
 1077:         return '/uploaded/'.$path.$fname;
 1078:     } else {
 1079:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
 1080:          ' to host '.$docuhome.': '.$fetchresult);
 1081:         return '/adm/notfound.html';
 1082:     }    
 1083: }
 1084: 
 1085: # ------------------------------------------------------------------------- Log
 1086: 
 1087: sub log {
 1088:     my ($dom,$nam,$hom,$what)=@_;
 1089:     return critical("log:$dom:$nam:$what",$hom);
 1090: }
 1091: 
 1092: # ------------------------------------------------------------------ Course Log
 1093: #
 1094: # This routine flushes several buffers of non-mission-critical nature
 1095: #
 1096: 
 1097: sub flushcourselogs {
 1098:     &logthis('Flushing log buffers');
 1099: #
 1100: # course logs
 1101: # This is a log of all transactions in a course, which can be used
 1102: # for data mining purposes
 1103: #
 1104: # It also collects the courseid database, which lists last transaction
 1105: # times and course titles for all courseids
 1106: #
 1107:     my %courseidbuffer=();
 1108:     foreach (keys %courselogs) {
 1109:         my $crsid=$_;
 1110:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1111: 		          &escape($courselogs{$crsid}),
 1112: 		          $coursehombuf{$crsid}) eq 'ok') {
 1113: 	    delete $courselogs{$crsid};
 1114:         } else {
 1115:             &logthis('Failed to flush log buffer for '.$crsid);
 1116:             if (length($courselogs{$crsid})>40000) {
 1117:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
 1118:                         " exceeded maximum size, deleting.</font>");
 1119:                delete $courselogs{$crsid};
 1120:             }
 1121:         }
 1122:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1123:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1124: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1125:         } else {
 1126:            $courseidbuffer{$coursehombuf{$crsid}}=
 1127: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1128:         }    
 1129:     }
 1130: #
 1131: # Write course id database (reverse lookup) to homeserver of courses 
 1132: # Is used in pickcourse
 1133: #
 1134:     foreach (keys %courseidbuffer) {
 1135:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1136:     }
 1137: #
 1138: # File accesses
 1139: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1140: #
 1141:     foreach (keys %accesshash) {
 1142:         my $entry=$_;
 1143:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
 1144:         my %temphash=($entry => $accesshash{$entry});
 1145:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
 1146: 	    delete $accesshash{$entry};
 1147:         }
 1148:     }
 1149: #
 1150: # Roles
 1151: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1152: #
 1153:     foreach (keys %userrolehash) {
 1154:         my $entry=$_;
 1155:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1156: 	    split(/\:/,$entry);
 1157:         if (&Apache::lonnet::put('nohist_userroles',
 1158:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1159:                 $rudom,$runame) eq 'ok') {
 1160: 	    delete $userrolehash{$entry};
 1161:         }
 1162:     }
 1163:     $dumpcount++;
 1164: }
 1165: 
 1166: sub courselog {
 1167:     my $what=shift;
 1168:     $what=time.':'.$what;
 1169:     unless ($ENV{'request.course.id'}) { return ''; }
 1170:     $coursedombuf{$ENV{'request.course.id'}}=
 1171:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1172:     $coursenumbuf{$ENV{'request.course.id'}}=
 1173:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1174:     $coursehombuf{$ENV{'request.course.id'}}=
 1175:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1176:     $coursedescrbuf{$ENV{'request.course.id'}}=
 1177:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1178:     if (defined $courselogs{$ENV{'request.course.id'}}) {
 1179: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
 1180:     } else {
 1181: 	$courselogs{$ENV{'request.course.id'}}.=$what;
 1182:     }
 1183:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
 1184: 	&flushcourselogs();
 1185:     }
 1186: }
 1187: 
 1188: sub courseacclog {
 1189:     my $fnsymb=shift;
 1190:     unless ($ENV{'request.course.id'}) { return ''; }
 1191:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
 1192:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
 1193:         $what.=':POST';
 1194: 	foreach (keys %ENV) {
 1195:             if ($_=~/^form\.(.*)/) {
 1196: 		$what.=':'.$1.'='.$ENV{$_};
 1197:             }
 1198:         }
 1199:     }
 1200:     &courselog($what);
 1201: }
 1202: 
 1203: sub countacc {
 1204:     my $url=&declutter(shift);
 1205:     unless ($ENV{'request.course.id'}) { return ''; }
 1206:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
 1207:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1208:     if (defined($accesshash{$key})) {
 1209: 	$accesshash{$key}++;
 1210:     } else {
 1211:         $accesshash{$key}=1;
 1212:     }
 1213: }
 1214: 
 1215: sub linklog {
 1216:     my ($from,$to)=@_;
 1217:     $from=&declutter($from);
 1218:     $to=&declutter($to);
 1219:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1220:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1221: }
 1222:   
 1223: sub userrolelog {
 1224:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1225:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
 1226:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
 1227:         ($trole=~/^cr/)) {
 1228:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1229:        $userrolehash
 1230:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1231:                     =$tend.':'.$tstart;
 1232:    }
 1233: }
 1234: 
 1235: sub get_course_adv_roles {
 1236:     my $cid=shift;
 1237:     $cid=$ENV{'request.course.id'} unless (defined($cid));
 1238:     my %coursehash=&coursedescription($cid);
 1239:     my %returnhash=();
 1240:     my %dumphash=
 1241:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1242:     my $now=time;
 1243:     foreach (keys %dumphash) {
 1244: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1245:         if (($tstart) && ($tstart<0)) { next; }
 1246:         if (($tend) && ($tend<$now)) { next; }
 1247:         if (($tstart) && ($now<$tstart)) { next; }
 1248:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1249:         my $key=&plaintext($role);
 1250:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1251:         if ($returnhash{$key}) {
 1252: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1253:         } else {
 1254:             $returnhash{$key}=$username.':'.$domain;
 1255:         }
 1256:     }
 1257:     return sort %returnhash;
 1258: }
 1259: 
 1260: # ---------------------------------------------------------- Course ID routines
 1261: # Deal with domain's nohist_courseid.db files
 1262: #
 1263: 
 1264: sub courseidput {
 1265:     my ($domain,$what,$coursehome)=@_;
 1266:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1267: }
 1268: 
 1269: sub courseiddump {
 1270:     my ($domfilter,$descfilter,$sincefilter)=@_;
 1271:     my %returnhash=();
 1272:     unless ($domfilter) { $domfilter=''; }
 1273:     foreach my $tryserver (keys %libserv) {
 1274: 	if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1275: 	    foreach (
 1276:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1277: 			       $sincefilter.':'.&escape($descfilter),
 1278:                                $tryserver))) {
 1279: 		my ($key,$value)=split(/\=/,$_);
 1280:                 if (($key) && ($value)) {
 1281: 		    $returnhash{&unescape($key)}=&unescape($value);
 1282:                 }
 1283:             }
 1284: 
 1285:         }
 1286:     }
 1287:     return %returnhash;
 1288: }
 1289: 
 1290: #
 1291: # ----------------------------------------------------------- Check out an item
 1292: 
 1293: sub checkout {
 1294:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 1295:     my $now=time;
 1296:     my $lonhost=$perlvar{'lonHostID'};
 1297:     my $infostr=&escape(
 1298:                  'CHECKOUTTOKEN&'.
 1299:                  $tuname.'&'.
 1300:                  $tudom.'&'.
 1301:                  $tcrsid.'&'.
 1302:                  $symb.'&'.
 1303: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 1304:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 1305:     if ($token=~/^error\:/) { 
 1306:         &logthis("<font color=blue>WARNING: ".
 1307:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 1308:                  "</font>");
 1309:         return ''; 
 1310:     }
 1311: 
 1312:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 1313:     $token=~tr/a-z/A-Z/;
 1314: 
 1315:     my %infohash=('resource.0.outtoken' => $token,
 1316:                   'resource.0.checkouttime' => $now,
 1317:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 1318: 
 1319:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1320:        return '';
 1321:     } else {
 1322:         &logthis("<font color=blue>WARNING: ".
 1323:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 1324:                  "</font>");
 1325:     }    
 1326: 
 1327:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1328:                          &escape('Checkout '.$infostr.' - '.
 1329:                                                  $token)) ne 'ok') {
 1330: 	return '';
 1331:     } else {
 1332:         &logthis("<font color=blue>WARNING: ".
 1333:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 1334:                  "</font>");
 1335:     }
 1336:     return $token;
 1337: }
 1338: 
 1339: # ------------------------------------------------------------ Check in an item
 1340: 
 1341: sub checkin {
 1342:     my $token=shift;
 1343:     my $now=time;
 1344:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 1345:     $lonhost=~tr/A-Z/a-z/;
 1346:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
 1347:     $dtoken=~s/\W/\_/g;
 1348:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 1349:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 1350: 
 1351:     unless (($tuname) && ($tudom)) {
 1352:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 1353:         return '';
 1354:     }
 1355:     
 1356:     unless (&allowed('mgr',$tcrsid)) {
 1357:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 1358:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
 1359:         return '';
 1360:     }
 1361: 
 1362:     my %infohash=('resource.0.intoken' => $token,
 1363:                   'resource.0.checkintime' => $now,
 1364:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 1365: 
 1366:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1367:        return '';
 1368:     }    
 1369: 
 1370:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1371:                          &escape('Checkin - '.$token)) ne 'ok') {
 1372: 	return '';
 1373:     }
 1374: 
 1375:     return ($symb,$tuname,$tudom,$tcrsid);    
 1376: }
 1377: 
 1378: # --------------------------------------------- Set Expire Date for Spreadsheet
 1379: 
 1380: sub expirespread {
 1381:     my ($uname,$udom,$stype,$usymb)=@_;
 1382:     my $cid=$ENV{'request.course.id'}; 
 1383:     if ($cid) {
 1384:        my $now=time;
 1385:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1386:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1387:                             $ENV{'course.'.$cid.'.num'}.
 1388: 	        	    ':nohist_expirationdates:'.
 1389:                             &escape($key).'='.$now,
 1390:                             $ENV{'course.'.$cid.'.home'})
 1391:     }
 1392:     return 'ok';
 1393: }
 1394: 
 1395: # ----------------------------------------------------- Devalidate Spreadsheets
 1396: 
 1397: sub devalidate {
 1398:     my ($symb,$uname,$udom)=@_;
 1399:     my $cid=$ENV{'request.course.id'}; 
 1400:     if ($cid) {
 1401: # delete the stored spreadsheets for
 1402: # - the student level sheet of this user in course's homespace
 1403: # - the assessment level sheet for this resource 
 1404: #   for this user in user's homespace
 1405: 	my $key=$uname.':'.$udom.':';
 1406:         my $status=
 1407: 	    &del('nohist_calculatedsheets',
 1408: 		 [$key.'studentcalc'],
 1409: 		 $ENV{'course.'.$cid.'.domain'},
 1410: 		 $ENV{'course.'.$cid.'.num'})
 1411: 		.' '.
 1412: 	    &del('nohist_calculatedsheets_'.$cid,
 1413: 		 [$key.'assesscalc:'.$symb]);
 1414:         unless ($status eq 'ok ok') {
 1415:            &logthis('Could not devalidate spreadsheet '.
 1416:                     $uname.' at '.$udom.' for '.
 1417: 		    $symb.': '.$status);
 1418:         }
 1419:     }
 1420: }
 1421: 
 1422: sub get_scalar {
 1423:     my ($string,$end) = @_;
 1424:     my $value;
 1425:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 1426: 	$value = $1;
 1427:     } elsif ($$string =~ s/^([^&]*?)&//) {
 1428: 	$value = $1;
 1429:     }
 1430:     return &unescape($value);
 1431: }
 1432: 
 1433: sub array2str {
 1434:   my (@array) = @_;
 1435:   my $result=&arrayref2str(\@array);
 1436:   $result=~s/^__ARRAY_REF__//;
 1437:   $result=~s/__END_ARRAY_REF__$//;
 1438:   return $result;
 1439: }
 1440: 
 1441: sub arrayref2str {
 1442:   my ($arrayref) = @_;
 1443:   my $result='__ARRAY_REF__';
 1444:   foreach my $elem (@$arrayref) {
 1445:     if(ref($elem) eq 'ARRAY') {
 1446:       $result.=&arrayref2str($elem).'&';
 1447:     } elsif(ref($elem) eq 'HASH') {
 1448:       $result.=&hashref2str($elem).'&';
 1449:     } elsif(ref($elem)) {
 1450:       #print("Got a ref of ".(ref($elem))." skipping.");
 1451:     } else {
 1452:       $result.=&escape($elem).'&';
 1453:     }
 1454:   }
 1455:   $result=~s/\&$//;
 1456:   $result .= '__END_ARRAY_REF__';
 1457:   return $result;
 1458: }
 1459: 
 1460: sub hash2str {
 1461:   my (%hash) = @_;
 1462:   my $result=&hashref2str(\%hash);
 1463:   $result=~s/^__HASH_REF__//;
 1464:   $result=~s/__END_HASH_REF__$//;
 1465:   return $result;
 1466: }
 1467: 
 1468: sub hashref2str {
 1469:   my ($hashref)=@_;
 1470:   my $result='__HASH_REF__';
 1471:   foreach (keys(%$hashref)) {
 1472:     if (ref($_) eq 'ARRAY') {
 1473:       $result.=&arrayref2str($_).'=';
 1474:     } elsif (ref($_) eq 'HASH') {
 1475:       $result.=&hashref2str($_).'=';
 1476:     } elsif (ref($_)) {
 1477:       $result.='=';
 1478:       #print("Got a ref of ".(ref($_))." skipping.");
 1479:     } else {
 1480: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 1481:     }
 1482: 
 1483:     if(ref($hashref->{$_}) eq 'ARRAY') {
 1484:       $result.=&arrayref2str($hashref->{$_}).'&';
 1485:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 1486:       $result.=&hashref2str($hashref->{$_}).'&';
 1487:     } elsif(ref($hashref->{$_})) {
 1488:        $result.='&';
 1489:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 1490:     } else {
 1491:       $result.=&escape($hashref->{$_}).'&';
 1492:     }
 1493:   }
 1494:   $result=~s/\&$//;
 1495:   $result .= '__END_HASH_REF__';
 1496:   return $result;
 1497: }
 1498: 
 1499: sub str2hash {
 1500:     my ($string)=@_;
 1501:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 1502:     return %$hash;
 1503: }
 1504: 
 1505: sub str2hashref {
 1506:   my ($string) = @_;
 1507: 
 1508:   my %hash;
 1509: 
 1510:   if($string !~ /^__HASH_REF__/) {
 1511:       if (! ($string eq '' || !defined($string))) {
 1512: 	  $hash{'error'}='Not hash reference';
 1513:       }
 1514:       return (\%hash, $string);
 1515:   }
 1516: 
 1517:   $string =~ s/^__HASH_REF__//;
 1518: 
 1519:   while($string !~ /^__END_HASH_REF__/) {
 1520:       #key
 1521:       my $key='';
 1522:       if($string =~ /^__HASH_REF__/) {
 1523:           ($key, $string)=&str2hashref($string);
 1524:           if(defined($key->{'error'})) {
 1525:               $hash{'error'}='Bad data';
 1526:               return (\%hash, $string);
 1527:           }
 1528:       } elsif($string =~ /^__ARRAY_REF__/) {
 1529:           ($key, $string)=&str2arrayref($string);
 1530:           if($key->[0] eq 'Array reference error') {
 1531:               $hash{'error'}='Bad data';
 1532:               return (\%hash, $string);
 1533:           }
 1534:       } else {
 1535:           $string =~ s/^(.*?)=//;
 1536: 	  $key=&unescape($1);
 1537:       }
 1538:       $string =~ s/^=//;
 1539: 
 1540:       #value
 1541:       my $value='';
 1542:       if($string =~ /^__HASH_REF__/) {
 1543:           ($value, $string)=&str2hashref($string);
 1544:           if(defined($value->{'error'})) {
 1545:               $hash{'error'}='Bad data';
 1546:               return (\%hash, $string);
 1547:           }
 1548:       } elsif($string =~ /^__ARRAY_REF__/) {
 1549:           ($value, $string)=&str2arrayref($string);
 1550:           if($value->[0] eq 'Array reference error') {
 1551:               $hash{'error'}='Bad data';
 1552:               return (\%hash, $string);
 1553:           }
 1554:       } else {
 1555: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 1556:       }
 1557:       $string =~ s/^&//;
 1558: 
 1559:       $hash{$key}=$value;
 1560:   }
 1561: 
 1562:   $string =~ s/^__END_HASH_REF__//;
 1563: 
 1564:   return (\%hash, $string);
 1565: }
 1566: 
 1567: sub str2array {
 1568:     my ($string)=@_;
 1569:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 1570:     return @$array;
 1571: }
 1572: 
 1573: sub str2arrayref {
 1574:   my ($string) = @_;
 1575:   my @array;
 1576: 
 1577:   if($string !~ /^__ARRAY_REF__/) {
 1578:       if (! ($string eq '' || !defined($string))) {
 1579: 	  $array[0]='Array reference error';
 1580:       }
 1581:       return (\@array, $string);
 1582:   }
 1583: 
 1584:   $string =~ s/^__ARRAY_REF__//;
 1585: 
 1586:   while($string !~ /^__END_ARRAY_REF__/) {
 1587:       my $value='';
 1588:       if($string =~ /^__HASH_REF__/) {
 1589:           ($value, $string)=&str2hashref($string);
 1590:           if(defined($value->{'error'})) {
 1591:               $array[0] ='Array reference error';
 1592:               return (\@array, $string);
 1593:           }
 1594:       } elsif($string =~ /^__ARRAY_REF__/) {
 1595:           ($value, $string)=&str2arrayref($string);
 1596:           if($value->[0] eq 'Array reference error') {
 1597:               $array[0] ='Array reference error';
 1598:               return (\@array, $string);
 1599:           }
 1600:       } else {
 1601: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 1602:       }
 1603:       $string =~ s/^&//;
 1604: 
 1605:       push(@array, $value);
 1606:   }
 1607: 
 1608:   $string =~ s/^__END_ARRAY_REF__//;
 1609: 
 1610:   return (\@array, $string);
 1611: }
 1612: 
 1613: # -------------------------------------------------------------------Temp Store
 1614: 
 1615: sub tmpreset {
 1616:   my ($symb,$namespace,$domain,$stuname) = @_;
 1617:   if (!$symb) {
 1618:     $symb=&symbread();
 1619:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
 1620:   }
 1621:   $symb=escape($symb);
 1622: 
 1623:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1624:   $namespace=~s/\//\_/g;
 1625:   $namespace=~s/\W//g;
 1626: 
 1627:   #FIXME needs to do something for /pub resources
 1628:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1629:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1630:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1631:   my %hash;
 1632:   if (tie(%hash,'GDBM_File',
 1633: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1634: 	  &GDBM_WRCREAT(),0640)) {
 1635:     foreach my $key (keys %hash) {
 1636:       if ($key=~ /:$symb/) {
 1637: 	delete($hash{$key});
 1638:       }
 1639:     }
 1640:   }
 1641: }
 1642: 
 1643: sub tmpstore {
 1644:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1645: 
 1646:   if (!$symb) {
 1647:     $symb=&symbread();
 1648:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1649:   }
 1650:   $symb=escape($symb);
 1651: 
 1652:   if (!$namespace) {
 1653:     # I don't think we would ever want to store this for a course.
 1654:     # it seems this will only be used if we don't have a course.
 1655:     #$namespace=$ENV{'request.course.id'};
 1656:     #if (!$namespace) {
 1657:       $namespace=$ENV{'request.state'};
 1658:     #}
 1659:   }
 1660:   $namespace=~s/\//\_/g;
 1661:   $namespace=~s/\W//g;
 1662: #FIXME needs to do something for /pub resources
 1663:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1664:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1665:   my $now=time;
 1666:   my %hash;
 1667:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1668:   if (tie(%hash,'GDBM_File',
 1669: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1670: 	  &GDBM_WRCREAT(),0640)) {
 1671:     $hash{"version:$symb"}++;
 1672:     my $version=$hash{"version:$symb"};
 1673:     my $allkeys=''; 
 1674:     foreach my $key (keys(%$storehash)) {
 1675:       $allkeys.=$key.':';
 1676:       $hash{"$version:$symb:$key"}=$$storehash{$key};
 1677:     }
 1678:     $hash{"$version:$symb:timestamp"}=$now;
 1679:     $allkeys.='timestamp';
 1680:     $hash{"$version:keys:$symb"}=$allkeys;
 1681:     if (untie(%hash)) {
 1682:       return 'ok';
 1683:     } else {
 1684:       return "error:$!";
 1685:     }
 1686:   } else {
 1687:     return "error:$!";
 1688:   }
 1689: }
 1690: 
 1691: # -----------------------------------------------------------------Temp Restore
 1692: 
 1693: sub tmprestore {
 1694:   my ($symb,$namespace,$domain,$stuname) = @_;
 1695: 
 1696:   if (!$symb) {
 1697:     $symb=&symbread();
 1698:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1699:   }
 1700:   $symb=escape($symb);
 1701: 
 1702:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1703:   #FIXME needs to do something for /pub resources
 1704:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1705:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1706: 
 1707:   my %returnhash;
 1708:   $namespace=~s/\//\_/g;
 1709:   $namespace=~s/\W//g;
 1710:   my %hash;
 1711:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1712:   if (tie(%hash,'GDBM_File',
 1713: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1714: 	  &GDBM_READER(),0640)) {
 1715:     my $version=$hash{"version:$symb"};
 1716:     $returnhash{'version'}=$version;
 1717:     my $scope;
 1718:     for ($scope=1;$scope<=$version;$scope++) {
 1719:       my $vkeys=$hash{"$scope:keys:$symb"};
 1720:       my @keys=split(/:/,$vkeys);
 1721:       my $key;
 1722:       $returnhash{"$scope:keys"}=$vkeys;
 1723:       foreach $key (@keys) {
 1724: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
 1725: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
 1726:       }
 1727:     }
 1728:     if (!(untie(%hash))) {
 1729:       return "error:$!";
 1730:     }
 1731:   } else {
 1732:     return "error:$!";
 1733:   }
 1734:   return %returnhash;
 1735: }
 1736: 
 1737: # ----------------------------------------------------------------------- Store
 1738: 
 1739: sub store {
 1740:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1741:     my $home='';
 1742: 
 1743:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1744: 
 1745:     $symb=&symbclean($symb);
 1746:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1747: 
 1748:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1749:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1750: 
 1751:     &devalidate($symb,$stuname,$domain);
 1752: 
 1753:     $symb=escape($symb);
 1754:     if (!$namespace) { 
 1755:        unless ($namespace=$ENV{'request.course.id'}) { 
 1756:           return ''; 
 1757:        } 
 1758:     }
 1759:     if (!$home) { $home=$ENV{'user.home'}; }
 1760:     my $namevalue='';
 1761:     foreach (keys %$storehash) {
 1762:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1763:     }
 1764:     $namevalue=~s/\&$//;
 1765:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 1766:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1767: }
 1768: 
 1769: # -------------------------------------------------------------- Critical Store
 1770: 
 1771: sub cstore {
 1772:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1773:     my $home='';
 1774: 
 1775:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1776: 
 1777:     $symb=&symbclean($symb);
 1778:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1779: 
 1780:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1781:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1782: 
 1783:     &devalidate($symb,$stuname,$domain);
 1784: 
 1785:     $symb=escape($symb);
 1786:     if (!$namespace) { 
 1787:        unless ($namespace=$ENV{'request.course.id'}) { 
 1788:           return ''; 
 1789:        } 
 1790:     }
 1791:     if (!$home) { $home=$ENV{'user.home'}; }
 1792: 
 1793:     my $namevalue='';
 1794:     foreach (keys %$storehash) {
 1795:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1796:     }
 1797:     $namevalue=~s/\&$//;
 1798:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 1799:     return critical
 1800:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1801: }
 1802: 
 1803: # --------------------------------------------------------------------- Restore
 1804: 
 1805: sub restore {
 1806:     my ($symb,$namespace,$domain,$stuname) = @_;
 1807:     my $home='';
 1808: 
 1809:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1810: 
 1811:     if (!$symb) {
 1812:       unless ($symb=escape(&symbread())) { return ''; }
 1813:     } else {
 1814:       $symb=&escape(&symbclean($symb));
 1815:     }
 1816:     if (!$namespace) { 
 1817:        unless ($namespace=$ENV{'request.course.id'}) { 
 1818:           return ''; 
 1819:        } 
 1820:     }
 1821:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1822:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1823:     if (!$home) { $home=$ENV{'user.home'}; }
 1824:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 1825: 
 1826:     my %returnhash=();
 1827:     foreach (split(/\&/,$answer)) {
 1828: 	my ($name,$value)=split(/\=/,$_);
 1829:         $returnhash{&unescape($name)}=&unescape($value);
 1830:     }
 1831:     my $version;
 1832:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1833:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 1834:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1835:        }
 1836:     }
 1837:     return %returnhash;
 1838: }
 1839: 
 1840: # ---------------------------------------------------------- Course Description
 1841: 
 1842: sub coursedescription {
 1843:     my $courseid=shift;
 1844:     $courseid=~s/^\///;
 1845:     $courseid=~s/\_/\//g;
 1846:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1847:     my $chome=&homeserver($cnum,$cdomain);
 1848:     my $normalid=$cdomain.'_'.$cnum;
 1849:     # need to always cache even if we get errors otherwise we keep 
 1850:     # trying and trying and trying to get the course description.
 1851:     my %envhash=();
 1852:     my %returnhash=();
 1853:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 1854:     if ($chome ne 'no_host') {
 1855:        %returnhash=&dump('environment',$cdomain,$cnum);
 1856:        if (!exists($returnhash{'con_lost'})) {
 1857:            $returnhash{'home'}= $chome;
 1858: 	   $returnhash{'domain'} = $cdomain;
 1859: 	   $returnhash{'num'} = $cnum;
 1860:            while (my ($name,$value) = each %returnhash) {
 1861:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 1862:            }
 1863:            $returnhash{'url'}=&clutter($returnhash{'url'});
 1864:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 1865: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 1866:            $envhash{'course.'.$normalid.'.home'}=$chome;
 1867:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 1868:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 1869:        }
 1870:     }
 1871:     &appenv(%envhash);
 1872:     return %returnhash;
 1873: }
 1874: 
 1875: # -------------------------------------------------------- Get user privileges
 1876: 
 1877: sub rolesinit {
 1878:     my ($domain,$username,$authhost)=@_;
 1879:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 1880:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 1881:     my %allroles=();
 1882:     my %thesepriv=();
 1883:     my $now=time;
 1884:     my $userroles="user.login.time=$now\n";
 1885:     my $thesestr;
 1886: 
 1887:     if ($rolesdump ne '') {
 1888:         foreach (split(/&/,$rolesdump)) {
 1889: 	  if ($_!~/^rolesdef\&/) {
 1890:             my ($area,$role)=split(/=/,$_);
 1891:             $area=~s/\_\w\w$//;
 1892:             my ($trole,$tend,$tstart)=split(/_/,$role);
 1893:             $userroles.='user.role.'.$trole.'.'.$area.'='.
 1894:                         $tstart.'.'.$tend."\n";
 1895: # log the associated role with the area
 1896:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 1897:             if ($tend!=0) {
 1898: 	        if ($tend<$now) {
 1899: 	            $trole='';
 1900:                 } 
 1901:             }
 1902:             if ($tstart!=0) {
 1903:                 if ($tstart>$now) {
 1904:                    $trole='';        
 1905:                 }
 1906:             }
 1907:             if (($area ne '') && ($trole ne '')) {
 1908: 		my $spec=$trole.'.'.$area;
 1909: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 1910: 		if ($trole =~ /^cr\//) {
 1911: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 1912: 		    my $homsvr=homeserver($rauthor,$rdomain);
 1913: 		    if ($hostname{$homsvr} ne '') {
 1914: 			my $roledef=
 1915: 			    reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
 1916: 				  $homsvr);
 1917: 			if (($roledef ne 'con_lost') && ($roledef ne '')) {
 1918: 			    my ($syspriv,$dompriv,$coursepriv)=
 1919: 				split(/\_/,unescape($roledef));
 1920: 			    if (defined($syspriv)) {
 1921: 				$allroles{'cm./'}.=':'.$syspriv;
 1922: 				$allroles{$spec.'./'}.=':'.$syspriv;
 1923: 			    }
 1924: 			    if ($tdomain ne '') {
 1925: 				if (defined($dompriv)) {
 1926: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 1927: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 1928: 				}
 1929: 				if ($trest ne '') {
 1930: 				    if (defined($coursepriv)) {
 1931: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
 1932: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 1933: 				    }
 1934: 				}
 1935: 			    }
 1936: 			}
 1937: 		    }
 1938: 		} else {
 1939: 		    if (defined($pr{$trole.':s'})) {
 1940: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 1941: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 1942: 		    }
 1943: 		    if ($tdomain ne '') {
 1944: 			if (defined($pr{$trole.':d'})) {
 1945: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1946: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1947: 			}
 1948: 			if ($trest ne '') {
 1949: 			    if (defined($pr{$trole.':c'})) {
 1950: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 1951: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 1952: 			    }
 1953: 			}
 1954: 		    }
 1955: 		}
 1956:             }
 1957:           } 
 1958:         }
 1959:         my $adv=0;
 1960:         my $author=0;
 1961:         foreach (keys %allroles) {
 1962:             %thesepriv=();
 1963:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
 1964:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 1965:             foreach (split(/:/,$allroles{$_})) {
 1966:                 if ($_ ne '') {
 1967: 		    my ($privilege,$restrictions)=split(/&/,$_);
 1968:                     if ($restrictions eq '') {
 1969: 			$thesepriv{$privilege}='F';
 1970:                     } else {
 1971:                         if ($thesepriv{$privilege} ne 'F') {
 1972: 			    $thesepriv{$privilege}.=$restrictions;
 1973:                         }
 1974:                     }
 1975:                 }
 1976:             }
 1977:             $thesestr='';
 1978:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 1979:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
 1980:         }
 1981:         $userroles.='user.adv='.$adv."\n".
 1982: 	            'user.author='.$author."\n";
 1983:         $ENV{'user.adv'}=$adv;
 1984:     }
 1985:     return $userroles;  
 1986: }
 1987: 
 1988: # --------------------------------------------------------------- get interface
 1989: 
 1990: sub get {
 1991:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1992:    my $items='';
 1993:    foreach (@$storearr) {
 1994:        $items.=escape($_).'&';
 1995:    }
 1996:    $items=~s/\&$//;
 1997:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1998:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1999:    my $uhome=&homeserver($uname,$udomain);
 2000: 
 2001:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2002:    my @pairs=split(/\&/,$rep);
 2003:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2004:      return @pairs;
 2005:    }
 2006:    my %returnhash=();
 2007:    my $i=0;
 2008:    foreach (@$storearr) {
 2009:       $returnhash{$_}=unescape($pairs[$i]);
 2010:       $i++;
 2011:    }
 2012:    return %returnhash;
 2013: }
 2014: 
 2015: # --------------------------------------------------------------- del interface
 2016: 
 2017: sub del {
 2018:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2019:    my $items='';
 2020:    foreach (@$storearr) {
 2021:        $items.=escape($_).'&';
 2022:    }
 2023:    $items=~s/\&$//;
 2024:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2025:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2026:    my $uhome=&homeserver($uname,$udomain);
 2027: 
 2028:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2029: }
 2030: 
 2031: # -------------------------------------------------------------- dump interface
 2032: 
 2033: sub dump {
 2034:    my ($namespace,$udomain,$uname,$regexp)=@_;
 2035:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2036:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2037:    my $uhome=&homeserver($uname,$udomain);
 2038:    if ($regexp) {
 2039:        $regexp=&escape($regexp);
 2040:    } else {
 2041:        $regexp='.';
 2042:    }
 2043:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 2044:    my @pairs=split(/\&/,$rep);
 2045:    my %returnhash=();
 2046:    foreach (@pairs) {
 2047:       my ($key,$value)=split(/=/,$_);
 2048:       $returnhash{unescape($key)}=unescape($value);
 2049:    }
 2050:    return %returnhash;
 2051: }
 2052: 
 2053: # --------------------------------------------------------------- currentdump
 2054: sub currentdump {
 2055:    my ($courseid,$sdom,$sname)=@_;
 2056:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2057:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
 2058:    $sname    = $ENV{'user.name'}         if (! defined($sname));
 2059:    my $uhome = &homeserver($sname,$sdom);
 2060:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2061:    return if ($rep =~ /^(error:|no_such_host)/);
 2062:    #
 2063:    my %returnhash=();
 2064:    #
 2065:    if ($rep eq "unknown_cmd") { 
 2066:        # an old lond will not know currentdump
 2067:        # Do a dump and make it look like a currentdump
 2068:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2069:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2070:        my %hash = @tmp;
 2071:        @tmp=();
 2072:        # Code ripped from lond, essentially.  The only difference
 2073:        # here is the unescaping done by lonnet::dump().  Conceivably
 2074:        # we might run in to problems with parameter names =~ /^v\./
 2075:        while (my ($key,$value) = each(%hash)) {
 2076:            my ($v,$symb,$param) = split(/:/,$key);
 2077:            next if ($v eq 'version' || $symb eq 'keys');
 2078:            next if (exists($returnhash{$symb}) &&
 2079:                     exists($returnhash{$symb}->{$param}) &&
 2080:                     $returnhash{$symb}->{'v.'.$param} > $v);
 2081:            $returnhash{$symb}->{$param}=$value;
 2082:            $returnhash{$symb}->{'v.'.$param}=$v;
 2083:        }
 2084:        #
 2085:        # Remove all of the keys in the hashes which keep track of
 2086:        # the version of the parameter.
 2087:        while (my ($symb,$param_hash) = each(%returnhash)) {
 2088:            # use a foreach because we are going to delete from the hash.
 2089:            foreach my $key (keys(%$param_hash)) {
 2090:                delete($param_hash->{$key}) if ($key =~ /^v\./);
 2091:            }
 2092:        }
 2093:    } else {
 2094:        my @pairs=split(/\&/,$rep);
 2095:        foreach (@pairs) {
 2096:            my ($key,$value)=split(/=/,$_);
 2097:            my ($symb,$param) = split(/:/,$key);
 2098:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2099:                                                           &unescape($value);
 2100:        }
 2101:    }
 2102:    return %returnhash;
 2103: }
 2104: 
 2105: # --------------------------------------------------------------- put interface
 2106: 
 2107: sub put {
 2108:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2109:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2110:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2111:    my $uhome=&homeserver($uname,$udomain);
 2112:    my $items='';
 2113:    foreach (keys %$storehash) {
 2114:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 2115:    }
 2116:    $items=~s/\&$//;
 2117:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2118: }
 2119: 
 2120: # ------------------------------------------------------ critical put interface
 2121: 
 2122: sub cput {
 2123:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2124:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2125:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2126:    my $uhome=&homeserver($uname,$udomain);
 2127:    my $items='';
 2128:    foreach (keys %$storehash) {
 2129:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 2130:    }
 2131:    $items=~s/\&$//;
 2132:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 2133: }
 2134: 
 2135: # -------------------------------------------------------------- eget interface
 2136: 
 2137: sub eget {
 2138:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2139:    my $items='';
 2140:    foreach (@$storearr) {
 2141:        $items.=escape($_).'&';
 2142:    }
 2143:    $items=~s/\&$//;
 2144:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2145:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2146:    my $uhome=&homeserver($uname,$udomain);
 2147:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 2148:    my @pairs=split(/\&/,$rep);
 2149:    my %returnhash=();
 2150:    my $i=0;
 2151:    foreach (@$storearr) {
 2152:       $returnhash{$_}=unescape($pairs[$i]);
 2153:       $i++;
 2154:    }
 2155:    return %returnhash;
 2156: }
 2157: 
 2158: # ---------------------------------------------- Custom access rule evaluation
 2159: 
 2160: sub customaccess {
 2161:     my ($priv,$uri)=@_;
 2162:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
 2163:     $urealm=~s/^\W//;
 2164:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 2165:     my $access=0;
 2166:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 2167: 	my ($effect,$realm,$role)=split(/\:/,$_);
 2168:         if ($role) {
 2169: 	   if ($role ne $urole) { next; }
 2170:         }
 2171:         foreach (split(/\s*\,\s*/,$realm)) {
 2172:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 2173:             if ($tdom) {
 2174: 		if ($tdom ne $udom) { next; }
 2175:             }
 2176:             if ($tcrs) {
 2177: 		if ($tcrs ne $ucrs) { next; }
 2178:             }
 2179:             if ($tsec) {
 2180: 		if ($tsec ne $usec) { next; }
 2181:             }
 2182:             $access=($effect eq 'allow');
 2183:             last;
 2184:         }
 2185:     }
 2186:     return $access;
 2187: }
 2188: 
 2189: # ------------------------------------------------- Check for a user privilege
 2190: 
 2191: sub allowed {
 2192:     my ($priv,$uri)=@_;
 2193: 
 2194:     my $orguri=$uri;
 2195:     $uri=&declutter($uri);
 2196: 
 2197: # Free bre access to adm and meta resources
 2198: 
 2199:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 2200: 	return 'F';
 2201:     }
 2202: 
 2203: # Free bre to public access
 2204: 
 2205:     if ($priv eq 'bre') {
 2206:         my $copyright=&metadata($uri,'copyright');
 2207: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
 2208:            return 'F'; 
 2209:         }
 2210:         if ($copyright eq 'priv') {
 2211:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2212: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
 2213: 		return '';
 2214:             }
 2215:         }
 2216:         if ($copyright eq 'domain') {
 2217:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2218: 	    unless (($ENV{'user.domain'} eq $1) ||
 2219:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
 2220: 		return '';
 2221:             }
 2222:         }
 2223:         if ($ENV{'request.role'}=~ /li\.\//) {
 2224:             # Library role, so allow browsing of resources in this domain.
 2225:             return 'F';
 2226:         }
 2227:         if ($copyright eq 'custom') {
 2228: 	    unless (&customaccess($priv,$uri)) { return ''; }
 2229:         }
 2230:     }
 2231:     # Domain coordinator is trying to create a course
 2232:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
 2233:         # uri is the requested domain in this case.
 2234:         # comparison to 'request.role.domain' shows if the user has selected
 2235:         # a role of dc for the domain in question. 
 2236:         return 'F' if ($uri eq $ENV{'request.role.domain'});
 2237:     }
 2238: 
 2239:     my $thisallowed='';
 2240:     my $statecond=0;
 2241:     my $courseprivid='';
 2242: 
 2243: # Course
 2244: 
 2245:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 2246:        $thisallowed.=$1;
 2247:     }
 2248: 
 2249: # Domain
 2250: 
 2251:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 2252:        =~/$priv\&([^\:]*)/) {
 2253:        $thisallowed.=$1;
 2254:     }
 2255: 
 2256: # Course: uri itself is a course
 2257:     my $courseuri=$uri;
 2258:     $courseuri=~s/\_(\d)/\/$1/;
 2259:     $courseuri=~s/^([^\/])/\/$1/;
 2260: 
 2261:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 2262:        =~/$priv\&([^\:]*)/) {
 2263:        $thisallowed.=$1;
 2264:     }
 2265: 
 2266: # URI is an uploaded document for this course
 2267: 
 2268:     if (($priv eq 'bre') && 
 2269:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
 2270:         return 'F';
 2271:     }
 2272: # Full access at system, domain or course-wide level? Exit.
 2273: 
 2274:     if ($thisallowed=~/F/) {
 2275: 	return 'F';
 2276:     }
 2277: 
 2278: # If this is generating or modifying users, exit with special codes
 2279: 
 2280:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 2281: 	return $thisallowed;
 2282:     }
 2283: #
 2284: # Gathered so far: system, domain and course wide privileges
 2285: #
 2286: # Course: See if uri or referer is an individual resource that is part of 
 2287: # the course
 2288: 
 2289:     if ($ENV{'request.course.id'}) {
 2290: 
 2291:        $courseprivid=$ENV{'request.course.id'};
 2292:        if ($ENV{'request.course.sec'}) {
 2293:           $courseprivid.='/'.$ENV{'request.course.sec'};
 2294:        }
 2295:        $courseprivid=~s/\_/\//;
 2296:        my $checkreferer=1;
 2297:        my ($match,$cond)=&is_on_map($uri);
 2298:        if ($match) {
 2299:            $statecond=$cond;
 2300:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2301:                =~/$priv\&([^\:]*)/) {
 2302:                $thisallowed.=$1;
 2303:                $checkreferer=0;
 2304:            }
 2305:        }
 2306:        
 2307:        if ($checkreferer) {
 2308: 	  my $refuri=$ENV{'httpref.'.$orguri};
 2309:             unless ($refuri) {
 2310:                 foreach (keys %ENV) {
 2311: 		    if ($_=~/^httpref\..*\*/) {
 2312: 			my $pattern=$_;
 2313:                         $pattern=~s/^httpref\.\/res\///;
 2314:                         $pattern=~s/\*/\[\^\/\]\+/g;
 2315:                         $pattern=~s/\//\\\//g;
 2316:                         if ($orguri=~/$pattern/) {
 2317: 			    $refuri=$ENV{$_};
 2318:                         }
 2319:                     }
 2320:                 }
 2321:             }
 2322: 
 2323:          if ($refuri) { 
 2324: 	  $refuri=&declutter($refuri);
 2325:           my ($match,$cond)=&is_on_map($refuri);
 2326:             if ($match) {
 2327:               my $refstatecond=$cond;
 2328:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2329:                   =~/$priv\&([^\:]*)/) {
 2330:                   $thisallowed.=$1;
 2331:                   $uri=$refuri;
 2332:                   $statecond=$refstatecond;
 2333:               }
 2334:           }
 2335:         }
 2336:        }
 2337:    }
 2338: 
 2339: #
 2340: # Gathered now: all privileges that could apply, and condition number
 2341: # 
 2342: #
 2343: # Full or no access?
 2344: #
 2345: 
 2346:     if ($thisallowed=~/F/) {
 2347: 	return 'F';
 2348:     }
 2349: 
 2350:     unless ($thisallowed) {
 2351:         return '';
 2352:     }
 2353: 
 2354: # Restrictions exist, deal with them
 2355: #
 2356: #   C:according to course preferences
 2357: #   R:according to resource settings
 2358: #   L:unless locked
 2359: #   X:according to user session state
 2360: #
 2361: 
 2362: # Possibly locked functionality, check all courses
 2363: # Locks might take effect only after 10 minutes cache expiration for other
 2364: # courses, and 2 minutes for current course
 2365: 
 2366:     my $envkey;
 2367:     if ($thisallowed=~/L/) {
 2368:         foreach $envkey (keys %ENV) {
 2369:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 2370:                my $courseid=$2;
 2371:                my $roleid=$1.'.'.$2;
 2372:                $courseid=~s/^\///;
 2373:                my $expiretime=600;
 2374:                if ($ENV{'request.role'} eq $roleid) {
 2375: 		  $expiretime=120;
 2376:                }
 2377: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 2378:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 2379:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 2380: 		   &coursedescription($courseid);
 2381:                }
 2382:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 2383:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 2384: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 2385:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2386:                             $ENV{'user.home'},
 2387:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 2388:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2389:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2390: 		       return '';
 2391:                    }
 2392:                }
 2393:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 2394:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 2395: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 2396:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2397:                             $ENV{'user.home'},
 2398:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 2399:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2400:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2401: 		       return '';
 2402:                    }
 2403:                }
 2404: 	   }
 2405:        }
 2406:     }
 2407:    
 2408: #
 2409: # Rest of the restrictions depend on selected course
 2410: #
 2411: 
 2412:     unless ($ENV{'request.course.id'}) {
 2413:        return '1';
 2414:     }
 2415: 
 2416: #
 2417: # Now user is definitely in a course
 2418: #
 2419: 
 2420: 
 2421: # Course preferences
 2422: 
 2423:    if ($thisallowed=~/C/) {
 2424:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2425:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
 2426:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 2427: 	   =~/$rolecode/) {
 2428:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2429:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 2430:                 $ENV{'request.course.id'});
 2431:            return '';
 2432:        }
 2433: 
 2434:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
 2435: 	   =~/$unamedom/) {
 2436:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2437:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 2438:                 $ENV{'request.course.id'});
 2439:            return '';
 2440:        }
 2441:    }
 2442: 
 2443: # Resource preferences
 2444: 
 2445:    if ($thisallowed=~/R/) {
 2446:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2447:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
 2448: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2449:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 2450:           return '';
 2451:        }
 2452:    }
 2453: 
 2454: # Restricted by state or randomout?
 2455: 
 2456:    if ($thisallowed=~/X/) {
 2457:       if ($ENV{'acc.randomout'}) {
 2458:          my $symb=&symbread($uri,1);
 2459:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
 2460:             return ''; 
 2461:          }
 2462:       }
 2463:       if (&condval($statecond)) {
 2464: 	 return '2';
 2465:       } else {
 2466:          return '';
 2467:       }
 2468:    }
 2469: 
 2470:    return 'F';
 2471: }
 2472: 
 2473: # --------------------------------------------------- Is a resource on the map?
 2474: 
 2475: sub is_on_map {
 2476:     my $uri=&declutter(shift);
 2477:     my @uriparts=split(/\//,$uri);
 2478:     my $filename=$uriparts[$#uriparts];
 2479:     my $pathname=$uri;
 2480:     $pathname=~s|/\Q$filename\E$||;
 2481:     $pathname=~s/^adm\/wrapper\///;    
 2482:     #Trying to find the conditional for the file
 2483:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 2484: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 2485:     if ($match) {
 2486: 	return (1,$1);
 2487:     } else {
 2488: 	return (0,0);
 2489:     }
 2490: }
 2491: 
 2492: # ----------------------------------------------------------------- Define Role
 2493: 
 2494: sub definerole {
 2495:   if (allowed('mcr','/')) {
 2496:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 2497:     foreach (split('/',$sysrole)) {
 2498: 	my ($crole,$cqual)=split(/\&/,$_);
 2499:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 2500:         if ($pr{'cr:s'}=~/$crole\&/) {
 2501: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 2502:                return "refused:s:$crole&$cqual"; 
 2503:             }
 2504:         }
 2505:     }
 2506:     foreach (split('/',$domrole)) {
 2507: 	my ($crole,$cqual)=split(/\&/,$_);
 2508:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 2509:         if ($pr{'cr:d'}=~/$crole\&/) {
 2510: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 2511:                return "refused:d:$crole&$cqual"; 
 2512:             }
 2513:         }
 2514:     }
 2515:     foreach (split('/',$courole)) {
 2516: 	my ($crole,$cqual)=split(/\&/,$_);
 2517:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 2518:         if ($pr{'cr:c'}=~/$crole\&/) {
 2519: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 2520:                return "refused:c:$crole&$cqual"; 
 2521:             }
 2522:         }
 2523:     }
 2524:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2525:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 2526: 	        "rolesdef_$rolename=".
 2527:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 2528:     return reply($command,$ENV{'user.home'});
 2529:   } else {
 2530:     return 'refused';
 2531:   }
 2532: }
 2533: 
 2534: # ---------------- Make a metadata query against the network of library servers
 2535: 
 2536: sub metadata_query {
 2537:     my ($query,$custom,$customshow,$server_array)=@_;
 2538:     my %rhash;
 2539:     my @server_list = (defined($server_array) ? @$server_array
 2540:                                               : keys(%libserv) );
 2541:     for my $server (@server_list) {
 2542: 	unless ($custom or $customshow) {
 2543: 	    my $reply=&reply("querysend:".&escape($query),$server);
 2544: 	    $rhash{$server}=$reply;
 2545: 	}
 2546: 	else {
 2547: 	    my $reply=&reply("querysend:".&escape($query).':'.
 2548: 			     &escape($custom).':'.&escape($customshow),
 2549: 			     $server);
 2550: 	    $rhash{$server}=$reply;
 2551: 	}
 2552:     }
 2553:     return \%rhash;
 2554: }
 2555: 
 2556: # ----------------------------------------- Send log queries and wait for reply
 2557: 
 2558: sub log_query {
 2559:     my ($uname,$udom,$query,%filters)=@_;
 2560:     my $uhome=&homeserver($uname,$udom);
 2561:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 2562:     my $uhost=$hostname{$uhome};
 2563:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 2564:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 2565:                        $uhome);
 2566:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
 2567:     return get_query_reply($queryid);
 2568: }
 2569: 
 2570: sub get_query_reply {
 2571:     my $queryid=shift;
 2572:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 2573:     my $reply='';
 2574:     for (1..100) {
 2575: 	sleep 2;
 2576:         if (-e $replyfile.'.end') {
 2577: 	    if (my $fh=Apache::File->new($replyfile)) {
 2578:                $reply.=<$fh>;
 2579:                $fh->close;
 2580: 	   } else { return 'error: reply_file_error'; }
 2581:            return &unescape($reply);
 2582: 	}
 2583:     }
 2584:     return 'timeout:'.$queryid;
 2585: }
 2586: 
 2587: sub courselog_query {
 2588: #
 2589: # possible filters:
 2590: # url: url or symb
 2591: # username
 2592: # domain
 2593: # action: view, submit, grade
 2594: # start: timestamp
 2595: # end: timestamp
 2596: #
 2597:     my (%filters)=@_;
 2598:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
 2599:     if ($filters{'url'}) {
 2600: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 2601:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 2602:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 2603:     }
 2604:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 2605:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 2606:     return &log_query($cname,$cdom,'courselog',%filters);
 2607: }
 2608: 
 2609: sub userlog_query {
 2610:     my ($uname,$udom,%filters)=@_;
 2611:     return &log_query($uname,$udom,'userlog',%filters);
 2612: }
 2613: 
 2614: # ------------------------------------------------------------------ Plain Text
 2615: 
 2616: sub plaintext {
 2617:     my $short=shift;
 2618:     return $prp{$short};
 2619: }
 2620: 
 2621: # ----------------------------------------------------------------- Assign Role
 2622: 
 2623: sub assignrole {
 2624:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 2625:     my $mrole;
 2626:     if ($role =~ /^cr\//) {
 2627: 	unless (&allowed('ccr',$url)) {
 2628:            &logthis('Refused custom assignrole: '.
 2629:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2630: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2631:            return 'refused'; 
 2632:         }
 2633:         $mrole='cr';
 2634:     } else {
 2635:         my $cwosec=$url;
 2636:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 2637:         unless (&allowed('c'.$role,$cwosec)) { 
 2638:            &logthis('Refused assignrole: '.
 2639:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2640: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2641:            return 'refused'; 
 2642:         }
 2643:         $mrole=$role;
 2644:     }
 2645:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2646:                 "$udom:$uname:$url".'_'."$mrole=$role";
 2647:     if ($end) { $command.='_'.$end; }
 2648:     if ($start) {
 2649: 	if ($end) { 
 2650:            $command.='_'.$start; 
 2651:         } else {
 2652:            $command.='_0_'.$start;
 2653:         }
 2654:     }
 2655: # actually delete
 2656:     if ($deleteflag) {
 2657: 	if (&allowed('dro',$udom)) {
 2658: # modify command to delete the role
 2659:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2660:                 "$udom:$uname:$url".'_'."$mrole";
 2661: # set start and finish to negative values for userrolelog
 2662:            $start=-1;
 2663:            $end=-1;
 2664:         }
 2665:     }
 2666: # send command
 2667:     my $answer=&reply($command,&homeserver($uname,$udom));
 2668: # log new user role if status is ok
 2669:     if ($answer eq 'ok') {
 2670: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
 2671:     }
 2672:     return $answer;
 2673: }
 2674: 
 2675: # -------------------------------------------------- Modify user authentication
 2676: # Overrides without validation
 2677: 
 2678: sub modifyuserauth {
 2679:     my ($udom,$uname,$umode,$upass)=@_;
 2680:     my $uhome=&homeserver($uname,$udom);
 2681:     unless (&allowed('mau',$udom)) { return 'refused'; }
 2682:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 2683:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2684:              ' in domain '.$ENV{'request.role.domain'});  
 2685:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 2686: 		     &escape($upass),$uhome);
 2687:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
 2688:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 2689:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2690:     &log($udom,,$uname,$uhome,
 2691:         'Authentication changed by '.$ENV{'user.domain'}.', '.
 2692:                                      $ENV{'user.name'}.', '.$umode.
 2693:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2694:     unless ($reply eq 'ok') {
 2695:         &logthis('Authentication mode error: '.$reply);
 2696: 	return 'error: '.$reply;
 2697:     }   
 2698:     return 'ok';
 2699: }
 2700: 
 2701: # --------------------------------------------------------------- Modify a user
 2702: 
 2703: sub modifyuser {
 2704:     my ($udom,    $uname, $uid,
 2705:         $umode,   $upass, $first,
 2706:         $middle,  $last,  $gene,
 2707:         $forceid, $desiredhome)=@_;
 2708:     $udom=~s/\W//g;
 2709:     $uname=~s/\W//g;
 2710:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 2711:              $umode.', '.$first.', '.$middle.', '.
 2712: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 2713:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 2714:                                      ' desiredhome not specified'). 
 2715:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2716:              ' in domain '.$ENV{'request.role.domain'});
 2717:     my $uhome=&homeserver($uname,$udom,'true');
 2718: # ----------------------------------------------------------------- Create User
 2719:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 2720:         my $unhome='';
 2721:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 2722:             $unhome = $desiredhome;
 2723: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 2724: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 2725:         } else { # load balancing routine for determining $unhome
 2726:             my $tryserver;
 2727:             my $loadm=10000000;
 2728:             foreach $tryserver (keys %libserv) {
 2729: 	       if ($hostdom{$tryserver} eq $udom) {
 2730:                   my $answer=reply('load',$tryserver);
 2731:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 2732: 		      $loadm=$answer;
 2733:                       $unhome=$tryserver;
 2734:                   }
 2735: 	       }
 2736: 	    }
 2737:         }
 2738:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 2739: 	    return 'error: unable to find a home server for '.$uname.
 2740:                    ' in domain '.$udom;
 2741:         }
 2742:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 2743:                          &escape($upass),$unhome);
 2744: 	unless ($reply eq 'ok') {
 2745:             return 'error: '.$reply;
 2746:         }   
 2747:         $uhome=&homeserver($uname,$udom,'true');
 2748:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 2749: 	    return 'error: verify home';
 2750:         }
 2751:     }   # End of creation of new user
 2752: # ---------------------------------------------------------------------- Add ID
 2753:     if ($uid) {
 2754:        $uid=~tr/A-Z/a-z/;
 2755:        my %uidhash=&idrget($udom,$uname);
 2756:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 2757:          && (!$forceid)) {
 2758: 	  unless ($uid eq $uidhash{$uname}) {
 2759: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 2760:           }
 2761:        } else {
 2762: 	  &idput($udom,($uname => $uid));
 2763:        }
 2764:     }
 2765: # -------------------------------------------------------------- Add names, etc
 2766:     my @tmp=&get('environment',
 2767: 		   ['firstname','middlename','lastname','generation'],
 2768: 		   $udom,$uname);
 2769:     my %names;
 2770:     if ($tmp[0] =~ m/^error:.*/) { 
 2771:         %names=(); 
 2772:     } else {
 2773:         %names = @tmp;
 2774:     }
 2775:     if ($first)  { $names{'firstname'}  = $first; }
 2776:     if ($middle) { $names{'middlename'} = $middle; }
 2777:     if ($last)   { $names{'lastname'}   = $last; }
 2778:     if ($gene)   { $names{'generation'} = $gene; }
 2779:     my $reply = &put('environment', \%names, $udom,$uname);
 2780:     if ($reply ne 'ok') { return 'error: '.$reply; }
 2781:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 2782:              $umode.', '.$first.', '.$middle.', '.
 2783: 	     $last.', '.$gene.' by '.
 2784:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2785:     return 'ok';
 2786: }
 2787: 
 2788: # -------------------------------------------------------------- Modify student
 2789: 
 2790: sub modifystudent {
 2791:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 2792:         $end,$start,$forceid,$desiredhome)=@_;
 2793:     my $cid='';
 2794:     unless ($cid=$ENV{'request.course.id'}) {
 2795: 	return 'not_in_class';
 2796:     }
 2797: # --------------------------------------------------------------- Make the user
 2798:     my $reply=&modifyuser
 2799: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 2800:          $desiredhome);
 2801:     unless ($reply eq 'ok') { return $reply; }
 2802:     # This will cause &modify_student_enrollment to get the uid from the
 2803:     # students environment
 2804:     $uid = undef if (!$forceid);
 2805:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
 2806:                                         $last,$gene,$usec,$end,$start);
 2807:     return $reply;
 2808: }
 2809: 
 2810: sub modify_student_enrollment {
 2811:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
 2812:     # Get the course id from the environment
 2813:     my $cid='';
 2814:     unless ($cid=$ENV{'request.course.id'}) {
 2815: 	return 'not_in_class';
 2816:     }
 2817:     # Make sure the user exists
 2818:     my $uhome=&homeserver($uname,$udom);
 2819:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2820: 	return 'error: no such user';
 2821:     }
 2822:     #
 2823:     # Get student data if we were not given enough information
 2824:     if (!defined($first)  || $first  eq '' || 
 2825:         !defined($last)   || $last   eq '' || 
 2826:         !defined($uid)    || $uid    eq '' || 
 2827:         !defined($middle) || $middle eq '' || 
 2828:         !defined($gene)   || $gene   eq '') {
 2829:         # They did not supply us with enough data to enroll the student, so
 2830:         # we need to pick up more information.
 2831:         my %tmp = &get('environment',
 2832:                        ['firstname','middlename','lastname', 'generation','id']
 2833:                        ,$udom,$uname);
 2834: 
 2835:         foreach (keys(%tmp)) {
 2836:             &logthis("key $_ = ".$tmp{$_});
 2837:         }
 2838:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 2839:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 2840:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 2841:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 2842:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 2843:     }
 2844:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
 2845:                                                            $first,$middle);
 2846:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 2847: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 2848:                       &escape($uname.':'.$udom).'='.
 2849:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
 2850: 	              $ENV{'course.'.$cid.'.home'});
 2851:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 2852: 	return 'error: '.$reply;
 2853:     }
 2854:     # Add student role to user
 2855:     my $uurl='/'.$cid;
 2856:     $uurl=~s/\_/\//g;
 2857:     if ($usec) {
 2858: 	$uurl.='/'.$usec;
 2859:     }
 2860:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 2861: }
 2862: 
 2863: # ------------------------------------------------- Write to course preferences
 2864: 
 2865: sub writecoursepref {
 2866:     my ($courseid,%prefs)=@_;
 2867:     $courseid=~s/^\///;
 2868:     $courseid=~s/\_/\//g;
 2869:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2870:     my $chome=homeserver($cnum,$cdomain);
 2871:     if (($chome eq '') || ($chome eq 'no_host')) { 
 2872: 	return 'error: no such course';
 2873:     }
 2874:     my $cstring='';
 2875:     foreach (keys %prefs) {
 2876: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 2877:     }
 2878:     $cstring=~s/\&$//;
 2879:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 2880: }
 2881: 
 2882: # ---------------------------------------------------------- Make/modify course
 2883: 
 2884: sub createcourse {
 2885:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
 2886:     $url=&declutter($url);
 2887:     my $cid='';
 2888:     unless (&allowed('ccc',$udom)) {
 2889:         return 'refused';
 2890:     }
 2891: # ------------------------------------------------------------------- Create ID
 2892:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2893:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2894: # ----------------------------------------------- Make sure that does not exist
 2895:    my $uhome=&homeserver($uname,$udom,'true');
 2896:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2897:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2898:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2899:        $uhome=&homeserver($uname,$udom,'true');       
 2900:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2901:            return 'error: unable to generate unique course-ID';
 2902:        } 
 2903:    }
 2904: # ------------------------------------------------ Check supplied server name
 2905:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
 2906:     if (! exists($libserv{$course_server})) {
 2907:         return 'error:bad server name '.$course_server;
 2908:     }
 2909: # ------------------------------------------------------------- Make the course
 2910:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 2911:                       $course_server);
 2912:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 2913:     $uhome=&homeserver($uname,$udom,'true');
 2914:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2915: 	return 'error: no such course';
 2916:     }
 2917: # ----------------------------------------------------------------- Course made
 2918: # log existance
 2919:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
 2920:                  $uhome);
 2921:     &flushcourselogs();
 2922: # set toplevel url
 2923:     my $topurl=$url;
 2924:     unless ($nonstandard) {
 2925: # ------------------------------------------ For standard courses, make top url
 2926:         my $mapurl=&clutter($url);
 2927:         if ($mapurl eq '/res/') { $mapurl=''; }
 2928:         $ENV{'form.initmap'}=(<<ENDINITMAP);
 2929: <map>
 2930: <resource id="1" type="start"></resource>
 2931: <resource id="2" src="$mapurl"></resource>
 2932: <resource id="3" type="finish"></resource>
 2933: <link index="1" from="1" to="2"></link>
 2934: <link index="2" from="2" to="3"></link>
 2935: </map>
 2936: ENDINITMAP
 2937:         $topurl=&declutter(
 2938:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
 2939:                           );
 2940:     }
 2941: # ----------------------------------------------------------- Write preferences
 2942:     &writecoursepref($udom.'_'.$uname,
 2943:                      ('description' => $description,
 2944:                       'url'         => $topurl));
 2945:     return '/'.$udom.'/'.$uname;
 2946: }
 2947: 
 2948: # ---------------------------------------------------------- Assign Custom Role
 2949: 
 2950: sub assigncustomrole {
 2951:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 2952:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 2953:                        $end,$start,$deleteflag);
 2954: }
 2955: 
 2956: # ----------------------------------------------------------------- Revoke Role
 2957: 
 2958: sub revokerole {
 2959:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 2960:     my $now=time;
 2961:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 2962: }
 2963: 
 2964: # ---------------------------------------------------------- Revoke Custom Role
 2965: 
 2966: sub revokecustomrole {
 2967:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 2968:     my $now=time;
 2969:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 2970:            $deleteflag);
 2971: }
 2972: 
 2973: # ------------------------------------------------------------ Directory lister
 2974: 
 2975: sub dirlist {
 2976:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 2977: 
 2978:     $uri=~s/^\///;
 2979:     $uri=~s/\/$//;
 2980:     my ($udom, $uname);
 2981:     (undef,$udom,$uname)=split(/\//,$uri);
 2982:     if(defined($userdomain)) {
 2983:         $udom = $userdomain;
 2984:     }
 2985:     if(defined($username)) {
 2986:         $uname = $username;
 2987:     }
 2988: 
 2989:     my $dirRoot = $perlvar{'lonDocRoot'};
 2990:     if(defined($alternateDirectoryRoot)) {
 2991:         $dirRoot = $alternateDirectoryRoot;
 2992:         $dirRoot =~ s/\/$//;
 2993:     }
 2994: 
 2995:     if($udom) {
 2996:         if($uname) {
 2997:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
 2998:                               homeserver($uname,$udom));
 2999:             return split(/:/,$listing);
 3000:         } elsif(!defined($alternateDirectoryRoot)) {
 3001:             my $tryserver;
 3002:             my %allusers=();
 3003:             foreach $tryserver (keys %libserv) {
 3004:                 if($hostdom{$tryserver} eq $udom) {
 3005:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 3006:                                       $udom, $tryserver);
 3007:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 3008:                         && ($listing ne 'con_lost')) {
 3009:                         foreach (split(/:/,$listing)) {
 3010:                             my ($entry,@stat)=split(/&/,$_);
 3011:                             $allusers{$entry}=1;
 3012:                         }
 3013:                     }
 3014:                 }
 3015:             }
 3016:             my $alluserstr='';
 3017:             foreach (sort keys %allusers) {
 3018:                 $alluserstr.=$_.'&user:';
 3019:             }
 3020:             $alluserstr=~s/:$//;
 3021:             return split(/:/,$alluserstr);
 3022:         } else {
 3023:             my @emptyResults = ();
 3024:             push(@emptyResults, 'missing user name');
 3025:             return split(':',@emptyResults);
 3026:         }
 3027:     } elsif(!defined($alternateDirectoryRoot)) {
 3028:         my $tryserver;
 3029:         my %alldom=();
 3030:         foreach $tryserver (keys %libserv) {
 3031:             $alldom{$hostdom{$tryserver}}=1;
 3032:         }
 3033:         my $alldomstr='';
 3034:         foreach (sort keys %alldom) {
 3035:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 3036:         }
 3037:         $alldomstr=~s/:$//;
 3038:         return split(/:/,$alldomstr);       
 3039:     } else {
 3040:         my @emptyResults = ();
 3041:         push(@emptyResults, 'missing domain');
 3042:         return split(':',@emptyResults);
 3043:     }
 3044: }
 3045: 
 3046: # --------------------------------------------- GetFileTimestamp
 3047: # This function utilizes dirlist and returns the date stamp for
 3048: # when it was last modified.  It will also return an error of -1
 3049: # if an error occurs
 3050: 
 3051: sub GetFileTimestamp {
 3052:     my ($studentDomain,$studentName,$filename,$root)=@_;
 3053:     $studentDomain=~s/\W//g;
 3054:     $studentName=~s/\W//g;
 3055:     my $subdir=$studentName.'__';
 3056:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 3057:     my $proname="$studentDomain/$subdir/$studentName";
 3058:     $proname .= '/'.$filename;
 3059:     my @dir = &Apache::lonnet::dirlist($proname, $studentDomain, $studentName,
 3060:                                        $root);
 3061:     my $fileStat = $dir[0];
 3062:     my @stats = split('&', $fileStat);
 3063:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 3064:         return $stats[9];
 3065:     } else {
 3066:         return -1;
 3067:     }
 3068: }
 3069: 
 3070: # -------------------------------------------------------- Value of a Condition
 3071: 
 3072: sub directcondval {
 3073:     my $number=shift;
 3074:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 3075:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 3076:     } else {
 3077:        return 2;
 3078:     }
 3079: }
 3080: 
 3081: sub condval {
 3082:     my $condidx=shift;
 3083:     my $result=0;
 3084:     my $allpathcond='';
 3085:     foreach (split(/\|/,$condidx)) {
 3086:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 3087: 	   $allpathcond.=
 3088:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 3089:        }
 3090:     }
 3091:     $allpathcond=~s/\|$//;
 3092:     if ($ENV{'request.course.id'}) {
 3093:        if ($allpathcond) {
 3094:           my $operand='|';
 3095: 	  my @stack;
 3096:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 3097:               if ($_ eq '(') {
 3098:                  push @stack,($operand,$result)
 3099:               } elsif ($_ eq ')') {
 3100:                   my $before=pop @stack;
 3101: 		  if (pop @stack eq '&') {
 3102: 		      $result=$result>$before?$before:$result;
 3103:                   } else {
 3104:                       $result=$result>$before?$result:$before;
 3105:                   }
 3106:               } elsif (($_ eq '&') || ($_ eq '|')) {
 3107:                   $operand=$_;
 3108:               } else {
 3109:                   my $new=directcondval($_);
 3110:                   if ($operand eq '&') {
 3111:                      $result=$result>$new?$new:$result;
 3112:                   } else {
 3113:                      $result=$result>$new?$result:$new;
 3114:                   }
 3115:               }
 3116:           }
 3117:        }
 3118:     }
 3119:     return $result;
 3120: }
 3121: 
 3122: # ---------------------------------------------------- Devalidate courseresdata
 3123: 
 3124: sub devalidatecourseresdata {
 3125:     my ($coursenum,$coursedomain)=@_;
 3126:     my $hashid=$coursenum.':'.$coursedomain;
 3127:     delete $courseresdatacache{$hashid.'.time'};
 3128: }
 3129: 
 3130: # --------------------------------------------------- Course Resourcedata Query
 3131: 
 3132: sub courseresdata {
 3133:     my ($coursenum,$coursedomain,@which)=@_;
 3134:     my $coursehom=&homeserver($coursenum,$coursedomain);
 3135:     my $hashid=$coursenum.':'.$coursedomain;
 3136:     my $dodump=0;
 3137:     if (!defined($courseresdatacache{$hashid.'.time'})) {
 3138: 	$dodump=1;
 3139:     } else {
 3140: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
 3141:     }
 3142:     if ($dodump) {
 3143: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 3144: 	my ($tmp) = keys(%dumpreply);
 3145: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 3146: 	    $courseresdatacache{$hashid.'.time'}=time;
 3147: 	    $courseresdatacache{$hashid}=\%dumpreply;
 3148: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3149: 	    return $tmp;
 3150: 	}
 3151:     }
 3152:     foreach my $item (@which) {
 3153: 	if (defined($courseresdatacache{$hashid}->{$item})) {
 3154: 	    return $courseresdatacache{$hashid}->{$item};
 3155: 	}
 3156:     }
 3157:     return undef;
 3158: }
 3159: 
 3160: # --------------------------------------------------------- Value of a Variable
 3161: 
 3162: sub EXT {
 3163:     my ($varname,$symbparm,$udom,$uname,)=@_;
 3164: 
 3165:     unless ($varname) { return ''; }
 3166:     #get real user name/domain, courseid and symb
 3167:     my $courseid;
 3168:     my $publicuser;
 3169:     if (!($uname && $udom)) {
 3170:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 3171: 	  &Apache::lonxml::whichuser();
 3172:       if (!$symbparm) {	$symbparm=$cursymb; }
 3173:     } else {
 3174: 	$courseid=$ENV{'request.course.id'};
 3175:     }
 3176:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 3177:     my $rest;
 3178:     if (defined($therest[0])) {
 3179:        $rest=join('.',@therest);
 3180:     } else {
 3181:        $rest='';
 3182:     }
 3183: 
 3184:     my $qualifierrest=$qualifier;
 3185:     if ($rest) { $qualifierrest.='.'.$rest; }
 3186:     my $spacequalifierrest=$space;
 3187:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 3188:     if ($realm eq 'user') {
 3189: # --------------------------------------------------------------- user.resource
 3190: 	if ($space eq 'resource') {
 3191: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
 3192: 		return $Apache::lonhomework::history{$qualifierrest};
 3193: 	    } else {
 3194: 		my %restored;
 3195: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
 3196: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 3197: 		} else {
 3198: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 3199: 		}
 3200: 		return $restored{$qualifierrest};
 3201: 	    }
 3202: # ----------------------------------------------------------------- user.access
 3203:         } elsif ($space eq 'access') {
 3204: 	    # FIXME - not supporting calls for a specific user
 3205:             return &allowed($qualifier,$rest);
 3206: # ------------------------------------------ user.preferences, user.environment
 3207:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 3208: 	    if (($uname eq $ENV{'user.name'}) &&
 3209: 		($udom eq $ENV{'user.domain'})) {
 3210: 		return $ENV{join('.',('environment',$qualifierrest))};
 3211: 	    } else {
 3212: 		my %returnhash;
 3213: 		if (!$publicuser) {
 3214: 		    %returnhash=&userenvironment($udom,$uname,
 3215: 						 $qualifierrest);
 3216: 		}
 3217: 		return $returnhash{$qualifierrest};
 3218: 	    }
 3219: # ----------------------------------------------------------------- user.course
 3220:         } elsif ($space eq 'course') {
 3221: 	    # FIXME - not supporting calls for a specific user
 3222:             return $ENV{join('.',('request.course',$qualifier))};
 3223: # ------------------------------------------------------------------- user.role
 3224:         } elsif ($space eq 'role') {
 3225: 	    # FIXME - not supporting calls for a specific user
 3226:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 3227:             if ($qualifier eq 'value') {
 3228: 		return $role;
 3229:             } elsif ($qualifier eq 'extent') {
 3230:                 return $where;
 3231:             }
 3232: # ----------------------------------------------------------------- user.domain
 3233:         } elsif ($space eq 'domain') {
 3234:             return $udom;
 3235: # ------------------------------------------------------------------- user.name
 3236:         } elsif ($space eq 'name') {
 3237:             return $uname;
 3238: # ---------------------------------------------------- Any other user namespace
 3239:         } else {
 3240: 	    my %reply;
 3241: 	    if (!$publicuser) {
 3242: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 3243: 	    }
 3244: 	    return $reply{$qualifierrest};
 3245:         }
 3246:     } elsif ($realm eq 'query') {
 3247: # ---------------------------------------------- pull stuff out of query string
 3248:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
 3249: 	return $ENV{'form.'.$space}; 
 3250:    } elsif ($realm eq 'request') {
 3251: # ------------------------------------------------------------- request.browser
 3252:         if ($space eq 'browser') {
 3253: 	    return $ENV{'browser.'.$qualifier};
 3254: # ------------------------------------------------------------ request.filename
 3255:         } else {
 3256:             return $ENV{'request.'.$spacequalifierrest};
 3257:         }
 3258:     } elsif ($realm eq 'course') {
 3259: # ---------------------------------------------------------- course.description
 3260:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
 3261:     } elsif ($realm eq 'resource') {
 3262: 
 3263: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
 3264: 
 3265: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 3266: 
 3267: # ----------------------------------------------------- Cascading lookup scheme
 3268: 	    if (!$symbparm) { $symbparm=&symbread(); }
 3269: 	    my $symbp=$symbparm;
 3270: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
 3271: 
 3272: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 3273: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 3274: 
 3275: 	    my $section;
 3276: 	    if (($ENV{'user.name'} eq $uname) &&
 3277: 		($ENV{'user.domain'} eq $udom)) {
 3278: 		$section=$ENV{'request.course.sec'};
 3279: 	    } else {
 3280: 		$section=&usection($udom,$uname,$courseid);
 3281: 	    }
 3282: 
 3283: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 3284: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 3285: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 3286: 
 3287: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
 3288: 	    my $courselevelr=$courseid.'.'.$symbparm;
 3289: 	    my $courselevelm=$courseid.'.'.$mapparm;
 3290: 
 3291: # ----------------------------------------------------------- first, check user
 3292: 	    #most student don't have any data set, check if there is some data
 3293:             #every thirty minutes
 3294: 	    if (!
 3295: 		(exists($ENV{'cache.studentresdata'})
 3296: 		    && (($ENV{'cache.studentresdata'}+1800) > time))) {
 3297: 		my %resourcedata=&get('resourcedata',
 3298: 				      [$courselevelr,$courselevelm,$courselevel],
 3299: 				      $udom,$uname);
 3300: 		my ($tmp)=keys(%resourcedata);
 3301: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 3302: 		    if ($resourcedata{$courselevelr}) {
 3303: 			return $resourcedata{$courselevelr}; }
 3304: 		    if ($resourcedata{$courselevelm}) {
 3305: 			return $resourcedata{$courselevelm}; }
 3306: 		    if ($resourcedata{$courselevel}) {
 3307: 			return $resourcedata{$courselevel}; }
 3308: 		} else {
 3309: 		    if ($tmp!~/No such file/) {
 3310: 			&logthis("<font color=blue>WARNING:".
 3311: 				 " Trying to get resource data for ".
 3312: 				 $uname." at ".$udom.": ".
 3313: 				 $tmp."</font>");
 3314: 		    } elsif ($tmp=~/error:No such file/) {
 3315: 			$ENV{'cache.studentresdata'}=time;
 3316: 			&appenv(('cache.studentresdata'=>
 3317: 				 $ENV{'cache.studentresdata'}));
 3318: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3319: 			return $tmp;
 3320: 		    }
 3321: 		}
 3322: 	    }
 3323: 
 3324: # -------------------------------------------------------- second, check course
 3325: 
 3326: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
 3327: 					  $ENV{'course.'.$courseid.'.domain'},
 3328: 					  ($seclevelr,$seclevelm,$seclevel,
 3329: 					   $courselevelr,$courselevelm,
 3330: 					   $courselevel));
 3331: 	    if (defined($coursereply)) { return $coursereply; }
 3332: 
 3333: # ------------------------------------------------------ third, check map parms
 3334: 	    my %parmhash=();
 3335: 	    my $thisparm='';
 3336: 	    if (tie(%parmhash,'GDBM_File',
 3337: 		    $ENV{'request.course.fn'}.'_parms.db',
 3338: 		    &GDBM_READER(),0640)) {
 3339: 		$thisparm=$parmhash{$symbparm};
 3340: 		untie(%parmhash);
 3341: 	    }
 3342: 	    if ($thisparm) { return $thisparm; }
 3343: 	}
 3344: # --------------------------------------------- last, look in resource metadata
 3345: 
 3346: 	$spacequalifierrest=~s/\./\_/;
 3347: 	my $filename;
 3348: 	if (!$symbparm) { $symbparm=&symbread(); }
 3349: 	if ($symbparm) {
 3350: 	    $filename=(split(/\_\_\_/,$symbparm))[2];
 3351: 	} else {
 3352: 	    $filename=$ENV{'request.filename'};
 3353: 	}
 3354: 	my $metadata=&metadata($filename,$spacequalifierrest);
 3355: 	if (defined($metadata)) { return $metadata; }
 3356: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 3357: 	if (defined($metadata)) { return $metadata; }
 3358: 
 3359: # ------------------------------------------------------------------ Cascade up
 3360: 	unless ($space eq '0') {
 3361: 	    my @parts=split(/_/,$space);
 3362: 	    my $id=pop(@parts);
 3363: 	    my $part=join('_',@parts);
 3364: 	    if ($part eq '') { $part='0'; }
 3365: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 3366: 				 $symbparm,$udom,$uname);
 3367: 	    if (defined($partgeneral)) { return $partgeneral; }
 3368: 	}
 3369: 
 3370: # ---------------------------------------------------- Any other user namespace
 3371:     } elsif ($realm eq 'environment') {
 3372: # ----------------------------------------------------------------- environment
 3373: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
 3374: 	    return $ENV{'environment.'.$spacequalifierrest};
 3375: 	} else {
 3376: 	    my %returnhash=&userenvironment($udom,$uname,
 3377: 					    $spacequalifierrest);
 3378: 	    return $returnhash{$spacequalifierrest};
 3379: 	}
 3380:     } elsif ($realm eq 'system') {
 3381: # ----------------------------------------------------------------- system.time
 3382: 	if ($space eq 'time') {
 3383: 	    return time;
 3384:         }
 3385:     }
 3386:     return '';
 3387: }
 3388: 
 3389: sub add_prefix_and_part {
 3390:     my ($prefix,$part)=@_;
 3391:     my $keyroot;
 3392:     if (defined($prefix) && $prefix !~ /^__/) {
 3393: 	# prefix that has a part already
 3394: 	$keyroot=$prefix;
 3395:     } elsif (defined($prefix)) {
 3396: 	# prefix that is missing a part
 3397: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 3398:     } else {
 3399: 	# no prefix at all
 3400: 	if (defined($part)) { $keyroot='_'.$part; }
 3401:     }
 3402:     return $keyroot;
 3403: }
 3404: 
 3405: # ---------------------------------------------------------------- Get metadata
 3406: 
 3407: sub metadata {
 3408:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 3409: 
 3410:     $uri=&declutter($uri);
 3411:     # if it is a non metadata possible uri return quickly
 3412:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
 3413:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
 3414: 	return '';
 3415:     }
 3416:     my $filename=$uri;
 3417:     $uri=~s/\.meta$//;
 3418: #
 3419: # Is the metadata already cached?
 3420: # Look at timestamp of caching
 3421: # Everything is cached by the main uri, libraries are never directly cached
 3422: #
 3423:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
 3424: #
 3425: # Is this a recursive call for a library?
 3426: #
 3427:         if ($liburi) {
 3428: 	    $liburi=&declutter($liburi);
 3429:             $filename=$liburi;
 3430:         }
 3431:         my %metathesekeys=();
 3432:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 3433: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
 3434:         my $parser=HTML::LCParser->new(\$metastring);
 3435:         my $token;
 3436:         undef %metathesekeys;
 3437: 	delete($metacache{$uri.':packages'});
 3438:         while ($token=$parser->get_token) {
 3439: 	    if ($token->[0] eq 'S') {
 3440: 		if (defined($token->[2]->{'package'})) {
 3441: #
 3442: # This is a package - get package info
 3443: #
 3444: 		    my $package=$token->[2]->{'package'};
 3445: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3446: 		    if (defined($token->[2]->{'id'})) { 
 3447: 			$keyroot.='_'.$token->[2]->{'id'}; 
 3448: 		    }
 3449: 		    if ($metacache{$uri.':packages'}) {
 3450: 			$metacache{$uri.':packages'}.=','.$package.$keyroot;
 3451: 		    } else {
 3452: 			$metacache{$uri.':packages'}=$package.$keyroot;
 3453: 		    }
 3454: 		    foreach (keys %packagetab) {
 3455: 			if ($_=~/^$package\&/) {
 3456: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 3457: 			    my $value=$packagetab{$_};
 3458: 			    my $part=$keyroot;
 3459: 			    $part=~s/^\_//;
 3460: 			    if ($subp eq 'display') {
 3461: 				$value.=' [Part: '.$part.']';
 3462: 			    }
 3463: 			    my $unikey='parameter'.$keyroot.'_'.$name;
 3464: 			    if ($subp eq 'default') {
 3465: 				$unikey='parameter_0_'.$name;
 3466: 				$metacache{$uri.':'.$unikey.'.part'}='0';
 3467: 			    } else {
 3468: 				$metacache{$uri.':'.$unikey.'.part'}=$part;
 3469: 				$metathesekeys{$unikey}=1;
 3470: 			    }
 3471: 			    unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 3472: 				$metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 3473: 			    }
 3474: 			    if (defined($metacache{$uri.':'.$unikey.'.default'})) {
 3475: 				$metacache{$uri.':'.$unikey}=
 3476: 				    $metacache{$uri.':'.$unikey.'.default'};
 3477: 			    }
 3478: 			}
 3479: 		    }
 3480: 		} else {
 3481: #
 3482: # This is not a package - some other kind of start tag
 3483: #
 3484: 		    my $entry=$token->[1];
 3485: 		    my $unikey;
 3486: 		    if ($entry eq 'import') {
 3487: 			$unikey='';
 3488: 		    } else {
 3489: 			$unikey=$entry;
 3490: 		    }
 3491: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3492: 
 3493: 		    if (defined($token->[2]->{'id'})) { 
 3494: 			$unikey.='_'.$token->[2]->{'id'}; 
 3495: 		    }
 3496: 
 3497: 		    if ($entry eq 'import') {
 3498: #
 3499: # Importing a library here
 3500: #
 3501: 			if ($depthcount<20) {
 3502: 			    my $location=$parser->get_text('/import');
 3503: 			    my $dir=$filename;
 3504: 			    $dir=~s|[^/]*$||;
 3505: 			    $location=&filelocation($dir,$location);
 3506: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 3507: 							       $location,$unikey,
 3508: 							       $depthcount+1)))) {
 3509: 				$metathesekeys{$_}=1;
 3510: 			    }
 3511: 			}
 3512: 		    } else { 
 3513: 			
 3514: 			if (defined($token->[2]->{'name'})) { 
 3515: 			    $unikey.='_'.$token->[2]->{'name'}; 
 3516: 			}
 3517: 			$metathesekeys{$unikey}=1;
 3518: 			foreach (@{$token->[3]}) {
 3519: 			    $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 3520: 			}
 3521: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 3522: 			my $default=$metacache{$uri.':'.$unikey.'.default'};
 3523: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 3524: 		 # only ws inside the tag, and not in default, so use default
 3525: 		 # as value
 3526: 			    $metacache{$uri.':'.$unikey}=$default;
 3527: 			} else {
 3528: 		  # either something interesting inside the tag or default
 3529:                   # uninteresting
 3530: 			    $metacache{$uri.':'.$unikey}=$internaltext;
 3531: 			}
 3532: # end of not-a-package not-a-library import
 3533: 		    }
 3534: # end of not-a-package start tag
 3535: 		}
 3536: # the next is the end of "start tag"
 3537: 	    }
 3538: 	}
 3539: # are there custom rights to evaluate
 3540: 	if ($metacache{$uri.':copyright'} eq 'custom') {
 3541: 
 3542:     #
 3543:     # Importing a rights file here
 3544:     #
 3545: 	    unless ($depthcount) {
 3546: 		my $location=$metacache{$uri.':customdistributionfile'};
 3547: 		my $dir=$filename;
 3548: 		$dir=~s|[^/]*$||;
 3549: 		$location=&filelocation($dir,$location);
 3550: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 3551: 						   $location,'_rights',
 3552: 						   $depthcount+1)))) {
 3553: 		    $metathesekeys{$_}=1;
 3554: 		}
 3555: 	    }
 3556: 	}
 3557: 	$metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 3558: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
 3559: 	$metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
 3560: 	$metacache{$uri.':cachedtimestamp'}=time;
 3561: # this is the end of "was not already recently cached
 3562:     }
 3563:     return $metacache{$uri.':'.$what};
 3564: }
 3565: 
 3566: sub metadata_generate_part0 {
 3567:     my ($metadata,$metacache,$uri) = @_;
 3568:     my %allnames;
 3569:     foreach my $metakey (sort keys %$metadata) {
 3570: 	if ($metakey=~/^parameter\_(.*)/) {
 3571: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
 3572: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
 3573: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 3574: 	    $allnames{$name}=$part;
 3575: 	  }
 3576: 	}
 3577:     }
 3578:     foreach my $name (keys(%allnames)) {
 3579:       $$metadata{"parameter_0_$name"}=1;
 3580:       my $key="$uri:parameter_0_$name";
 3581:       $$metacache{"$key.part"}='0';
 3582:       $$metacache{"$key.name"}=$name;
 3583:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
 3584: 					   $allnames{$name}.'_'.$name.
 3585: 					   '.type'};
 3586:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
 3587: 			     '.display'};
 3588:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 3589:       $olddis=~s/$expr/\[Part: 0\]/;
 3590:       $$metacache{"$key.display"}=$olddis;
 3591:     }
 3592: }
 3593: 
 3594: # ------------------------------------------------- Get the title of a resource
 3595: 
 3596: sub gettitle {
 3597:     my $urlsymb=shift;
 3598:     my $symb=&symbread($urlsymb);
 3599:     unless ($symb) {
 3600: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
 3601:         return &metadata($urlsymb,'title'); 
 3602:     }
 3603:     if ($titlecache{$symb}) { return $titlecache{$symb}; }
 3604:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3605:     my $title='';
 3606:     my %bighash;
 3607:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3608:                             &GDBM_READER(),0640)) {
 3609:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
 3610:         $title=$bighash{'title_'.$mapid.'.'.$resid};
 3611:         untie %bighash;
 3612:     }
 3613:     $title=~s/\&colon\;/\:/gs;
 3614:     if ($title) {
 3615:         $titlecache{$symb}=$title;
 3616:         return $title;
 3617:     } else {
 3618: 	return &metadata($urlsymb,'title');
 3619:     }
 3620: }
 3621:     
 3622: # ------------------------------------------------- Update symbolic store links
 3623: 
 3624: sub symblist {
 3625:     my ($mapname,%newhash)=@_;
 3626:     $mapname=declutter($mapname);
 3627:     my %hash;
 3628:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 3629:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3630:                       &GDBM_WRCREAT(),0640)) {
 3631: 	    foreach (keys %newhash) {
 3632:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 3633:             }
 3634:             if (untie(%hash)) {
 3635: 		return 'ok';
 3636:             }
 3637:         }
 3638:     }
 3639:     return 'error';
 3640: }
 3641: 
 3642: # --------------------------------------------------------------- Verify a symb
 3643: 
 3644: sub symbverify {
 3645:     my ($symb,$thisfn)=@_;
 3646:     $thisfn=&declutter($thisfn);
 3647: # direct jump to resource in page or to a sequence - will construct own symbs
 3648:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 3649: # check URL part
 3650:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3651:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
 3652: 
 3653:     $symb=&symbclean($symb);
 3654: 
 3655:     my %bighash;
 3656:     my $okay=0;
 3657:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3658:                             &GDBM_READER(),0640)) {
 3659:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3660:         unless ($ids) { 
 3661:            $ids=$bighash{'ids_/'.$thisfn};
 3662:         }
 3663:         if ($ids) {
 3664: # ------------------------------------------------------------------- Has ID(s)
 3665: 	    foreach (split(/\,/,$ids)) {
 3666:                my ($mapid,$resid)=split(/\./,$_);
 3667:                if (
 3668:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 3669:    eq $symb) { 
 3670:                   $okay=1; 
 3671:                }
 3672: 	   }
 3673:         }
 3674: 	untie(%bighash);
 3675:     }
 3676:     return $okay;
 3677: }
 3678: 
 3679: # --------------------------------------------------------------- Clean-up symb
 3680: 
 3681: sub symbclean {
 3682:     my $symb=shift;
 3683: 
 3684: # remove version from map
 3685:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 3686: 
 3687: # remove version from URL
 3688:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 3689: 
 3690:     return $symb;
 3691: }
 3692: 
 3693: # ------------------------------------------------------ Return symb list entry
 3694: 
 3695: sub symbread {
 3696:     my ($thisfn,$donotrecurse)=@_;
 3697: # no filename provided? try from environment
 3698:     unless ($thisfn) {
 3699:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
 3700: 	$thisfn=$ENV{'request.filename'};
 3701:     }
 3702: # is that filename actually a symb? Verify, clean, and return
 3703:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 3704: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
 3705:     }
 3706:     $thisfn=declutter($thisfn);
 3707:     my %hash;
 3708:     my %bighash;
 3709:     my $syval='';
 3710:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 3711:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3712:                       &GDBM_READER(),0640)) {
 3713: 	    $syval=$hash{$thisfn};
 3714:             untie(%hash);
 3715:         }
 3716: # ---------------------------------------------------------- There was an entry
 3717:         if ($syval) {
 3718:            unless ($syval=~/\_\d+$/) {
 3719: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 3720:                   &appenv('request.ambiguous' => $thisfn);
 3721:                   return '';
 3722:                }    
 3723:                $syval.=$1;
 3724: 	   }
 3725:         } else {
 3726: # ------------------------------------------------------- Was not in symb table
 3727:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3728:                             &GDBM_READER(),0640)) {
 3729: # ---------------------------------------------- Get ID(s) for current resource
 3730:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3731:               unless ($ids) { 
 3732:                  $ids=$bighash{'ids_/'.$thisfn};
 3733:               }
 3734:               unless ($ids) {
 3735: # alias?
 3736: 		  $ids=$bighash{'mapalias_'.$thisfn};
 3737:               }
 3738:               if ($ids) {
 3739: # ------------------------------------------------------------------- Has ID(s)
 3740:                  my @possibilities=split(/\,/,$ids);
 3741:                  if ($#possibilities==0) {
 3742: # ----------------------------------------------- There is only one possibility
 3743: 		     my ($mapid,$resid)=split(/\./,$ids);
 3744:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 3745:                  } elsif (!$donotrecurse) {
 3746: # ------------------------------------------ There is more than one possibility
 3747:                      my $realpossible=0;
 3748:                      foreach (@possibilities) {
 3749: 			 my $file=$bighash{'src_'.$_};
 3750:                          if (&allowed('bre',$file)) {
 3751:          		    my ($mapid,$resid)=split(/\./,$_);
 3752:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 3753: 				$realpossible++;
 3754:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 3755:                                        '___'.$resid;
 3756:                             }
 3757: 			 }
 3758:                      }
 3759: 		     if ($realpossible!=1) { $syval=''; }
 3760:                  } else {
 3761:                      $syval='';
 3762:                  }
 3763: 	      }
 3764:               untie(%bighash)
 3765:            } 
 3766:         }
 3767:         if ($syval) {
 3768:            return &symbclean($syval.'___'.$thisfn); 
 3769:         }
 3770:     }
 3771:     &appenv('request.ambiguous' => $thisfn);
 3772:     return '';
 3773: }
 3774: 
 3775: # ---------------------------------------------------------- Return random seed
 3776: 
 3777: sub numval {
 3778:     my $txt=shift;
 3779:     $txt=~tr/A-J/0-9/;
 3780:     $txt=~tr/a-j/0-9/;
 3781:     $txt=~tr/K-T/0-9/;
 3782:     $txt=~tr/k-t/0-9/;
 3783:     $txt=~tr/U-Z/0-5/;
 3784:     $txt=~tr/u-z/0-5/;
 3785:     $txt=~s/\D//g;
 3786:     return int($txt);
 3787: }
 3788: 
 3789: sub latest_rnd_algorithm_id {
 3790:     return '64bit';
 3791: }
 3792: 
 3793: sub rndseed {
 3794:     my ($symb,$courseid,$domain,$username)=@_;
 3795: 
 3796:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 3797:     if (!$symb) {
 3798: 	unless ($symb=$wsymb) { return time; }
 3799:     }
 3800:     if (!$courseid) { $courseid=$wcourseid; }
 3801:     if (!$domain) { $domain=$wdomain; }
 3802:     if (!$username) { $username=$wusername }
 3803:     my $which=$ENV{"course.$courseid.rndseed"};
 3804:     my $CODE=$ENV{'scantron.CODE'};
 3805:     if (defined($CODE)) {
 3806: 	&rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 3807:     } elsif ($which eq '64bit') {
 3808: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 3809:     }
 3810:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 3811: }
 3812: 
 3813: sub rndseed_32bit {
 3814:     my ($symb,$courseid,$domain,$username)=@_;
 3815:     {
 3816: 	use integer;
 3817: 	my $symbchck=unpack("%32C*",$symb) << 27;
 3818: 	my $symbseed=numval($symb) << 22;
 3819: 	my $namechck=unpack("%32C*",$username) << 17;
 3820: 	my $nameseed=numval($username) << 12;
 3821: 	my $domainseed=unpack("%32C*",$domain) << 7;
 3822: 	my $courseseed=unpack("%32C*",$courseid);
 3823: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 3824: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3825: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 3826: 	return $num;
 3827:     }
 3828: }
 3829: 
 3830: sub rndseed_64bit {
 3831:     my ($symb,$courseid,$domain,$username)=@_;
 3832:     {
 3833: 	use integer;
 3834: 	my $symbchck=unpack("%32S*",$symb) << 21;
 3835: 	my $symbseed=numval($symb) << 10;
 3836: 	my $namechck=unpack("%32S*",$username);
 3837: 	
 3838: 	my $nameseed=numval($username) << 21;
 3839: 	my $domainseed=unpack("%32S*",$domain) << 10;
 3840: 	my $courseseed=unpack("%32S*",$courseid);
 3841: 	
 3842: 	my $num1=$symbchck+$symbseed+$namechck;
 3843: 	my $num2=$nameseed+$domainseed+$courseseed;
 3844: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3845: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 3846: 	return "$num1,$num2";
 3847:     }
 3848: }
 3849: 
 3850: sub rndseed_CODE_64bit {
 3851:     my ($symb,$courseid,$domain,$username)=@_;
 3852:     {
 3853: 	use integer;
 3854: 	my $symbchck=unpack("%32S*",$symb) << 16;
 3855: 	my $symbseed=numval($symb);
 3856: 	my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
 3857: 	my $courseseed=unpack("%32S*",$courseid);
 3858: 	my $num1=$symbseed+$CODEseed;
 3859: 	my $num2=$courseseed+$symbchck;
 3860: 	#&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
 3861: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 3862: 	return "$num1,$num2";
 3863:     }
 3864: }
 3865: 
 3866: sub setup_random_from_rndseed {
 3867:     my ($rndseed)=@_;
 3868:     if ($rndseed =~/,/) {
 3869: 	my ($num1,$num2)=split(/,/,$rndseed);
 3870: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 3871:     } else {
 3872: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 3873:     }
 3874: }
 3875: 
 3876: sub ireceipt {
 3877:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 3878:     my $cuname=unpack("%32C*",$funame);
 3879:     my $cudom=unpack("%32C*",$fudom);
 3880:     my $cucourseid=unpack("%32C*",$fucourseid);
 3881:     my $cusymb=unpack("%32C*",$fusymb);
 3882:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 3883:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 3884:            ($cunique%$cuname+
 3885:             $cunique%$cudom+
 3886:             $cusymb%$cuname+
 3887:             $cusymb%$cudom+
 3888:             $cucourseid%$cuname+
 3889:             $cucourseid%$cudom);
 3890: }
 3891: 
 3892: sub receipt {
 3893:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 3894:   return &ireceipt($name,$domain,$courseid,$symb);
 3895: }
 3896: 
 3897: # ------------------------------------------------------------ Serves up a file
 3898: # returns either the contents of the file or a -1
 3899: sub getfile {
 3900:  my $file=shift;
 3901:  if ($file=~/^\/*uploaded\//) { # user file
 3902:     my $ua=new LWP::UserAgent;
 3903:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
 3904:     my $response=$ua->request($request);
 3905:     if ($response->is_success()) {
 3906:        return $response->content;
 3907:     } else { 
 3908:        return -1; 
 3909:     }
 3910:  } else { # normal file from res space
 3911:   &repcopy($file);
 3912:   if (! -e $file ) { return -1; };
 3913:   my $fh=Apache::File->new($file);
 3914:   my $a='';
 3915:   while (<$fh>) { $a .=$_; }
 3916:   return $a;
 3917:  }
 3918: }
 3919: 
 3920: sub filelocation {
 3921:   my ($dir,$file) = @_;
 3922:   my $location;
 3923:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 3924:   if ($file=~m:^/~:) { # is a contruction space reference
 3925:     $location = $file;
 3926:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 3927:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 3928:     $location=$file;
 3929:   } else {
 3930:     $file=~s/^$perlvar{'lonDocRoot'}//;
 3931:     $file=~s:^/*res::;
 3932:     if ( !( $file =~ m:^/:) ) {
 3933:       $location = $dir. '/'.$file;
 3934:     } else {
 3935:       $location = '/home/httpd/html/res'.$file;
 3936:     }
 3937:   }
 3938:   $location=~s://+:/:g; # remove duplicate /
 3939:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 3940:   return $location;
 3941: }
 3942: 
 3943: sub hreflocation {
 3944:     my ($dir,$file)=@_;
 3945:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 3946:        my $finalpath=filelocation($dir,$file);
 3947:        $finalpath=~s/^\/home\/httpd\/html//;
 3948:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
 3949:        return $finalpath;
 3950:     } else {
 3951:        return $file;
 3952:     }
 3953: }
 3954: 
 3955: # ------------------------------------------------------------- Declutters URLs
 3956: 
 3957: sub declutter {
 3958:     my $thisfn=shift;
 3959:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 3960:     $thisfn=~s/^\///;
 3961:     $thisfn=~s/^res\///;
 3962:     $thisfn=~s/\?.+$//;
 3963:     return $thisfn;
 3964: }
 3965: 
 3966: # ------------------------------------------------------------- Clutter up URLs
 3967: 
 3968: sub clutter {
 3969:     my $thisfn='/'.&declutter(shift);
 3970:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
 3971:        $thisfn='/res'.$thisfn; 
 3972:     }
 3973:     return $thisfn;
 3974: }
 3975: 
 3976: # -------------------------------------------------------- Escape Special Chars
 3977: 
 3978: sub escape {
 3979:     my $str=shift;
 3980:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 3981:     return $str;
 3982: }
 3983: 
 3984: # ----------------------------------------------------- Un-Escape Special Chars
 3985: 
 3986: sub unescape {
 3987:     my $str=shift;
 3988:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 3989:     return $str;
 3990: }
 3991: 
 3992: # ================================================================ Main Program
 3993: 
 3994: sub goodbye {
 3995:    &logthis("Starting Shut down");
 3996:    &flushcourselogs();
 3997:    &logthis("Shutting down");
 3998:    return DONE;
 3999: }
 4000: 
 4001: BEGIN {
 4002: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 4003:     unless ($readit) {
 4004: {
 4005:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
 4006: 
 4007:     while (my $configline=<$config>) {
 4008:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4009: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4010:            chomp($varvalue);
 4011:            $perlvar{$varname}=$varvalue;
 4012:         }
 4013:     }
 4014: }
 4015: {
 4016:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
 4017: 
 4018:     while (my $configline=<$config>) {
 4019:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4020: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4021:            chomp($varvalue);
 4022:            $perlvar{$varname}=$varvalue;
 4023:         }
 4024:     }
 4025: }
 4026: 
 4027: # ------------------------------------------------------------ Read domain file
 4028: {
 4029:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
 4030:                             '/domain.tab');
 4031:     %domaindescription = ();
 4032:     %domain_auth_def = ();
 4033:     %domain_auth_arg_def = ();
 4034:     if ($fh) {
 4035:        while (<$fh>) {
 4036:            next if /^\#/;
 4037:            chomp;
 4038:            my ($domain, $domain_description, $def_auth, $def_auth_arg)
 4039:                = split(/:/,$_,4);
 4040:            $domain_auth_def{$domain}=$def_auth;
 4041:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 4042:            $domaindescription{$domain}=$domain_description;
 4043: #          &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 4044: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 4045:        }
 4046:     }
 4047: }
 4048: 
 4049: 
 4050: # ------------------------------------------------------------- Read hosts file
 4051: {
 4052:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 4053: 
 4054:     while (my $configline=<$config>) {
 4055:        next if ($configline =~ /^(\#|\s*$)/);
 4056:        chomp($configline);
 4057:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 4058:        if ($id && $domain && $role && $name && $ip) {
 4059: 	 $hostname{$id}=$name;
 4060: 	 $hostdom{$id}=$domain;
 4061: 	 $hostip{$id}=$ip;
 4062: 	 $iphost{$ip}=$id;
 4063: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 4064:        } else {
 4065: 	 if ($configline) {
 4066: 	   &logthis("Skipping hosts.tab line -$configline-");
 4067: 	 }
 4068:        }
 4069:     }
 4070: }
 4071: 
 4072: # ------------------------------------------------------ Read spare server file
 4073: {
 4074:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 4075: 
 4076:     while (my $configline=<$config>) {
 4077:        chomp($configline);
 4078:        if ($configline) {
 4079:           $spareid{$configline}=1;
 4080:        }
 4081:     }
 4082: }
 4083: # ------------------------------------------------------------ Read permissions
 4084: {
 4085:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 4086: 
 4087:     while (my $configline=<$config>) {
 4088:        chomp($configline);
 4089:       if ($configline) {
 4090:        my ($role,$perm)=split(/ /,$configline);
 4091:        if ($perm ne '') { $pr{$role}=$perm; }
 4092:       }
 4093:     }
 4094: }
 4095: 
 4096: # -------------------------------------------- Read plain texts for permissions
 4097: {
 4098:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 4099: 
 4100:     while (my $configline=<$config>) {
 4101:        chomp($configline);
 4102:       if ($configline) {
 4103:        my ($short,$plain)=split(/:/,$configline);
 4104:        if ($plain ne '') { $prp{$short}=$plain; }
 4105:       }
 4106:     }
 4107: }
 4108: 
 4109: # ---------------------------------------------------------- Read package table
 4110: {
 4111:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 4112: 
 4113:     while (my $configline=<$config>) {
 4114:        chomp($configline);
 4115:        my ($short,$plain)=split(/:/,$configline);
 4116:        my ($pack,$name)=split(/\&/,$short);
 4117:        if ($plain ne '') {
 4118:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 4119:           $packagetab{$short}=$plain; 
 4120:        }
 4121:     }
 4122: }
 4123: 
 4124: # ------------- set up temporary directory
 4125: {
 4126:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 4127: 
 4128: }
 4129: 
 4130: %metacache=();
 4131: 
 4132: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 4133: $dumpcount=0;
 4134: 
 4135: &logtouch();
 4136: &logthis('<font color=yellow>INFO: Read configuration</font>');
 4137: $readit=1;
 4138: }
 4139: }
 4140: 
 4141: 1;
 4142: __END__
 4143: 
 4144: =pod
 4145: 
 4146: =head1 NAME
 4147: 
 4148: Apache::lonnet - Subroutines to ask questions about things in the network.
 4149: 
 4150: =head1 SYNOPSIS
 4151: 
 4152: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 4153: 
 4154:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 4155: 
 4156: Common parameters:
 4157: 
 4158: =over 4
 4159: 
 4160: =item *
 4161: 
 4162: $uname : an internal username (if $cname expecting a course Id specifically)
 4163: 
 4164: =item *
 4165: 
 4166: $udom : a domain (if $cdom expecting a course's domain specifically)
 4167: 
 4168: =item *
 4169: 
 4170: $symb : a resource instance identifier
 4171: 
 4172: =item *
 4173: 
 4174: $namespace : the name of a .db file that contains the data needed or
 4175: being set.
 4176: 
 4177: =back
 4178: 
 4179: =head1 INTRODUCTION
 4180: 
 4181: This module provides subroutines which interact with the
 4182: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
 4183: - classes
 4184: - users 
 4185: - resources
 4186: 
 4187: For many of these objects you can also use this to store data about
 4188: them or modify them in various ways.
 4189: 
 4190: This is part of the LearningOnline Network with CAPA project
 4191: described at http://www.lon-capa.org.
 4192: 
 4193: =head1 RETURN MESSAGES
 4194: 
 4195: =over 4
 4196: 
 4197: =item *
 4198: 
 4199: con_lost : unable to contact remote host
 4200: 
 4201: =item *
 4202: 
 4203: con_delayed : unable to contact remote host, message will be delivered
 4204: when the connection is brought back up
 4205: 
 4206: =item *
 4207: 
 4208: con_failed : unable to contact remote host and unable to save message
 4209: for later delivery
 4210: 
 4211: =item *
 4212: 
 4213: error: : an error a occured, a description of the error follows the :
 4214: 
 4215: =item *
 4216: 
 4217: no_such_host : unable to fund a host associated with the user/domain
 4218: that was requested
 4219: 
 4220: =back
 4221: 
 4222: =head1 PUBLIC SUBROUTINES
 4223: 
 4224: =head2 Session Environment Functions
 4225: 
 4226: =over 4
 4227: 
 4228: =item *
 4229: 
 4230: appenv(%hash) : the value of %hash is written to the user envirnoment
 4231: file, and will be restored for each access this user makes during this
 4232: session, also modifies the %ENV for the current process
 4233: 
 4234: =item *
 4235: 
 4236: 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.
 4237: 
 4238: =back
 4239: 
 4240: =head2 User Information
 4241: 
 4242: =over 4
 4243: 
 4244: =item *
 4245: 
 4246: queryauthenticate($uname,$udom) : try to determine user's current
 4247: authentication scheme
 4248: 
 4249: =item *
 4250: 
 4251: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
 4252: servers (first use the current one), $upass should be the users password
 4253: 
 4254: =item *
 4255: 
 4256: homeserver($uname,$udom) : find the server which has the user's
 4257: directory and files (there must be only one), this caches the answer,
 4258: and also caches if there is a borken connection.
 4259: 
 4260: =item *
 4261: 
 4262: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
 4263: unique resource in a domain, there must be only 1 ID per username, and
 4264: only 1 username per ID in a specific domain) (returns hash:
 4265: id=>name,id=>name)
 4266: 
 4267: =item *
 4268: 
 4269: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
 4270: name=>id,name=>id)
 4271: 
 4272: =item *
 4273: 
 4274: idput($udom,%ids) : store away a list of names and associated IDs
 4275: 
 4276: =item *
 4277: 
 4278: rolesinit($udom,$username,$authhost) : get user privileges
 4279: 
 4280: =item *
 4281: 
 4282: usection($udom,$uname,$cname) : finds the section of student in the
 4283: course $cname, return section name/number or '' for "not in course"
 4284: and '-1' for "no section"
 4285: 
 4286: =item *
 4287: 
 4288: userenvironment($udom,$uname,@what) : gets the values of the keys
 4289: passed in @what from the requested user's environment, returns a hash
 4290: 
 4291: =back
 4292: 
 4293: =head2 User Roles
 4294: 
 4295: =over 4
 4296: 
 4297: =item *
 4298: 
 4299: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 4300: actions
 4301:  F: full access
 4302:  U,I,K: authentication modes (cxx only)
 4303:  '': forbidden
 4304:  1: user needs to choose course
 4305:  2: browse allowed
 4306: 
 4307: =item *
 4308: 
 4309: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 4310: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 4311: and course level
 4312: 
 4313: =item *
 4314: 
 4315: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 4316: explanation of a user role term
 4317: 
 4318: =back
 4319: 
 4320: =head2 User Modification
 4321: 
 4322: =over 4
 4323: 
 4324: =item *
 4325: 
 4326: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 4327: user for the level given by URL.  Optional start and end dates (leave empty
 4328: string or zero for "no date")
 4329: 
 4330: =item *
 4331: 
 4332: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 4333: change a users, password, possible return values are: ok,
 4334: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 4335: refused
 4336: 
 4337: =item *
 4338: 
 4339: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 4340: 
 4341: =item *
 4342: 
 4343: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 4344: modify user
 4345: 
 4346: =item *
 4347: 
 4348: modifystudent
 4349: 
 4350: modify a students enrollment and identification information.
 4351: The course id is resolved based on the current users environment.  
 4352: This means the envoking user must be a course coordinator or otherwise
 4353: associated with a course.
 4354: 
 4355: This call is essentially a wrapper for lonnet::modifyuser and
 4356: lonnet::modify_student_enrollment
 4357: 
 4358: Inputs: 
 4359: 
 4360: =over 4
 4361: 
 4362: =item B<$udom> Students loncapa domain
 4363: 
 4364: =item B<$uname> Students loncapa login name
 4365: 
 4366: =item B<$uid> Students id/student number
 4367: 
 4368: =item B<$umode> Students authentication mode
 4369: 
 4370: =item B<$upass> Students password
 4371: 
 4372: =item B<$first> Students first name
 4373: 
 4374: =item B<$middle> Students middle name
 4375: 
 4376: =item B<$last> Students last name
 4377: 
 4378: =item B<$gene> Students generation
 4379: 
 4380: =item B<$usec> Students section in course
 4381: 
 4382: =item B<$end> Unix time of the roles expiration
 4383: 
 4384: =item B<$start> Unix time of the roles start date
 4385: 
 4386: =item B<$forceid> If defined, allow $uid to be changed
 4387: 
 4388: =item B<$desiredhome> server to use as home server for student
 4389: 
 4390: =back
 4391: 
 4392: =item *
 4393: 
 4394: modify_student_enrollment
 4395: 
 4396: Change a students enrollment status in a class.  The environment variable
 4397: 'role.request.course' must be defined for this function to proceed.
 4398: 
 4399: Inputs:
 4400: 
 4401: =over 4
 4402: 
 4403: =item $udom, students domain
 4404: 
 4405: =item $uname, students name
 4406: 
 4407: =item $uid, students user id
 4408: 
 4409: =item $first, students first name
 4410: 
 4411: =item $middle
 4412: 
 4413: =item $last
 4414: 
 4415: =item $gene
 4416: 
 4417: =item $usec
 4418: 
 4419: =item $end
 4420: 
 4421: =item $start
 4422: 
 4423: =back
 4424: 
 4425: 
 4426: =item *
 4427: 
 4428: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 4429: custom role; give a custom role to a user for the level given by URL.  Specify
 4430: name and domain of role author, and role name
 4431: 
 4432: =item *
 4433: 
 4434: revokerole($udom,$uname,$url,$role) : revoke a role for url
 4435: 
 4436: =item *
 4437: 
 4438: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 4439: 
 4440: =back
 4441: 
 4442: =head2 Course Infomation
 4443: 
 4444: =over 4
 4445: 
 4446: =item *
 4447: 
 4448: coursedescription($courseid) : course description
 4449: 
 4450: =item *
 4451: 
 4452: courseresdata($coursenum,$coursedomain,@which) : request for current
 4453: parameter setting for a specific course, @what should be a list of
 4454: parameters to ask about. This routine caches answers for 5 minutes.
 4455: 
 4456: =back
 4457: 
 4458: =head2 Course Modification
 4459: 
 4460: =over 4
 4461: 
 4462: =item *
 4463: 
 4464: writecoursepref($courseid,%prefs) : write preferences (environment
 4465: database) for a course
 4466: 
 4467: =item *
 4468: 
 4469: createcourse($udom,$description,$url) : make/modify course
 4470: 
 4471: =back
 4472: 
 4473: =head2 Resource Subroutines
 4474: 
 4475: =over 4
 4476: 
 4477: =item *
 4478: 
 4479: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 4480: 
 4481: =item *
 4482: 
 4483: repcopy($filename) : subscribes to the requested file, and attempts to
 4484: replicate from the owning library server, Might return
 4485: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 4486: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 4487: resource. Expects the local filesystem pathname
 4488: (/home/httpd/html/res/....)
 4489: 
 4490: =back
 4491: 
 4492: =head2 Resource Information
 4493: 
 4494: =over 4
 4495: 
 4496: =item *
 4497: 
 4498: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 4499: a vairety of different possible values, $varname should be a request
 4500: string, and the other parameters can be used to specify who and what
 4501: one is asking about.
 4502: 
 4503: Possible values for $varname are environment.lastname (or other item
 4504: from the envirnment hash), user.name (or someother aspect about the
 4505: user), resource.0.maxtries (or some other part and parameter of a
 4506: resource)
 4507: 
 4508: =item *
 4509: 
 4510: directcondval($number) : get current value of a condition; reads from a state
 4511: string
 4512: 
 4513: =item *
 4514: 
 4515: condval($condidx) : value of condition index based on state
 4516: 
 4517: =item *
 4518: 
 4519: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 4520: resource's metadata, $what should be either a specific key, or either
 4521: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 4522: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 4523: 
 4524: this function automatically caches all requests
 4525: 
 4526: =item *
 4527: 
 4528: metadata_query($query,$custom,$customshow) : make a metadata query against the
 4529: network of library servers; returns file handle of where SQL and regex results
 4530: will be stored for query
 4531: 
 4532: =item *
 4533: 
 4534: symbread($filename) : return symbolic list entry (filename argument optional);
 4535: returns the data handle
 4536: 
 4537: =item *
 4538: 
 4539: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 4540: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
 4541: failure, user must be in a course, as it assumes the existance of the
 4542: course initi hash, and uses $ENV('request.course.id'}
 4543: 
 4544: 
 4545: =item *
 4546: 
 4547: symbclean($symb) : removes versions numbers from a symb, returns the
 4548: cleaned symb
 4549: 
 4550: =item *
 4551: 
 4552: is_on_map($uri) : checks if the $uri is somewhere on the current
 4553: course map, user must be in a course for it to work.
 4554: 
 4555: =item *
 4556: 
 4557: numval($salt) : return random seed value (addend for rndseed)
 4558: 
 4559: =item *
 4560: 
 4561: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 4562: a random seed, all arguments are optional, if they aren't sent it uses the
 4563: environment to derive them. Note: if symb isn't sent and it can't get one
 4564: from &symbread it will use the current time as its return value
 4565: 
 4566: =item *
 4567: 
 4568: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 4569: unfakeable, receipt
 4570: 
 4571: =item *
 4572: 
 4573: receipt() : API to ireceipt working off of ENV values; given out to users
 4574: 
 4575: =item *
 4576: 
 4577: countacc($url) : count the number of accesses to a given URL
 4578: 
 4579: =item *
 4580: 
 4581: 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
 4582: 
 4583: =item *
 4584: 
 4585: 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)
 4586: 
 4587: =item *
 4588: 
 4589: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 4590: 
 4591: =item *
 4592: 
 4593: devalidate($symb) : devalidate temporary spreadsheet calculations,
 4594: forcing spreadsheet to reevaluate the resource scores next time.
 4595: 
 4596: =back
 4597: 
 4598: =head2 Storing/Retreiving Data
 4599: 
 4600: =over 4
 4601: 
 4602: =item *
 4603: 
 4604: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 4605: for this url; hashref needs to be given and should be a \%hashname; the
 4606: remaining args aren't required and if they aren't passed or are '' they will
 4607: be derived from the ENV
 4608: 
 4609: =item *
 4610: 
 4611: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 4612: uses critical subroutine
 4613: 
 4614: =item *
 4615: 
 4616: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 4617: all args are optional
 4618: 
 4619: =item *
 4620: 
 4621: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 4622: works very similar to store/cstore, but all data is stored in a
 4623: temporary location and can be reset using tmpreset, $storehash should
 4624: be a hash reference, returns nothing on success
 4625: 
 4626: =item *
 4627: 
 4628: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 4629: similar to restore, but all data is stored in a temporary location and
 4630: can be reset using tmpreset. Returns a hash of values on success,
 4631: error string otherwise.
 4632: 
 4633: =item *
 4634: 
 4635: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 4636: deltes all keys for $symb form the temporary storage hash.
 4637: 
 4638: =item *
 4639: 
 4640: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4641: reference filled in from namesp ($udom and $uname are optional)
 4642: 
 4643: =item *
 4644: 
 4645: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 4646: namesp ($udom and $uname are optional)
 4647: 
 4648: =item *
 4649: 
 4650: dump($namespace,$udom,$uname,$regexp) : 
 4651: dumps the complete (or key matching regexp) namespace into a hash
 4652: ($udom, $uname and $regexp are optional)
 4653: 
 4654: =item *
 4655: 
 4656: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 4657: ($udom and $uname are optional)
 4658: 
 4659: =item *
 4660: 
 4661: cput($namespace,$storehash,$udom,$uname) : critical put
 4662: ($udom and $uname are optional)
 4663: 
 4664: =item *
 4665: 
 4666: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4667: reference filled in from namesp (encrypts the return communication)
 4668: ($udom and $uname are optional)
 4669: 
 4670: =item *
 4671: 
 4672: log($udom,$name,$home,$message) : write to permanent log for user; use
 4673: critical subroutine
 4674: 
 4675: =back
 4676: 
 4677: =head2 Network Status Functions
 4678: 
 4679: =over 4
 4680: 
 4681: =item *
 4682: 
 4683: dirlist($uri) : return directory list based on URI
 4684: 
 4685: =item *
 4686: 
 4687: spareserver() : find server with least workload from spare.tab
 4688: 
 4689: =back
 4690: 
 4691: =head2 Apache Request
 4692: 
 4693: =over 4
 4694: 
 4695: =item *
 4696: 
 4697: ssi($url,%hash) : server side include, does a complete request cycle on url to
 4698: localhost, posts hash
 4699: 
 4700: =back
 4701: 
 4702: =head2 Data to String to Data
 4703: 
 4704: =over 4
 4705: 
 4706: =item *
 4707: 
 4708: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 4709: and '&' separators, supports elements that are arrayrefs and hashrefs
 4710: 
 4711: =item *
 4712: 
 4713: hashref2str($hashref) : convert a hashref into a string complete with
 4714: escaping and '=' and '&' separators, supports elements that are
 4715: arrayrefs and hashrefs
 4716: 
 4717: =item *
 4718: 
 4719: arrayref2str($arrayref) : convert an arrayref into a string complete
 4720: with escaping and '&' separators, supports elements that are arrayrefs
 4721: and hashrefs
 4722: 
 4723: =item *
 4724: 
 4725: str2hash($string) : convert string to hash using unescaping and
 4726: splitting on '=' and '&', supports elements that are arrayrefs and
 4727: hashrefs
 4728: 
 4729: =item *
 4730: 
 4731: str2array($string) : convert string to hash using unescaping and
 4732: splitting on '&', supports elements that are arrayrefs and hashrefs
 4733: 
 4734: =back
 4735: 
 4736: =head2 Logging Routines
 4737: 
 4738: =over 4
 4739: 
 4740: These routines allow one to make log messages in the lonnet.log and
 4741: lonnet.perm logfiles.
 4742: 
 4743: =item *
 4744: 
 4745: logtouch() : make sure the logfile, lonnet.log, exists
 4746: 
 4747: =item *
 4748: 
 4749: logthis() : append message to the normal lonnet.log file, it gets
 4750: preiodically rolled over and deleted.
 4751: 
 4752: =item *
 4753: 
 4754: logperm() : append a permanent message to lonnet.perm.log, this log
 4755: file never gets deleted by any automated portion of the system, only
 4756: messages of critical importance should go in here.
 4757: 
 4758: =back
 4759: 
 4760: =head2 General File Helper Routines
 4761: 
 4762: =over 4
 4763: 
 4764: =item *
 4765: 
 4766: getfile($file) : returns the entire contents of a file or -1; it
 4767: properly subscribes to and replicates the file if neccessary.
 4768: 
 4769: =item *
 4770: 
 4771: filelocation($dir,$file) : returns file system location of a file
 4772: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 4773: directory that relative $file lookups are to looked in ($dir of /a/dir
 4774: and a file of ../bob will become /a/bob)
 4775: 
 4776: =item *
 4777: 
 4778: hreflocation($dir,$file) : returns file system location or a URL; same as
 4779: filelocation except for hrefs
 4780: 
 4781: =item *
 4782: 
 4783: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 4784: 
 4785: =back
 4786: 
 4787: =head2 HTTP Helper Routines
 4788: 
 4789: =over 4
 4790: 
 4791: =item *
 4792: 
 4793: escape() : unpack non-word characters into CGI-compatible hex codes
 4794: 
 4795: =item *
 4796: 
 4797: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 4798: 
 4799: =back
 4800: 
 4801: =head1 PRIVATE SUBROUTINES
 4802: 
 4803: =head2 Underlying communication routines (Shouldn't call)
 4804: 
 4805: =over 4
 4806: 
 4807: =item *
 4808: 
 4809: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 4810: 
 4811: =item *
 4812: 
 4813: reply() : uses subreply to send a message to remote machine, logs all failures
 4814: 
 4815: =item *
 4816: 
 4817: critical() : passes a critical message to another server; if cannot
 4818: get through then place message in connection buffer directory and
 4819: returns con_delayed, if incapable of saving message, returns
 4820: con_failed
 4821: 
 4822: =item *
 4823: 
 4824: reconlonc() : tries to reconnect lonc client processes.
 4825: 
 4826: =back
 4827: 
 4828: =head2 Resource Access Logging
 4829: 
 4830: =over 4
 4831: 
 4832: =item *
 4833: 
 4834: flushcourselogs() : flush (save) buffer logs and access logs
 4835: 
 4836: =item *
 4837: 
 4838: courselog($what) : save message for course in hash
 4839: 
 4840: =item *
 4841: 
 4842: courseacclog($what) : save message for course using &courselog().  Perform
 4843: special processing for specific resource types (problems, exams, quizzes, etc).
 4844: 
 4845: =item *
 4846: 
 4847: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 4848: as a PerlChildExitHandler
 4849: 
 4850: =back
 4851: 
 4852: =head2 Other
 4853: 
 4854: =over 4
 4855: 
 4856: =item *
 4857: 
 4858: symblist($mapname,%newhash) : update symbolic storage links
 4859: 
 4860: =back
 4861: 
 4862: =cut

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