File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.628: download - view: text, annotated - select for diffs
Fri Apr 22 21:01:25 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- reset $env, before transferring profile into it just in case
- only empty $env on intial request not on sub requests

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

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