File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.448: download - view: text, annotated - select for diffs
Wed Nov 12 19:51:43 2003 UTC (20 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- converting from Apache::File to open()

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

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