File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.620: download - view: text, annotated - select for diffs
Thu Apr 7 06:56:24 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- ENV -> env

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

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