File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.538: download - view: text, annotated - select for diffs
Thu Sep 2 18:01:52 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- modified getfile,repcopy, and added repcopy_userfile
    repcopy hands userfile repcopies off to repcopy_userfile
    repcopy_userfile can take either urls or paths
- lonuploadrep changed to use the repcopy instead of using getfile and trhrowing the contents away

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

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