File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.457: download - view: text, annotated - select for diffs
Mon Dec 8 13:50:57 2003 UTC (20 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Modifications to support standalone use of modify_student_enrollment routine in lonnet.pm. Fixed a scope issue, parameters passed to determine homeserver of a course, and list passed to classlist.db

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

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