File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.525: download - view: text, annotated - select for diffs
Thu Aug 5 16:59:29 2004 UTC (19 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#3270, speel thing was screwing up the ssi_body call

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

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