File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.284: download - view: text, annotated - select for diffs
Tue Sep 17 19:45:11 2002 UTC (21 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Changes to fix handling of spare.tab.  Firstly, do not omit self from
spare.tab.  Secondly, compare load averages to self (initially) when
determining which server to offload onto.

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

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