File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.545: download - view: text, annotated - select for diffs
Tue Sep 21 22:38:10 2004 UTC (19 years, 9 months ago) by banghart
Branches: MAIN
CVS tags: memcached, HEAD
	modify sub allowed to permit user to browse portfolio space

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

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