File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.527: download - view: text, annotated - select for diffs
Mon Aug 23 15:23:53 2004 UTC (19 years, 10 months ago) by sakharuk
Branches: MAIN
CVS tags: HEAD
Bug 2259 (Printing of simplepages and aboutme doesn't work) is fixed. Any critical remarks are welcomed.

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

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