File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.710: download - view: text, annotated - select for diffs
Fri Feb 10 22:33:48 2006 UTC (18 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#4635 ext resources that ended in / caused oddities

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

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