File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.329: download - view: text, annotated - select for diffs
Thu Feb 13 22:22:01 2003 UTC (21 years, 5 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Now define temp directory in lonnet.

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

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