File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.521: download - view: text, annotated - select for diffs
Tue Jul 6 18:02:33 2004 UTC (19 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: version_1_1_99_3, version_1_1_99_2, HEAD
sub auto_instcode_format() - used by lonsupportreq.pm to request institutional code translation from localenroll::instcode_format on homeserver of a course.

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

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