File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.531: download - view: text, annotated - select for diffs
Tue Aug 24 07:26:04 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- rename is working

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

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