File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.520: download - view: text, annotated - select for diffs
Fri Jul 2 21:55:13 2004 UTC (20 years ago) by albertel
Branches: MAIN
CVS tags: version_1_1_99_1, HEAD
- stye police fixes, getting closer

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

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