File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.615: download - view: text, annotated - select for diffs
Tue Mar 22 16:49:25 2005 UTC (19 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- sorry I was stupid

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

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