File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.283: download - view: text, annotated - select for diffs
Mon Sep 16 20:09:47 2002 UTC (21 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Overload protection

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

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