File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.451: download - view: text, annotated - select for diffs
Tue Dec 2 19:35:26 2003 UTC (20 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- match the outermost <body> </body>

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

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