File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.425: download - view: text, annotated - select for diffs
Sat Oct 4 02:27:02 2003 UTC (20 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- trying to share cache data with other servers let me know if anything goes pear shaped
  (metacache is not converted because it looks like it is generally faster to parse the metadata  file, might be worthwhile to do a a metadata cache save at child exit and at child start up)

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

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