File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.591: download - view: text, annotated - select for diffs
Fri Jan 28 09:26:57 2005 UTC (19 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#597

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.591 2005/01/28 09:26:57 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:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 2104:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2105:   if ($domain eq 'public' && $stuname eq 'public') {
 2106:       $stuname=$ENV{'REMOTE_ADDR'};
 2107:   }
 2108:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2109:   my %hash;
 2110:   if (tie(%hash,'GDBM_File',
 2111: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2112: 	  &GDBM_WRCREAT(),0640)) {
 2113:     foreach my $key (keys %hash) {
 2114:       if ($key=~ /:$symb/) {
 2115: 	delete($hash{$key});
 2116:       }
 2117:     }
 2118:   }
 2119: }
 2120: 
 2121: sub tmpstore {
 2122:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2123: 
 2124:   if (!$symb) {
 2125:     $symb=&symbread();
 2126:     if (!$symb) { $symb= $ENV{'request.url'}; }
 2127:   }
 2128:   $symb=escape($symb);
 2129: 
 2130:   if (!$namespace) {
 2131:     # I don't think we would ever want to store this for a course.
 2132:     # it seems this will only be used if we don't have a course.
 2133:     #$namespace=$ENV{'request.course.id'};
 2134:     #if (!$namespace) {
 2135:       $namespace=$ENV{'request.state'};
 2136:     #}
 2137:   }
 2138:   $namespace=~s/\//\_/g;
 2139:   $namespace=~s/\W//g;
 2140:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 2141:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2142:   if ($domain eq 'public' && $stuname eq 'public') {
 2143:       $stuname=$ENV{'REMOTE_ADDR'};
 2144:   }
 2145:   my $now=time;
 2146:   my %hash;
 2147:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2148:   if (tie(%hash,'GDBM_File',
 2149: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2150: 	  &GDBM_WRCREAT(),0640)) {
 2151:     $hash{"version:$symb"}++;
 2152:     my $version=$hash{"version:$symb"};
 2153:     my $allkeys=''; 
 2154:     foreach my $key (keys(%$storehash)) {
 2155:       $allkeys.=$key.':';
 2156:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2157:     }
 2158:     $hash{"$version:$symb:timestamp"}=$now;
 2159:     $allkeys.='timestamp';
 2160:     $hash{"$version:keys:$symb"}=$allkeys;
 2161:     if (untie(%hash)) {
 2162:       return 'ok';
 2163:     } else {
 2164:       return "error:$!";
 2165:     }
 2166:   } else {
 2167:     return "error:$!";
 2168:   }
 2169: }
 2170: 
 2171: # -----------------------------------------------------------------Temp Restore
 2172: 
 2173: sub tmprestore {
 2174:   my ($symb,$namespace,$domain,$stuname) = @_;
 2175: 
 2176:   if (!$symb) {
 2177:     $symb=&symbread();
 2178:     if (!$symb) { $symb= $ENV{'request.url'}; }
 2179:   }
 2180:   $symb=escape($symb);
 2181: 
 2182:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 2183: 
 2184:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 2185:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2186:   if ($domain eq 'public' && $stuname eq 'public') {
 2187:       $stuname=$ENV{'REMOTE_ADDR'};
 2188:   }
 2189:   my %returnhash;
 2190:   $namespace=~s/\//\_/g;
 2191:   $namespace=~s/\W//g;
 2192:   my %hash;
 2193:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2194:   if (tie(%hash,'GDBM_File',
 2195: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2196: 	  &GDBM_READER(),0640)) {
 2197:     my $version=$hash{"version:$symb"};
 2198:     $returnhash{'version'}=$version;
 2199:     my $scope;
 2200:     for ($scope=1;$scope<=$version;$scope++) {
 2201:       my $vkeys=$hash{"$scope:keys:$symb"};
 2202:       my @keys=split(/:/,$vkeys);
 2203:       my $key;
 2204:       $returnhash{"$scope:keys"}=$vkeys;
 2205:       foreach $key (@keys) {
 2206: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2207: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2208:       }
 2209:     }
 2210:     if (!(untie(%hash))) {
 2211:       return "error:$!";
 2212:     }
 2213:   } else {
 2214:     return "error:$!";
 2215:   }
 2216:   return %returnhash;
 2217: }
 2218: 
 2219: # ----------------------------------------------------------------------- Store
 2220: 
 2221: sub store {
 2222:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2223:     my $home='';
 2224: 
 2225:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2226: 
 2227:     $symb=&symbclean($symb);
 2228:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2229: 
 2230:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 2231:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2232: 
 2233:     &devalidate($symb,$stuname,$domain);
 2234: 
 2235:     $symb=escape($symb);
 2236:     if (!$namespace) { 
 2237:        unless ($namespace=$ENV{'request.course.id'}) { 
 2238:           return ''; 
 2239:        } 
 2240:     }
 2241:     if (!$home) { $home=$ENV{'user.home'}; }
 2242: 
 2243:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2244:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2245: 
 2246:     my $namevalue='';
 2247:     foreach (keys %$storehash) {
 2248:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2249:     }
 2250:     $namevalue=~s/\&$//;
 2251:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2252:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2253: }
 2254: 
 2255: # -------------------------------------------------------------- Critical Store
 2256: 
 2257: sub cstore {
 2258:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2259:     my $home='';
 2260: 
 2261:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2262: 
 2263:     $symb=&symbclean($symb);
 2264:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2265: 
 2266:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 2267:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2268: 
 2269:     &devalidate($symb,$stuname,$domain);
 2270: 
 2271:     $symb=escape($symb);
 2272:     if (!$namespace) { 
 2273:        unless ($namespace=$ENV{'request.course.id'}) { 
 2274:           return ''; 
 2275:        } 
 2276:     }
 2277:     if (!$home) { $home=$ENV{'user.home'}; }
 2278: 
 2279:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2280:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2281: 
 2282:     my $namevalue='';
 2283:     foreach (keys %$storehash) {
 2284:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2285:     }
 2286:     $namevalue=~s/\&$//;
 2287:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2288:     return critical
 2289:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2290: }
 2291: 
 2292: # --------------------------------------------------------------------- Restore
 2293: 
 2294: sub restore {
 2295:     my ($symb,$namespace,$domain,$stuname) = @_;
 2296:     my $home='';
 2297: 
 2298:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2299: 
 2300:     if (!$symb) {
 2301:       unless ($symb=escape(&symbread())) { return ''; }
 2302:     } else {
 2303:       $symb=&escape(&symbclean($symb));
 2304:     }
 2305:     if (!$namespace) { 
 2306:        unless ($namespace=$ENV{'request.course.id'}) { 
 2307:           return ''; 
 2308:        } 
 2309:     }
 2310:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 2311:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2312:     if (!$home) { $home=$ENV{'user.home'}; }
 2313:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2314: 
 2315:     my %returnhash=();
 2316:     foreach (split(/\&/,$answer)) {
 2317: 	my ($name,$value)=split(/\=/,$_);
 2318:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2319:     }
 2320:     my $version;
 2321:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2322:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2323:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2324:        }
 2325:     }
 2326:     return %returnhash;
 2327: }
 2328: 
 2329: # ---------------------------------------------------------- Course Description
 2330: 
 2331: sub coursedescription {
 2332:     my $courseid=shift;
 2333:     $courseid=~s/^\///;
 2334:     $courseid=~s/\_/\//g;
 2335:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2336:     my $chome=&homeserver($cnum,$cdomain);
 2337:     my $normalid=$cdomain.'_'.$cnum;
 2338:     # need to always cache even if we get errors otherwise we keep 
 2339:     # trying and trying and trying to get the course description.
 2340:     my %envhash=();
 2341:     my %returnhash=();
 2342:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 2343:     if ($chome ne 'no_host') {
 2344:        %returnhash=&dump('environment',$cdomain,$cnum);
 2345:        if (!exists($returnhash{'con_lost'})) {
 2346:            $returnhash{'home'}= $chome;
 2347: 	   $returnhash{'domain'} = $cdomain;
 2348: 	   $returnhash{'num'} = $cnum;
 2349:            while (my ($name,$value) = each %returnhash) {
 2350:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2351:            }
 2352:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2353:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2354: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2355:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2356:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2357:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2358:        }
 2359:     }
 2360:     &appenv(%envhash);
 2361:     return %returnhash;
 2362: }
 2363: 
 2364: # -------------------------------------------------See if a user is privileged
 2365: 
 2366: sub privileged {
 2367:     my ($username,$domain)=@_;
 2368:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2369: 			&homeserver($username,$domain));
 2370:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2371:     my $now=time;
 2372:     if ($rolesdump ne '') {
 2373:         foreach (split(/&/,$rolesdump)) {
 2374: 	    if ($_!~/^rolesdef_/) {
 2375: 		my ($area,$role)=split(/=/,$_);
 2376: 		$area=~s/\_\w\w$//;
 2377: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2378: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2379: 		    my $active=1;
 2380: 		    if ($tend) {
 2381: 			if ($tend<$now) { $active=0; }
 2382: 		    }
 2383: 		    if ($tstart) {
 2384: 			if ($tstart>$now) { $active=0; }
 2385: 		    }
 2386: 		    if ($active) { return 1; }
 2387: 		}
 2388: 	    }
 2389: 	}
 2390:     }
 2391:     return 0;
 2392: }
 2393: 
 2394: # -------------------------------------------------------- Get user privileges
 2395: 
 2396: sub rolesinit {
 2397:     my ($domain,$username,$authhost)=@_;
 2398:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2399:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2400:     my %allroles=();
 2401:     my $now=time;
 2402:     my $userroles="user.login.time=$now\n";
 2403: 
 2404:     if ($rolesdump ne '') {
 2405:         foreach (split(/&/,$rolesdump)) {
 2406: 	  if ($_!~/^rolesdef_/) {
 2407:             my ($area,$role)=split(/=/,$_);
 2408: 	    $area=~s/\_\w\w$//;
 2409: 	    
 2410:             my ($trole,$tend,$tstart);
 2411: 	    if ($role=~/^cr/) { 
 2412: 		($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2413: 		($tend,$tstart)=split('_',$trest);
 2414: 	    } else {
 2415: 		($trole,$tend,$tstart)=split(/_/,$role);
 2416: 	    }
 2417:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
 2418:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2419:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2420:             if (($area ne '') && ($trole ne '')) {
 2421: 		my $spec=$trole.'.'.$area;
 2422: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2423: 		if ($trole =~ /^cr\//) {
 2424:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2425: 		} else {
 2426:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2427: 		}
 2428:             }
 2429:           } 
 2430:         }
 2431:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
 2432:         $userroles.='user.adv='.$adv."\n".
 2433: 	            'user.author='.$author."\n";
 2434:         $ENV{'user.adv'}=$adv;
 2435:     }
 2436:     return $userroles;  
 2437: }
 2438: 
 2439: sub set_arearole {
 2440:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2441: # log the associated role with the area
 2442:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2443:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
 2444: }
 2445: 
 2446: sub custom_roleprivs {
 2447:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2448:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2449:     my $homsvr=homeserver($rauthor,$rdomain);
 2450:     if ($hostname{$homsvr} ne '') {
 2451:         my ($rdummy,$roledef)=
 2452:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2453:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2454:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2455:             if (defined($syspriv)) {
 2456:                 $$allroles{'cm./'}.=':'.$syspriv;
 2457:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2458:             }
 2459:             if ($tdomain ne '') {
 2460:                 if (defined($dompriv)) {
 2461:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2462:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2463:                 }
 2464:                 if (($trest ne '') && (defined($coursepriv))) {
 2465:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2466:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2467:                 }
 2468:             }
 2469:         }
 2470:     }
 2471: }
 2472: 
 2473: 
 2474: sub standard_roleprivs {
 2475:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2476:     if (defined($pr{$trole.':s'})) {
 2477:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2478:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2479:     }
 2480:     if ($tdomain ne '') {
 2481:         if (defined($pr{$trole.':d'})) {
 2482:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2483:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2484:         }
 2485:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2486:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2487:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2488:         }
 2489:     }
 2490: }
 2491: 
 2492: sub set_userprivs {
 2493:     my ($userroles,$allroles) = @_; 
 2494:     my $author=0;
 2495:     my $adv=0;
 2496:     foreach (keys %{$allroles}) {
 2497:         my %thesepriv=();
 2498:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2499:         foreach (split(/:/,$$allroles{$_})) {
 2500:             if ($_ ne '') {
 2501:                 my ($privilege,$restrictions)=split(/&/,$_);
 2502:                 if ($restrictions eq '') {
 2503:                     $thesepriv{$privilege}='F';
 2504:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2505:                     $thesepriv{$privilege}.=$restrictions;
 2506:                 }
 2507:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2508:             }
 2509:         }
 2510:         my $thesestr='';
 2511:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2512:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
 2513:     }
 2514:     return ($author,$adv);
 2515: }
 2516: 
 2517: # --------------------------------------------------------------- get interface
 2518: 
 2519: sub get {
 2520:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2521:    my $items='';
 2522:    foreach (@$storearr) {
 2523:        $items.=escape($_).'&';
 2524:    }
 2525:    $items=~s/\&$//;
 2526:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2527:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2528:    my $uhome=&homeserver($uname,$udomain);
 2529: 
 2530:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2531:    my @pairs=split(/\&/,$rep);
 2532:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2533:      return @pairs;
 2534:    }
 2535:    my %returnhash=();
 2536:    my $i=0;
 2537:    foreach (@$storearr) {
 2538:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2539:       $i++;
 2540:    }
 2541:    return %returnhash;
 2542: }
 2543: 
 2544: # --------------------------------------------------------------- del interface
 2545: 
 2546: sub del {
 2547:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2548:    my $items='';
 2549:    foreach (@$storearr) {
 2550:        $items.=escape($_).'&';
 2551:    }
 2552:    $items=~s/\&$//;
 2553:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2554:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2555:    my $uhome=&homeserver($uname,$udomain);
 2556: 
 2557:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2558: }
 2559: 
 2560: # -------------------------------------------------------------- dump interface
 2561: 
 2562: sub dump {
 2563:    my ($namespace,$udomain,$uname,$regexp)=@_;
 2564:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2565:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2566:    my $uhome=&homeserver($uname,$udomain);
 2567:    if ($regexp) {
 2568:        $regexp=&escape($regexp);
 2569:    } else {
 2570:        $regexp='.';
 2571:    }
 2572:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 2573:    my @pairs=split(/\&/,$rep);
 2574:    my %returnhash=();
 2575:    foreach (@pairs) {
 2576:       my ($key,$value)=split(/=/,$_);
 2577:       $returnhash{unescape($key)}=&thaw_unescape($value);
 2578:    }
 2579:    return %returnhash;
 2580: }
 2581: 
 2582: # -------------------------------------------------------------- keys interface
 2583: 
 2584: sub getkeys {
 2585:    my ($namespace,$udomain,$uname)=@_;
 2586:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2587:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2588:    my $uhome=&homeserver($uname,$udomain);
 2589:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2590:    my @keyarray=();
 2591:    foreach (split(/\&/,$rep)) {
 2592:       push (@keyarray,&unescape($_));
 2593:    }
 2594:    return @keyarray;
 2595: }
 2596: 
 2597: # --------------------------------------------------------------- currentdump
 2598: sub currentdump {
 2599:    my ($courseid,$sdom,$sname)=@_;
 2600:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2601:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
 2602:    $sname    = $ENV{'user.name'}         if (! defined($sname));
 2603:    my $uhome = &homeserver($sname,$sdom);
 2604:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2605:    return if ($rep =~ /^(error:|no_such_host)/);
 2606:    #
 2607:    my %returnhash=();
 2608:    #
 2609:    if ($rep eq "unknown_cmd") { 
 2610:        # an old lond will not know currentdump
 2611:        # Do a dump and make it look like a currentdump
 2612:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2613:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2614:        my %hash = @tmp;
 2615:        @tmp=();
 2616:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2617:    } else {
 2618:        my @pairs=split(/\&/,$rep);
 2619:        foreach (@pairs) {
 2620:            my ($key,$value)=split(/=/,$_);
 2621:            my ($symb,$param) = split(/:/,$key);
 2622:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2623:                                                         &thaw_unescape($value);
 2624:        }
 2625:    }
 2626:    return %returnhash;
 2627: }
 2628: 
 2629: sub convert_dump_to_currentdump{
 2630:     my %hash = %{shift()};
 2631:     my %returnhash;
 2632:     # Code ripped from lond, essentially.  The only difference
 2633:     # here is the unescaping done by lonnet::dump().  Conceivably
 2634:     # we might run in to problems with parameter names =~ /^v\./
 2635:     while (my ($key,$value) = each(%hash)) {
 2636:         my ($v,$symb,$param) = split(/:/,$key);
 2637:         next if ($v eq 'version' || $symb eq 'keys');
 2638:         next if (exists($returnhash{$symb}) &&
 2639:                  exists($returnhash{$symb}->{$param}) &&
 2640:                  $returnhash{$symb}->{'v.'.$param} > $v);
 2641:         $returnhash{$symb}->{$param}=$value;
 2642:         $returnhash{$symb}->{'v.'.$param}=$v;
 2643:     }
 2644:     #
 2645:     # Remove all of the keys in the hashes which keep track of
 2646:     # the version of the parameter.
 2647:     while (my ($symb,$param_hash) = each(%returnhash)) {
 2648:         # use a foreach because we are going to delete from the hash.
 2649:         foreach my $key (keys(%$param_hash)) {
 2650:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 2651:         }
 2652:     }
 2653:     return \%returnhash;
 2654: }
 2655: 
 2656: # --------------------------------------------------------------- inc interface
 2657: 
 2658: sub inc {
 2659:     my ($namespace,$store,$udomain,$uname) = @_;
 2660:     if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2661:     if (!$uname) { $uname=$ENV{'user.name'}; }
 2662:     my $uhome=&homeserver($uname,$udomain);
 2663:     my $items='';
 2664:     if (! ref($store)) {
 2665:         # got a single value, so use that instead
 2666:         $items = &escape($store).'=&';
 2667:     } elsif (ref($store) eq 'SCALAR') {
 2668:         $items = &escape($$store).'=&';        
 2669:     } elsif (ref($store) eq 'ARRAY') {
 2670:         $items = join('=&',map {&escape($_);} @{$store});
 2671:     } elsif (ref($store) eq 'HASH') {
 2672:         while (my($key,$value) = each(%{$store})) {
 2673:             $items.= &escape($key).'='.&escape($value).'&';
 2674:         }
 2675:     }
 2676:     $items=~s/\&$//;
 2677:     return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 2678: }
 2679: 
 2680: # --------------------------------------------------------------- put interface
 2681: 
 2682: sub put {
 2683:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2684:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2685:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2686:    my $uhome=&homeserver($uname,$udomain);
 2687:    my $items='';
 2688:    foreach (keys %$storehash) {
 2689:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2690:    }
 2691:    $items=~s/\&$//;
 2692:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2693: }
 2694: 
 2695: # ---------------------------------------------------------- putstore interface
 2696:                                                                                      
 2697: sub putstore {
 2698:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2699:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2700:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2701:    my $uhome=&homeserver($uname,$udomain);
 2702:    my $items='';
 2703:    my %allitems = ();
 2704:    foreach (keys %$storehash) {
 2705:        if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 2706:            my $key = $1.':keys:'.$2;
 2707:            $allitems{$key} .= $3.':';
 2708:        }
 2709:        $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
 2710:    }
 2711:    foreach (keys %allitems) {
 2712:        $allitems{$_} =~ s/\:$//;
 2713:        $items.= $_.'='.$allitems{$_}.'&';
 2714:    }
 2715:    $items=~s/\&$//;
 2716:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2717: }
 2718: 
 2719: # ------------------------------------------------------ critical put interface
 2720: 
 2721: sub cput {
 2722:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2723:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2724:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2725:    my $uhome=&homeserver($uname,$udomain);
 2726:    my $items='';
 2727:    foreach (keys %$storehash) {
 2728:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2729:    }
 2730:    $items=~s/\&$//;
 2731:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 2732: }
 2733: 
 2734: # -------------------------------------------------------------- eget interface
 2735: 
 2736: sub eget {
 2737:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2738:    my $items='';
 2739:    foreach (@$storearr) {
 2740:        $items.=escape($_).'&';
 2741:    }
 2742:    $items=~s/\&$//;
 2743:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2744:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2745:    my $uhome=&homeserver($uname,$udomain);
 2746:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 2747:    my @pairs=split(/\&/,$rep);
 2748:    my %returnhash=();
 2749:    my $i=0;
 2750:    foreach (@$storearr) {
 2751:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2752:       $i++;
 2753:    }
 2754:    return %returnhash;
 2755: }
 2756: 
 2757: # ---------------------------------------------- Custom access rule evaluation
 2758: 
 2759: sub customaccess {
 2760:     my ($priv,$uri)=@_;
 2761:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
 2762:     $urealm=~s/^\W//;
 2763:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 2764:     my $access=0;
 2765:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 2766: 	my ($effect,$realm,$role)=split(/\:/,$_);
 2767:         if ($role) {
 2768: 	   if ($role ne $urole) { next; }
 2769:         }
 2770:         foreach (split(/\s*\,\s*/,$realm)) {
 2771:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 2772:             if ($tdom) {
 2773: 		if ($tdom ne $udom) { next; }
 2774:             }
 2775:             if ($tcrs) {
 2776: 		if ($tcrs ne $ucrs) { next; }
 2777:             }
 2778:             if ($tsec) {
 2779: 		if ($tsec ne $usec) { next; }
 2780:             }
 2781:             $access=($effect eq 'allow');
 2782:             last;
 2783:         }
 2784: 	if ($realm eq '' && $role eq '') {
 2785:             $access=($effect eq 'allow');
 2786: 	}
 2787:     }
 2788:     return $access;
 2789: }
 2790: 
 2791: # ------------------------------------------------- Check for a user privilege
 2792: 
 2793: sub allowed {
 2794:     my ($priv,$uri,$symb)=@_;
 2795:     $uri=&deversion($uri);
 2796:     my $orguri=$uri;
 2797:     $uri=&declutter($uri);
 2798:     
 2799:     
 2800:     
 2801:     if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
 2802: # Free bre access to adm and meta resources
 2803:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
 2804: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 2805: 	return 'F';
 2806:     }
 2807: 
 2808: # Free bre access to user's own portfolio contents
 2809:     my ($space,$domain,$name,$dir)=split('/',$uri);
 2810:     if (('uploaded' eq $space) && ($ENV{'user.name'} eq $name) && 
 2811: 	($ENV{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
 2812:         return 'F';
 2813:     }
 2814: 
 2815: # Free bre to public access
 2816: 
 2817:     if ($priv eq 'bre') {
 2818:         my $copyright=&metadata($uri,'copyright');
 2819: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
 2820:            return 'F'; 
 2821:         }
 2822:         if ($copyright eq 'priv') {
 2823:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2824: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
 2825: 		return '';
 2826:             }
 2827:         }
 2828:         if ($copyright eq 'domain') {
 2829:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2830: 	    unless (($ENV{'user.domain'} eq $1) ||
 2831:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
 2832: 		return '';
 2833:             }
 2834:         }
 2835:         if ($ENV{'request.role'}=~ /li\.\//) {
 2836:             # Library role, so allow browsing of resources in this domain.
 2837:             return 'F';
 2838:         }
 2839:         if ($copyright eq 'custom') {
 2840: 	    unless (&customaccess($priv,$uri)) { return ''; }
 2841:         }
 2842:     }
 2843:     # Domain coordinator is trying to create a course
 2844:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
 2845:         # uri is the requested domain in this case.
 2846:         # comparison to 'request.role.domain' shows if the user has selected
 2847:         # a role of dc for the domain in question. 
 2848:         return 'F' if ($uri eq $ENV{'request.role.domain'});
 2849:     }
 2850: 
 2851:     my $thisallowed='';
 2852:     my $statecond=0;
 2853:     my $courseprivid='';
 2854: 
 2855: # Course
 2856: 
 2857:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 2858:        $thisallowed.=$1;
 2859:     }
 2860: 
 2861: # Domain
 2862: 
 2863:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 2864:        =~/\Q$priv\E\&([^\:]*)/) {
 2865:        $thisallowed.=$1;
 2866:     }
 2867: 
 2868: # Course: uri itself is a course
 2869:     my $courseuri=$uri;
 2870:     $courseuri=~s/\_(\d)/\/$1/;
 2871:     $courseuri=~s/^([^\/])/\/$1/;
 2872: 
 2873:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 2874:        =~/\Q$priv\E\&([^\:]*)/) {
 2875:        $thisallowed.=$1;
 2876:     }
 2877: 
 2878: # URI is an uploaded document for this course
 2879: 
 2880:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 2881: 	my $refuri=$ENV{'httpref.'.$orguri};
 2882: 	if ($refuri) {
 2883: 	    if ($refuri =~ m|^/adm/|) {
 2884: 		$thisallowed='F';
 2885: 	    }
 2886: 	}
 2887:     }
 2888: 
 2889: # Full access at system, domain or course-wide level? Exit.
 2890: 
 2891:     if ($thisallowed=~/F/) {
 2892: 	return 'F';
 2893:     }
 2894: 
 2895: # If this is generating or modifying users, exit with special codes
 2896: 
 2897:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) {
 2898: 	return $thisallowed;
 2899:     }
 2900: #
 2901: # Gathered so far: system, domain and course wide privileges
 2902: #
 2903: # Course: See if uri or referer is an individual resource that is part of 
 2904: # the course
 2905: 
 2906:     if ($ENV{'request.course.id'}) {
 2907: 
 2908:        $courseprivid=$ENV{'request.course.id'};
 2909:        if ($ENV{'request.course.sec'}) {
 2910:           $courseprivid.='/'.$ENV{'request.course.sec'};
 2911:        }
 2912:        $courseprivid=~s/\_/\//;
 2913:        my $checkreferer=1;
 2914:        my ($match,$cond)=&is_on_map($uri);
 2915:        if ($match) {
 2916:            $statecond=$cond;
 2917:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2918:                =~/\Q$priv\E\&([^\:]*)/) {
 2919:                $thisallowed.=$1;
 2920:                $checkreferer=0;
 2921:            }
 2922:        }
 2923:        
 2924:        if ($checkreferer) {
 2925: 	  my $refuri=$ENV{'httpref.'.$orguri};
 2926:             unless ($refuri) {
 2927:                 foreach (keys %ENV) {
 2928: 		    if ($_=~/^httpref\..*\*/) {
 2929: 			my $pattern=$_;
 2930:                         $pattern=~s/^httpref\.\/res\///;
 2931:                         $pattern=~s/\*/\[\^\/\]\+/g;
 2932:                         $pattern=~s/\//\\\//g;
 2933:                         if ($orguri=~/$pattern/) {
 2934: 			    $refuri=$ENV{$_};
 2935:                         }
 2936:                     }
 2937:                 }
 2938:             }
 2939: 
 2940:          if ($refuri) { 
 2941: 	  $refuri=&declutter($refuri);
 2942:           my ($match,$cond)=&is_on_map($refuri);
 2943:             if ($match) {
 2944:               my $refstatecond=$cond;
 2945:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2946:                   =~/\Q$priv\E\&([^\:]*)/) {
 2947:                   $thisallowed.=$1;
 2948:                   $uri=$refuri;
 2949:                   $statecond=$refstatecond;
 2950:               }
 2951:           }
 2952:         }
 2953:        }
 2954:    }
 2955: 
 2956: #
 2957: # Gathered now: all privileges that could apply, and condition number
 2958: # 
 2959: #
 2960: # Full or no access?
 2961: #
 2962: 
 2963:     if ($thisallowed=~/F/) {
 2964: 	return 'F';
 2965:     }
 2966: 
 2967:     unless ($thisallowed) {
 2968:         return '';
 2969:     }
 2970: 
 2971: # Restrictions exist, deal with them
 2972: #
 2973: #   C:according to course preferences
 2974: #   R:according to resource settings
 2975: #   L:unless locked
 2976: #   X:according to user session state
 2977: #
 2978: 
 2979: # Possibly locked functionality, check all courses
 2980: # Locks might take effect only after 10 minutes cache expiration for other
 2981: # courses, and 2 minutes for current course
 2982: 
 2983:     my $envkey;
 2984:     if ($thisallowed=~/L/) {
 2985:         foreach $envkey (keys %ENV) {
 2986:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 2987:                my $courseid=$2;
 2988:                my $roleid=$1.'.'.$2;
 2989:                $courseid=~s/^\///;
 2990:                my $expiretime=600;
 2991:                if ($ENV{'request.role'} eq $roleid) {
 2992: 		  $expiretime=120;
 2993:                }
 2994: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 2995:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 2996:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 2997: 		   &coursedescription($courseid);
 2998:                }
 2999:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3000:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3001: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3002:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 3003:                             $ENV{'user.home'},
 3004:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3005:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3006:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 3007: 		       return '';
 3008:                    }
 3009:                }
 3010:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3011:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3012: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 3013:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 3014:                             $ENV{'user.home'},
 3015:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3016:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3017:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 3018: 		       return '';
 3019:                    }
 3020:                }
 3021: 	   }
 3022:        }
 3023:     }
 3024:    
 3025: #
 3026: # Rest of the restrictions depend on selected course
 3027: #
 3028: 
 3029:     unless ($ENV{'request.course.id'}) {
 3030:        return '1';
 3031:     }
 3032: 
 3033: #
 3034: # Now user is definitely in a course
 3035: #
 3036: 
 3037: 
 3038: # Course preferences
 3039: 
 3040:    if ($thisallowed=~/C/) {
 3041:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 3042:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
 3043:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3044: 	   =~/\Q$rolecode\E/) {
 3045:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 3046:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3047:                 $ENV{'request.course.id'});
 3048:            return '';
 3049:        }
 3050: 
 3051:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
 3052: 	   =~/\Q$unamedom\E/) {
 3053:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 3054:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3055:                 $ENV{'request.course.id'});
 3056:            return '';
 3057:        }
 3058:    }
 3059: 
 3060: # Resource preferences
 3061: 
 3062:    if ($thisallowed=~/R/) {
 3063:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 3064:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3065: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 3066:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3067:           return '';
 3068:        }
 3069:    }
 3070: 
 3071: # Restricted by state or randomout?
 3072: 
 3073:    if ($thisallowed=~/X/) {
 3074:       if ($ENV{'acc.randomout'}) {
 3075: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3076:          if (($symb) && ($ENV{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3077:             return ''; 
 3078:          }
 3079:       }
 3080:       if (&condval($statecond)) {
 3081: 	 return '2';
 3082:       } else {
 3083:          return '';
 3084:       }
 3085:    }
 3086: 
 3087:    return 'F';
 3088: }
 3089: 
 3090: # --------------------------------------------------- Is a resource on the map?
 3091: 
 3092: sub is_on_map {
 3093:     my $uri=&declutter(shift);
 3094:     $uri=~s/\.\d+\.(\w+)$/\.$1/;
 3095:     my @uriparts=split(/\//,$uri);
 3096:     my $filename=$uriparts[$#uriparts];
 3097:     my $pathname=$uri;
 3098:     $pathname=~s|/\Q$filename\E$||;
 3099:     $pathname=~s/^adm\/wrapper\///;    
 3100:     #Trying to find the conditional for the file
 3101:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 3102: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3103:     if ($match) {
 3104: 	return (1,$1);
 3105:     } else {
 3106: 	return (0,0);
 3107:     }
 3108: }
 3109: 
 3110: # --------------------------------------------------------- Get symb from alias
 3111: 
 3112: sub get_symb_from_alias {
 3113:     my $symb=shift;
 3114:     my ($map,$resid,$url)=&decode_symb($symb);
 3115: # Already is a symb
 3116:     if ($url) { return $symb; }
 3117: # Must be an alias
 3118:     my $aliassymb='';
 3119:     my %bighash;
 3120:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3121:                             &GDBM_READER(),0640)) {
 3122:         my $rid=$bighash{'mapalias_'.$symb};
 3123: 	if ($rid) {
 3124: 	    my ($mapid,$resid)=split(/\./,$rid);
 3125: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3126: 				    $resid,$bighash{'src_'.$rid});
 3127: 	}
 3128:         untie %bighash;
 3129:     }
 3130:     return $aliassymb;
 3131: }
 3132: 
 3133: # ----------------------------------------------------------------- Define Role
 3134: 
 3135: sub definerole {
 3136:   if (allowed('mcr','/')) {
 3137:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3138:     foreach (split(':',$sysrole)) {
 3139: 	my ($crole,$cqual)=split(/\&/,$_);
 3140:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3141:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3142: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3143:                return "refused:s:$crole&$cqual"; 
 3144:             }
 3145:         }
 3146:     }
 3147:     foreach (split(':',$domrole)) {
 3148: 	my ($crole,$cqual)=split(/\&/,$_);
 3149:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3150:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3151: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3152:                return "refused:d:$crole&$cqual"; 
 3153:             }
 3154:         }
 3155:     }
 3156:     foreach (split(':',$courole)) {
 3157: 	my ($crole,$cqual)=split(/\&/,$_);
 3158:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3159:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3160: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3161:                return "refused:c:$crole&$cqual"; 
 3162:             }
 3163:         }
 3164:     }
 3165:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 3166:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 3167: 	        "rolesdef_$rolename=".
 3168:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3169:     return reply($command,$ENV{'user.home'});
 3170:   } else {
 3171:     return 'refused';
 3172:   }
 3173: }
 3174: 
 3175: # ---------------- Make a metadata query against the network of library servers
 3176: 
 3177: sub metadata_query {
 3178:     my ($query,$custom,$customshow,$server_array)=@_;
 3179:     my %rhash;
 3180:     my @server_list = (defined($server_array) ? @$server_array
 3181:                                               : keys(%libserv) );
 3182:     for my $server (@server_list) {
 3183: 	unless ($custom or $customshow) {
 3184: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3185: 	    $rhash{$server}=$reply;
 3186: 	}
 3187: 	else {
 3188: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3189: 			     &escape($custom).':'.&escape($customshow),
 3190: 			     $server);
 3191: 	    $rhash{$server}=$reply;
 3192: 	}
 3193:     }
 3194:     return \%rhash;
 3195: }
 3196: 
 3197: # ----------------------------------------- Send log queries and wait for reply
 3198: 
 3199: sub log_query {
 3200:     my ($uname,$udom,$query,%filters)=@_;
 3201:     my $uhome=&homeserver($uname,$udom);
 3202:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3203:     my $uhost=$hostname{$uhome};
 3204:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3205:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3206:                        $uhome);
 3207:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3208:     return get_query_reply($queryid);
 3209: }
 3210: 
 3211: # ------- Request retrieval of institutional classlists for course(s)
 3212: 
 3213: sub fetch_enrollment_query {
 3214:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3215:     my $homeserver;
 3216:     my $maxtries = 1;
 3217:     if ($context eq 'automated') {
 3218:         $homeserver = $perlvar{'lonHostID'};
 3219:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3220:     } else {
 3221:         $homeserver = &homeserver($cnum,$dom);
 3222:     }
 3223:     my $host=$hostname{$homeserver};
 3224:     my $cmd = '';
 3225:     foreach (keys %{$affiliatesref}) {
 3226:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3227:     }
 3228:     $cmd =~ s/%%$//;
 3229:     $cmd = &escape($cmd);
 3230:     my $query = 'fetchenrollment';
 3231:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$ENV{'user.name'}.':'.$cmd,$homeserver);
 3232:     unless ($queryid=~/^\Q$host\E\_/) { 
 3233:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3234:         return 'error: '.$queryid;
 3235:     }
 3236:     my $reply = &get_query_reply($queryid);
 3237:     my $tries = 1;
 3238:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3239:         $reply = &get_query_reply($queryid);
 3240:         $tries ++;
 3241:     }
 3242:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3243:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$ENV{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3244:     } else {
 3245:         my @responses = split/:/,$reply;
 3246:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3247:             foreach (@responses) {
 3248:                 my ($key,$value) = split/=/,$_;
 3249:                 $$replyref{$key} = $value;
 3250:             }
 3251:         } else {
 3252:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3253:             foreach (@responses) {
 3254:                 my ($key,$value) = split/=/,$_;
 3255:                 $$replyref{$key} = $value;
 3256:                 if ($value > 0) {
 3257:                     foreach (@{$$affiliatesref{$key}}) {
 3258:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3259:                         my $destname = $pathname.'/'.$filename;
 3260:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 3261:                         if ($xml_classlist =~ /^error/) {
 3262:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 3263:                         } else {
 3264:                             if ( open(FILE,">$destname") ) {
 3265:                                 print FILE &unescape($xml_classlist);
 3266:                                 close(FILE);
 3267:                             } else {
 3268:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 3269:                             }
 3270:                         }
 3271:                     }
 3272:                 }
 3273:             }
 3274:         }
 3275:         return 'ok';
 3276:     }
 3277:     return 'error';
 3278: }
 3279: 
 3280: sub get_query_reply {
 3281:     my $queryid=shift;
 3282:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 3283:     my $reply='';
 3284:     for (1..100) {
 3285: 	sleep 2;
 3286:         if (-e $replyfile.'.end') {
 3287: 	    if (open(my $fh,$replyfile)) {
 3288:                $reply.=<$fh>;
 3289:                close($fh);
 3290: 	   } else { return 'error: reply_file_error'; }
 3291:            return &unescape($reply);
 3292: 	}
 3293:     }
 3294:     return 'timeout:'.$queryid;
 3295: }
 3296: 
 3297: sub courselog_query {
 3298: #
 3299: # possible filters:
 3300: # url: url or symb
 3301: # username
 3302: # domain
 3303: # action: view, submit, grade
 3304: # start: timestamp
 3305: # end: timestamp
 3306: #
 3307:     my (%filters)=@_;
 3308:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
 3309:     if ($filters{'url'}) {
 3310: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 3311:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 3312:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 3313:     }
 3314:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 3315:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 3316:     return &log_query($cname,$cdom,'courselog',%filters);
 3317: }
 3318: 
 3319: sub userlog_query {
 3320:     my ($uname,$udom,%filters)=@_;
 3321:     return &log_query($uname,$udom,'userlog',%filters);
 3322: }
 3323: 
 3324: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 3325: 
 3326: sub auto_run {
 3327:     my ($cnum,$cdom) = @_;
 3328:     my $homeserver = &homeserver($cnum,$cdom);
 3329:     my $response = &reply('autorun:'.$cdom,$homeserver);
 3330:     return $response;
 3331: }
 3332:                                                                                    
 3333: sub auto_get_sections {
 3334:     my ($cnum,$cdom,$inst_coursecode) = @_;
 3335:     my $homeserver = &homeserver($cnum,$cdom);
 3336:     my @secs = ();
 3337:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 3338:     unless ($response eq 'refused') {
 3339:         @secs = split/:/,$response;
 3340:     }
 3341:     return @secs;
 3342: }
 3343:                                                                                    
 3344: sub auto_new_course {
 3345:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 3346:     my $homeserver = &homeserver($cnum,$cdom);
 3347:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 3348:     return $response;
 3349: }
 3350:                                                                                    
 3351: sub auto_validate_courseID {
 3352:     my ($cnum,$cdom,$inst_course_id) = @_;
 3353:     my $homeserver = &homeserver($cnum,$cdom);
 3354:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 3355:     return $response;
 3356: }
 3357:                                                                                    
 3358: sub auto_create_password {
 3359:     my ($cnum,$cdom,$authparam) = @_;
 3360:     my $homeserver = &homeserver($cnum,$cdom); 
 3361:     my $create_passwd = 0;
 3362:     my $authchk = '';
 3363:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 3364:     if ($response eq 'refused') {
 3365:         $authchk = 'refused';
 3366:     } else {
 3367:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 3368:     }
 3369:     return ($authparam,$create_passwd,$authchk);
 3370: }
 3371: 
 3372: sub auto_instcode_format {
 3373:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 3374:     my $courses = '';
 3375:     my $homeserver;
 3376:     if ($caller eq 'global') {
 3377:         foreach my $tryserver (keys %libserv) {
 3378:             if ($hostdom{$tryserver} eq $codedom) {
 3379:                 $homeserver = $tryserver;
 3380:                 last;
 3381:             }
 3382:         }
 3383:         if (($ENV{'user.name'}) && ($ENV{'user.domain'} eq $codedom)) {
 3384:             $homeserver = &homeserver($ENV{'user.name'},$codedom);
 3385:         }
 3386:     } else {
 3387:         $homeserver = &homeserver($caller,$codedom);
 3388:     }
 3389:     foreach (keys %{$instcodes}) {
 3390:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 3391:     }
 3392:     chop($courses);
 3393:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
 3394:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 3395:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
 3396:         %{$codes} = &str2hash($codes_str);
 3397:         @{$codetitles} = &str2array($codetitles_str);
 3398:         %{$cat_titles} = &str2hash($cat_titles_str);
 3399:         %{$cat_order} = &str2hash($cat_order_str);
 3400:         return 'ok';
 3401:     }
 3402:     return $response;
 3403: }
 3404: 
 3405: # ------------------------------------------------------------------ Plain Text
 3406: 
 3407: sub plaintext {
 3408:     my $short=shift;
 3409:     return &mt($prp{$short});
 3410: }
 3411: 
 3412: # ----------------------------------------------------------------- Assign Role
 3413: 
 3414: sub assignrole {
 3415:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 3416:     my $mrole;
 3417:     if ($role =~ /^cr\//) {
 3418:         my $cwosec=$url;
 3419:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 3420: 	unless (&allowed('ccr',$cwosec)) {
 3421:            &logthis('Refused custom assignrole: '.
 3422:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 3423: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 3424:            return 'refused'; 
 3425:         }
 3426:         $mrole='cr';
 3427:     } else {
 3428:         my $cwosec=$url;
 3429:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 3430:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 3431:            &logthis('Refused assignrole: '.
 3432:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 3433: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 3434:            return 'refused'; 
 3435:         }
 3436:         $mrole=$role;
 3437:     }
 3438:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 3439:                 "$udom:$uname:$url".'_'."$mrole=$role";
 3440:     if ($end) { $command.='_'.$end; }
 3441:     if ($start) {
 3442: 	if ($end) { 
 3443:            $command.='_'.$start; 
 3444:         } else {
 3445:            $command.='_0_'.$start;
 3446:         }
 3447:     }
 3448: # actually delete
 3449:     if ($deleteflag) {
 3450: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 3451: # modify command to delete the role
 3452:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
 3453:                 "$udom:$uname:$url".'_'."$mrole";
 3454: 	   &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 3455: # set start and finish to negative values for userrolelog
 3456:            $start=-1;
 3457:            $end=-1;
 3458:         }
 3459:     }
 3460: # send command
 3461:     my $answer=&reply($command,&homeserver($uname,$udom));
 3462: # log new user role if status is ok
 3463:     if ($answer eq 'ok') {
 3464: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
 3465:     }
 3466:     return $answer;
 3467: }
 3468: 
 3469: # -------------------------------------------------- Modify user authentication
 3470: # Overrides without validation
 3471: 
 3472: sub modifyuserauth {
 3473:     my ($udom,$uname,$umode,$upass)=@_;
 3474:     my $uhome=&homeserver($uname,$udom);
 3475:     unless (&allowed('mau',$udom)) { return 'refused'; }
 3476:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 3477:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 3478:              ' in domain '.$ENV{'request.role.domain'});  
 3479:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 3480: 		     &escape($upass),$uhome);
 3481:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
 3482:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 3483:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 3484:     &log($udom,,$uname,$uhome,
 3485:         'Authentication changed by '.$ENV{'user.domain'}.', '.
 3486:                                      $ENV{'user.name'}.', '.$umode.
 3487:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 3488:     unless ($reply eq 'ok') {
 3489:         &logthis('Authentication mode error: '.$reply);
 3490: 	return 'error: '.$reply;
 3491:     }   
 3492:     return 'ok';
 3493: }
 3494: 
 3495: # --------------------------------------------------------------- Modify a user
 3496: 
 3497: sub modifyuser {
 3498:     my ($udom,    $uname, $uid,
 3499:         $umode,   $upass, $first,
 3500:         $middle,  $last,  $gene,
 3501:         $forceid, $desiredhome, $email)=@_;
 3502:     $udom=~s/\W//g;
 3503:     $uname=~s/\W//g;
 3504:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 3505:              $umode.', '.$first.', '.$middle.', '.
 3506: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 3507:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 3508:                                      ' desiredhome not specified'). 
 3509:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 3510:              ' in domain '.$ENV{'request.role.domain'});
 3511:     my $uhome=&homeserver($uname,$udom,'true');
 3512: # ----------------------------------------------------------------- Create User
 3513:     if (($uhome eq 'no_host') && 
 3514: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 3515:         my $unhome='';
 3516:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 3517:             $unhome = $desiredhome;
 3518: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 3519: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 3520:         } else { # load balancing routine for determining $unhome
 3521:             my $tryserver;
 3522:             my $loadm=10000000;
 3523:             foreach $tryserver (keys %libserv) {
 3524: 	       if ($hostdom{$tryserver} eq $udom) {
 3525:                   my $answer=reply('load',$tryserver);
 3526:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 3527: 		      $loadm=$answer;
 3528:                       $unhome=$tryserver;
 3529:                   }
 3530: 	       }
 3531: 	    }
 3532:         }
 3533:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 3534: 	    return 'error: unable to find a home server for '.$uname.
 3535:                    ' in domain '.$udom;
 3536:         }
 3537:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 3538:                          &escape($upass),$unhome);
 3539: 	unless ($reply eq 'ok') {
 3540:             return 'error: '.$reply;
 3541:         }   
 3542:         $uhome=&homeserver($uname,$udom,'true');
 3543:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 3544: 	    return 'error: unable verify users home machine.';
 3545:         }
 3546:     }   # End of creation of new user
 3547: # ---------------------------------------------------------------------- Add ID
 3548:     if ($uid) {
 3549:        $uid=~tr/A-Z/a-z/;
 3550:        my %uidhash=&idrget($udom,$uname);
 3551:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 3552:          && (!$forceid)) {
 3553: 	  unless ($uid eq $uidhash{$uname}) {
 3554: 	      return 'error: user id "'.$uid.'" does not match '.
 3555:                   'current user id "'.$uidhash{$uname}.'".';
 3556:           }
 3557:        } else {
 3558: 	  &idput($udom,($uname => $uid));
 3559:        }
 3560:     }
 3561: # -------------------------------------------------------------- Add names, etc
 3562:     my @tmp=&get('environment',
 3563: 		   ['firstname','middlename','lastname','generation'],
 3564: 		   $udom,$uname);
 3565:     my %names;
 3566:     if ($tmp[0] =~ m/^error:.*/) { 
 3567:         %names=(); 
 3568:     } else {
 3569:         %names = @tmp;
 3570:     }
 3571: #
 3572: # Make sure to not trash student environment if instructor does not bother
 3573: # to supply name and email information
 3574: #
 3575:     if ($first)  { $names{'firstname'}  = $first; }
 3576:     if (defined($middle)) { $names{'middlename'} = $middle; }
 3577:     if ($last)   { $names{'lastname'}   = $last; }
 3578:     if (defined($gene))   { $names{'generation'} = $gene; }
 3579:     if ($email)  { $names{'notification'} = $email;
 3580:                    $names{'critnotification'} = $email; }
 3581: 
 3582:     my $reply = &put('environment', \%names, $udom,$uname);
 3583:     if ($reply ne 'ok') { return 'error: '.$reply; }
 3584:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 3585:              $umode.', '.$first.', '.$middle.', '.
 3586: 	     $last.', '.$gene.' by '.
 3587:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 3588:     return 'ok';
 3589: }
 3590: 
 3591: # -------------------------------------------------------------- Modify student
 3592: 
 3593: sub modifystudent {
 3594:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 3595:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 3596:     if (!$cid) {
 3597: 	unless ($cid=$ENV{'request.course.id'}) {
 3598: 	    return 'not_in_class';
 3599: 	}
 3600:     }
 3601: # --------------------------------------------------------------- Make the user
 3602:     my $reply=&modifyuser
 3603: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 3604:          $desiredhome,$email);
 3605:     unless ($reply eq 'ok') { return $reply; }
 3606:     # This will cause &modify_student_enrollment to get the uid from the
 3607:     # students environment
 3608:     $uid = undef if (!$forceid);
 3609:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 3610: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 3611:     return $reply;
 3612: }
 3613: 
 3614: sub modify_student_enrollment {
 3615:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 3616:     my ($cdom,$cnum,$chome);
 3617:     if (!$cid) {
 3618: 	unless ($cid=$ENV{'request.course.id'}) {
 3619: 	    return 'not_in_class';
 3620: 	}
 3621: 	$cdom=$ENV{'course.'.$cid.'.domain'};
 3622: 	$cnum=$ENV{'course.'.$cid.'.num'};
 3623:     } else {
 3624: 	($cdom,$cnum)=split(/_/,$cid);
 3625:     }
 3626:     $chome=$ENV{'course.'.$cid.'.home'};
 3627:     if (!$chome) {
 3628: 	$chome=&homeserver($cnum,$cdom);
 3629:     }
 3630:     if (!$chome) { return 'unknown_course'; }
 3631:     # Make sure the user exists
 3632:     my $uhome=&homeserver($uname,$udom);
 3633:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 3634: 	return 'error: no such user';
 3635:     }
 3636:     # Get student data if we were not given enough information
 3637:     if (!defined($first)  || $first  eq '' || 
 3638:         !defined($last)   || $last   eq '' || 
 3639:         !defined($uid)    || $uid    eq '' || 
 3640:         !defined($middle) || $middle eq '' || 
 3641:         !defined($gene)   || $gene   eq '') {
 3642:         # They did not supply us with enough data to enroll the student, so
 3643:         # we need to pick up more information.
 3644:         my %tmp = &get('environment',
 3645:                        ['firstname','middlename','lastname', 'generation','id']
 3646:                        ,$udom,$uname);
 3647: 
 3648:         #foreach (keys(%tmp)) {
 3649:         #    &logthis("key $_ = ".$tmp{$_});
 3650:         #}
 3651:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 3652:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 3653:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 3654:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 3655:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 3656:     }
 3657:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 3658:     my $reply=cput('classlist',
 3659: 		   {"$uname:$udom" => 
 3660: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 3661: 		   $cdom,$cnum);
 3662:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 3663: 	return 'error: '.$reply;
 3664:     }
 3665:     # Add student role to user
 3666:     my $uurl='/'.$cid;
 3667:     $uurl=~s/\_/\//g;
 3668:     if ($usec) {
 3669: 	$uurl.='/'.$usec;
 3670:     }
 3671:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 3672: }
 3673: 
 3674: sub format_name {
 3675:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 3676:     my $name;
 3677:     if ($first ne 'lastname') {
 3678: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 3679:     } else {
 3680: 	if ($lastname=~/\S/) {
 3681: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 3682: 	    $name=~s/\s+,/,/;
 3683: 	} else {
 3684: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 3685: 	}
 3686:     }
 3687:     $name=~s/^\s+//;
 3688:     $name=~s/\s+$//;
 3689:     $name=~s/\s+/ /g;
 3690:     return $name;
 3691: }
 3692: 
 3693: # ------------------------------------------------- Write to course preferences
 3694: 
 3695: sub writecoursepref {
 3696:     my ($courseid,%prefs)=@_;
 3697:     $courseid=~s/^\///;
 3698:     $courseid=~s/\_/\//g;
 3699:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3700:     my $chome=homeserver($cnum,$cdomain);
 3701:     if (($chome eq '') || ($chome eq 'no_host')) { 
 3702: 	return 'error: no such course';
 3703:     }
 3704:     my $cstring='';
 3705:     foreach (keys %prefs) {
 3706: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 3707:     }
 3708:     $cstring=~s/\&$//;
 3709:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 3710: }
 3711: 
 3712: # ---------------------------------------------------------- Make/modify course
 3713: 
 3714: sub createcourse {
 3715:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
 3716:     $url=&declutter($url);
 3717:     my $cid='';
 3718:     unless (&allowed('ccc',$udom)) {
 3719:         return 'refused';
 3720:     }
 3721: # ------------------------------------------------------------------- Create ID
 3722:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 3723:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 3724: # ----------------------------------------------- Make sure that does not exist
 3725:    my $uhome=&homeserver($uname,$udom,'true');
 3726:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 3727:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 3728:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 3729:        $uhome=&homeserver($uname,$udom,'true');       
 3730:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 3731:            return 'error: unable to generate unique course-ID';
 3732:        } 
 3733:    }
 3734: # ------------------------------------------------ Check supplied server name
 3735:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
 3736:     if (! exists($libserv{$course_server})) {
 3737:         return 'error:bad server name '.$course_server;
 3738:     }
 3739: # ------------------------------------------------------------- Make the course
 3740:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 3741:                       $course_server);
 3742:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 3743:     $uhome=&homeserver($uname,$udom,'true');
 3744:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 3745: 	return 'error: no such course';
 3746:     }
 3747: # ----------------------------------------------------------------- Course made
 3748: # log existence
 3749:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 3750:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
 3751:     &flushcourselogs();
 3752: # set toplevel url
 3753:     my $topurl=$url;
 3754:     unless ($nonstandard) {
 3755: # ------------------------------------------ For standard courses, make top url
 3756:         my $mapurl=&clutter($url);
 3757:         if ($mapurl eq '/res/') { $mapurl=''; }
 3758:         $ENV{'form.initmap'}=(<<ENDINITMAP);
 3759: <map>
 3760: <resource id="1" type="start"></resource>
 3761: <resource id="2" src="$mapurl"></resource>
 3762: <resource id="3" type="finish"></resource>
 3763: <link index="1" from="1" to="2"></link>
 3764: <link index="2" from="2" to="3"></link>
 3765: </map>
 3766: ENDINITMAP
 3767:         $topurl=&declutter(
 3768:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
 3769:                           );
 3770:     }
 3771: # ----------------------------------------------------------- Write preferences
 3772:     &writecoursepref($udom.'_'.$uname,
 3773:                      ('description' => $description,
 3774:                       'url'         => $topurl));
 3775:     return '/'.$udom.'/'.$uname;
 3776: }
 3777: 
 3778: # ---------------------------------------------------------- Assign Custom Role
 3779: 
 3780: sub assigncustomrole {
 3781:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 3782:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 3783:                        $end,$start,$deleteflag);
 3784: }
 3785: 
 3786: # ----------------------------------------------------------------- Revoke Role
 3787: 
 3788: sub revokerole {
 3789:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 3790:     my $now=time;
 3791:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 3792: }
 3793: 
 3794: # ---------------------------------------------------------- Revoke Custom Role
 3795: 
 3796: sub revokecustomrole {
 3797:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 3798:     my $now=time;
 3799:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 3800:            $deleteflag);
 3801: }
 3802: 
 3803: # ------------------------------------------------------------ Disk usage
 3804: sub diskusage {
 3805:     my ($udom,$uname,$directoryRoot)=@_;
 3806:     $directoryRoot =~ s/\/$//;
 3807:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 3808:     return $listing;
 3809: }
 3810: 
 3811: sub is_locked {
 3812:     my ($file_name, $domain, $user) = @_;
 3813:     my @check;
 3814:     my $is_locked;
 3815:     push @check, $file_name;
 3816:     my %locked = &Apache::lonnet::get('file_permissions',\@check,
 3817:                                         $ENV{'user.domain'},$ENV{'user.name'});
 3818:     if (ref($locked{$file_name}) eq 'ARRAY') {
 3819:         $is_locked = 'true';
 3820:     } else {
 3821:         $is_locked = 'false';
 3822:     }
 3823: }
 3824: 
 3825: # ------------------------------------------------------------- Mark as Read Only
 3826: 
 3827: sub mark_as_readonly {
 3828:     my ($domain,$user,$files,$what) = @_;
 3829:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 3830:     foreach my $file (@{$files}) {
 3831:         push(@{$current_permissions{$file}},$what);
 3832:     }
 3833:     &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user);
 3834:     return;
 3835: }
 3836: 
 3837: # ------------------------------------------------------------Save Selected Files
 3838: 
 3839: sub save_selected_files {
 3840:     my ($user, $path, @files) = @_;
 3841:     my $filename = $user."savedfiles";
 3842:     my @other_files = &files_not_in_path($user, $path);
 3843:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3844:     foreach my $file (@files) {
 3845:         print (OUT $ENV{'form.currentpath'}.$file."\n");
 3846:     }
 3847:     foreach my $file (@other_files) {
 3848:         print (OUT $file."\n");
 3849:     }
 3850:     close (OUT);
 3851:     return 'ok';
 3852: }
 3853: 
 3854: sub clear_selected_files {
 3855:     my ($user) = @_;
 3856:     my $filename = $user."savedfiles";
 3857:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3858:     print (OUT undef);
 3859:     close (OUT);
 3860:     return ("ok");    
 3861: }
 3862: 
 3863: sub files_in_path {
 3864:     my ($user, $path) = @_;
 3865:     my $filename = $user."savedfiles";
 3866:     my %return_files;
 3867:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3868:     while (my $line_in = <IN>) {
 3869:         chomp ($line_in);
 3870:         my @paths_and_file = split (m!/!, $line_in);
 3871:         my $file_part = pop (@paths_and_file);
 3872:         my $path_part = join ('/', @paths_and_file);
 3873:         $path_part.='/';
 3874:         my $path_and_file = $path_part.$file_part;
 3875:         if ($path_part eq $path) {
 3876:             $return_files{$file_part}= 'selected';
 3877:         }
 3878:     }
 3879:     close (IN);
 3880:     return (\%return_files);
 3881: }
 3882: 
 3883: # called in portfolio select mode, to show files selected NOT in current directory
 3884: sub files_not_in_path {
 3885:     my ($user, $path) = @_;
 3886:     my $filename = $user."savedfiles";
 3887:     my @return_files;
 3888:     my $path_part;
 3889:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3890:     while (<IN>) {
 3891:         #ok, I know it's clunky, but I want it to work
 3892:         my @paths_and_file = split m!/!, $_;
 3893:         my $file_part = pop (@paths_and_file);
 3894:         chomp ($file_part);
 3895:         my $path_part = join ('/', @paths_and_file);
 3896:         $path_part .= '/';
 3897:         my $path_and_file = $path_part.$file_part;
 3898:         if ($path_part ne $path) {
 3899:             push (@return_files, ($path_and_file));
 3900:         }
 3901:     }
 3902:     close (OUT);
 3903:     return (@return_files);
 3904: }
 3905: 
 3906: #--------------------------------------------------------------Get Marked as Read Only
 3907: 
 3908: sub get_marked_as_readonly {
 3909:     my ($domain,$user,$what) = @_;
 3910:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 3911:     my @readonly_files;
 3912:     while (my ($file_name,$value) = each(%current_permissions)) {
 3913:         if (ref($value) eq "ARRAY"){
 3914:             foreach my $stored_what (@{$value}) {
 3915:                 if ($stored_what eq $what) {
 3916:                     push(@readonly_files, $file_name);
 3917:                 } elsif (!defined($what)) {
 3918:                     push(@readonly_files, $file_name);
 3919:                 }
 3920:             }
 3921:         } 
 3922:     }
 3923:     return @readonly_files;
 3924: }
 3925: #-----------------------------------------------------------Get Marked as Read Only Hash
 3926: 
 3927: sub get_marked_as_readonly_hash {
 3928:     my ($domain,$user,$what) = @_;
 3929:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 3930:     my %readonly_files;
 3931:     while (my ($file_name,$value) = each(%current_permissions)) {
 3932:         if (ref($value) eq "ARRAY"){
 3933:             foreach my $stored_what (@{$value}) {
 3934:                 if ($stored_what eq $what) {
 3935:                     $readonly_files{$file_name} = 'locked';
 3936:                 } elsif (!defined($what)) {
 3937:                     $readonly_files{$file_name} = 'locked';
 3938:                 }
 3939:             }
 3940:         } 
 3941:     }
 3942:     return %readonly_files;
 3943: }
 3944: # ------------------------------------------------------------ Unmark as Read Only
 3945: 
 3946: sub unmark_as_readonly {
 3947:     # unmarks all files locked by $what 
 3948:     # for portfolio submissions, $what contains $crsid and $symb
 3949:     my ($domain,$user,$what) = @_;
 3950:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 3951:     my @readonly_files = &Apache::lonnet::get_marked_as_readonly($domain,$user,$what);
 3952:     foreach my $file(@readonly_files){
 3953:         my $current_locks = $current_permissions{$file};
 3954:         my @new_locks;
 3955:         my @del_keys;
 3956:         if (ref($current_locks) eq "ARRAY"){
 3957:             foreach my $locker (@{$current_locks}) {
 3958:                 unless ($locker eq $what) {
 3959:                     push(@new_locks, $what);
 3960:                 }
 3961:             }
 3962:             if (@new_locks > 0) {
 3963:                 $current_permissions{$file} = \@new_locks;
 3964:             } else {
 3965:                 push(@del_keys, $file);
 3966:                 &Apache::lonnet::del('file_permissions',\@del_keys, $domain, $user);
 3967:                 delete $current_permissions{$file};
 3968:             }
 3969:         }
 3970:     }
 3971:     &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user);
 3972:     return;
 3973: }
 3974: 
 3975: # ------------------------------------------------------------ Directory lister
 3976: 
 3977: sub dirlist {
 3978:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 3979: 
 3980:     $uri=~s/^\///;
 3981:     $uri=~s/\/$//;
 3982:     my ($udom, $uname);
 3983:     (undef,$udom,$uname)=split(/\//,$uri);
 3984:     if(defined($userdomain)) {
 3985:         $udom = $userdomain;
 3986:     }
 3987:     if(defined($username)) {
 3988:         $uname = $username;
 3989:     }
 3990: 
 3991:     my $dirRoot = $perlvar{'lonDocRoot'};
 3992:     if(defined($alternateDirectoryRoot)) {
 3993:         $dirRoot = $alternateDirectoryRoot;
 3994:         $dirRoot =~ s/\/$//;
 3995:     }
 3996: 
 3997:     if($udom) {
 3998:         if($uname) {
 3999:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
 4000:                               homeserver($uname,$udom));
 4001:             return split(/:/,$listing);
 4002:         } elsif(!defined($alternateDirectoryRoot)) {
 4003:             my $tryserver;
 4004:             my %allusers=();
 4005:             foreach $tryserver (keys %libserv) {
 4006:                 if($hostdom{$tryserver} eq $udom) {
 4007:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 4008:                                       $udom, $tryserver);
 4009:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 4010:                         && ($listing ne 'con_lost')) {
 4011:                         foreach (split(/:/,$listing)) {
 4012:                             my ($entry,@stat)=split(/&/,$_);
 4013:                             $allusers{$entry}=1;
 4014:                         }
 4015:                     }
 4016:                 }
 4017:             }
 4018:             my $alluserstr='';
 4019:             foreach (sort keys %allusers) {
 4020:                 $alluserstr.=$_.'&user:';
 4021:             }
 4022:             $alluserstr=~s/:$//;
 4023:             return split(/:/,$alluserstr);
 4024:         } else {
 4025:             my @emptyResults = ();
 4026:             push(@emptyResults, 'missing user name');
 4027:             return split(':',@emptyResults);
 4028:         }
 4029:     } elsif(!defined($alternateDirectoryRoot)) {
 4030:         my $tryserver;
 4031:         my %alldom=();
 4032:         foreach $tryserver (keys %libserv) {
 4033:             $alldom{$hostdom{$tryserver}}=1;
 4034:         }
 4035:         my $alldomstr='';
 4036:         foreach (sort keys %alldom) {
 4037:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 4038:         }
 4039:         $alldomstr=~s/:$//;
 4040:         return split(/:/,$alldomstr);       
 4041:     } else {
 4042:         my @emptyResults = ();
 4043:         push(@emptyResults, 'missing domain');
 4044:         return split(':',@emptyResults);
 4045:     }
 4046: }
 4047: 
 4048: # --------------------------------------------- GetFileTimestamp
 4049: # This function utilizes dirlist and returns the date stamp for
 4050: # when it was last modified.  It will also return an error of -1
 4051: # if an error occurs
 4052: 
 4053: ##
 4054: ## FIXME: This subroutine assumes its caller knows something about the
 4055: ## directory structure of the home server for the student ($root).
 4056: ## Not a good assumption to make.  Since this is for looking up files
 4057: ## in user directories, the full path should be constructed by lond, not
 4058: ## whatever machine we request data from.
 4059: ##
 4060: sub GetFileTimestamp {
 4061:     my ($studentDomain,$studentName,$filename,$root)=@_;
 4062:     $studentDomain=~s/\W//g;
 4063:     $studentName=~s/\W//g;
 4064:     my $subdir=$studentName.'__';
 4065:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4066:     my $proname="$studentDomain/$subdir/$studentName";
 4067:     $proname .= '/'.$filename;
 4068:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 4069:                                               $studentName, $root);
 4070:     my @stats = split('&', $fileStat);
 4071:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4072:         # @stats contains first the filename, then the stat output
 4073:         return $stats[10]; # so this is 10 instead of 9.
 4074:     } else {
 4075:         return -1;
 4076:     }
 4077: }
 4078: 
 4079: # -------------------------------------------------------- Value of a Condition
 4080: 
 4081: sub directcondval {
 4082:     my $number=shift;
 4083:     if (!defined($ENV{'user.state.'.$ENV{'request.course.id'}})) {
 4084: 	&Apache::lonuserstate::evalstate();
 4085:     }
 4086:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 4087:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 4088:     } else {
 4089:        return 2;
 4090:     }
 4091: }
 4092: 
 4093: sub condval {
 4094:     my $condidx=shift;
 4095:     my $result=0;
 4096:     my $allpathcond='';
 4097:     foreach (split(/\|/,$condidx)) {
 4098:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 4099: 	   $allpathcond.=
 4100:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 4101:        }
 4102:     }
 4103:     $allpathcond=~s/\|$//;
 4104:     if ($ENV{'request.course.id'}) {
 4105:        if ($allpathcond) {
 4106:           my $operand='|';
 4107: 	  my @stack;
 4108:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 4109:               if ($_ eq '(') {
 4110:                  push @stack,($operand,$result)
 4111:               } elsif ($_ eq ')') {
 4112:                   my $before=pop @stack;
 4113: 		  if (pop @stack eq '&') {
 4114: 		      $result=$result>$before?$before:$result;
 4115:                   } else {
 4116:                       $result=$result>$before?$result:$before;
 4117:                   }
 4118:               } elsif (($_ eq '&') || ($_ eq '|')) {
 4119:                   $operand=$_;
 4120:               } else {
 4121:                   my $new=directcondval($_);
 4122:                   if ($operand eq '&') {
 4123:                      $result=$result>$new?$new:$result;
 4124:                   } else {
 4125:                      $result=$result>$new?$result:$new;
 4126:                   }
 4127:               }
 4128:           }
 4129:        }
 4130:     }
 4131:     return $result;
 4132: }
 4133: 
 4134: # ---------------------------------------------------- Devalidate courseresdata
 4135: 
 4136: sub devalidatecourseresdata {
 4137:     my ($coursenum,$coursedomain)=@_;
 4138:     my $hashid=$coursenum.':'.$coursedomain;
 4139:     &devalidate_cache(\%courseresdatacache,$hashid,'courseres');
 4140: }
 4141: 
 4142: # --------------------------------------------------- Course Resourcedata Query
 4143: 
 4144: sub courseresdata {
 4145:     my ($coursenum,$coursedomain,@which)=@_;
 4146:     my $coursehom=&homeserver($coursenum,$coursedomain);
 4147:     my $hashid=$coursenum.':'.$coursedomain;
 4148:     my ($result,$cached)=&is_cached(\%courseresdatacache,$hashid,'courseres');
 4149:     unless (defined($cached)) {
 4150: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 4151: 	$result=\%dumpreply;
 4152: 	my ($tmp) = keys(%dumpreply);
 4153: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 4154: 	    &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
 4155: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4156: 	    return $tmp;
 4157: 	} elsif ($tmp =~ /^(error)/) {
 4158: 	    $result=undef;
 4159: 	    &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
 4160: 	}
 4161:     }
 4162:     foreach my $item (@which) {
 4163: 	if (defined($result->{$item})) {
 4164: 	    return $result->{$item};
 4165: 	}
 4166:     }
 4167:     return undef;
 4168: }
 4169: 
 4170: #
 4171: # EXT resource caching routines
 4172: #
 4173: 
 4174: sub clear_EXT_cache_status {
 4175:     &delenv('cache.EXT.');
 4176: }
 4177: 
 4178: sub EXT_cache_status {
 4179:     my ($target_domain,$target_user) = @_;
 4180:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4181:     if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
 4182:         # We know already the user has no data
 4183:         return 1;
 4184:     } else {
 4185:         return 0;
 4186:     }
 4187: }
 4188: 
 4189: sub EXT_cache_set {
 4190:     my ($target_domain,$target_user) = @_;
 4191:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4192:     &appenv($cachename => time);
 4193: }
 4194: 
 4195: # --------------------------------------------------------- Value of a Variable
 4196: sub EXT {
 4197:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 4198: 
 4199:     unless ($varname) { return ''; }
 4200:     #get real user name/domain, courseid and symb
 4201:     my $courseid;
 4202:     my $publicuser;
 4203:     if ($symbparm) {
 4204: 	$symbparm=&get_symb_from_alias($symbparm);
 4205:     }
 4206:     if (!($uname && $udom)) {
 4207:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 4208: 	  &Apache::lonxml::whichuser($symbparm);
 4209:       if (!$symbparm) {	$symbparm=$cursymb; }
 4210:     } else {
 4211: 	$courseid=$ENV{'request.course.id'};
 4212:     }
 4213:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 4214:     my $rest;
 4215:     if (defined($therest[0])) {
 4216:        $rest=join('.',@therest);
 4217:     } else {
 4218:        $rest='';
 4219:     }
 4220: 
 4221:     my $qualifierrest=$qualifier;
 4222:     if ($rest) { $qualifierrest.='.'.$rest; }
 4223:     my $spacequalifierrest=$space;
 4224:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 4225:     if ($realm eq 'user') {
 4226: # --------------------------------------------------------------- user.resource
 4227: 	if ($space eq 'resource') {
 4228: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
 4229: 		return $Apache::lonhomework::history{$qualifierrest};
 4230: 	    } else {
 4231: 		my %restored;
 4232: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
 4233: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 4234: 		} else {
 4235: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 4236: 		}
 4237: 		return $restored{$qualifierrest};
 4238: 	    }
 4239: # ----------------------------------------------------------------- user.access
 4240:         } elsif ($space eq 'access') {
 4241: 	    # FIXME - not supporting calls for a specific user
 4242:             return &allowed($qualifier,$rest);
 4243: # ------------------------------------------ user.preferences, user.environment
 4244:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 4245: 	    if (($uname eq $ENV{'user.name'}) &&
 4246: 		($udom eq $ENV{'user.domain'})) {
 4247: 		return $ENV{join('.',('environment',$qualifierrest))};
 4248: 	    } else {
 4249: 		my %returnhash;
 4250: 		if (!$publicuser) {
 4251: 		    %returnhash=&userenvironment($udom,$uname,
 4252: 						 $qualifierrest);
 4253: 		}
 4254: 		return $returnhash{$qualifierrest};
 4255: 	    }
 4256: # ----------------------------------------------------------------- user.course
 4257:         } elsif ($space eq 'course') {
 4258: 	    # FIXME - not supporting calls for a specific user
 4259:             return $ENV{join('.',('request.course',$qualifier))};
 4260: # ------------------------------------------------------------------- user.role
 4261:         } elsif ($space eq 'role') {
 4262: 	    # FIXME - not supporting calls for a specific user
 4263:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 4264:             if ($qualifier eq 'value') {
 4265: 		return $role;
 4266:             } elsif ($qualifier eq 'extent') {
 4267:                 return $where;
 4268:             }
 4269: # ----------------------------------------------------------------- user.domain
 4270:         } elsif ($space eq 'domain') {
 4271:             return $udom;
 4272: # ------------------------------------------------------------------- user.name
 4273:         } elsif ($space eq 'name') {
 4274:             return $uname;
 4275: # ---------------------------------------------------- Any other user namespace
 4276:         } else {
 4277: 	    my %reply;
 4278: 	    if (!$publicuser) {
 4279: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 4280: 	    }
 4281: 	    return $reply{$qualifierrest};
 4282:         }
 4283:     } elsif ($realm eq 'query') {
 4284: # ---------------------------------------------- pull stuff out of query string
 4285:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4286: 						[$spacequalifierrest]);
 4287: 	return $ENV{'form.'.$spacequalifierrest}; 
 4288:    } elsif ($realm eq 'request') {
 4289: # ------------------------------------------------------------- request.browser
 4290:         if ($space eq 'browser') {
 4291: 	    if ($qualifier eq 'textremote') {
 4292: 		if (&mt('textual_remote_display') eq 'on') {
 4293: 		    return 1;
 4294: 		} else {
 4295: 		    return 0;
 4296: 		}
 4297: 	    } else {
 4298: 		return $ENV{'browser.'.$qualifier};
 4299: 	    }
 4300: # ------------------------------------------------------------ request.filename
 4301:         } else {
 4302:             return $ENV{'request.'.$spacequalifierrest};
 4303:         }
 4304:     } elsif ($realm eq 'course') {
 4305: # ---------------------------------------------------------- course.description
 4306:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
 4307:     } elsif ($realm eq 'resource') {
 4308: 
 4309: 	my $section;
 4310: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
 4311: 	    if (!$symbparm) { $symbparm=&symbread(); }
 4312: 	}
 4313: 	if ($symbparm && defined($courseid) && 
 4314: 	    $courseid eq $ENV{'request.course.id'}) {
 4315: 
 4316: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 4317: 
 4318: # ----------------------------------------------------- Cascading lookup scheme
 4319: 	    my $symbp=$symbparm;
 4320: 	    my $mapp=(&decode_symb($symbp))[0];
 4321: 
 4322: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 4323: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 4324: 
 4325: 	    if (($ENV{'user.name'} eq $uname) &&
 4326: 		($ENV{'user.domain'} eq $udom)) {
 4327: 		$section=$ENV{'request.course.sec'};
 4328: 	    } else {
 4329: 		if (! defined($usection)) {
 4330: 		    $section=&getsection($udom,$uname,$courseid);
 4331: 		} else {
 4332: 		    $section = $usection;
 4333: 		}
 4334: 	    }
 4335: 
 4336: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 4337: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 4338: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 4339: 
 4340: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
 4341: 	    my $courselevelr=$courseid.'.'.$symbparm;
 4342: 	    my $courselevelm=$courseid.'.'.$mapparm;
 4343: 
 4344: # ----------------------------------------------------------- first, check user
 4345: 	    #most student don\'t have any data set, check if there is some data
 4346: 	    if (! &EXT_cache_status($udom,$uname)) {
 4347: 		my $hashid="$udom:$uname";
 4348: 		my ($result,$cached)=&is_cached(\%userresdatacache,$hashid,
 4349: 						'userres');
 4350: 		if (!defined($cached)) {
 4351: 		    my %resourcedata=&dump('resourcedata',$udom,$uname);
 4352: 		    $result=\%resourcedata;
 4353: 		    &do_cache(\%userresdatacache,$hashid,$result,'userres');
 4354: 		}
 4355: 		my ($tmp)=keys(%$result);
 4356: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 4357: 		    if ($$result{$courselevelr}) {
 4358: 			return $$result{$courselevelr}; }
 4359: 		    if ($$result{$courselevelm}) {
 4360: 			return $$result{$courselevelm}; }
 4361: 		    if ($$result{$courselevel}) {
 4362: 			return $$result{$courselevel}; }
 4363: 		} else {
 4364: 		    #error 2 occurs when the .db doesn't exist
 4365: 		    if ($tmp!~/error: 2 /) {
 4366: 			&logthis("<font color=blue>WARNING:".
 4367: 				 " Trying to get resource data for ".
 4368: 				 $uname." at ".$udom.": ".
 4369: 				 $tmp."</font>");
 4370: 		    } elsif ($tmp=~/error: 2 /) {
 4371: 			&EXT_cache_set($udom,$uname);
 4372: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4373: 			return $tmp;
 4374: 		    }
 4375: 		}
 4376: 	    }
 4377: 
 4378: # -------------------------------------------------------- second, check course
 4379: 
 4380: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
 4381: 					   $ENV{'course.'.$courseid.'.domain'},
 4382: 					   ($seclevelr,$seclevelm,$seclevel,
 4383: 					    $courselevelr,$courselevelm,
 4384: 					    $courselevel));
 4385: 	    if (defined($coursereply)) { return $coursereply; }
 4386: 
 4387: # ------------------------------------------------------ third, check map parms
 4388: 	    my %parmhash=();
 4389: 	    my $thisparm='';
 4390: 	    if (tie(%parmhash,'GDBM_File',
 4391: 		    $ENV{'request.course.fn'}.'_parms.db',
 4392: 		    &GDBM_READER(),0640)) {
 4393: 		$thisparm=$parmhash{$symbparm};
 4394: 		untie(%parmhash);
 4395: 	    }
 4396: 	    if ($thisparm) { return $thisparm; }
 4397: 	}
 4398: # --------------------------------------------- last, look in resource metadata
 4399: 
 4400: 	$spacequalifierrest=~s/\./\_/;
 4401: 	my $filename;
 4402: 	if (!$symbparm) { $symbparm=&symbread(); }
 4403: 	if ($symbparm) {
 4404: 	    $filename=(&decode_symb($symbparm))[2];
 4405: 	} else {
 4406: 	    $filename=$ENV{'request.filename'};
 4407: 	}
 4408: 	my $metadata=&metadata($filename,$spacequalifierrest);
 4409: 	if (defined($metadata)) { return $metadata; }
 4410: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 4411: 	if (defined($metadata)) { return $metadata; }
 4412: 
 4413: # ------------------------------------------------------------------ Cascade up
 4414: 	unless ($space eq '0') {
 4415: 	    my @parts=split(/_/,$space);
 4416: 	    my $id=pop(@parts);
 4417: 	    my $part=join('_',@parts);
 4418: 	    if ($part eq '') { $part='0'; }
 4419: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 4420: 				 $symbparm,$udom,$uname,$section,1);
 4421: 	    if (defined($partgeneral)) { return $partgeneral; }
 4422: 	}
 4423: 	if ($recurse) { return undef; }
 4424: 	my $pack_def=&packages_tab_default($filename,$varname);
 4425: 	if (defined($pack_def)) { return $pack_def; }
 4426: 
 4427: # ---------------------------------------------------- Any other user namespace
 4428:     } elsif ($realm eq 'environment') {
 4429: # ----------------------------------------------------------------- environment
 4430: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
 4431: 	    return $ENV{'environment.'.$spacequalifierrest};
 4432: 	} else {
 4433: 	    my %returnhash=&userenvironment($udom,$uname,
 4434: 					    $spacequalifierrest);
 4435: 	    return $returnhash{$spacequalifierrest};
 4436: 	}
 4437:     } elsif ($realm eq 'system') {
 4438: # ----------------------------------------------------------------- system.time
 4439: 	if ($space eq 'time') {
 4440: 	    return time;
 4441:         }
 4442:     }
 4443:     return '';
 4444: }
 4445: 
 4446: sub packages_tab_default {
 4447:     my ($uri,$varname)=@_;
 4448:     my (undef,$part,$name)=split(/\./,$varname);
 4449:     my $packages=&metadata($uri,'packages');
 4450:     foreach my $package (split(/,/,$packages)) {
 4451: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 4452: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 4453: 	    return $packagetab{"$pack_type&$name&default"};
 4454: 	}
 4455: 	if ($pack_type eq 'part') { $pack_part='0'; }
 4456: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 4457: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 4458: 	}
 4459:     }
 4460:     return undef;
 4461: }
 4462: 
 4463: sub add_prefix_and_part {
 4464:     my ($prefix,$part)=@_;
 4465:     my $keyroot;
 4466:     if (defined($prefix) && $prefix !~ /^__/) {
 4467: 	# prefix that has a part already
 4468: 	$keyroot=$prefix;
 4469:     } elsif (defined($prefix)) {
 4470: 	# prefix that is missing a part
 4471: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 4472:     } else {
 4473: 	# no prefix at all
 4474: 	if (defined($part)) { $keyroot='_'.$part; }
 4475:     }
 4476:     return $keyroot;
 4477: }
 4478: 
 4479: # ---------------------------------------------------------------- Get metadata
 4480: 
 4481: sub metadata {
 4482:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 4483:     $uri=&declutter($uri);
 4484:     # if it is a non metadata possible uri return quickly
 4485:     if (($uri eq '') || 
 4486: 	(($uri =~ m|^/*adm/|) && 
 4487: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 4488:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 4489: 	($uri =~ m|home/[^/]+/public_html/|)) {
 4490: 	return undef;
 4491:     }
 4492:     my $filename=$uri;
 4493:     $uri=~s/\.meta$//;
 4494: #
 4495: # Is the metadata already cached?
 4496: # Look at timestamp of caching
 4497: # Everything is cached by the main uri, libraries are never directly cached
 4498: #
 4499:     if (!defined($liburi)) {
 4500: 	my ($result,$cached)=&is_cached(\%metacache,$uri,'meta');
 4501: 	if (defined($cached)) { return $result->{':'.$what}; }
 4502:     }
 4503:     {
 4504: #
 4505: # Is this a recursive call for a library?
 4506: #
 4507: 	if (! exists($metacache{$uri})) {
 4508: 	    $metacache{$uri}={};
 4509: 	}
 4510:         if ($liburi) {
 4511: 	    $liburi=&declutter($liburi);
 4512:             $filename=$liburi;
 4513:         } else {
 4514: 	    &devalidate_cache(\%metacache,$uri,'meta');
 4515: 	}
 4516:         my %metathesekeys=();
 4517:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 4518: 	my $metastring;
 4519: 	if ($uri !~ m|^uploaded/|) {
 4520: 	    my $file=&filelocation('',&clutter($filename));
 4521: 	    push(@{$metacache{$uri.'.file'}},$file);
 4522: 	    $metastring=&getfile($file);
 4523: 	}
 4524:         my $parser=HTML::LCParser->new(\$metastring);
 4525:         my $token;
 4526:         undef %metathesekeys;
 4527:         while ($token=$parser->get_token) {
 4528: 	    if ($token->[0] eq 'S') {
 4529: 		if (defined($token->[2]->{'package'})) {
 4530: #
 4531: # This is a package - get package info
 4532: #
 4533: 		    my $package=$token->[2]->{'package'};
 4534: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 4535: 		    if (defined($token->[2]->{'id'})) { 
 4536: 			$keyroot.='_'.$token->[2]->{'id'}; 
 4537: 		    }
 4538: 		    if ($metacache{$uri}->{':packages'}) {
 4539: 			$metacache{$uri}->{':packages'}.=','.$package.$keyroot;
 4540: 		    } else {
 4541: 			$metacache{$uri}->{':packages'}=$package.$keyroot;
 4542: 		    }
 4543: 		    foreach (keys %packagetab) {
 4544: 			my $part=$keyroot;
 4545: 			$part=~s/^\_//;
 4546: 			if ($_=~/^\Q$package\E\&/ || 
 4547: 			    $_=~/^\Q$package\E_0\&/) {
 4548: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 4549: 			    # ignore package.tab specified default values
 4550:                             # here &package_tab_default() will fetch those
 4551: 			    if ($subp eq 'default') { next; }
 4552: 			    my $value=$packagetab{$_};
 4553: 			    my $unikey;
 4554: 			    if ($pack =~ /_0$/) {
 4555: 				$unikey='parameter_0_'.$name;
 4556: 				$part=0;
 4557: 			    } else {
 4558: 				$unikey='parameter'.$keyroot.'_'.$name;
 4559: 			    }
 4560: 			    if ($subp eq 'display') {
 4561: 				$value.=' [Part: '.$part.']';
 4562: 			    }
 4563: 			    $metacache{$uri}->{':'.$unikey.'.part'}=$part;
 4564: 			    $metathesekeys{$unikey}=1;
 4565: 			    unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) {
 4566: 				$metacache{$uri}->{':'.$unikey.'.'.$subp}=$value;
 4567: 			    }
 4568: 			    if (defined($metacache{$uri}->{':'.$unikey.'.default'})) {
 4569: 				$metacache{$uri}->{':'.$unikey}=
 4570: 				    $metacache{$uri}->{':'.$unikey.'.default'};
 4571: 			    }
 4572: 			}
 4573: 		    }
 4574: 		} else {
 4575: #
 4576: # This is not a package - some other kind of start tag
 4577: #
 4578: 		    my $entry=$token->[1];
 4579: 		    my $unikey;
 4580: 		    if ($entry eq 'import') {
 4581: 			$unikey='';
 4582: 		    } else {
 4583: 			$unikey=$entry;
 4584: 		    }
 4585: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 4586: 
 4587: 		    if (defined($token->[2]->{'id'})) { 
 4588: 			$unikey.='_'.$token->[2]->{'id'}; 
 4589: 		    }
 4590: 
 4591: 		    if ($entry eq 'import') {
 4592: #
 4593: # Importing a library here
 4594: #
 4595: 			if ($depthcount<20) {
 4596: 			    my $location=$parser->get_text('/import');
 4597: 			    my $dir=$filename;
 4598: 			    $dir=~s|[^/]*$||;
 4599: 			    $location=&filelocation($dir,$location);
 4600: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 4601: 							       $location,$unikey,
 4602: 							       $depthcount+1)))) {
 4603: 				$metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
 4604: 				$metathesekeys{$_}=1;
 4605: 			    }
 4606: 			}
 4607: 		    } else { 
 4608: 			
 4609: 			if (defined($token->[2]->{'name'})) { 
 4610: 			    $unikey.='_'.$token->[2]->{'name'}; 
 4611: 			}
 4612: 			$metathesekeys{$unikey}=1;
 4613: 			foreach (@{$token->[3]}) {
 4614: 			    $metacache{$uri}->{':'.$unikey.'.'.$_}=$token->[2]->{$_};
 4615: 			}
 4616: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 4617: 			my $default=$metacache{$uri}->{':'.$unikey.'.default'};
 4618: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 4619: 		 # only ws inside the tag, and not in default, so use default
 4620: 		 # as value
 4621: 			    $metacache{$uri}->{':'.$unikey}=$default;
 4622: 			} else {
 4623: 		  # either something interesting inside the tag or default
 4624:                   # uninteresting
 4625: 			    $metacache{$uri}->{':'.$unikey}=$internaltext;
 4626: 			}
 4627: # end of not-a-package not-a-library import
 4628: 		    }
 4629: # end of not-a-package start tag
 4630: 		}
 4631: # the next is the end of "start tag"
 4632: 	    }
 4633: 	}
 4634: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 4635: 	foreach my $key (sort(keys(%packagetab))) {
 4636: 	    #&logthis("extsion1 $extension $key !!");
 4637: 	    #no specific packages #how's our extension
 4638: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 4639: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 4640: 					 \%metathesekeys);
 4641: 	}
 4642: 	if (!exists($metacache{$uri}->{':packages'})) {
 4643: 	    foreach my $key (sort(keys(%packagetab))) {
 4644: 		#no specific packages well let's get default then
 4645: 		if ($key!~/^default&/) { next; }
 4646: 		&metadata_create_package_def($uri,$key,'default',
 4647: 					     \%metathesekeys);
 4648: 	    }
 4649: 	}
 4650: # are there custom rights to evaluate
 4651: 	if ($metacache{$uri}->{':copyright'} eq 'custom') {
 4652: 
 4653:     #
 4654:     # Importing a rights file here
 4655:     #
 4656: 	    unless ($depthcount) {
 4657: 		my $location=$metacache{$uri}->{':customdistributionfile'};
 4658: 		my $dir=$filename;
 4659: 		$dir=~s|[^/]*$||;
 4660: 		$location=&filelocation($dir,$location);
 4661: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 4662: 						   $location,'_rights',
 4663: 						   $depthcount+1)))) {
 4664: 		    $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
 4665: 		    $metathesekeys{$_}=1;
 4666: 		}
 4667: 	    }
 4668: 	}
 4669: 	$metacache{$uri}->{':keys'}=join(',',keys %metathesekeys);
 4670: 	&metadata_generate_part0(\%metathesekeys,$metacache{$uri},$uri);
 4671: 	$metacache{$uri}->{':allpossiblekeys'}=join(',',keys %metathesekeys);
 4672: 	&do_cache(\%metacache,$uri,$metacache{$uri},'meta');
 4673: # this is the end of "was not already recently cached
 4674:     }
 4675:     return $metacache{$uri}->{':'.$what};
 4676: }
 4677: 
 4678: sub metadata_create_package_def {
 4679:     my ($uri,$key,$package,$metathesekeys)=@_;
 4680:     my ($pack,$name,$subp)=split(/\&/,$key);
 4681:     if ($subp eq 'default') { next; }
 4682:     
 4683:     if (defined($metacache{$uri}->{':packages'})) {
 4684: 	$metacache{$uri}->{':packages'}.=','.$package;
 4685:     } else {
 4686: 	$metacache{$uri}->{':packages'}=$package;
 4687:     }
 4688:     my $value=$packagetab{$key};
 4689:     my $unikey;
 4690:     $unikey='parameter_0_'.$name;
 4691:     $metacache{$uri}->{':'.$unikey.'.part'}=0;
 4692:     $$metathesekeys{$unikey}=1;
 4693:     unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) {
 4694: 	$metacache{$uri}->{':'.$unikey.'.'.$subp}=$value;
 4695:     }
 4696:     if (defined($metacache{$uri}->{':'.$unikey.'.default'})) {
 4697: 	$metacache{$uri}->{':'.$unikey}=
 4698: 	    $metacache{$uri}->{':'.$unikey.'.default'};
 4699:     }
 4700: }
 4701: 
 4702: sub metadata_generate_part0 {
 4703:     my ($metadata,$metacache,$uri) = @_;
 4704:     my %allnames;
 4705:     foreach my $metakey (sort keys %$metadata) {
 4706: 	if ($metakey=~/^parameter\_(.*)/) {
 4707: 	  my $part=$$metacache{':'.$metakey.'.part'};
 4708: 	  my $name=$$metacache{':'.$metakey.'.name'};
 4709: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 4710: 	    $allnames{$name}=$part;
 4711: 	  }
 4712: 	}
 4713:     }
 4714:     foreach my $name (keys(%allnames)) {
 4715:       $$metadata{"parameter_0_$name"}=1;
 4716:       my $key=":parameter_0_$name";
 4717:       $$metacache{"$key.part"}='0';
 4718:       $$metacache{"$key.name"}=$name;
 4719:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 4720: 					   $allnames{$name}.'_'.$name.
 4721: 					   '.type'};
 4722:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 4723: 			     '.display'};
 4724:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 4725:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 4726:       $$metacache{"$key.display"}=$olddis;
 4727:     }
 4728: }
 4729: 
 4730: # ------------------------------------------------- Get the title of a resource
 4731: 
 4732: sub gettitle {
 4733:     my $urlsymb=shift;
 4734:     my $symb=&symbread($urlsymb);
 4735:     if ($symb) {
 4736: 	my ($result,$cached)=&is_cached(\%titlecache,$symb,'title',600);
 4737: 	if (defined($cached)) { 
 4738: 	    return $result;
 4739: 	}
 4740: 	my ($map,$resid,$url)=&decode_symb($symb);
 4741: 	my $title='';
 4742: 	my %bighash;
 4743: 	if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4744: 		&GDBM_READER(),0640)) {
 4745: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 4746: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 4747: 	    untie %bighash;
 4748: 	}
 4749: 	$title=~s/\&colon\;/\:/gs;
 4750: 	if ($title) {
 4751: 	    return &do_cache(\%titlecache,$symb,$title,'title');
 4752: 	}
 4753: 	$urlsymb=$url;
 4754:     }
 4755:     my $title=&metadata($urlsymb,'title');
 4756:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 4757:     return $title;
 4758: }
 4759:     
 4760: # ------------------------------------------------- Update symbolic store links
 4761: 
 4762: sub symblist {
 4763:     my ($mapname,%newhash)=@_;
 4764:     $mapname=&deversion(&declutter($mapname));
 4765:     my %hash;
 4766:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 4767:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 4768:                       &GDBM_WRCREAT(),0640)) {
 4769: 	    foreach (keys %newhash) {
 4770:                 $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_});
 4771:             }
 4772:             if (untie(%hash)) {
 4773: 		return 'ok';
 4774:             }
 4775:         }
 4776:     }
 4777:     return 'error';
 4778: }
 4779: 
 4780: # --------------------------------------------------------------- Verify a symb
 4781: 
 4782: sub symbverify {
 4783:     my ($symb,$thisurl)=@_;
 4784:     my $thisfn=$thisurl;
 4785: # wrapper not part of symbs
 4786:     $thisfn=~s/^\/adm\/wrapper//;
 4787:     $thisfn=&declutter($thisfn);
 4788: # direct jump to resource in page or to a sequence - will construct own symbs
 4789:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 4790: # check URL part
 4791:     my ($map,$resid,$url)=&decode_symb($symb);
 4792: 
 4793:     unless ($url eq $thisfn) { return 0; }
 4794: 
 4795:     $symb=&symbclean($symb);
 4796:     $thisurl=&deversion($thisurl);
 4797:     $thisfn=&deversion($thisfn);
 4798: 
 4799:     my %bighash;
 4800:     my $okay=0;
 4801: 
 4802:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4803:                             &GDBM_READER(),0640)) {
 4804:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 4805:         unless ($ids) { 
 4806:            $ids=$bighash{'ids_/'.$thisurl};
 4807:         }
 4808:         if ($ids) {
 4809: # ------------------------------------------------------------------- Has ID(s)
 4810: 	    foreach (split(/\,/,$ids)) {
 4811:                my ($mapid,$resid)=split(/\./,$_);
 4812:                if (
 4813:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 4814:    eq $symb) { 
 4815: 		   if (($ENV{'request.role.adv'}) ||
 4816: 		       $bighash{'encrypted_'.$_} eq $ENV{'request.enc'}) {
 4817: 		       $okay=1; 
 4818: 		   }
 4819: 	       }
 4820: 	   }
 4821:         }
 4822: 	untie(%bighash);
 4823:     }
 4824:     return $okay;
 4825: }
 4826: 
 4827: # --------------------------------------------------------------- Clean-up symb
 4828: 
 4829: sub symbclean {
 4830:     my $symb=shift;
 4831:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 4832: # remove version from map
 4833:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 4834: 
 4835: # remove version from URL
 4836:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 4837: 
 4838: # remove wrapper
 4839: 
 4840:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 4841:     return $symb;
 4842: }
 4843: 
 4844: # ---------------------------------------------- Split symb to find map and url
 4845: 
 4846: sub encode_symb {
 4847:     my ($map,$resid,$url)=@_;
 4848:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 4849: }
 4850: 
 4851: sub decode_symb {
 4852:     my $symb=shift;
 4853:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 4854:     my ($map,$resid,$url)=split(/___/,$symb);
 4855:     return (&fixversion($map),$resid,&fixversion($url));
 4856: }
 4857: 
 4858: sub fixversion {
 4859:     my $fn=shift;
 4860:     if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
 4861:     my %bighash;
 4862:     my $uri=&clutter($fn);
 4863:     my $key=$ENV{'request.course.id'}.'_'.$uri;
 4864: # is this cached?
 4865:     my ($result,$cached)=&is_cached(\%courseresversioncache,$key,
 4866: 				    'courseresversion',600);
 4867:     if (defined($cached)) { return $result; }
 4868: # unfortunately not cached, or expired
 4869:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4870: 	    &GDBM_READER(),0640)) {
 4871:  	if ($bighash{'version_'.$uri}) {
 4872:  	    my $version=$bighash{'version_'.$uri};
 4873:  	    unless (($version eq 'mostrecent') || 
 4874: 		    ($version==&getversion($uri))) {
 4875:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 4876:  	    }
 4877:  	}
 4878:  	untie %bighash;
 4879:     }
 4880:     return &do_cache
 4881: 	(\%courseresversioncache,$key,&declutter($uri),'courseresversion');
 4882: }
 4883: 
 4884: sub deversion {
 4885:     my $url=shift;
 4886:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 4887:     return $url;
 4888: }
 4889: 
 4890: # ------------------------------------------------------ Return symb list entry
 4891: 
 4892: sub symbread {
 4893:     my ($thisfn,$donotrecurse)=@_;
 4894:     my $cache_str='request.symbread.cached.'.$thisfn;
 4895:     if (defined($ENV{$cache_str})) { return $ENV{$cache_str}; }
 4896: # no filename provided? try from environment
 4897:     unless ($thisfn) {
 4898:         if ($ENV{'request.symb'}) {
 4899: 	    return $ENV{$cache_str}=&symbclean($ENV{'request.symb'});
 4900: 	}
 4901: 	$thisfn=$ENV{'request.filename'};
 4902:     }
 4903:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 4904: # is that filename actually a symb? Verify, clean, and return
 4905:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 4906: 	if (&symbverify($thisfn,$1)) {
 4907: 	    return $ENV{$cache_str}=&symbclean($thisfn);
 4908: 	}
 4909:     }
 4910:     $thisfn=declutter($thisfn);
 4911:     my %hash;
 4912:     my %bighash;
 4913:     my $syval='';
 4914:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 4915:         my $targetfn = $thisfn;
 4916:         if ( ($thisfn =~ m/^uploaded\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 4917:             $targetfn = 'adm/wrapper/'.$thisfn;
 4918:         }
 4919:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 4920:                       &GDBM_READER(),0640)) {
 4921: 	    $syval=$hash{$targetfn};
 4922:             untie(%hash);
 4923:         }
 4924: # ---------------------------------------------------------- There was an entry
 4925:         if ($syval) {
 4926:            unless ($syval=~/\_\d+$/) {
 4927: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 4928:                   &appenv('request.ambiguous' => $thisfn);
 4929: 		  return $ENV{$cache_str}='';
 4930:                }    
 4931:                $syval.=$1;
 4932: 	   }
 4933:         } else {
 4934: # ------------------------------------------------------- Was not in symb table
 4935:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4936:                             &GDBM_READER(),0640)) {
 4937: # ---------------------------------------------- Get ID(s) for current resource
 4938:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 4939:               unless ($ids) { 
 4940:                  $ids=$bighash{'ids_/'.$thisfn};
 4941:               }
 4942:               unless ($ids) {
 4943: # alias?
 4944: 		  $ids=$bighash{'mapalias_'.$thisfn};
 4945:               }
 4946:               if ($ids) {
 4947: # ------------------------------------------------------------------- Has ID(s)
 4948:                  my @possibilities=split(/\,/,$ids);
 4949:                  if ($#possibilities==0) {
 4950: # ----------------------------------------------- There is only one possibility
 4951: 		     my ($mapid,$resid)=split(/\./,$ids);
 4952:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 4953:                  } elsif (!$donotrecurse) {
 4954: # ------------------------------------------ There is more than one possibility
 4955:                      my $realpossible=0;
 4956:                      foreach (@possibilities) {
 4957: 			 my $file=$bighash{'src_'.$_};
 4958:                          if (&allowed('bre',$file)) {
 4959:          		    my ($mapid,$resid)=split(/\./,$_);
 4960:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 4961: 				$realpossible++;
 4962:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 4963:                                        '___'.$resid;
 4964:                             }
 4965: 			 }
 4966:                      }
 4967: 		     if ($realpossible!=1) { $syval=''; }
 4968:                  } else {
 4969:                      $syval='';
 4970:                  }
 4971: 	      }
 4972:               untie(%bighash)
 4973:            }
 4974:         }
 4975:         if ($syval) {
 4976: 	    return $ENV{$cache_str}=&symbclean($syval.'___'.$thisfn);
 4977:         }
 4978:     }
 4979:     &appenv('request.ambiguous' => $thisfn);
 4980:     return $ENV{$cache_str}='';
 4981: }
 4982: 
 4983: # ---------------------------------------------------------- Return random seed
 4984: 
 4985: sub numval {
 4986:     my $txt=shift;
 4987:     $txt=~tr/A-J/0-9/;
 4988:     $txt=~tr/a-j/0-9/;
 4989:     $txt=~tr/K-T/0-9/;
 4990:     $txt=~tr/k-t/0-9/;
 4991:     $txt=~tr/U-Z/0-5/;
 4992:     $txt=~tr/u-z/0-5/;
 4993:     $txt=~s/\D//g;
 4994:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 4995:     return int($txt);
 4996: }
 4997: 
 4998: sub numval2 {
 4999:     my $txt=shift;
 5000:     $txt=~tr/A-J/0-9/;
 5001:     $txt=~tr/a-j/0-9/;
 5002:     $txt=~tr/K-T/0-9/;
 5003:     $txt=~tr/k-t/0-9/;
 5004:     $txt=~tr/U-Z/0-5/;
 5005:     $txt=~tr/u-z/0-5/;
 5006:     $txt=~s/\D//g;
 5007:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5008:     my $total;
 5009:     foreach my $val (@txts) { $total+=$val; }
 5010:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 5011:     return int($total);
 5012: }
 5013: 
 5014: sub numval3 {
 5015:     use integer;
 5016:     my $txt=shift;
 5017:     $txt=~tr/A-J/0-9/;
 5018:     $txt=~tr/a-j/0-9/;
 5019:     $txt=~tr/K-T/0-9/;
 5020:     $txt=~tr/k-t/0-9/;
 5021:     $txt=~tr/U-Z/0-5/;
 5022:     $txt=~tr/u-z/0-5/;
 5023:     $txt=~s/\D//g;
 5024:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5025:     my $total;
 5026:     foreach my $val (@txts) { $total+=$val; }
 5027:     if ($_64bit) { $total=(($total<<32)>>32); }
 5028:     return $total;
 5029: }
 5030: 
 5031: sub latest_rnd_algorithm_id {
 5032:     return '64bit4';
 5033: }
 5034: 
 5035: sub get_rand_alg {
 5036:     my ($courseid)=@_;
 5037:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 5038:     if ($courseid) {
 5039: 	return $ENV{"course.$courseid.rndseed"};
 5040:     }
 5041:     return &latest_rnd_algorithm_id();
 5042: }
 5043: 
 5044: sub validCODE {
 5045:     my ($CODE)=@_;
 5046:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 5047:     return 0;
 5048: }
 5049: 
 5050: sub getCODE {
 5051:     if (&validCODE($ENV{'form.CODE'})) { return $ENV{'form.CODE'}; }
 5052:     if (defined($Apache::lonhomework::parsing_a_problem) &&
 5053: 	&validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 5054: 	return $Apache::lonhomework::history{'resource.CODE'};
 5055:     }
 5056:     return undef;
 5057: }
 5058: 
 5059: sub rndseed {
 5060:     my ($symb,$courseid,$domain,$username)=@_;
 5061: 
 5062:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 5063:     if (!$symb) {
 5064: 	unless ($symb=$wsymb) { return time; }
 5065:     }
 5066:     if (!$courseid) { $courseid=$wcourseid; }
 5067:     if (!$domain) { $domain=$wdomain; }
 5068:     if (!$username) { $username=$wusername }
 5069:     my $which=&get_rand_alg();
 5070:     if (defined(&getCODE())) {
 5071: 	if ($which eq '64bit4') {
 5072: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 5073: 	} else {
 5074: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 5075: 	}
 5076:     } elsif ($which eq '64bit4') {
 5077: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 5078:     } elsif ($which eq '64bit3') {
 5079: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 5080:     } elsif ($which eq '64bit2') {
 5081: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 5082:     } elsif ($which eq '64bit') {
 5083: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 5084:     }
 5085:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 5086: }
 5087: 
 5088: sub rndseed_32bit {
 5089:     my ($symb,$courseid,$domain,$username)=@_;
 5090:     {
 5091: 	use integer;
 5092: 	my $symbchck=unpack("%32C*",$symb) << 27;
 5093: 	my $symbseed=numval($symb) << 22;
 5094: 	my $namechck=unpack("%32C*",$username) << 17;
 5095: 	my $nameseed=numval($username) << 12;
 5096: 	my $domainseed=unpack("%32C*",$domain) << 7;
 5097: 	my $courseseed=unpack("%32C*",$courseid);
 5098: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 5099: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5100: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5101: 	if ($_64bit) { $num=(($num<<32)>>32); }
 5102: 	return $num;
 5103:     }
 5104: }
 5105: 
 5106: sub rndseed_64bit {
 5107:     my ($symb,$courseid,$domain,$username)=@_;
 5108:     {
 5109: 	use integer;
 5110: 	my $symbchck=unpack("%32S*",$symb) << 21;
 5111: 	my $symbseed=numval($symb) << 10;
 5112: 	my $namechck=unpack("%32S*",$username);
 5113: 	
 5114: 	my $nameseed=numval($username) << 21;
 5115: 	my $domainseed=unpack("%32S*",$domain) << 10;
 5116: 	my $courseseed=unpack("%32S*",$courseid);
 5117: 	
 5118: 	my $num1=$symbchck+$symbseed+$namechck;
 5119: 	my $num2=$nameseed+$domainseed+$courseseed;
 5120: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5121: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5122: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5123: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5124: 	return "$num1,$num2";
 5125:     }
 5126: }
 5127: 
 5128: sub rndseed_64bit2 {
 5129:     my ($symb,$courseid,$domain,$username)=@_;
 5130:     {
 5131: 	use integer;
 5132: 	# strings need to be an even # of cahracters long, it it is odd the
 5133:         # last characters gets thrown away
 5134: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5135: 	my $symbseed=numval($symb) << 10;
 5136: 	my $namechck=unpack("%32S*",$username.' ');
 5137: 	
 5138: 	my $nameseed=numval($username) << 21;
 5139: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5140: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5141: 	
 5142: 	my $num1=$symbchck+$symbseed+$namechck;
 5143: 	my $num2=$nameseed+$domainseed+$courseseed;
 5144: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5145: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5146: 	return "$num1,$num2";
 5147:     }
 5148: }
 5149: 
 5150: sub rndseed_64bit3 {
 5151:     my ($symb,$courseid,$domain,$username)=@_;
 5152:     {
 5153: 	use integer;
 5154: 	# strings need to be an even # of cahracters long, it it is odd the
 5155:         # last characters gets thrown away
 5156: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5157: 	my $symbseed=numval2($symb) << 10;
 5158: 	my $namechck=unpack("%32S*",$username.' ');
 5159: 	
 5160: 	my $nameseed=numval2($username) << 21;
 5161: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5162: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5163: 	
 5164: 	my $num1=$symbchck+$symbseed+$namechck;
 5165: 	my $num2=$nameseed+$domainseed+$courseseed;
 5166: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5167: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 5168: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5169: 	
 5170: 	return "$num1:$num2";
 5171:     }
 5172: }
 5173: 
 5174: sub rndseed_64bit4 {
 5175:     my ($symb,$courseid,$domain,$username)=@_;
 5176:     {
 5177: 	use integer;
 5178: 	# strings need to be an even # of cahracters long, it it is odd the
 5179:         # last characters gets thrown away
 5180: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5181: 	my $symbseed=numval3($symb) << 10;
 5182: 	my $namechck=unpack("%32S*",$username.' ');
 5183: 	
 5184: 	my $nameseed=numval3($username) << 21;
 5185: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5186: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5187: 	
 5188: 	my $num1=$symbchck+$symbseed+$namechck;
 5189: 	my $num2=$nameseed+$domainseed+$courseseed;
 5190: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5191: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 5192: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5193: 	
 5194: 	return "$num1:$num2";
 5195:     }
 5196: }
 5197: 
 5198: sub rndseed_CODE_64bit {
 5199:     my ($symb,$courseid,$domain,$username)=@_;
 5200:     {
 5201: 	use integer;
 5202: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 5203: 	my $symbseed=numval2($symb);
 5204: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 5205: 	my $CODEseed=numval(&getCODE());
 5206: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5207: 	my $num1=$symbseed+$CODEchck;
 5208: 	my $num2=$CODEseed+$courseseed+$symbchck;
 5209: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 5210: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 5211: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 5212: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 5213: 	return "$num1:$num2";
 5214:     }
 5215: }
 5216: 
 5217: sub rndseed_CODE_64bit4 {
 5218:     my ($symb,$courseid,$domain,$username)=@_;
 5219:     {
 5220: 	use integer;
 5221: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 5222: 	my $symbseed=numval3($symb);
 5223: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 5224: 	my $CODEseed=numval3(&getCODE());
 5225: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5226: 	my $num1=$symbseed+$CODEchck;
 5227: 	my $num2=$CODEseed+$courseseed+$symbchck;
 5228: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 5229: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 5230: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 5231: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 5232: 	return "$num1:$num2";
 5233:     }
 5234: }
 5235: 
 5236: sub setup_random_from_rndseed {
 5237:     my ($rndseed)=@_;
 5238:     if ($rndseed =~/([,:])/) {
 5239: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 5240: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 5241:     } else {
 5242: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 5243:     }
 5244: }
 5245: 
 5246: sub latest_receipt_algorithm_id {
 5247:     return 'receipt2';
 5248: }
 5249: 
 5250: sub recunique {
 5251:     my $fucourseid=shift;
 5252:     my $unique;
 5253:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 5254: 	$unique=$ENV{"course.$fucourseid.internal.encseed"};
 5255:     } else {
 5256: 	$unique=$perlvar{'lonReceipt'};
 5257:     }
 5258:     return unpack("%32C*",$unique);
 5259: }
 5260: 
 5261: sub recprefix {
 5262:     my $fucourseid=shift;
 5263:     my $prefix;
 5264:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 5265: 	$prefix=$ENV{"course.$fucourseid.internal.encpref"};
 5266:     } else {
 5267: 	$prefix=$perlvar{'lonHostID'};
 5268:     }
 5269:     return unpack("%32C*",$prefix);
 5270: }
 5271: 
 5272: sub ireceipt {
 5273:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 5274:     my $cuname=unpack("%32C*",$funame);
 5275:     my $cudom=unpack("%32C*",$fudom);
 5276:     my $cucourseid=unpack("%32C*",$fucourseid);
 5277:     my $cusymb=unpack("%32C*",$fusymb);
 5278:     my $cunique=&recunique($fucourseid);
 5279:     my $cpart=unpack("%32S*",$part);
 5280:     my $return =&recprefix($fucourseid).'-';
 5281:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 5282: 	$ENV{'request.state'} eq 'construct') {
 5283: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 5284: 			       " and ".($cpart%$cudom));
 5285: 			       
 5286: 	$return.= ($cunique%$cuname+
 5287: 		   $cunique%$cudom+
 5288: 		   $cusymb%$cuname+
 5289: 		   $cusymb%$cudom+
 5290: 		   $cucourseid%$cuname+
 5291: 		   $cucourseid%$cudom+
 5292: 		   $cpart%$cuname+
 5293: 		   $cpart%$cudom);
 5294:     } else {
 5295: 	$return.= ($cunique%$cuname+
 5296: 		   $cunique%$cudom+
 5297: 		   $cusymb%$cuname+
 5298: 		   $cusymb%$cudom+
 5299: 		   $cucourseid%$cuname+
 5300: 		   $cucourseid%$cudom);
 5301:     }
 5302:     return $return;
 5303: }
 5304: 
 5305: sub receipt {
 5306:     my ($part)=@_;
 5307:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 5308:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 5309: }
 5310: 
 5311: # ------------------------------------------------------------ Serves up a file
 5312: # returns either the contents of the file or 
 5313: # -1 if the file doesn't exist
 5314: #
 5315: # if the target is a file that was uploaded via DOCS, 
 5316: # a check will be made to see if a current copy exists on the local server,
 5317: # if it does this will be served, otherwise a copy will be retrieved from
 5318: # the home server for the course and stored in /home/httpd/html/userfiles on
 5319: # the local server.   
 5320: 
 5321: sub getfile {
 5322:     my ($file) = @_;
 5323: 
 5324:     if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); }
 5325:     &repcopy($file);
 5326:     return &readfile($file);
 5327: }
 5328: 
 5329: sub repcopy_userfile {
 5330:     my ($file)=@_;
 5331: 
 5332:     if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); }
 5333:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return OK; }
 5334: 
 5335:     my ($cdom,$cnum,$filename) = 
 5336: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 5337:     my ($info,$rtncode);
 5338:     my $uri="/uploaded/$cdom/$cnum/$filename";
 5339:     if (-e "$file") {
 5340: 	my @fileinfo = stat($file);
 5341: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 5342: 	if ($lwpresp ne 'ok') {
 5343: 	    if ($rtncode eq '404') {
 5344: 		unlink($file);
 5345: 	    }
 5346: 	    #my $ua=new LWP::UserAgent;
 5347: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 5348: 	    #my $response=$ua->request($request);
 5349: 	    #if ($response->is_success()) {
 5350: 	#	return $response->content;
 5351: 	#    } else {
 5352: 	#	return -1;
 5353: 	#    }
 5354: 	    return -1;
 5355: 	}
 5356: 	if ($info < $fileinfo[9]) {
 5357: 	    return OK;
 5358: 	}
 5359: 	$info = '';
 5360: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 5361: 	if ($lwpresp ne 'ok') {
 5362: 	    return -1;
 5363: 	}
 5364:     } else {
 5365: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 5366: 	if ($lwpresp ne 'ok') {
 5367: 	    my $ua=new LWP::UserAgent;
 5368: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 5369: 	    my $response=$ua->request($request);
 5370: 	    if ($response->is_success()) {
 5371: 		$info=$response->content;
 5372: 	    } else {
 5373: 		return -1;
 5374: 	    }
 5375: 	}
 5376: 	my @parts = ($cdom,$cnum); 
 5377: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 5378: 	    push @parts, split(/\//,$1);
 5379: 	}
 5380: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 5381: 	foreach my $part (@parts) {
 5382: 	    $path .= '/'.$part;
 5383: 	    if (!-e $path) {
 5384: 		mkdir($path,0770);
 5385: 	    }
 5386: 	}
 5387:     }
 5388:     open(FILE,">$file");
 5389:     print FILE $info;
 5390:     close(FILE);
 5391:     return OK;
 5392: }
 5393: 
 5394: sub tokenwrapper {
 5395:     my $uri=shift;
 5396:     $uri=~s|^http\://([^/]+)||;
 5397:     $uri=~s|^/||;
 5398:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
 5399:     my $token=$1;
 5400:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 5401:     if ($udom && $uname && $file) {
 5402: 	$file=~s|(\?\.*)*$||;
 5403:         &appenv("userfile.$udom/$uname/$file" => $ENV{'request.course.id'});
 5404:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 5405:                (($uri=~/\?/)?'&':'?').'token='.$token.
 5406:                                '&tokenissued='.$perlvar{'lonHostID'};
 5407:     } else {
 5408:         return '/adm/notfound.html';
 5409:     }
 5410: }
 5411: 
 5412: sub getuploaded {
 5413:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 5414:     $uri=~s/^\///;
 5415:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 5416:     my $ua=new LWP::UserAgent;
 5417:     my $request=new HTTP::Request($reqtype,$uri);
 5418:     my $response=$ua->request($request);
 5419:     $$rtncode = $response->code;
 5420:     if (! $response->is_success()) {
 5421: 	return 'failed';
 5422:     }      
 5423:     if ($reqtype eq 'HEAD') {
 5424: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 5425:     } elsif ($reqtype eq 'GET') {
 5426: 	$$info = $response->content;
 5427:     }
 5428:     return 'ok';
 5429: }
 5430: 
 5431: sub readfile {
 5432:     my $file = shift;
 5433:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 5434:     my $fh;
 5435:     open($fh,"<$file");
 5436:     my $a='';
 5437:     while (<$fh>) { $a .=$_; }
 5438:     return $a;
 5439: }
 5440: 
 5441: sub filelocation {
 5442:     my ($dir,$file) = @_;
 5443:     my $location;
 5444:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 5445:     if ($file=~m:^/~:) { # is a contruction space reference
 5446:         $location = $file;
 5447:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 5448:     } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 5449:         my ($udom,$uname,$filename)=
 5450:   	    ($file=~m|^/+uploaded/+([^/]+)/+([^/]+)/+(.*)$|);
 5451:         my $home=&homeserver($uname,$udom);
 5452:         my $is_me=0;
 5453:         my @ids=&current_machine_ids();
 5454:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 5455:         if ($is_me) {
 5456:   	    $location=&Apache::loncommon::propath($udom,$uname).
 5457:   	      '/userfiles/'.$filename;
 5458:         } else {
 5459:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 5460:   	      $udom.'/'.$uname.'/'.$filename;
 5461:         }
 5462:     } elsif ($file =~ /^\/adm\/portfolio\//) {
 5463:         $file =~ s:^/adm/portfolio/::;
 5464:         $location = $location=&Apache::loncommon::propath($ENV{'user.domain'},$ENV{'user.name'}).'/userfiles/portfolio/'.$file;
 5465:     } else {
 5466:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 5467:         $file=~s:^/res/:/:;
 5468:         if ( !( $file =~ m:^/:) ) {
 5469:             $location = $dir. '/'.$file;
 5470:         } else {
 5471:             $location = '/home/httpd/html/res'.$file;
 5472:         }
 5473:     }
 5474:     $location=~s://+:/:g; # remove duplicate /
 5475:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 5476:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 5477:     return $location;
 5478: }
 5479: 
 5480: sub hreflocation {
 5481:     my ($dir,$file)=@_;
 5482:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 5483: 	my $finalpath=filelocation($dir,$file);
 5484: 	$finalpath=~s-^/home/httpd/html--;
 5485: 	$finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
 5486: 	return $finalpath;
 5487:     } elsif ($file=~m-^/home-) {
 5488: 	$file=~s-^/home/httpd/html--;
 5489: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 5490: 	return $file;
 5491:     }
 5492:     return $file;
 5493: }
 5494: 
 5495: sub current_machine_domains {
 5496:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 5497:     my @domains;
 5498:     while( my($id, $name) = each(%hostname)) {
 5499: #	&logthis("-$id-$name-$hostname-");
 5500: 	if ($hostname eq $name) {
 5501: 	    push(@domains,$hostdom{$id});
 5502: 	}
 5503:     }
 5504:     return @domains;
 5505: }
 5506: 
 5507: sub current_machine_ids {
 5508:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 5509:     my @ids;
 5510:     while( my($id, $name) = each(%hostname)) {
 5511: #	&logthis("-$id-$name-$hostname-");
 5512: 	if ($hostname eq $name) {
 5513: 	    push(@ids,$id);
 5514: 	}
 5515:     }
 5516:     return @ids;
 5517: }
 5518: 
 5519: # ------------------------------------------------------------- Declutters URLs
 5520: 
 5521: sub declutter {
 5522:     my $thisfn=shift;
 5523:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 5524:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 5525:     $thisfn=~s/^\///;
 5526:     $thisfn=~s/^res\///;
 5527:     $thisfn=~s/\?.+$//;
 5528:     return $thisfn;
 5529: }
 5530: 
 5531: # ------------------------------------------------------------- Clutter up URLs
 5532: 
 5533: sub clutter {
 5534:     my $thisfn='/'.&declutter(shift);
 5535:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv|public)\//) { 
 5536:        $thisfn='/res'.$thisfn; 
 5537:     }
 5538:     return $thisfn;
 5539: }
 5540: 
 5541: sub freeze_escape {
 5542:     my ($value)=@_;
 5543:     if (ref($value)) {
 5544: 	$value=&nfreeze($value);
 5545: 	return '__FROZEN__'.&escape($value);
 5546:     }
 5547:     return &escape($value);
 5548: }
 5549: 
 5550: # -------------------------------------------------------- Escape Special Chars
 5551: 
 5552: sub escape {
 5553:     my $str=shift;
 5554:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 5555:     return $str;
 5556: }
 5557: 
 5558: # ----------------------------------------------------- Un-Escape Special Chars
 5559: 
 5560: sub unescape {
 5561:     my $str=shift;
 5562:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 5563:     return $str;
 5564: }
 5565: 
 5566: sub thaw_unescape {
 5567:     my ($value)=@_;
 5568:     if ($value =~ /^__FROZEN__/) {
 5569: 	substr($value,0,10,undef);
 5570: 	$value=&unescape($value);
 5571: 	return &thaw($value);
 5572:     }
 5573:     return &unescape($value);
 5574: }
 5575: 
 5576: sub mod_perl_version {
 5577:     return 1;
 5578:     if (defined($perlvar{'MODPERL2'})) {
 5579: 	return 2;
 5580:     }
 5581: }
 5582: 
 5583: sub correct_line_ends {
 5584:     my ($result)=@_;
 5585:     $$result =~s/\r\n/\n/mg;
 5586:     $$result =~s/\r/\n/mg;
 5587: }
 5588: # ================================================================ Main Program
 5589: 
 5590: sub goodbye {
 5591:    &logthis("Starting Shut down");
 5592: #not converted to using infrastruture and probably shouldn't be
 5593:    &logthis(sprintf("%-20s is %s",'%badServerCache',scalar(%badServerCache)));
 5594: #converted
 5595:    &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 5596:    &logthis(sprintf("%-20s is %s",'%homecache',scalar(%homecache)));
 5597:    &logthis(sprintf("%-20s is %s",'%titlecache',scalar(%titlecache)));
 5598:    &logthis(sprintf("%-20s is %s",'%courseresdatacache',scalar(%courseresdatacache)));
 5599: #1.1 only
 5600:    &logthis(sprintf("%-20s is %s",'%userresdatacache',scalar(%userresdatacache)));
 5601:    &logthis(sprintf("%-20s is %s",'%getsectioncache',scalar(%getsectioncache)));
 5602:    &logthis(sprintf("%-20s is %s",'%courseresversioncache',scalar(%courseresversioncache)));
 5603:    &logthis(sprintf("%-20s is %s",'%resversioncache',scalar(%resversioncache)));
 5604:    &flushcourselogs();
 5605:    &logthis("Shutting down");
 5606:    return DONE;
 5607: }
 5608: 
 5609: BEGIN {
 5610: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 5611:     unless ($readit) {
 5612: {
 5613:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 5614:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 5615: 
 5616:     while (my $configline=<$config>) {
 5617:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 5618: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 5619:            chomp($varvalue);
 5620:            $perlvar{$varname}=$varvalue;
 5621:         }
 5622:     }
 5623:     close($config);
 5624: }
 5625: {
 5626:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 5627: 
 5628:     while (my $configline=<$config>) {
 5629:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 5630: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 5631:            chomp($varvalue);
 5632:            $perlvar{$varname}=$varvalue;
 5633:         }
 5634:     }
 5635:     close($config);
 5636: }
 5637: 
 5638: # ------------------------------------------------------------ Read domain file
 5639: {
 5640:     %domaindescription = ();
 5641:     %domain_auth_def = ();
 5642:     %domain_auth_arg_def = ();
 5643:     my $fh;
 5644:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 5645:        while (<$fh>) {
 5646:            next if (/^(\#|\s*$)/);
 5647: #           next if /^\#/;
 5648:            chomp;
 5649:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 5650: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
 5651: 	   $domain_auth_def{$domain}=$def_auth;
 5652:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 5653: 	   $domaindescription{$domain}=$domain_description;
 5654: 	   $domain_lang_def{$domain}=$def_lang;
 5655: 	   $domain_city{$domain}=$city;
 5656: 	   $domain_longi{$domain}=$longi;
 5657: 	   $domain_lati{$domain}=$lati;
 5658: 
 5659:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 5660: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 5661: 	}
 5662:     }
 5663:     close ($fh);
 5664: }
 5665: 
 5666: 
 5667: # ------------------------------------------------------------- Read hosts file
 5668: {
 5669:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 5670: 
 5671:     while (my $configline=<$config>) {
 5672:        next if ($configline =~ /^(\#|\s*$)/);
 5673:        chomp($configline);
 5674:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 5675:        if ($id && $domain && $role && $name && $ip) {
 5676: 	 $hostname{$id}=$name;
 5677: 	 $hostdom{$id}=$domain;
 5678: 	 $hostip{$id}=$ip;
 5679: 	 $iphost{$ip}=$id;
 5680: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 5681:        }
 5682:     }
 5683:     close($config);
 5684: }
 5685: 
 5686: # ------------------------------------------------------ Read spare server file
 5687: {
 5688:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 5689: 
 5690:     while (my $configline=<$config>) {
 5691:        chomp($configline);
 5692:        if ($configline) {
 5693:           $spareid{$configline}=1;
 5694:        }
 5695:     }
 5696:     close($config);
 5697: }
 5698: # ------------------------------------------------------------ Read permissions
 5699: {
 5700:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 5701: 
 5702:     while (my $configline=<$config>) {
 5703: 	chomp($configline);
 5704: 	if ($configline) {
 5705: 	    my ($role,$perm)=split(/ /,$configline);
 5706: 	    if ($perm ne '') { $pr{$role}=$perm; }
 5707: 	}
 5708:     }
 5709:     close($config);
 5710: }
 5711: 
 5712: # -------------------------------------------- Read plain texts for permissions
 5713: {
 5714:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 5715: 
 5716:     while (my $configline=<$config>) {
 5717: 	chomp($configline);
 5718: 	if ($configline) {
 5719: 	    my ($short,$plain)=split(/:/,$configline);
 5720: 	    if ($plain ne '') { $prp{$short}=$plain; }
 5721: 	}
 5722:     }
 5723:     close($config);
 5724: }
 5725: 
 5726: # ---------------------------------------------------------- Read package table
 5727: {
 5728:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 5729: 
 5730:     while (my $configline=<$config>) {
 5731: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 5732: 	chomp($configline);
 5733: 	my ($short,$plain)=split(/:/,$configline);
 5734: 	my ($pack,$name)=split(/\&/,$short);
 5735: 	if ($plain ne '') {
 5736: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 5737: 	    $packagetab{$short}=$plain; 
 5738: 	}
 5739:     }
 5740:     close($config);
 5741: }
 5742: 
 5743: # ------------- set up temporary directory
 5744: {
 5745:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 5746: 
 5747: }
 5748: 
 5749: %metacache=();
 5750: 
 5751: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 5752: $dumpcount=0;
 5753: 
 5754: &logtouch();
 5755: &logthis('<font color=yellow>INFO: Read configuration</font>');
 5756: $readit=1;
 5757:     {
 5758: 	use integer;
 5759: 	my $test=(2**32)+1;
 5760: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 5761: 	&logthis(" Detected 64bit platform ($_64bit)");
 5762:     }
 5763: }
 5764: }
 5765: 
 5766: 1;
 5767: __END__
 5768: 
 5769: =pod
 5770: 
 5771: =head1 NAME
 5772: 
 5773: Apache::lonnet - Subroutines to ask questions about things in the network.
 5774: 
 5775: =head1 SYNOPSIS
 5776: 
 5777: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 5778: 
 5779:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 5780: 
 5781: Common parameters:
 5782: 
 5783: =over 4
 5784: 
 5785: =item *
 5786: 
 5787: $uname : an internal username (if $cname expecting a course Id specifically)
 5788: 
 5789: =item *
 5790: 
 5791: $udom : a domain (if $cdom expecting a course's domain specifically)
 5792: 
 5793: =item *
 5794: 
 5795: $symb : a resource instance identifier
 5796: 
 5797: =item *
 5798: 
 5799: $namespace : the name of a .db file that contains the data needed or
 5800: being set.
 5801: 
 5802: =back
 5803: 
 5804: =head1 OVERVIEW
 5805: 
 5806: lonnet provides subroutines which interact with the
 5807: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 5808: about classes, users, and resources.
 5809: 
 5810: For many of these objects you can also use this to store data about
 5811: them or modify them in various ways.
 5812: 
 5813: =head2 Symbs
 5814: 
 5815: To identify a specific instance of a resource, LON-CAPA uses symbols
 5816: or "symbs"X<symb>. These identifiers are built from the URL of the
 5817: map, the resource number of the resource in the map, and the URL of
 5818: the resource itself. The latter is somewhat redundant, but might help
 5819: if maps change.
 5820: 
 5821: An example is
 5822: 
 5823:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 5824: 
 5825: The respective map entry is
 5826: 
 5827:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 5828:   title="Problem 2">
 5829:  </resource>
 5830: 
 5831: Symbs are used by the random number generator, as well as to store and
 5832: restore data specific to a certain instance of for example a problem.
 5833: 
 5834: =head2 Storing And Retrieving Data
 5835: 
 5836: X<store()>X<cstore()>X<restore()>Three of the most important functions
 5837: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 5838: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 5839: is is the non-critical message twin of cstore. These functions are for
 5840: handlers to store a perl hash to a user's permanent data space in an
 5841: easy manner, and to retrieve it again on another call. It is expected
 5842: that a handler would use this once at the beginning to retrieve data,
 5843: and then again once at the end to send only the new data back.
 5844: 
 5845: The data is stored in the user's data directory on the user's
 5846: homeserver under the ID of the course.
 5847: 
 5848: The hash that is returned by restore will have all of the previous
 5849: value for all of the elements of the hash.
 5850: 
 5851: Example:
 5852: 
 5853:  #creating a hash
 5854:  my %hash;
 5855:  $hash{'foo'}='bar';
 5856: 
 5857:  #storing it
 5858:  &Apache::lonnet::cstore(\%hash);
 5859: 
 5860:  #changing a value
 5861:  $hash{'foo'}='notbar';
 5862: 
 5863:  #adding a new value
 5864:  $hash{'bar'}='foo';
 5865:  &Apache::lonnet::cstore(\%hash);
 5866: 
 5867:  #retrieving the hash
 5868:  my %history=&Apache::lonnet::restore();
 5869: 
 5870:  #print the hash
 5871:  foreach my $key (sort(keys(%history))) {
 5872:    print("\%history{$key} = $history{$key}");
 5873:  }
 5874: 
 5875: Will print out:
 5876: 
 5877:  %history{1:foo} = bar
 5878:  %history{1:keys} = foo:timestamp
 5879:  %history{1:timestamp} = 990455579
 5880:  %history{2:bar} = foo
 5881:  %history{2:foo} = notbar
 5882:  %history{2:keys} = foo:bar:timestamp
 5883:  %history{2:timestamp} = 990455580
 5884:  %history{bar} = foo
 5885:  %history{foo} = notbar
 5886:  %history{timestamp} = 990455580
 5887:  %history{version} = 2
 5888: 
 5889: Note that the special hash entries C<keys>, C<version> and
 5890: C<timestamp> were added to the hash. C<version> will be equal to the
 5891: total number of versions of the data that have been stored. The
 5892: C<timestamp> attribute will be the UNIX time the hash was
 5893: stored. C<keys> is available in every historical section to list which
 5894: keys were added or changed at a specific historical revision of a
 5895: hash.
 5896: 
 5897: B<Warning>: do not store the hash that restore returns directly. This
 5898: will cause a mess since it will restore the historical keys as if the
 5899: were new keys. I.E. 1:foo will become 1:1:foo etc.
 5900: 
 5901: Calling convention:
 5902: 
 5903:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 5904:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 5905: 
 5906: For more detailed information, see lonnet specific documentation.
 5907: 
 5908: =head1 RETURN MESSAGES
 5909: 
 5910: =over 4
 5911: 
 5912: =item * B<con_lost>: unable to contact remote host
 5913: 
 5914: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 5915: when the connection is brought back up
 5916: 
 5917: =item * B<con_failed>: unable to contact remote host and unable to save message
 5918: for later delivery
 5919: 
 5920: =item * B<error:>: an error a occured, a description of the error follows the :
 5921: 
 5922: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 5923: that was requested
 5924: 
 5925: =back
 5926: 
 5927: =head1 PUBLIC SUBROUTINES
 5928: 
 5929: =head2 Session Environment Functions
 5930: 
 5931: =over 4
 5932: 
 5933: =item * 
 5934: X<appenv()>
 5935: B<appenv(%hash)>: the value of %hash is written to
 5936: the user envirnoment file, and will be restored for each access this
 5937: user makes during this session, also modifies the %ENV for the current
 5938: process
 5939: 
 5940: =item *
 5941: X<delenv()>
 5942: B<delenv($regexp)>: removes all items from the session
 5943: environment file that matches the regular expression in $regexp. The
 5944: values are also delted from the current processes %ENV.
 5945: 
 5946: =back
 5947: 
 5948: =head2 User Information
 5949: 
 5950: =over 4
 5951: 
 5952: =item *
 5953: X<queryauthenticate()>
 5954: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 5955: authentication scheme
 5956: 
 5957: =item *
 5958: X<authenticate()>
 5959: B<authenticate($uname,$upass,$udom)>: try to
 5960: authenticate user from domain's lib servers (first use the current
 5961: one). C<$upass> should be the users password.
 5962: 
 5963: =item *
 5964: X<homeserver()>
 5965: B<homeserver($uname,$udom)>: find the server which has
 5966: the user's directory and files (there must be only one), this caches
 5967: the answer, and also caches if there is a borken connection.
 5968: 
 5969: =item *
 5970: X<idget()>
 5971: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 5972: (IDs are a unique resource in a domain, there must be only 1 ID per
 5973: username, and only 1 username per ID in a specific domain) (returns
 5974: hash: id=>name,id=>name)
 5975: 
 5976: =item *
 5977: X<idrget()>
 5978: B<idrget($udom,@unames)>: find the IDs behind a list of
 5979: usernames (returns hash: name=>id,name=>id)
 5980: 
 5981: =item *
 5982: X<idput()>
 5983: B<idput($udom,%ids)>: store away a list of names and associated IDs
 5984: 
 5985: =item *
 5986: X<rolesinit()>
 5987: B<rolesinit($udom,$username,$authhost)>: get user privileges
 5988: 
 5989: =item *
 5990: X<getsection()>
 5991: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 5992: course $cname, return section name/number or '' for "not in course"
 5993: and '-1' for "no section"
 5994: 
 5995: =item *
 5996: X<userenvironment()>
 5997: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 5998: passed in @what from the requested user's environment, returns a hash
 5999: 
 6000: =back
 6001: 
 6002: =head2 User Roles
 6003: 
 6004: =over 4
 6005: 
 6006: =item *
 6007: 
 6008: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 6009: actions
 6010:  F: full access
 6011:  U,I,K: authentication modes (cxx only)
 6012:  '': forbidden
 6013:  1: user needs to choose course
 6014:  2: browse allowed
 6015: 
 6016: =item *
 6017: 
 6018: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 6019: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 6020: and course level
 6021: 
 6022: =item *
 6023: 
 6024: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 6025: explanation of a user role term
 6026: 
 6027: =back
 6028: 
 6029: =head2 User Modification
 6030: 
 6031: =over 4
 6032: 
 6033: =item *
 6034: 
 6035: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 6036: user for the level given by URL.  Optional start and end dates (leave empty
 6037: string or zero for "no date")
 6038: 
 6039: =item *
 6040: 
 6041: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 6042: change a users, password, possible return values are: ok,
 6043: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 6044: refused
 6045: 
 6046: =item *
 6047: 
 6048: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 6049: 
 6050: =item *
 6051: 
 6052: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 6053: modify user
 6054: 
 6055: =item *
 6056: 
 6057: modifystudent
 6058: 
 6059: modify a students enrollment and identification information.
 6060: The course id is resolved based on the current users environment.  
 6061: This means the envoking user must be a course coordinator or otherwise
 6062: associated with a course.
 6063: 
 6064: This call is essentially a wrapper for lonnet::modifyuser and
 6065: lonnet::modify_student_enrollment
 6066: 
 6067: Inputs: 
 6068: 
 6069: =over 4
 6070: 
 6071: =item B<$udom> Students loncapa domain
 6072: 
 6073: =item B<$uname> Students loncapa login name
 6074: 
 6075: =item B<$uid> Students id/student number
 6076: 
 6077: =item B<$umode> Students authentication mode
 6078: 
 6079: =item B<$upass> Students password
 6080: 
 6081: =item B<$first> Students first name
 6082: 
 6083: =item B<$middle> Students middle name
 6084: 
 6085: =item B<$last> Students last name
 6086: 
 6087: =item B<$gene> Students generation
 6088: 
 6089: =item B<$usec> Students section in course
 6090: 
 6091: =item B<$end> Unix time of the roles expiration
 6092: 
 6093: =item B<$start> Unix time of the roles start date
 6094: 
 6095: =item B<$forceid> If defined, allow $uid to be changed
 6096: 
 6097: =item B<$desiredhome> server to use as home server for student
 6098: 
 6099: =back
 6100: 
 6101: =item *
 6102: 
 6103: modify_student_enrollment
 6104: 
 6105: Change a students enrollment status in a class.  The environment variable
 6106: 'role.request.course' must be defined for this function to proceed.
 6107: 
 6108: Inputs:
 6109: 
 6110: =over 4
 6111: 
 6112: =item $udom, students domain
 6113: 
 6114: =item $uname, students name
 6115: 
 6116: =item $uid, students user id
 6117: 
 6118: =item $first, students first name
 6119: 
 6120: =item $middle
 6121: 
 6122: =item $last
 6123: 
 6124: =item $gene
 6125: 
 6126: =item $usec
 6127: 
 6128: =item $end
 6129: 
 6130: =item $start
 6131: 
 6132: =back
 6133: 
 6134: 
 6135: =item *
 6136: 
 6137: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 6138: custom role; give a custom role to a user for the level given by URL.  Specify
 6139: name and domain of role author, and role name
 6140: 
 6141: =item *
 6142: 
 6143: revokerole($udom,$uname,$url,$role) : revoke a role for url
 6144: 
 6145: =item *
 6146: 
 6147: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 6148: 
 6149: =back
 6150: 
 6151: =head2 Course Infomation
 6152: 
 6153: =over 4
 6154: 
 6155: =item *
 6156: 
 6157: coursedescription($courseid) : course description
 6158: 
 6159: =item *
 6160: 
 6161: courseresdata($coursenum,$coursedomain,@which) : request for current
 6162: parameter setting for a specific course, @what should be a list of
 6163: parameters to ask about. This routine caches answers for 5 minutes.
 6164: 
 6165: =back
 6166: 
 6167: =head2 Course Modification
 6168: 
 6169: =over 4
 6170: 
 6171: =item *
 6172: 
 6173: writecoursepref($courseid,%prefs) : write preferences (environment
 6174: database) for a course
 6175: 
 6176: =item *
 6177: 
 6178: createcourse($udom,$description,$url) : make/modify course
 6179: 
 6180: =back
 6181: 
 6182: =head2 Resource Subroutines
 6183: 
 6184: =over 4
 6185: 
 6186: =item *
 6187: 
 6188: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 6189: 
 6190: =item *
 6191: 
 6192: repcopy($filename) : subscribes to the requested file, and attempts to
 6193: replicate from the owning library server, Might return
 6194: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 6195: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 6196: resource. Expects the local filesystem pathname
 6197: (/home/httpd/html/res/....)
 6198: 
 6199: =back
 6200: 
 6201: =head2 Resource Information
 6202: 
 6203: =over 4
 6204: 
 6205: =item *
 6206: 
 6207: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 6208: a vairety of different possible values, $varname should be a request
 6209: string, and the other parameters can be used to specify who and what
 6210: one is asking about.
 6211: 
 6212: Possible values for $varname are environment.lastname (or other item
 6213: from the envirnment hash), user.name (or someother aspect about the
 6214: user), resource.0.maxtries (or some other part and parameter of a
 6215: resource)
 6216: 
 6217: =item *
 6218: 
 6219: directcondval($number) : get current value of a condition; reads from a state
 6220: string
 6221: 
 6222: =item *
 6223: 
 6224: condval($condidx) : value of condition index based on state
 6225: 
 6226: =item *
 6227: 
 6228: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 6229: resource's metadata, $what should be either a specific key, or either
 6230: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 6231: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 6232: 
 6233: this function automatically caches all requests
 6234: 
 6235: =item *
 6236: 
 6237: metadata_query($query,$custom,$customshow) : make a metadata query against the
 6238: network of library servers; returns file handle of where SQL and regex results
 6239: will be stored for query
 6240: 
 6241: =item *
 6242: 
 6243: symbread($filename) : return symbolic list entry (filename argument optional);
 6244: returns the data handle
 6245: 
 6246: =item *
 6247: 
 6248: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 6249: a possible symb for the URL in $thisfn, and if is an encryypted
 6250: resource that the user accessed using /enc/ returns a 1 on success, 0
 6251: on failure, user must be in a course, as it assumes the existance of
 6252: the course initial hash, and uses $ENV('request.course.id'}
 6253: 
 6254: 
 6255: =item *
 6256: 
 6257: symbclean($symb) : removes versions numbers from a symb, returns the
 6258: cleaned symb
 6259: 
 6260: =item *
 6261: 
 6262: is_on_map($uri) : checks if the $uri is somewhere on the current
 6263: course map, user must be in a course for it to work.
 6264: 
 6265: =item *
 6266: 
 6267: numval($salt) : return random seed value (addend for rndseed)
 6268: 
 6269: =item *
 6270: 
 6271: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 6272: a random seed, all arguments are optional, if they aren't sent it uses the
 6273: environment to derive them. Note: if symb isn't sent and it can't get one
 6274: from &symbread it will use the current time as its return value
 6275: 
 6276: =item *
 6277: 
 6278: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 6279: unfakeable, receipt
 6280: 
 6281: =item *
 6282: 
 6283: receipt() : API to ireceipt working off of ENV values; given out to users
 6284: 
 6285: =item *
 6286: 
 6287: countacc($url) : count the number of accesses to a given URL
 6288: 
 6289: =item *
 6290: 
 6291: 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
 6292: 
 6293: =item *
 6294: 
 6295: 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)
 6296: 
 6297: =item *
 6298: 
 6299: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 6300: 
 6301: =item *
 6302: 
 6303: devalidate($symb) : devalidate temporary spreadsheet calculations,
 6304: forcing spreadsheet to reevaluate the resource scores next time.
 6305: 
 6306: =back
 6307: 
 6308: =head2 Storing/Retreiving Data
 6309: 
 6310: =over 4
 6311: 
 6312: =item *
 6313: 
 6314: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 6315: for this url; hashref needs to be given and should be a \%hashname; the
 6316: remaining args aren't required and if they aren't passed or are '' they will
 6317: be derived from the ENV
 6318: 
 6319: =item *
 6320: 
 6321: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 6322: uses critical subroutine
 6323: 
 6324: =item *
 6325: 
 6326: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 6327: all args are optional
 6328: 
 6329: =item *
 6330: 
 6331: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 6332: works very similar to store/cstore, but all data is stored in a
 6333: temporary location and can be reset using tmpreset, $storehash should
 6334: be a hash reference, returns nothing on success
 6335: 
 6336: =item *
 6337: 
 6338: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 6339: similar to restore, but all data is stored in a temporary location and
 6340: can be reset using tmpreset. Returns a hash of values on success,
 6341: error string otherwise.
 6342: 
 6343: =item *
 6344: 
 6345: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 6346: deltes all keys for $symb form the temporary storage hash.
 6347: 
 6348: =item *
 6349: 
 6350: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 6351: reference filled in from namesp ($udom and $uname are optional)
 6352: 
 6353: =item *
 6354: 
 6355: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 6356: namesp ($udom and $uname are optional)
 6357: 
 6358: =item *
 6359: 
 6360: dump($namespace,$udom,$uname,$regexp) : 
 6361: dumps the complete (or key matching regexp) namespace into a hash
 6362: ($udom, $uname and $regexp are optional)
 6363: 
 6364: =item *
 6365: 
 6366: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 6367: $store can be a scalar, an array reference, or if the amount to be 
 6368: incremented is > 1, a hash reference.
 6369: 
 6370: ($udom and $uname are optional)
 6371: 
 6372: =item *
 6373: 
 6374: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 6375: ($udom and $uname are optional)
 6376: 
 6377: =item *
 6378: 
 6379: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
 6380: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
 6381: used in records written by &store and retrieved by &restore.  This function 
 6382: was created for use in editing discussion posts, without incrementing the
 6383: version number included in the key for a particular post. The colon 
 6384: separated list of attribute names (e.g., the value associated with the key 
 6385: 1:keys:$symb) is also generated and passed in the ampersand separated 
 6386: items sent to lonnet::reply().  
 6387: 
 6388: =item *
 6389: 
 6390: cput($namespace,$storehash,$udom,$uname) : critical put
 6391: ($udom and $uname are optional)
 6392: 
 6393: =item *
 6394: 
 6395: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 6396: reference filled in from namesp (encrypts the return communication)
 6397: ($udom and $uname are optional)
 6398: 
 6399: =item *
 6400: 
 6401: log($udom,$name,$home,$message) : write to permanent log for user; use
 6402: critical subroutine
 6403: 
 6404: =back
 6405: 
 6406: =head2 Network Status Functions
 6407: 
 6408: =over 4
 6409: 
 6410: =item *
 6411: 
 6412: dirlist($uri) : return directory list based on URI
 6413: 
 6414: =item *
 6415: 
 6416: spareserver() : find server with least workload from spare.tab
 6417: 
 6418: =back
 6419: 
 6420: =head2 Apache Request
 6421: 
 6422: =over 4
 6423: 
 6424: =item *
 6425: 
 6426: ssi($url,%hash) : server side include, does a complete request cycle on url to
 6427: localhost, posts hash
 6428: 
 6429: =back
 6430: 
 6431: =head2 Data to String to Data
 6432: 
 6433: =over 4
 6434: 
 6435: =item *
 6436: 
 6437: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 6438: and '&' separators, supports elements that are arrayrefs and hashrefs
 6439: 
 6440: =item *
 6441: 
 6442: hashref2str($hashref) : convert a hashref into a string complete with
 6443: escaping and '=' and '&' separators, supports elements that are
 6444: arrayrefs and hashrefs
 6445: 
 6446: =item *
 6447: 
 6448: arrayref2str($arrayref) : convert an arrayref into a string complete
 6449: with escaping and '&' separators, supports elements that are arrayrefs
 6450: and hashrefs
 6451: 
 6452: =item *
 6453: 
 6454: str2hash($string) : convert string to hash using unescaping and
 6455: splitting on '=' and '&', supports elements that are arrayrefs and
 6456: hashrefs
 6457: 
 6458: =item *
 6459: 
 6460: str2array($string) : convert string to hash using unescaping and
 6461: splitting on '&', supports elements that are arrayrefs and hashrefs
 6462: 
 6463: =back
 6464: 
 6465: =head2 Logging Routines
 6466: 
 6467: =over 4
 6468: 
 6469: These routines allow one to make log messages in the lonnet.log and
 6470: lonnet.perm logfiles.
 6471: 
 6472: =item *
 6473: 
 6474: logtouch() : make sure the logfile, lonnet.log, exists
 6475: 
 6476: =item *
 6477: 
 6478: logthis() : append message to the normal lonnet.log file, it gets
 6479: preiodically rolled over and deleted.
 6480: 
 6481: =item *
 6482: 
 6483: logperm() : append a permanent message to lonnet.perm.log, this log
 6484: file never gets deleted by any automated portion of the system, only
 6485: messages of critical importance should go in here.
 6486: 
 6487: =back
 6488: 
 6489: =head2 General File Helper Routines
 6490: 
 6491: =over 4
 6492: 
 6493: =item *
 6494: 
 6495: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 6496: (a) files in /uploaded
 6497:   (i) If a local copy of the file exists - 
 6498:       compares modification date of local copy with last-modified date for 
 6499:       definitive version stored on home server for course. If local copy is 
 6500:       stale, requests a new version from the home server and stores it. 
 6501:       If the original has been removed from the home server, then local copy 
 6502:       is unlinked.
 6503:   (ii) If local copy does not exist -
 6504:       requests the file from the home server and stores it. 
 6505:   
 6506:   If $caller is 'uploadrep':  
 6507:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 6508:     for request for files originally uploaded via DOCS. 
 6509:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 6510:   
 6511:   Otherwise:
 6512:      This indicates a call from the content generation phase of the request.
 6513:      -  returns the entire contents of the file or -1.
 6514:      
 6515: (b) files in /res
 6516:    - returns the entire contents of a file or -1; 
 6517:    it properly subscribes to and replicates the file if neccessary.
 6518: 
 6519: =item *
 6520: 
 6521: filelocation($dir,$file) : returns file system location of a file
 6522: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 6523: directory that relative $file lookups are to looked in ($dir of /a/dir
 6524: and a file of ../bob will become /a/bob)
 6525: 
 6526: =item *
 6527: 
 6528: hreflocation($dir,$file) : returns file system location or a URL; same as
 6529: filelocation except for hrefs
 6530: 
 6531: =item *
 6532: 
 6533: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 6534: 
 6535: =back
 6536: 
 6537: =head2 HTTP Helper Routines
 6538: 
 6539: =over 4
 6540: 
 6541: =item *
 6542: 
 6543: escape() : unpack non-word characters into CGI-compatible hex codes
 6544: 
 6545: =item *
 6546: 
 6547: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 6548: 
 6549: =back
 6550: 
 6551: =head1 PRIVATE SUBROUTINES
 6552: 
 6553: =head2 Underlying communication routines (Shouldn't call)
 6554: 
 6555: =over 4
 6556: 
 6557: =item *
 6558: 
 6559: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 6560: 
 6561: =item *
 6562: 
 6563: reply() : uses subreply to send a message to remote machine, logs all failures
 6564: 
 6565: =item *
 6566: 
 6567: critical() : passes a critical message to another server; if cannot
 6568: get through then place message in connection buffer directory and
 6569: returns con_delayed, if incapable of saving message, returns
 6570: con_failed
 6571: 
 6572: =item *
 6573: 
 6574: reconlonc() : tries to reconnect lonc client processes.
 6575: 
 6576: =back
 6577: 
 6578: =head2 Resource Access Logging
 6579: 
 6580: =over 4
 6581: 
 6582: =item *
 6583: 
 6584: flushcourselogs() : flush (save) buffer logs and access logs
 6585: 
 6586: =item *
 6587: 
 6588: courselog($what) : save message for course in hash
 6589: 
 6590: =item *
 6591: 
 6592: courseacclog($what) : save message for course using &courselog().  Perform
 6593: special processing for specific resource types (problems, exams, quizzes, etc).
 6594: 
 6595: =item *
 6596: 
 6597: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 6598: as a PerlChildExitHandler
 6599: 
 6600: =back
 6601: 
 6602: =head2 Other
 6603: 
 6604: =over 4
 6605: 
 6606: =item *
 6607: 
 6608: symblist($mapname,%newhash) : update symbolic storage links
 6609: 
 6610: =back
 6611: 
 6612: =cut

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