File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.475: download - view: text, annotated - select for diffs
Mon Mar 8 23:04:00 2004 UTC (20 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- bug#2571

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

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