File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.480: download - view: text, annotated - select for diffs
Tue Mar 30 20:46:24 2004 UTC (20 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
* Store an encryption key in course environment, to be used for receipts
and eventually URL encryption
* Modify receipt algorithm 2 to use this key and also a stored key prefix.

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

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