File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.587.2.2: download - view: text, annotated - select for diffs
Fri Jan 28 09:25:18 2005 UTC (19 years, 6 months ago) by albertel
Branches: version_1_3_X
- BUG#597, store,restore,tmpstore,tmprestore,putstore all understand object references and can store them and restore them.

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

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