File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.492: download - view: text, annotated - select for diffs
Thu Apr 29 17:25:11 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- removing the tokenwrapper mechanism and shift to using httpref mode

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

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