File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.349: download - view: text, annotated - select for diffs
Mon Mar 24 18:18:09 2003 UTC (21 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug 764: Building reverse lookup database of user roles

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

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