File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.674: download - view: text, annotated - select for diffs
Tue Nov 1 15:07:29 2005 UTC (18 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Better spread out new course IDs so they don't all pile up in the same directory.

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

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