File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.405: download - view: text, annotated - select for diffs
Mon Aug 25 17:20:09 2003 UTC (20 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- apache/mod_perl 2 now longer does us the favor of reinitiliazing ENV every request, so we need to delete all of the items we put in.

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

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