File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.353: download - view: text, annotated - select for diffs
Wed Mar 26 04:57:04 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Additional work on pick-a-course function from reverse lookup. Does not work
yet, but getting there.

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

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