File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.470: download - view: text, annotated - select for diffs
Mon Feb 2 20:21:25 2004 UTC (20 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
* Making it part of the course environment which privileged users (DC, CC)
  should NOT be hidden from the staff listings on syllabi, etc
* Automatically make the chosen Course Coordinator non-hidden
* Removing the &mt from grading options "standard" and "external" - the
  value of the setting cannot be language dependent, since if for a example
  a user sets it to the German translation of "standard" a user with Spanish
  language setting would see the wrong grading
* invented new option "spreadsheet," just to have one

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

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