File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.540: download - view: text, annotated - select for diffs
Thu Sep 9 08:26:46 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#3427, filenames like syl.08.04.doc would cause sillyness.

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

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