File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.453: download - view: text, annotated - select for diffs
Thu Dec 4 21:00:23 2003 UTC (20 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#2421, recursive metadata calss where throwing away the data (but not the keys) from the recursive call, modified it so that it looks more like the metadata call before the caching was modified,
- now restores the assumption that the lower metadata calls store their data into the same hash location as the calling metadata function, rather than a local hast that is then save into the cache.

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

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