File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.504: download - view: text, annotated - select for diffs
Thu May 27 22:25:16 2004 UTC (20 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- new parmater 'interval'
- lonnavmaps, lonhomework respect the 'interval' value
    - if it exits
    - they check if it has been accessed yet (lonnet::get_first_access)
    - if it has then duedate is first_access+interval
    - if it hasn't then duedate is duedate

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

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