File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.363: download - view: text, annotated - select for diffs
Fri Apr 18 13:47:55 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Replace escaped colon

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

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