File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.530: download - view: text, annotated - select for diffs
Tue Aug 24 06:43:21 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- can create directories now

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

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