File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.600: download - view: text, annotated - select for diffs
Wed Feb 23 23:19:42 2005 UTC (19 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- make_room call was screwing things over

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

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