File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.452: download - view: text, annotated - select for diffs
Thu Dec 4 20:09:35 2003 UTC (20 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- the disk based caching is having issues, disabling it for now (BUG# 2417)

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.452 2003/12/04 20:09:35 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use 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: 	my %lcmetacache;
 3850:         if ($liburi) {
 3851: 	    $liburi=&declutter($liburi);
 3852:             $filename=$liburi;
 3853:         } else {
 3854: 	    &devalidate_cache(\%metacache,$uri,'meta');
 3855: 	}
 3856:         my %metathesekeys=();
 3857:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 3858: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
 3859:         my $parser=HTML::LCParser->new(\$metastring);
 3860:         my $token;
 3861:         undef %metathesekeys;
 3862:         while ($token=$parser->get_token) {
 3863: 	    if ($token->[0] eq 'S') {
 3864: 		if (defined($token->[2]->{'package'})) {
 3865: #
 3866: # This is a package - get package info
 3867: #
 3868: 		    my $package=$token->[2]->{'package'};
 3869: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3870: 		    if (defined($token->[2]->{'id'})) { 
 3871: 			$keyroot.='_'.$token->[2]->{'id'}; 
 3872: 		    }
 3873: 		    if ($lcmetacache{':packages'}) {
 3874: 			$lcmetacache{':packages'}.=','.$package.$keyroot;
 3875: 		    } else {
 3876: 			$lcmetacache{':packages'}=$package.$keyroot;
 3877: 		    }
 3878: 		    foreach (keys %packagetab) {
 3879: 			my $part=$keyroot;
 3880: 			$part=~s/^\_//;
 3881: 			if ($_=~/^\Q$package\E\&/ || 
 3882: 			    $_=~/^\Q$package\E_0\&/) {
 3883: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 3884: 			    # ignore package.tab specified default values
 3885:                             # here &package_tab_default() will fetch those
 3886: 			    if ($subp eq 'default') { next; }
 3887: 			    my $value=$packagetab{$_};
 3888: 			    my $unikey;
 3889: 			    if ($pack =~ /_0$/) {
 3890: 				$unikey='parameter_0_'.$name;
 3891: 				$part=0;
 3892: 			    } else {
 3893: 				$unikey='parameter'.$keyroot.'_'.$name;
 3894: 			    }
 3895: 			    if ($subp eq 'display') {
 3896: 				$value.=' [Part: '.$part.']';
 3897: 			    }
 3898: 			    $lcmetacache{':'.$unikey.'.part'}=$part;
 3899: 			    $metathesekeys{$unikey}=1;
 3900: 			    unless (defined($lcmetacache{':'.$unikey.'.'.$subp})) {
 3901: 				$lcmetacache{':'.$unikey.'.'.$subp}=$value;
 3902: 			    }
 3903: 			    if (defined($lcmetacache{':'.$unikey.'.default'})) {
 3904: 				$lcmetacache{':'.$unikey}=
 3905: 				    $lcmetacache{':'.$unikey.'.default'};
 3906: 			    }
 3907: 			}
 3908: 		    }
 3909: 		} else {
 3910: #
 3911: # This is not a package - some other kind of start tag
 3912: #
 3913: 		    my $entry=$token->[1];
 3914: 		    my $unikey;
 3915: 		    if ($entry eq 'import') {
 3916: 			$unikey='';
 3917: 		    } else {
 3918: 			$unikey=$entry;
 3919: 		    }
 3920: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3921: 
 3922: 		    if (defined($token->[2]->{'id'})) { 
 3923: 			$unikey.='_'.$token->[2]->{'id'}; 
 3924: 		    }
 3925: 
 3926: 		    if ($entry eq 'import') {
 3927: #
 3928: # Importing a library here
 3929: #
 3930: 			if ($depthcount<20) {
 3931: 			    my $location=$parser->get_text('/import');
 3932: 			    my $dir=$filename;
 3933: 			    $dir=~s|[^/]*$||;
 3934: 			    $location=&filelocation($dir,$location);
 3935: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 3936: 							       $location,$unikey,
 3937: 							       $depthcount+1)))) {
 3938: 				$metathesekeys{$_}=1;
 3939: 			    }
 3940: 			}
 3941: 		    } else { 
 3942: 			
 3943: 			if (defined($token->[2]->{'name'})) { 
 3944: 			    $unikey.='_'.$token->[2]->{'name'}; 
 3945: 			}
 3946: 			$metathesekeys{$unikey}=1;
 3947: 			foreach (@{$token->[3]}) {
 3948: 			    $lcmetacache{':'.$unikey.'.'.$_}=$token->[2]->{$_};
 3949: 			}
 3950: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 3951: 			my $default=$lcmetacache{':'.$unikey.'.default'};
 3952: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 3953: 		 # only ws inside the tag, and not in default, so use default
 3954: 		 # as value
 3955: 			    $lcmetacache{':'.$unikey}=$default;
 3956: 			} else {
 3957: 		  # either something interesting inside the tag or default
 3958:                   # uninteresting
 3959: 			    $lcmetacache{':'.$unikey}=$internaltext;
 3960: 			}
 3961: # end of not-a-package not-a-library import
 3962: 		    }
 3963: # end of not-a-package start tag
 3964: 		}
 3965: # the next is the end of "start tag"
 3966: 	    }
 3967: 	}
 3968: # are there custom rights to evaluate
 3969: 	if ($lcmetacache{':copyright'} eq 'custom') {
 3970: 
 3971:     #
 3972:     # Importing a rights file here
 3973:     #
 3974: 	    unless ($depthcount) {
 3975: 		my $location=$lcmetacache{':customdistributionfile'};
 3976: 		my $dir=$filename;
 3977: 		$dir=~s|[^/]*$||;
 3978: 		$location=&filelocation($dir,$location);
 3979: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 3980: 						   $location,'_rights',
 3981: 						   $depthcount+1)))) {
 3982: 		    $metathesekeys{$_}=1;
 3983: 		}
 3984: 	    }
 3985: 	}
 3986: 	$lcmetacache{':keys'}=join(',',keys %metathesekeys);
 3987: 	&metadata_generate_part0(\%metathesekeys,\%lcmetacache,$uri);
 3988: 	$lcmetacache{':allpossiblekeys'}=join(',',keys %metathesekeys);
 3989: 	&do_cache(\%metacache,$uri,\%lcmetacache,'meta');
 3990: # this is the end of "was not already recently cached
 3991:     }
 3992:     return $metacache{$uri}->{':'.$what};
 3993: }
 3994: 
 3995: sub metadata_generate_part0 {
 3996:     my ($metadata,$metacache,$uri) = @_;
 3997:     my %allnames;
 3998:     foreach my $metakey (sort keys %$metadata) {
 3999: 	if ($metakey=~/^parameter\_(.*)/) {
 4000: 	  my $part=$$metacache{':'.$metakey.'.part'};
 4001: 	  my $name=$$metacache{':'.$metakey.'.name'};
 4002: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 4003: 	    $allnames{$name}=$part;
 4004: 	  }
 4005: 	}
 4006:     }
 4007:     foreach my $name (keys(%allnames)) {
 4008:       $$metadata{"parameter_0_$name"}=1;
 4009:       my $key=":parameter_0_$name";
 4010:       $$metacache{"$key.part"}='0';
 4011:       $$metacache{"$key.name"}=$name;
 4012:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 4013: 					   $allnames{$name}.'_'.$name.
 4014: 					   '.type'};
 4015:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 4016: 			     '.display'};
 4017:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 4018:       $olddis=~s/$expr/\[Part: 0\]/;
 4019:       $$metacache{"$key.display"}=$olddis;
 4020:     }
 4021: }
 4022: 
 4023: # ------------------------------------------------- Get the title of a resource
 4024: 
 4025: sub gettitle {
 4026:     my $urlsymb=shift;
 4027:     my $symb=&symbread($urlsymb);
 4028:     unless ($symb) {
 4029: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
 4030:         return &metadata($urlsymb,'title'); 
 4031:     }
 4032:     my ($result,$cached)=&is_cached(\%titlecache,$symb,'title',600);
 4033:     if (defined($cached)) { return $result; }
 4034:     my ($map,$resid,$url)=&decode_symb($symb);
 4035:     my $title='';
 4036:     my %bighash;
 4037:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4038:                             &GDBM_READER(),0640)) {
 4039:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
 4040:         $title=$bighash{'title_'.$mapid.'.'.$resid};
 4041:         untie %bighash;
 4042:     }
 4043:     $title=~s/\&colon\;/\:/gs;
 4044:     if ($title) {
 4045:         return &do_cache(\%titlecache,$symb,$title,'title');
 4046:     } else {
 4047: 	return &metadata($urlsymb,'title');
 4048:     }
 4049: }
 4050:     
 4051: # ------------------------------------------------- Update symbolic store links
 4052: 
 4053: sub symblist {
 4054:     my ($mapname,%newhash)=@_;
 4055:     $mapname=&deversion(&declutter($mapname));
 4056:     my %hash;
 4057:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 4058:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 4059:                       &GDBM_WRCREAT(),0640)) {
 4060: 	    foreach (keys %newhash) {
 4061:                 $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_});
 4062:             }
 4063:             if (untie(%hash)) {
 4064: 		return 'ok';
 4065:             }
 4066:         }
 4067:     }
 4068:     return 'error';
 4069: }
 4070: 
 4071: # --------------------------------------------------------------- Verify a symb
 4072: 
 4073: sub symbverify {
 4074:     my ($symb,$thisfn)=@_;
 4075:     $thisfn=&declutter($thisfn);
 4076: # direct jump to resource in page or to a sequence - will construct own symbs
 4077:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 4078: # check URL part
 4079:     my ($map,$resid,$url)=&decode_symb($symb);
 4080: 
 4081:     unless ($url eq $thisfn) { return 0; }
 4082: 
 4083:     $symb=&symbclean($symb);
 4084:     $thisfn=&deversion($thisfn);
 4085: 
 4086:     my %bighash;
 4087:     my $okay=0;
 4088: 
 4089:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4090:                             &GDBM_READER(),0640)) {
 4091:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
 4092:         unless ($ids) { 
 4093:            $ids=$bighash{'ids_/'.$thisfn};
 4094:         }
 4095:         if ($ids) {
 4096: # ------------------------------------------------------------------- Has ID(s)
 4097: 	    foreach (split(/\,/,$ids)) {
 4098:                my ($mapid,$resid)=split(/\./,$_);
 4099:                if (
 4100:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 4101:    eq $symb) { 
 4102:                   $okay=1; 
 4103:                }
 4104: 	   }
 4105:         }
 4106: 	untie(%bighash);
 4107:     }
 4108:     return $okay;
 4109: }
 4110: 
 4111: # --------------------------------------------------------------- Clean-up symb
 4112: 
 4113: sub symbclean {
 4114:     my $symb=shift;
 4115: 
 4116: # remove version from map
 4117:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 4118: 
 4119: # remove version from URL
 4120:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 4121: 
 4122:     return $symb;
 4123: }
 4124: 
 4125: # ---------------------------------------------- Split symb to find map and url
 4126: 
 4127: sub encode_symb {
 4128:     my ($map,$resid,$url)=@_;
 4129:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 4130: }
 4131: 
 4132: sub decode_symb {
 4133:     my ($map,$resid,$url)=split(/\_\_\_/,shift);
 4134:     return (&fixversion($map),$resid,&fixversion($url));
 4135: }
 4136: 
 4137: sub fixversion {
 4138:     my $fn=shift;
 4139:     if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
 4140:     my %bighash;
 4141:     my $uri=&clutter($fn);
 4142:     my $key=$ENV{'request.course.id'}.'_'.$uri;
 4143: # is this cached?
 4144:     my ($result,$cached)=&is_cached(\%courseresversioncache,$key,
 4145: 				    'courseresversion',600);
 4146:     if (defined($cached)) { return $result; }
 4147: # unfortunately not cached, or expired
 4148:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4149: 	    &GDBM_READER(),0640)) {
 4150:  	if ($bighash{'version_'.$uri}) {
 4151:  	    my $version=$bighash{'version_'.$uri};
 4152:  	    unless (($version eq 'mostrecent') || 
 4153: 		    ($version==&getversion($uri))) {
 4154:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 4155:  	    }
 4156:  	}
 4157:  	untie %bighash;
 4158:     }
 4159:     return &do_cache
 4160: 	(\%courseresversioncache,$key,&declutter($uri),'courseresversion');
 4161: }
 4162: 
 4163: sub deversion {
 4164:     my $url=shift;
 4165:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 4166:     return $url;
 4167: }
 4168: 
 4169: # ------------------------------------------------------ Return symb list entry
 4170: 
 4171: sub symbread {
 4172:     my ($thisfn,$donotrecurse)=@_;
 4173: # no filename provided? try from environment
 4174:     unless ($thisfn) {
 4175:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
 4176: 	$thisfn=$ENV{'request.filename'};
 4177:     }
 4178: # is that filename actually a symb? Verify, clean, and return
 4179:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 4180: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
 4181:     }
 4182:     $thisfn=declutter($thisfn);
 4183:     my %hash;
 4184:     my %bighash;
 4185:     my $syval='';
 4186:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 4187:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 4188:                       &GDBM_READER(),0640)) {
 4189: 	    $syval=$hash{$thisfn};
 4190:             untie(%hash);
 4191:         }
 4192: # ---------------------------------------------------------- There was an entry
 4193:         if ($syval) {
 4194:            unless ($syval=~/\_\d+$/) {
 4195: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 4196:                   &appenv('request.ambiguous' => $thisfn);
 4197:                   return '';
 4198:                }    
 4199:                $syval.=$1;
 4200: 	   }
 4201:         } else {
 4202: # ------------------------------------------------------- Was not in symb table
 4203:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4204:                             &GDBM_READER(),0640)) {
 4205: # ---------------------------------------------- Get ID(s) for current resource
 4206:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 4207:               unless ($ids) { 
 4208:                  $ids=$bighash{'ids_/'.$thisfn};
 4209:               }
 4210:               unless ($ids) {
 4211: # alias?
 4212: 		  $ids=$bighash{'mapalias_'.$thisfn};
 4213:               }
 4214:               if ($ids) {
 4215: # ------------------------------------------------------------------- Has ID(s)
 4216:                  my @possibilities=split(/\,/,$ids);
 4217:                  if ($#possibilities==0) {
 4218: # ----------------------------------------------- There is only one possibility
 4219: 		     my ($mapid,$resid)=split(/\./,$ids);
 4220:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 4221:                  } elsif (!$donotrecurse) {
 4222: # ------------------------------------------ There is more than one possibility
 4223:                      my $realpossible=0;
 4224:                      foreach (@possibilities) {
 4225: 			 my $file=$bighash{'src_'.$_};
 4226:                          if (&allowed('bre',$file)) {
 4227:          		    my ($mapid,$resid)=split(/\./,$_);
 4228:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 4229: 				$realpossible++;
 4230:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 4231:                                        '___'.$resid;
 4232:                             }
 4233: 			 }
 4234:                      }
 4235: 		     if ($realpossible!=1) { $syval=''; }
 4236:                  } else {
 4237:                      $syval='';
 4238:                  }
 4239: 	      }
 4240:               untie(%bighash)
 4241:            } 
 4242:         }
 4243:         if ($syval) {
 4244:            return &symbclean($syval.'___'.$thisfn); 
 4245:         }
 4246:     }
 4247:     &appenv('request.ambiguous' => $thisfn);
 4248:     return '';
 4249: }
 4250: 
 4251: # ---------------------------------------------------------- Return random seed
 4252: 
 4253: sub numval {
 4254:     my $txt=shift;
 4255:     $txt=~tr/A-J/0-9/;
 4256:     $txt=~tr/a-j/0-9/;
 4257:     $txt=~tr/K-T/0-9/;
 4258:     $txt=~tr/k-t/0-9/;
 4259:     $txt=~tr/U-Z/0-5/;
 4260:     $txt=~tr/u-z/0-5/;
 4261:     $txt=~s/\D//g;
 4262:     return int($txt);
 4263: }
 4264: 
 4265: sub latest_rnd_algorithm_id {
 4266:     return '64bit2';
 4267: }
 4268: 
 4269: sub rndseed {
 4270:     my ($symb,$courseid,$domain,$username)=@_;
 4271: 
 4272:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 4273:     if (!$symb) {
 4274: 	unless ($symb=$wsymb) { return time; }
 4275:     }
 4276:     if (!$courseid) { $courseid=$wcourseid; }
 4277:     if (!$domain) { $domain=$wdomain; }
 4278:     if (!$username) { $username=$wusername }
 4279:     my $which=$ENV{"course.$courseid.rndseed"};
 4280:     my $CODE=$ENV{'scantron.CODE'};
 4281:     if (defined($CODE)) {
 4282: 	&rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 4283:     } elsif ($which eq '64bit2') {
 4284: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 4285:     } elsif ($which eq '64bit') {
 4286: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 4287:     }
 4288:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 4289: }
 4290: 
 4291: sub rndseed_32bit {
 4292:     my ($symb,$courseid,$domain,$username)=@_;
 4293:     {
 4294: 	use integer;
 4295: 	my $symbchck=unpack("%32C*",$symb) << 27;
 4296: 	my $symbseed=numval($symb) << 22;
 4297: 	my $namechck=unpack("%32C*",$username) << 17;
 4298: 	my $nameseed=numval($username) << 12;
 4299: 	my $domainseed=unpack("%32C*",$domain) << 7;
 4300: 	my $courseseed=unpack("%32C*",$courseid);
 4301: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 4302: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 4303: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 4304: 	return $num;
 4305:     }
 4306: }
 4307: 
 4308: sub rndseed_64bit {
 4309:     my ($symb,$courseid,$domain,$username)=@_;
 4310:     {
 4311: 	use integer;
 4312: 	my $symbchck=unpack("%32S*",$symb) << 21;
 4313: 	my $symbseed=numval($symb) << 10;
 4314: 	my $namechck=unpack("%32S*",$username);
 4315: 	
 4316: 	my $nameseed=numval($username) << 21;
 4317: 	my $domainseed=unpack("%32S*",$domain) << 10;
 4318: 	my $courseseed=unpack("%32S*",$courseid);
 4319: 	
 4320: 	my $num1=$symbchck+$symbseed+$namechck;
 4321: 	my $num2=$nameseed+$domainseed+$courseseed;
 4322: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 4323: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 4324: 	return "$num1,$num2";
 4325:     }
 4326: }
 4327: 
 4328: sub rndseed_64bit2 {
 4329:     my ($symb,$courseid,$domain,$username)=@_;
 4330:     {
 4331: 	use integer;
 4332: 	# strings need to be an even # of cahracters long, it it is odd the
 4333:         # last characters gets thrown away
 4334: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 4335: 	my $symbseed=numval($symb) << 10;
 4336: 	my $namechck=unpack("%32S*",$username.' ');
 4337: 	
 4338: 	my $nameseed=numval($username) << 21;
 4339: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 4340: 	my $courseseed=unpack("%32S*",$courseid.' ');
 4341: 	
 4342: 	my $num1=$symbchck+$symbseed+$namechck;
 4343: 	my $num2=$nameseed+$domainseed+$courseseed;
 4344: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 4345: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 4346: 	return "$num1,$num2";
 4347:     }
 4348: }
 4349: 
 4350: sub rndseed_CODE_64bit {
 4351:     my ($symb,$courseid,$domain,$username)=@_;
 4352:     {
 4353: 	use integer;
 4354: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 4355: 	my $symbseed=numval($symb);
 4356: 	my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
 4357: 	my $courseseed=unpack("%32S*",$courseid.' ');
 4358: 	my $num1=$symbseed+$CODEseed;
 4359: 	my $num2=$courseseed+$symbchck;
 4360: 	#&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
 4361: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 4362: 	return "$num1,$num2";
 4363:     }
 4364: }
 4365: 
 4366: sub setup_random_from_rndseed {
 4367:     my ($rndseed)=@_;
 4368:     if ($rndseed =~/,/) {
 4369: 	my ($num1,$num2)=split(/,/,$rndseed);
 4370: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 4371:     } else {
 4372: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 4373:     }
 4374: }
 4375: 
 4376: sub ireceipt {
 4377:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 4378:     my $cuname=unpack("%32C*",$funame);
 4379:     my $cudom=unpack("%32C*",$fudom);
 4380:     my $cucourseid=unpack("%32C*",$fucourseid);
 4381:     my $cusymb=unpack("%32C*",$fusymb);
 4382:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 4383:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 4384:            ($cunique%$cuname+
 4385:             $cunique%$cudom+
 4386:             $cusymb%$cuname+
 4387:             $cusymb%$cudom+
 4388:             $cucourseid%$cuname+
 4389:             $cucourseid%$cudom);
 4390: }
 4391: 
 4392: sub receipt {
 4393:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 4394:   return &ireceipt($name,$domain,$courseid,$symb);
 4395: }
 4396: 
 4397: # ------------------------------------------------------------ Serves up a file
 4398: # returns either the contents of the file or a -1
 4399: sub getfile {
 4400:  my $file=shift;
 4401:  if ($file=~/^\/*uploaded\//) { # user file
 4402:     my $ua=new LWP::UserAgent;
 4403:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
 4404:     my $response=$ua->request($request);
 4405:     if ($response->is_success()) {
 4406:        return $response->content;
 4407:     } else { 
 4408:        return -1; 
 4409:     }
 4410:  } else { # normal file from res space
 4411:   &repcopy($file);
 4412:   if (! -e $file ) { return -1; };
 4413:   my $fh;
 4414:   open($fh,"<$file");
 4415:   my $a='';
 4416:   while (<$fh>) { $a .=$_; }
 4417:   return $a;
 4418:  }
 4419: }
 4420: 
 4421: sub filelocation {
 4422:   my ($dir,$file) = @_;
 4423:   my $location;
 4424:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 4425:   if ($file=~m:^/~:) { # is a contruction space reference
 4426:     $location = $file;
 4427:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 4428:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 4429:     $location=$file;
 4430:   } else {
 4431:     $file=~s/^$perlvar{'lonDocRoot'}//;
 4432:     $file=~s:^/*res::;
 4433:     if ( !( $file =~ m:^/:) ) {
 4434:       $location = $dir. '/'.$file;
 4435:     } else {
 4436:       $location = '/home/httpd/html/res'.$file;
 4437:     }
 4438:   }
 4439:   $location=~s://+:/:g; # remove duplicate /
 4440:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 4441:   return $location;
 4442: }
 4443: 
 4444: sub hreflocation {
 4445:     my ($dir,$file)=@_;
 4446:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 4447:        my $finalpath=filelocation($dir,$file);
 4448:        $finalpath=~s/^\/home\/httpd\/html//;
 4449:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
 4450:        return $finalpath;
 4451:     } else {
 4452:        return $file;
 4453:     }
 4454: }
 4455: 
 4456: # ------------------------------------------------------------- Declutters URLs
 4457: 
 4458: sub declutter {
 4459:     my $thisfn=shift;
 4460:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 4461:     $thisfn=~s/^\///;
 4462:     $thisfn=~s/^res\///;
 4463:     $thisfn=~s/\?.+$//;
 4464:     return $thisfn;
 4465: }
 4466: 
 4467: # ------------------------------------------------------------- Clutter up URLs
 4468: 
 4469: sub clutter {
 4470:     my $thisfn='/'.&declutter(shift);
 4471:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
 4472:        $thisfn='/res'.$thisfn; 
 4473:     }
 4474:     return $thisfn;
 4475: }
 4476: 
 4477: # -------------------------------------------------------- Escape Special Chars
 4478: 
 4479: sub escape {
 4480:     my $str=shift;
 4481:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 4482:     return $str;
 4483: }
 4484: 
 4485: # ----------------------------------------------------- Un-Escape Special Chars
 4486: 
 4487: sub unescape {
 4488:     my $str=shift;
 4489:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4490:     return $str;
 4491: }
 4492: 
 4493: sub mod_perl_version {
 4494:     if (defined($perlvar{'MODPERL2'})) {
 4495: 	return 2;
 4496:     }
 4497:     return 1;
 4498: }
 4499: 
 4500: sub correct_line_ends {
 4501:     my ($result)=@_;
 4502:     $$result =~s/\r\n/\n/mg;
 4503:     $$result =~s/\r/\n/mg;
 4504: }
 4505: # ================================================================ Main Program
 4506: 
 4507: sub goodbye {
 4508:    &logthis("Starting Shut down");
 4509: #not converted to using infrastruture and probably shouldn't be
 4510:    &logthis(sprintf("%-20s is %s",'%badServerCache',scalar(%badServerCache)));
 4511: #converted
 4512:    &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 4513:    &logthis(sprintf("%-20s is %s",'%homecache',scalar(%homecache)));
 4514:    &logthis(sprintf("%-20s is %s",'%titlecache',scalar(%titlecache)));
 4515:    &logthis(sprintf("%-20s is %s",'%courseresdatacache',scalar(%courseresdatacache)));
 4516: #1.1 only
 4517:    &logthis(sprintf("%-20s is %s",'%userresdatacache',scalar(%userresdatacache)));
 4518:    &logthis(sprintf("%-20s is %s",'%usectioncache',scalar(%usectioncache)));
 4519:    &logthis(sprintf("%-20s is %s",'%courseresversioncache',scalar(%courseresversioncache)));
 4520:    &logthis(sprintf("%-20s is %s",'%resversioncache',scalar(%resversioncache)));
 4521:    &flushcourselogs();
 4522:    &logthis("Shutting down");
 4523:    return DONE;
 4524: }
 4525: 
 4526: BEGIN {
 4527: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 4528:     unless ($readit) {
 4529: {
 4530:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 4531: 
 4532:     while (my $configline=<$config>) {
 4533:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4534: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4535:            chomp($varvalue);
 4536:            $perlvar{$varname}=$varvalue;
 4537:         }
 4538:     }
 4539:     close($config);
 4540: }
 4541: {
 4542:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 4543: 
 4544:     while (my $configline=<$config>) {
 4545:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4546: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4547:            chomp($varvalue);
 4548:            $perlvar{$varname}=$varvalue;
 4549:         }
 4550:     }
 4551:     close($config);
 4552: }
 4553: 
 4554: # ------------------------------------------------------------ Read domain file
 4555: {
 4556:     %domaindescription = ();
 4557:     %domain_auth_def = ();
 4558:     %domain_auth_arg_def = ();
 4559:     my $fh;
 4560:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 4561:        while (<$fh>) {
 4562:            next if (/^(\#|\s*$)/);
 4563: #           next if /^\#/;
 4564:            chomp;
 4565:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 4566: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
 4567: 	   $domain_auth_def{$domain}=$def_auth;
 4568:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 4569: 	   $domaindescription{$domain}=$domain_description;
 4570: 	   $domain_lang_def{$domain}=$def_lang;
 4571: 	   $domain_city{$domain}=$city;
 4572: 	   $domain_longi{$domain}=$longi;
 4573: 	   $domain_lati{$domain}=$lati;
 4574: 
 4575:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 4576: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 4577: 	}
 4578:     }
 4579:     close ($fh);
 4580: }
 4581: 
 4582: 
 4583: # ------------------------------------------------------------- Read hosts file
 4584: {
 4585:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 4586: 
 4587:     while (my $configline=<$config>) {
 4588:        next if ($configline =~ /^(\#|\s*$)/);
 4589:        chomp($configline);
 4590:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 4591:        if ($id && $domain && $role && $name && $ip) {
 4592: 	 $hostname{$id}=$name;
 4593: 	 $hostdom{$id}=$domain;
 4594: 	 $hostip{$id}=$ip;
 4595: 	 $iphost{$ip}=$id;
 4596: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 4597:        } else {
 4598: 	 if ($configline) {
 4599: 	   &logthis("Skipping hosts.tab line -$configline-");
 4600: 	 }
 4601:        }
 4602:     }
 4603:     close($config);
 4604: }
 4605: 
 4606: # ------------------------------------------------------ Read spare server file
 4607: {
 4608:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 4609: 
 4610:     while (my $configline=<$config>) {
 4611:        chomp($configline);
 4612:        if ($configline) {
 4613:           $spareid{$configline}=1;
 4614:        }
 4615:     }
 4616:     close($config);
 4617: }
 4618: # ------------------------------------------------------------ Read permissions
 4619: {
 4620:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 4621: 
 4622:     while (my $configline=<$config>) {
 4623: 	chomp($configline);
 4624: 	if ($configline) {
 4625: 	    my ($role,$perm)=split(/ /,$configline);
 4626: 	    if ($perm ne '') { $pr{$role}=$perm; }
 4627: 	}
 4628:     }
 4629:     close($config);
 4630: }
 4631: 
 4632: # -------------------------------------------- Read plain texts for permissions
 4633: {
 4634:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 4635: 
 4636:     while (my $configline=<$config>) {
 4637: 	chomp($configline);
 4638: 	if ($configline) {
 4639: 	    my ($short,$plain)=split(/:/,$configline);
 4640: 	    if ($plain ne '') { $prp{$short}=$plain; }
 4641: 	}
 4642:     }
 4643:     close($config);
 4644: }
 4645: 
 4646: # ---------------------------------------------------------- Read package table
 4647: {
 4648:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 4649: 
 4650:     while (my $configline=<$config>) {
 4651: 	chomp($configline);
 4652: 	my ($short,$plain)=split(/:/,$configline);
 4653: 	my ($pack,$name)=split(/\&/,$short);
 4654: 	if ($plain ne '') {
 4655: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 4656: 	    $packagetab{$short}=$plain; 
 4657: 	}
 4658:     }
 4659:     close($config);
 4660: }
 4661: 
 4662: # ------------- set up temporary directory
 4663: {
 4664:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 4665: 
 4666: }
 4667: 
 4668: %metacache=();
 4669: 
 4670: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 4671: $dumpcount=0;
 4672: 
 4673: &logtouch();
 4674: &logthis('<font color=yellow>INFO: Read configuration</font>');
 4675: $readit=1;
 4676: }
 4677: }
 4678: 
 4679: 1;
 4680: __END__
 4681: 
 4682: =pod
 4683: 
 4684: =head1 NAME
 4685: 
 4686: Apache::lonnet - Subroutines to ask questions about things in the network.
 4687: 
 4688: =head1 SYNOPSIS
 4689: 
 4690: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 4691: 
 4692:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 4693: 
 4694: Common parameters:
 4695: 
 4696: =over 4
 4697: 
 4698: =item *
 4699: 
 4700: $uname : an internal username (if $cname expecting a course Id specifically)
 4701: 
 4702: =item *
 4703: 
 4704: $udom : a domain (if $cdom expecting a course's domain specifically)
 4705: 
 4706: =item *
 4707: 
 4708: $symb : a resource instance identifier
 4709: 
 4710: =item *
 4711: 
 4712: $namespace : the name of a .db file that contains the data needed or
 4713: being set.
 4714: 
 4715: =back
 4716: 
 4717: =head1 OVERVIEW
 4718: 
 4719: lonnet provides subroutines which interact with the
 4720: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 4721: about classes, users, and resources.
 4722: 
 4723: For many of these objects you can also use this to store data about
 4724: them or modify them in various ways.
 4725: 
 4726: =head2 Symbs
 4727: 
 4728: To identify a specific instance of a resource, LON-CAPA uses symbols
 4729: or "symbs"X<symb>. These identifiers are built from the URL of the
 4730: map, the resource number of the resource in the map, and the URL of
 4731: the resource itself. The latter is somewhat redundant, but might help
 4732: if maps change.
 4733: 
 4734: An example is
 4735: 
 4736:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 4737: 
 4738: The respective map entry is
 4739: 
 4740:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 4741:   title="Problem 2">
 4742:  </resource>
 4743: 
 4744: Symbs are used by the random number generator, as well as to store and
 4745: restore data specific to a certain instance of for example a problem.
 4746: 
 4747: =head2 Storing And Retrieving Data
 4748: 
 4749: X<store()>X<cstore()>X<restore()>Three of the most important functions
 4750: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 4751: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 4752: is is the non-critical message twin of cstore. These functions are for
 4753: handlers to store a perl hash to a user's permanent data space in an
 4754: easy manner, and to retrieve it again on another call. It is expected
 4755: that a handler would use this once at the beginning to retrieve data,
 4756: and then again once at the end to send only the new data back.
 4757: 
 4758: The data is stored in the user's data directory on the user's
 4759: homeserver under the ID of the course.
 4760: 
 4761: The hash that is returned by restore will have all of the previous
 4762: value for all of the elements of the hash.
 4763: 
 4764: Example:
 4765: 
 4766:  #creating a hash
 4767:  my %hash;
 4768:  $hash{'foo'}='bar';
 4769: 
 4770:  #storing it
 4771:  &Apache::lonnet::cstore(\%hash);
 4772: 
 4773:  #changing a value
 4774:  $hash{'foo'}='notbar';
 4775: 
 4776:  #adding a new value
 4777:  $hash{'bar'}='foo';
 4778:  &Apache::lonnet::cstore(\%hash);
 4779: 
 4780:  #retrieving the hash
 4781:  my %history=&Apache::lonnet::restore();
 4782: 
 4783:  #print the hash
 4784:  foreach my $key (sort(keys(%history))) {
 4785:    print("\%history{$key} = $history{$key}");
 4786:  }
 4787: 
 4788: Will print out:
 4789: 
 4790:  %history{1:foo} = bar
 4791:  %history{1:keys} = foo:timestamp
 4792:  %history{1:timestamp} = 990455579
 4793:  %history{2:bar} = foo
 4794:  %history{2:foo} = notbar
 4795:  %history{2:keys} = foo:bar:timestamp
 4796:  %history{2:timestamp} = 990455580
 4797:  %history{bar} = foo
 4798:  %history{foo} = notbar
 4799:  %history{timestamp} = 990455580
 4800:  %history{version} = 2
 4801: 
 4802: Note that the special hash entries C<keys>, C<version> and
 4803: C<timestamp> were added to the hash. C<version> will be equal to the
 4804: total number of versions of the data that have been stored. The
 4805: C<timestamp> attribute will be the UNIX time the hash was
 4806: stored. C<keys> is available in every historical section to list which
 4807: keys were added or changed at a specific historical revision of a
 4808: hash.
 4809: 
 4810: B<Warning>: do not store the hash that restore returns directly. This
 4811: will cause a mess since it will restore the historical keys as if the
 4812: were new keys. I.E. 1:foo will become 1:1:foo etc.
 4813: 
 4814: Calling convention:
 4815: 
 4816:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 4817:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 4818: 
 4819: For more detailed information, see lonnet specific documentation.
 4820: 
 4821: =head1 RETURN MESSAGES
 4822: 
 4823: =over 4
 4824: 
 4825: =item * B<con_lost>: unable to contact remote host
 4826: 
 4827: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 4828: when the connection is brought back up
 4829: 
 4830: =item * B<con_failed>: unable to contact remote host and unable to save message
 4831: for later delivery
 4832: 
 4833: =item * B<error:>: an error a occured, a description of the error follows the :
 4834: 
 4835: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 4836: that was requested
 4837: 
 4838: =back
 4839: 
 4840: =head1 PUBLIC SUBROUTINES
 4841: 
 4842: =head2 Session Environment Functions
 4843: 
 4844: =over 4
 4845: 
 4846: =item * 
 4847: X<appenv()>
 4848: B<appenv(%hash)>: the value of %hash is written to
 4849: the user envirnoment file, and will be restored for each access this
 4850: user makes during this session, also modifies the %ENV for the current
 4851: process
 4852: 
 4853: =item *
 4854: X<delenv()>
 4855: B<delenv($regexp)>: removes all items from the session
 4856: environment file that matches the regular expression in $regexp. The
 4857: values are also delted from the current processes %ENV.
 4858: 
 4859: =back
 4860: 
 4861: =head2 User Information
 4862: 
 4863: =over 4
 4864: 
 4865: =item *
 4866: X<queryauthenticate()>
 4867: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 4868: authentication scheme
 4869: 
 4870: =item *
 4871: X<authenticate()>
 4872: B<authenticate($uname,$upass,$udom)>: try to
 4873: authenticate user from domain's lib servers (first use the current
 4874: one). C<$upass> should be the users password.
 4875: 
 4876: =item *
 4877: X<homeserver()>
 4878: B<homeserver($uname,$udom)>: find the server which has
 4879: the user's directory and files (there must be only one), this caches
 4880: the answer, and also caches if there is a borken connection.
 4881: 
 4882: =item *
 4883: X<idget()>
 4884: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 4885: (IDs are a unique resource in a domain, there must be only 1 ID per
 4886: username, and only 1 username per ID in a specific domain) (returns
 4887: hash: id=>name,id=>name)
 4888: 
 4889: =item *
 4890: X<idrget()>
 4891: B<idrget($udom,@unames)>: find the IDs behind a list of
 4892: usernames (returns hash: name=>id,name=>id)
 4893: 
 4894: =item *
 4895: X<idput()>
 4896: B<idput($udom,%ids)>: store away a list of names and associated IDs
 4897: 
 4898: =item *
 4899: X<rolesinit()>
 4900: B<rolesinit($udom,$username,$authhost)>: get user privileges
 4901: 
 4902: =item *
 4903: X<usection()>
 4904: B<usection($udom,$uname,$cname)>: finds the section of student in the
 4905: course $cname, return section name/number or '' for "not in course"
 4906: and '-1' for "no section"
 4907: 
 4908: =item *
 4909: X<userenvironment()>
 4910: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 4911: passed in @what from the requested user's environment, returns a hash
 4912: 
 4913: =back
 4914: 
 4915: =head2 User Roles
 4916: 
 4917: =over 4
 4918: 
 4919: =item *
 4920: 
 4921: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 4922: actions
 4923:  F: full access
 4924:  U,I,K: authentication modes (cxx only)
 4925:  '': forbidden
 4926:  1: user needs to choose course
 4927:  2: browse allowed
 4928: 
 4929: =item *
 4930: 
 4931: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 4932: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 4933: and course level
 4934: 
 4935: =item *
 4936: 
 4937: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 4938: explanation of a user role term
 4939: 
 4940: =back
 4941: 
 4942: =head2 User Modification
 4943: 
 4944: =over 4
 4945: 
 4946: =item *
 4947: 
 4948: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 4949: user for the level given by URL.  Optional start and end dates (leave empty
 4950: string or zero for "no date")
 4951: 
 4952: =item *
 4953: 
 4954: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 4955: change a users, password, possible return values are: ok,
 4956: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 4957: refused
 4958: 
 4959: =item *
 4960: 
 4961: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 4962: 
 4963: =item *
 4964: 
 4965: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 4966: modify user
 4967: 
 4968: =item *
 4969: 
 4970: modifystudent
 4971: 
 4972: modify a students enrollment and identification information.
 4973: The course id is resolved based on the current users environment.  
 4974: This means the envoking user must be a course coordinator or otherwise
 4975: associated with a course.
 4976: 
 4977: This call is essentially a wrapper for lonnet::modifyuser and
 4978: lonnet::modify_student_enrollment
 4979: 
 4980: Inputs: 
 4981: 
 4982: =over 4
 4983: 
 4984: =item B<$udom> Students loncapa domain
 4985: 
 4986: =item B<$uname> Students loncapa login name
 4987: 
 4988: =item B<$uid> Students id/student number
 4989: 
 4990: =item B<$umode> Students authentication mode
 4991: 
 4992: =item B<$upass> Students password
 4993: 
 4994: =item B<$first> Students first name
 4995: 
 4996: =item B<$middle> Students middle name
 4997: 
 4998: =item B<$last> Students last name
 4999: 
 5000: =item B<$gene> Students generation
 5001: 
 5002: =item B<$usec> Students section in course
 5003: 
 5004: =item B<$end> Unix time of the roles expiration
 5005: 
 5006: =item B<$start> Unix time of the roles start date
 5007: 
 5008: =item B<$forceid> If defined, allow $uid to be changed
 5009: 
 5010: =item B<$desiredhome> server to use as home server for student
 5011: 
 5012: =back
 5013: 
 5014: =item *
 5015: 
 5016: modify_student_enrollment
 5017: 
 5018: Change a students enrollment status in a class.  The environment variable
 5019: 'role.request.course' must be defined for this function to proceed.
 5020: 
 5021: Inputs:
 5022: 
 5023: =over 4
 5024: 
 5025: =item $udom, students domain
 5026: 
 5027: =item $uname, students name
 5028: 
 5029: =item $uid, students user id
 5030: 
 5031: =item $first, students first name
 5032: 
 5033: =item $middle
 5034: 
 5035: =item $last
 5036: 
 5037: =item $gene
 5038: 
 5039: =item $usec
 5040: 
 5041: =item $end
 5042: 
 5043: =item $start
 5044: 
 5045: =back
 5046: 
 5047: 
 5048: =item *
 5049: 
 5050: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 5051: custom role; give a custom role to a user for the level given by URL.  Specify
 5052: name and domain of role author, and role name
 5053: 
 5054: =item *
 5055: 
 5056: revokerole($udom,$uname,$url,$role) : revoke a role for url
 5057: 
 5058: =item *
 5059: 
 5060: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 5061: 
 5062: =back
 5063: 
 5064: =head2 Course Infomation
 5065: 
 5066: =over 4
 5067: 
 5068: =item *
 5069: 
 5070: coursedescription($courseid) : course description
 5071: 
 5072: =item *
 5073: 
 5074: courseresdata($coursenum,$coursedomain,@which) : request for current
 5075: parameter setting for a specific course, @what should be a list of
 5076: parameters to ask about. This routine caches answers for 5 minutes.
 5077: 
 5078: =back
 5079: 
 5080: =head2 Course Modification
 5081: 
 5082: =over 4
 5083: 
 5084: =item *
 5085: 
 5086: writecoursepref($courseid,%prefs) : write preferences (environment
 5087: database) for a course
 5088: 
 5089: =item *
 5090: 
 5091: createcourse($udom,$description,$url) : make/modify course
 5092: 
 5093: =back
 5094: 
 5095: =head2 Resource Subroutines
 5096: 
 5097: =over 4
 5098: 
 5099: =item *
 5100: 
 5101: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 5102: 
 5103: =item *
 5104: 
 5105: repcopy($filename) : subscribes to the requested file, and attempts to
 5106: replicate from the owning library server, Might return
 5107: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 5108: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 5109: resource. Expects the local filesystem pathname
 5110: (/home/httpd/html/res/....)
 5111: 
 5112: =back
 5113: 
 5114: =head2 Resource Information
 5115: 
 5116: =over 4
 5117: 
 5118: =item *
 5119: 
 5120: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 5121: a vairety of different possible values, $varname should be a request
 5122: string, and the other parameters can be used to specify who and what
 5123: one is asking about.
 5124: 
 5125: Possible values for $varname are environment.lastname (or other item
 5126: from the envirnment hash), user.name (or someother aspect about the
 5127: user), resource.0.maxtries (or some other part and parameter of a
 5128: resource)
 5129: 
 5130: =item *
 5131: 
 5132: directcondval($number) : get current value of a condition; reads from a state
 5133: string
 5134: 
 5135: =item *
 5136: 
 5137: condval($condidx) : value of condition index based on state
 5138: 
 5139: =item *
 5140: 
 5141: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 5142: resource's metadata, $what should be either a specific key, or either
 5143: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 5144: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 5145: 
 5146: this function automatically caches all requests
 5147: 
 5148: =item *
 5149: 
 5150: metadata_query($query,$custom,$customshow) : make a metadata query against the
 5151: network of library servers; returns file handle of where SQL and regex results
 5152: will be stored for query
 5153: 
 5154: =item *
 5155: 
 5156: symbread($filename) : return symbolic list entry (filename argument optional);
 5157: returns the data handle
 5158: 
 5159: =item *
 5160: 
 5161: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 5162: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
 5163: failure, user must be in a course, as it assumes the existance of the
 5164: course initi hash, and uses $ENV('request.course.id'}
 5165: 
 5166: 
 5167: =item *
 5168: 
 5169: symbclean($symb) : removes versions numbers from a symb, returns the
 5170: cleaned symb
 5171: 
 5172: =item *
 5173: 
 5174: is_on_map($uri) : checks if the $uri is somewhere on the current
 5175: course map, user must be in a course for it to work.
 5176: 
 5177: =item *
 5178: 
 5179: numval($salt) : return random seed value (addend for rndseed)
 5180: 
 5181: =item *
 5182: 
 5183: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 5184: a random seed, all arguments are optional, if they aren't sent it uses the
 5185: environment to derive them. Note: if symb isn't sent and it can't get one
 5186: from &symbread it will use the current time as its return value
 5187: 
 5188: =item *
 5189: 
 5190: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 5191: unfakeable, receipt
 5192: 
 5193: =item *
 5194: 
 5195: receipt() : API to ireceipt working off of ENV values; given out to users
 5196: 
 5197: =item *
 5198: 
 5199: countacc($url) : count the number of accesses to a given URL
 5200: 
 5201: =item *
 5202: 
 5203: 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
 5204: 
 5205: =item *
 5206: 
 5207: 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)
 5208: 
 5209: =item *
 5210: 
 5211: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 5212: 
 5213: =item *
 5214: 
 5215: devalidate($symb) : devalidate temporary spreadsheet calculations,
 5216: forcing spreadsheet to reevaluate the resource scores next time.
 5217: 
 5218: =back
 5219: 
 5220: =head2 Storing/Retreiving Data
 5221: 
 5222: =over 4
 5223: 
 5224: =item *
 5225: 
 5226: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 5227: for this url; hashref needs to be given and should be a \%hashname; the
 5228: remaining args aren't required and if they aren't passed or are '' they will
 5229: be derived from the ENV
 5230: 
 5231: =item *
 5232: 
 5233: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 5234: uses critical subroutine
 5235: 
 5236: =item *
 5237: 
 5238: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 5239: all args are optional
 5240: 
 5241: =item *
 5242: 
 5243: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 5244: works very similar to store/cstore, but all data is stored in a
 5245: temporary location and can be reset using tmpreset, $storehash should
 5246: be a hash reference, returns nothing on success
 5247: 
 5248: =item *
 5249: 
 5250: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 5251: similar to restore, but all data is stored in a temporary location and
 5252: can be reset using tmpreset. Returns a hash of values on success,
 5253: error string otherwise.
 5254: 
 5255: =item *
 5256: 
 5257: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 5258: deltes all keys for $symb form the temporary storage hash.
 5259: 
 5260: =item *
 5261: 
 5262: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 5263: reference filled in from namesp ($udom and $uname are optional)
 5264: 
 5265: =item *
 5266: 
 5267: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 5268: namesp ($udom and $uname are optional)
 5269: 
 5270: =item *
 5271: 
 5272: dump($namespace,$udom,$uname,$regexp) : 
 5273: dumps the complete (or key matching regexp) namespace into a hash
 5274: ($udom, $uname and $regexp are optional)
 5275: 
 5276: =item *
 5277: 
 5278: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 5279: $store can be a scalar, an array reference, or if the amount to be 
 5280: incremented is > 1, a hash reference.
 5281: 
 5282: ($udom and $uname are optional)
 5283: 
 5284: =item *
 5285: 
 5286: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 5287: ($udom and $uname are optional)
 5288: 
 5289: =item *
 5290: 
 5291: cput($namespace,$storehash,$udom,$uname) : critical put
 5292: ($udom and $uname are optional)
 5293: 
 5294: =item *
 5295: 
 5296: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 5297: reference filled in from namesp (encrypts the return communication)
 5298: ($udom and $uname are optional)
 5299: 
 5300: =item *
 5301: 
 5302: log($udom,$name,$home,$message) : write to permanent log for user; use
 5303: critical subroutine
 5304: 
 5305: =back
 5306: 
 5307: =head2 Network Status Functions
 5308: 
 5309: =over 4
 5310: 
 5311: =item *
 5312: 
 5313: dirlist($uri) : return directory list based on URI
 5314: 
 5315: =item *
 5316: 
 5317: spareserver() : find server with least workload from spare.tab
 5318: 
 5319: =back
 5320: 
 5321: =head2 Apache Request
 5322: 
 5323: =over 4
 5324: 
 5325: =item *
 5326: 
 5327: ssi($url,%hash) : server side include, does a complete request cycle on url to
 5328: localhost, posts hash
 5329: 
 5330: =back
 5331: 
 5332: =head2 Data to String to Data
 5333: 
 5334: =over 4
 5335: 
 5336: =item *
 5337: 
 5338: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 5339: and '&' separators, supports elements that are arrayrefs and hashrefs
 5340: 
 5341: =item *
 5342: 
 5343: hashref2str($hashref) : convert a hashref into a string complete with
 5344: escaping and '=' and '&' separators, supports elements that are
 5345: arrayrefs and hashrefs
 5346: 
 5347: =item *
 5348: 
 5349: arrayref2str($arrayref) : convert an arrayref into a string complete
 5350: with escaping and '&' separators, supports elements that are arrayrefs
 5351: and hashrefs
 5352: 
 5353: =item *
 5354: 
 5355: str2hash($string) : convert string to hash using unescaping and
 5356: splitting on '=' and '&', supports elements that are arrayrefs and
 5357: hashrefs
 5358: 
 5359: =item *
 5360: 
 5361: str2array($string) : convert string to hash using unescaping and
 5362: splitting on '&', supports elements that are arrayrefs and hashrefs
 5363: 
 5364: =back
 5365: 
 5366: =head2 Logging Routines
 5367: 
 5368: =over 4
 5369: 
 5370: These routines allow one to make log messages in the lonnet.log and
 5371: lonnet.perm logfiles.
 5372: 
 5373: =item *
 5374: 
 5375: logtouch() : make sure the logfile, lonnet.log, exists
 5376: 
 5377: =item *
 5378: 
 5379: logthis() : append message to the normal lonnet.log file, it gets
 5380: preiodically rolled over and deleted.
 5381: 
 5382: =item *
 5383: 
 5384: logperm() : append a permanent message to lonnet.perm.log, this log
 5385: file never gets deleted by any automated portion of the system, only
 5386: messages of critical importance should go in here.
 5387: 
 5388: =back
 5389: 
 5390: =head2 General File Helper Routines
 5391: 
 5392: =over 4
 5393: 
 5394: =item *
 5395: 
 5396: getfile($file) : returns the entire contents of a file or -1; it
 5397: properly subscribes to and replicates the file if neccessary.
 5398: 
 5399: =item *
 5400: 
 5401: filelocation($dir,$file) : returns file system location of a file
 5402: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 5403: directory that relative $file lookups are to looked in ($dir of /a/dir
 5404: and a file of ../bob will become /a/bob)
 5405: 
 5406: =item *
 5407: 
 5408: hreflocation($dir,$file) : returns file system location or a URL; same as
 5409: filelocation except for hrefs
 5410: 
 5411: =item *
 5412: 
 5413: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 5414: 
 5415: =back
 5416: 
 5417: =head2 HTTP Helper Routines
 5418: 
 5419: =over 4
 5420: 
 5421: =item *
 5422: 
 5423: escape() : unpack non-word characters into CGI-compatible hex codes
 5424: 
 5425: =item *
 5426: 
 5427: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 5428: 
 5429: =back
 5430: 
 5431: =head1 PRIVATE SUBROUTINES
 5432: 
 5433: =head2 Underlying communication routines (Shouldn't call)
 5434: 
 5435: =over 4
 5436: 
 5437: =item *
 5438: 
 5439: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 5440: 
 5441: =item *
 5442: 
 5443: reply() : uses subreply to send a message to remote machine, logs all failures
 5444: 
 5445: =item *
 5446: 
 5447: critical() : passes a critical message to another server; if cannot
 5448: get through then place message in connection buffer directory and
 5449: returns con_delayed, if incapable of saving message, returns
 5450: con_failed
 5451: 
 5452: =item *
 5453: 
 5454: reconlonc() : tries to reconnect lonc client processes.
 5455: 
 5456: =back
 5457: 
 5458: =head2 Resource Access Logging
 5459: 
 5460: =over 4
 5461: 
 5462: =item *
 5463: 
 5464: flushcourselogs() : flush (save) buffer logs and access logs
 5465: 
 5466: =item *
 5467: 
 5468: courselog($what) : save message for course in hash
 5469: 
 5470: =item *
 5471: 
 5472: courseacclog($what) : save message for course using &courselog().  Perform
 5473: special processing for specific resource types (problems, exams, quizzes, etc).
 5474: 
 5475: =item *
 5476: 
 5477: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 5478: as a PerlChildExitHandler
 5479: 
 5480: =back
 5481: 
 5482: =head2 Other
 5483: 
 5484: =over 4
 5485: 
 5486: =item *
 5487: 
 5488: symblist($mapname,%newhash) : update symbolic storage links
 5489: 
 5490: =back
 5491: 
 5492: =cut

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