File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.625: download - view: text, annotated - select for diffs
Mon Apr 18 21:10:41 2005 UTC (19 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Increment total tries used, total number correct, unique students attempting part for each part for each instance of a problem in course.  Added lonnet::cinc - critical wrapper to lonnet::inc used to increment nohist_resourcetracker.db. Provides rapid look-up for lonwhatsnew.pm.  Decrement function (to do) needed where status reset.

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

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