File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.542: download - view: text, annotated - select for diffs
Fri Sep 17 02:40:35 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- okay cache value returned by value passed in, fixes a visual problem in printing

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

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