File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.537: download - view: text, annotated - select for diffs
Tue Aug 31 15:40:49 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- stylistic improvements

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

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