File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.498: download - view: text, annotated - select for diffs
Sun May 9 00:45:01 2004 UTC (20 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #2970: Key authority other than course possible

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

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