File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.619: download - view: text, annotated - select for diffs
Tue Apr 5 20:43:27 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- the great ENV -> env switch has commenced

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

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