File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.729: download - view: text, annotated - select for diffs
Tue Apr 18 18:11:16 2006 UTC (18 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
New log style. Need to delete old log files if you already have some.

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

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