File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.589: download - view: text, annotated - select for diffs
Tue Jan 18 22:09:14 2005 UTC (19 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- removing old code that expected continual lonc/d links as the assumption is no longer true

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

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