File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.482: download - view: text, annotated - select for diffs
Thu Apr 1 14:55:18 2004 UTC (20 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- style police

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

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