File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.352: download - view: text, annotated - select for diffs
Tue Mar 25 22:03:23 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Reverse lookup course id database file.
/home/httpd/lonUsers/domain/nohist_courseids.db
Gets generated by lonnet::flushcourselogs
Includes courseid, description, and last access time
New commands in lond:
* courseidput - to write to this file
* courseiddump - to quere it
Not concerned about backward compatibility, since only used by
non-mission-critical functionality, and only called if server is updated
anyway. 'no_such_cmd' not a problem.

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

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