File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.528: download - view: text, annotated - select for diffs
Mon Aug 23 15:56:46 2004 UTC (19 years, 10 months ago) by sakharuk
Branches: MAIN
CVS tags: HEAD
Removed logthis line (actually it was not my line).

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

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