File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.467: download - view: text, annotated - select for diffs
Fri Jan 30 14:42:00 2004 UTC (20 years, 5 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Reduce lonnet.log spew from multi-domain code (-r 1.465) so I can
see my own lonnet.log spew.  I assume the output is not needed for
general testing.

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

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