File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.491: download - view: text, annotated - select for diffs
Thu Apr 29 07:57:47 2004 UTC (20 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- can now grade an Anonymous exam
   - CODE is noticed by rndseed in either the student record
     (Apache::lonhomework::history) or %ENV and used
   - analyze mode now needs student data loaded and does so
   - CODE is stored into student data

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

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