File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.342: download - view: text, annotated - select for diffs
Wed Mar 19 16:50:14 2003 UTC (21 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Incorporate "role" into custom access rights

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

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