Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.453

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.453   ! albertel    4: # $Id: lonnet.pm,v 1.452 2003/12/04 20:09:35 albertel Exp $
1.178     www         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: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.11      www        35: use vars 
1.300     albertel   36: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
1.440     www        37:    %libserv %pr %prp %metacache %packagetab %titlecache %courseresversioncache %resversioncache
1.349     www        38:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
1.352     www        39:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache 
1.420     albertel   40:    %userresdatacache %usectioncache %domaindescription %domain_auth_def %domain_auth_arg_def 
1.403     www        41:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir);
                     42: 
1.1       albertel   43: use IO::Socket;
1.31      www        44: use GDBM_File;
1.8       www        45: use Apache::Constants qw(:common :http);
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.294     matthew    48: use Apache::loncoursedata;
1.414     www        49: use Apache::lonlocal;
1.428     albertel   50: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw);
1.425     albertel   51: use Time::HiRes();
1.195     www        52: my $readit;
1.1       albertel   53: 
1.449     matthew    54: =pod
                     55: 
                     56: =head1 Package Variables
                     57: 
                     58: These are largely undocumented, so if you decipher one please note it here.
                     59: 
                     60: =over 4
                     61: 
                     62: =item $processmarker
                     63: 
                     64: Contains the time this process was started and this servers host id.
                     65: 
                     66: =item $dumpcount
                     67: 
                     68: Counts the number of times a message log flush has been attempted (regardless
                     69: of success) by this process.  Used as part of the filename when messages are
                     70: delayed.
                     71: 
                     72: =back
                     73: 
                     74: =cut
                     75: 
                     76: 
1.1       albertel   77: # --------------------------------------------------------------------- Logging
                     78: 
1.163     harris41   79: sub logtouch {
                     80:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel   81:     unless (-e "$execdir/logs/lonnet.log") {	
                     82: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41   83: 	close $fh;
                     84:     }
                     85:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                     86:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                     87: }
                     88: 
1.1       albertel   89: sub logthis {
                     90:     my $message=shift;
                     91:     my $execdir=$perlvar{'lonDaemons'};
                     92:     my $now=time;
                     93:     my $local=localtime($now);
1.448     albertel   94:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                     95: 	print $fh "$local ($$): $message\n";
                     96: 	close($fh);
                     97:     }
1.1       albertel   98:     return 1;
                     99: }
                    100: 
                    101: sub logperm {
                    102:     my $message=shift;
                    103:     my $execdir=$perlvar{'lonDaemons'};
                    104:     my $now=time;
                    105:     my $local=localtime($now);
1.448     albertel  106:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    107: 	print $fh "$now:$message:$local\n";
                    108: 	close($fh);
                    109:     }
1.1       albertel  110:     return 1;
                    111: }
                    112: 
                    113: # -------------------------------------------------- Non-critical communication
                    114: sub subreply {
                    115:     my ($cmd,$server)=@_;
                    116:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    117:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    118:                                      Type    => SOCK_STREAM,
                    119:                                      Timeout => 10)
                    120:        or return "con_lost";
                    121:     print $client "$cmd\n";
                    122:     my $answer=<$client>;
1.9       www       123:     if (!$answer) { $answer="con_lost"; }
1.1       albertel  124:     chomp($answer);
                    125:     return $answer;
                    126: }
                    127: 
                    128: sub reply {
                    129:     my ($cmd,$server)=@_;
1.205     www       130:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  131:     my $answer=subreply($cmd,$server);
1.203     www       132:     if ($answer eq 'con_lost') {
1.311     matthew   133:         #sleep 5; 
                    134:         #$answer=subreply($cmd,$server);
                    135:         #if ($answer eq 'con_lost') {
1.233     albertel  136: 	#   &logthis("Second attempt con_lost on $server");
                    137:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
                    138:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    139:         #                                    Type    => SOCK_STREAM,
                    140:         #                                    Timeout => 10)
                    141:         #              or return "con_lost";
                    142:         #   &logthis("Killing socket");
                    143:         #   print $client "close_connection_exit\n";
                    144:            #sleep 5;
                    145:         #   $answer=subreply($cmd,$server);       
                    146:        #}   
1.203     www       147:     }
1.65      www       148:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       149:        &logthis("<font color=blue>WARNING:".
                    150:                 " $cmd to $server returned $answer</font>");
                    151:     }
1.1       albertel  152:     return $answer;
                    153: }
                    154: 
                    155: # ----------------------------------------------------------- Send USR1 to lonc
                    156: 
                    157: sub reconlonc {
                    158:     my $peerfile=shift;
                    159:     &logthis("Trying to reconnect for $peerfile");
                    160:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  161:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  162: 	my $loncpid=<$fh>;
                    163:         chomp($loncpid);
                    164:         if (kill 0 => $loncpid) {
                    165: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    166:             kill USR1 => $loncpid;
                    167:             sleep 1;
                    168:             if (-e "$peerfile") { return; }
                    169:             &logthis("$peerfile still not there, give it another try");
                    170:             sleep 5;
                    171:             if (-e "$peerfile") { return; }
1.12      www       172:             &logthis(
                    173:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  174:         } else {
1.12      www       175: 	    &logthis(
                    176:                "<font color=blue>WARNING:".
                    177:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  178:         }
                    179:     } else {
1.12      www       180:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  181:     }
                    182: }
                    183: 
                    184: # ------------------------------------------------------ Critical communication
1.12      www       185: 
1.1       albertel  186: sub critical {
                    187:     my ($cmd,$server)=@_;
1.89      www       188:     unless ($hostname{$server}) {
                    189:         &logthis("<font color=blue>WARNING:".
                    190:                " Critical message to unknown server ($server)</font>");
                    191:         return 'no_such_host';
                    192:     }
1.1       albertel  193:     my $answer=reply($cmd,$server);
                    194:     if ($answer eq 'con_lost') {
                    195:         my $pingreply=reply('ping',$server);
                    196: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
                    197:         my $pongreply=reply('pong',$server);
                    198:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
                    199:         $answer=reply($cmd,$server);
                    200:         if ($answer eq 'con_lost') {
                    201:             my $now=time;
                    202:             my $middlename=$cmd;
1.5       www       203:             $middlename=substr($middlename,0,16);
1.1       albertel  204:             $middlename=~s/\W//g;
                    205:             my $dfilename=
1.305     www       206:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    207:             $dumpcount++;
1.1       albertel  208:             {
1.448     albertel  209: 		my $dfh;
                    210: 		if (open($dfh,">$dfilename")) {
                    211: 		    print $dfh "$cmd\n"; 
                    212: 		    close($dfh);
                    213: 		}
1.1       albertel  214:             }
                    215:             sleep 2;
                    216:             my $wcmd='';
                    217:             {
1.448     albertel  218: 		my $dfh;
                    219: 		if (open($dfh,"<$dfilename")) {
                    220: 		    $wcmd=<$dfh>; 
                    221: 		    close($dfh);
                    222: 		}
1.1       albertel  223:             }
                    224:             chomp($wcmd);
1.7       www       225:             if ($wcmd eq $cmd) {
1.12      www       226: 		&logthis("<font color=blue>WARNING: ".
                    227:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  228:                 &logperm("D:$server:$cmd");
                    229: 	        return 'con_delayed';
                    230:             } else {
1.12      www       231:                 &logthis("<font color=red>CRITICAL:"
                    232:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  233:                 &logperm("F:$server:$cmd");
                    234:                 return 'con_failed';
                    235:             }
                    236:         }
                    237:     }
                    238:     return $answer;
1.405     albertel  239: }
                    240: 
1.412     www       241: #
1.405     albertel  242: # -------------- Remove all key from the env that start witha lowercase letter
1.412     www       243: #                (Which is always a lon-capa value)
                    244: 
1.405     albertel  245: sub cleanenv {
1.412     www       246: #    unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; }
                    247: #    unless (&Apache::exists_config_define("MODPERL2")) { return; }
1.405     albertel  248:     foreach my $key (keys(%ENV)) {
                    249: 	if ($key =~ /^[a-z]/) {
                    250: 	    delete($ENV{$key});
                    251: 	}
                    252:     }
1.374     www       253: }
                    254:  
                    255: # ------------------------------------------- Transfer profile into environment
                    256: 
                    257: sub transfer_profile_to_env {
                    258:     my ($lonidsdir,$handle)=@_;
                    259:     my @profile;
                    260:     {
1.448     albertel  261: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       262: 	flock($idf,LOCK_SH);
                    263: 	@profile=<$idf>;
1.448     albertel  264: 	close($idf);
1.374     www       265:     }
                    266:     my $envi;
1.433     matthew   267:     my %Remove;
1.374     www       268:     for ($envi=0;$envi<=$#profile;$envi++) {
                    269: 	chomp($profile[$envi]);
                    270: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
                    271: 	$ENV{$envname} = $envvalue;
1.433     matthew   272:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    273:             if ($time < time-300) {
                    274:                 $Remove{$key}++;
                    275:             }
                    276:         }
                    277:     }
1.446     albertel  278:     $ENV{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   279:     foreach my $expired_key (keys(%Remove)) {
                    280:         &delenv($expired_key);
1.374     www       281:     }
1.1       albertel  282: }
                    283: 
1.5       www       284: # ---------------------------------------------------------- Append Environment
                    285: 
                    286: sub appenv {
1.6       www       287:     my %newenv=@_;
1.191     harris41  288:     foreach (keys %newenv) {
1.35      www       289: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    290:             &logthis("<font color=blue>WARNING: ".
1.151     www       291:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    292:                 .'</font>');
1.35      www       293: 	    delete($newenv{$_});
                    294:         } else {
                    295:             $ENV{$_}=$newenv{$_};
                    296:         }
1.191     harris41  297:     }
1.95      www       298: 
                    299:     my $lockfh;
1.448     albertel  300:     unless (open($lockfh,"$ENV{'user.environment'}")) {
                    301: 	return 'error: '.$!;
1.95      www       302:     }
                    303:     unless (flock($lockfh,LOCK_EX)) {
                    304:          &logthis("<font color=blue>WARNING: ".
                    305:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  306:          close($lockfh);
1.95      www       307:          return 'error: '.$!;
                    308:     }
                    309: 
1.6       www       310:     my @oldenv;
                    311:     {
1.448     albertel  312: 	my $fh;
                    313: 	unless (open($fh,"$ENV{'user.environment'}")) {
                    314: 	    return 'error: '.$!;
                    315: 	}
                    316: 	@oldenv=<$fh>;
                    317: 	close($fh);
1.6       www       318:     }
                    319:     for (my $i=0; $i<=$#oldenv; $i++) {
                    320:         chomp($oldenv[$i]);
1.9       www       321:         if ($oldenv[$i] ne '') {
1.448     albertel  322: 	    my ($name,$value)=split(/=/,$oldenv[$i]);
                    323: 	    unless (defined($newenv{$name})) {
                    324: 		$newenv{$name}=$value;
                    325: 	    }
1.9       www       326:         }
1.6       www       327:     }
                    328:     {
1.448     albertel  329: 	my $fh;
                    330: 	unless (open($fh,">$ENV{'user.environment'}")) {
                    331: 	    return 'error';
                    332: 	}
                    333: 	my $newname;
                    334: 	foreach $newname (keys %newenv) {
                    335: 	    print $fh "$newname=$newenv{$newname}\n";
                    336: 	}
                    337: 	close($fh);
1.56      www       338:     }
1.448     albertel  339: 	
                    340:     close($lockfh);
1.56      www       341:     return 'ok';
                    342: }
                    343: # ----------------------------------------------------- Delete from Environment
                    344: 
                    345: sub delenv {
                    346:     my $delthis=shift;
                    347:     my %newenv=();
                    348:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    349:         &logthis("<font color=blue>WARNING: ".
                    350:                 "Attempt to delete from environment ".$delthis);
                    351:         return 'error';
                    352:     }
                    353:     my @oldenv;
                    354:     {
1.448     albertel  355: 	my $fh;
                    356: 	unless (open($fh,"$ENV{'user.environment'}")) {
                    357: 	    return 'error';
                    358: 	}
                    359: 	unless (flock($fh,LOCK_SH)) {
                    360: 	    &logthis("<font color=blue>WARNING: ".
                    361: 		     'Could not obtain shared lock in delenv: '.$!);
                    362: 	    close($fh);
                    363: 	    return 'error: '.$!;
                    364: 	}
                    365: 	@oldenv=<$fh>;
                    366: 	close($fh);
1.56      www       367:     }
                    368:     {
1.448     albertel  369: 	my $fh;
                    370: 	unless (open($fh,">$ENV{'user.environment'}")) {
                    371: 	    return 'error';
                    372: 	}
                    373: 	unless (flock($fh,LOCK_EX)) {
                    374: 	    &logthis("<font color=blue>WARNING: ".
                    375: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    376: 	    close($fh);
                    377: 	    return 'error: '.$!;
                    378: 	}
                    379: 	foreach (@oldenv) {
                    380: 	    unless ($_=~/^$delthis/) { print $fh $_; }
                    381: 	}
                    382: 	close($fh);
1.5       www       383:     }
                    384:     return 'ok';
1.369     albertel  385: }
                    386: 
                    387: # ------------------------------------------ Find out current server userload
                    388: # there is a copy in lond
                    389: sub userload {
                    390:     my $numusers=0;
                    391:     {
                    392: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    393: 	my $filename;
                    394: 	my $curtime=time;
                    395: 	while ($filename=readdir(LONIDS)) {
                    396: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  397: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  398: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  399: 	}
                    400: 	closedir(LONIDS);
                    401:     }
                    402:     my $userloadpercent=0;
                    403:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    404:     if ($maxuserload) {
1.371     albertel  405: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  406:     }
1.372     albertel  407:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  408:     return $userloadpercent;
1.283     www       409: }
                    410: 
                    411: # ------------------------------------------ Fight off request when overloaded
                    412: 
                    413: sub overloaderror {
                    414:     my ($r,$checkserver)=@_;
                    415:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    416:     my $loadavg;
                    417:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  418:        open(my $loadfile,'/proc/loadavg');
1.283     www       419:        $loadavg=<$loadfile>;
                    420:        $loadavg =~ s/\s.*//g;
1.285     matthew   421:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  422:        close($loadfile);
1.283     www       423:     } else {
                    424:        $loadavg=&reply('load',$checkserver);
                    425:     }
1.285     matthew   426:     my $overload=$loadavg-100;
1.283     www       427:     if ($overload>0) {
1.285     matthew   428: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       429:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
                    430:         return 413;
                    431:     }    
                    432:     return '';
1.5       www       433: }
1.1       albertel  434: 
                    435: # ------------------------------ Find server with least workload from spare.tab
1.11      www       436: 
1.1       albertel  437: sub spareserver {
1.370     albertel  438:     my ($loadpercent,$userloadpercent) = @_;
1.1       albertel  439:     my $tryserver;
                    440:     my $spareserver='';
1.370     albertel  441:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    442:     my $lowestserver=$loadpercent > $userloadpercent?
                    443: 	             $loadpercent :  $userloadpercent;
1.1       albertel  444:     foreach $tryserver (keys %spareid) {
1.411     albertel  445: 	my $loadans=reply('load',$tryserver);
                    446: 	my $userloadans=reply('userload',$tryserver);
                    447: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    448: 	    next; #didn't get a number from the server
                    449: 	}
                    450: 	my $answer;
                    451: 	if ($loadans =~ /\d/) {
                    452: 	    if ($userloadans =~ /\d/) {
                    453: 		#both are numbers, pick the bigger one
                    454: 		$answer=$loadans > $userloadans?
                    455: 		    $loadans :  $userloadans;
                    456: 	    } else {
                    457: 		$answer = $loadans;
                    458: 	    }
                    459: 	} else {
                    460: 	    $answer = $userloadans;
                    461: 	}
                    462: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    463: 	    $spareserver="http://$hostname{$tryserver}";
                    464: 	    $lowestserver=$answer;
                    465: 	}
1.370     albertel  466:     }
1.1       albertel  467:     return $spareserver;
1.202     matthew   468: }
                    469: 
                    470: # --------------------------------------------- Try to change a user's password
                    471: 
                    472: sub changepass {
                    473:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    474:     $currentpass = &escape($currentpass);
                    475:     $newpass     = &escape($newpass);
                    476:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    477: 		       $server);
                    478:     if (! $answer) {
                    479: 	&logthis("No reply on password change request to $server ".
                    480: 		 "by $uname in domain $udom.");
                    481:     } elsif ($answer =~ "^ok") {
                    482:         &logthis("$uname in $udom successfully changed their password ".
                    483: 		 "on $server.");
                    484:     } elsif ($answer =~ "^pwchange_failure") {
                    485: 	&logthis("$uname in $udom was unable to change their password ".
                    486: 		 "on $server.  The action was blocked by either lcpasswd ".
                    487: 		 "or pwchange");
                    488:     } elsif ($answer =~ "^non_authorized") {
                    489:         &logthis("$uname in $udom did not get their password correct when ".
                    490: 		 "attempting to change it on $server.");
                    491:     } elsif ($answer =~ "^auth_mode_error") {
                    492:         &logthis("$uname in $udom attempted to change their password despite ".
                    493: 		 "not being locally or internally authenticated on $server.");
                    494:     } elsif ($answer =~ "^unknown_user") {
                    495:         &logthis("$uname in $udom attempted to change their password ".
                    496: 		 "on $server but were unable to because $server is not ".
                    497: 		 "their home server.");
                    498:     } elsif ($answer =~ "^refused") {
                    499: 	&logthis("$server refused to change $uname in $udom password because ".
                    500: 		 "it was sent an unencrypted request to change the password.");
                    501:     }
                    502:     return $answer;
1.1       albertel  503: }
                    504: 
1.169     harris41  505: # ----------------------- Try to determine user's current authentication scheme
                    506: 
                    507: sub queryauthenticate {
                    508:     my ($uname,$udom)=@_;
                    509:     if (($perlvar{'lonRole'} eq 'library') && 
                    510:         ($udom eq $perlvar{'lonDefDomain'})) {
                    511: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
                    512: 			 $perlvar{'lonHostID'});
                    513: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    514: 	    if (length($answer)) {
                    515: 		return $answer;
                    516: 	    }
                    517: 	    else {
                    518: 	&logthis("User $uname at $udom lacks an authentication mechanism");
                    519: 		return 'no_host';
                    520: 	    }
                    521: 	}
                    522:     }
                    523: 
                    524:     my $tryserver;
                    525:     foreach $tryserver (keys %libserv) {
                    526: 	if ($hostdom{$tryserver} eq $udom) {
                    527:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
                    528: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    529: 	       if (length($answer)) {
                    530: 		   return $answer;
                    531: 	       }
                    532: 	       else {
                    533: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
                    534: 		   return 'no_host';
                    535: 	       }
                    536: 	   }
                    537:        }
                    538:     }
                    539:     &logthis("User $uname at $udom lacks an authentication mechanism");    
                    540:     return 'no_host';
                    541: }
                    542: 
1.1       albertel  543: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       544: 
1.1       albertel  545: sub authenticate {
                    546:     my ($uname,$upass,$udom)=@_;
1.12      www       547:     $upass=escape($upass);
1.199     www       548:     $uname=~s/\W//g;
1.1       albertel  549:     if (($perlvar{'lonRole'} eq 'library') && 
                    550:         ($udom eq $perlvar{'lonDefDomain'})) {
1.3       www       551:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2       www       552:         if ($answer =~ /authorized/) {
1.9       www       553:               if ($answer eq 'authorized') {
                    554:                  &logthis("User $uname at $udom authorized by local server"); 
                    555:                  return $perlvar{'lonHostID'}; 
                    556:               }
                    557:               if ($answer eq 'non_authorized') {
                    558:                  &logthis("User $uname at $udom rejected by local server"); 
                    559:                  return 'no_host'; 
                    560:               }
1.2       www       561: 	}
1.1       albertel  562:     }
                    563: 
                    564:     my $tryserver;
                    565:     foreach $tryserver (keys %libserv) {
                    566: 	if ($hostdom{$tryserver} eq $udom) {
1.10      www       567:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1       albertel  568:            if ($answer =~ /authorized/) {
1.9       www       569:               if ($answer eq 'authorized') {
                    570:                  &logthis("User $uname at $udom authorized by $tryserver"); 
                    571:                  return $tryserver; 
                    572:               }
                    573:               if ($answer eq 'non_authorized') {
                    574:                  &logthis("User $uname at $udom rejected by $tryserver");
                    575:                  return 'no_host';
                    576:               } 
1.1       albertel  577: 	   }
                    578:        }
1.9       www       579:     }
                    580:     &logthis("User $uname at $udom could not be authenticated");    
1.1       albertel  581:     return 'no_host';
                    582: }
                    583: 
                    584: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       585: 
1.1       albertel  586: sub homeserver {
1.230     stredwic  587:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  588:     my $index="$uname:$udom";
1.426     albertel  589: 
                    590:     my ($result,$cached)=&is_cached(\%homecache,$index,'home',86400);
                    591:     if (defined($cached)) { return $result; }
1.1       albertel  592:     my $tryserver;
                    593:     foreach $tryserver (keys %libserv) {
1.230     stredwic  594:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  595: 		 exists($badServerCache{$tryserver}));
1.1       albertel  596: 	if ($hostdom{$tryserver} eq $udom) {
                    597:            my $answer=reply("home:$udom:$uname",$tryserver);
                    598:            if ($answer eq 'found') { 
1.426     albertel  599: 	       return &do_cache(\%homecache,$index,$tryserver,'home');
1.231     stredwic  600:            } elsif ($answer eq 'no_host') {
                    601: 	       $badServerCache{$tryserver}=1;
1.221     matthew   602:            }
1.1       albertel  603:        }
                    604:     }    
                    605:     return 'no_host';
1.70      www       606: }
                    607: 
                    608: # ------------------------------------- Find the usernames behind a list of IDs
                    609: 
                    610: sub idget {
                    611:     my ($udom,@ids)=@_;
                    612:     my %returnhash=();
                    613:     
                    614:     my $tryserver;
                    615:     foreach $tryserver (keys %libserv) {
                    616:        if ($hostdom{$tryserver} eq $udom) {
                    617: 	  my $idlist=join('&',@ids);
                    618:           $idlist=~tr/A-Z/a-z/; 
                    619: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    620:           my @answer=();
1.76      www       621:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       622: 	      @answer=split(/\&/,$reply);
                    623:           }                    ;
                    624:           my $i;
                    625:           for ($i=0;$i<=$#ids;$i++) {
                    626:               if ($answer[$i]) {
                    627: 		  $returnhash{$ids[$i]}=$answer[$i];
                    628:               } 
                    629:           }
                    630:        }
                    631:     }    
                    632:     return %returnhash;
                    633: }
                    634: 
                    635: # ------------------------------------- Find the IDs behind a list of usernames
                    636: 
                    637: sub idrget {
                    638:     my ($udom,@unames)=@_;
                    639:     my %returnhash=();
1.191     harris41  640:     foreach (@unames) {
1.70      www       641:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  642:     }
1.70      www       643:     return %returnhash;
                    644: }
                    645: 
                    646: # ------------------------------- Store away a list of names and associated IDs
                    647: 
                    648: sub idput {
                    649:     my ($udom,%ids)=@_;
                    650:     my %servers=();
1.191     harris41  651:     foreach (keys %ids) {
1.70      www       652:         my $uhom=&homeserver($_,$udom);
                    653:         if ($uhom ne 'no_host') {
                    654:             my $id=&escape($ids{$_});
                    655:             $id=~tr/A-Z/a-z/;
                    656:             my $unam=&escape($_);
                    657: 	    if ($servers{$uhom}) {
                    658: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    659:             } else {
                    660:                 $servers{$uhom}=$id.'='.$unam;
                    661:             }
                    662:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
                    663:         }
1.191     harris41  664:     }
                    665:     foreach (keys %servers) {
1.70      www       666:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  667:     }
1.344     www       668: }
                    669: 
                    670: # --------------------------------------------------- Assign a key to a student
                    671: 
                    672: sub assign_access_key {
1.364     www       673: #
                    674: # a valid key looks like uname:udom#comments
                    675: # comments are being appended
                    676: #
                    677:     my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1.344     www       678:     $cdom=
                    679:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    680:     $cnum=
                    681:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    682:     $udom=$ENV{'user.name'} unless (defined($udom));
                    683:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       684:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       685:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
                    686:         ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) { 
                    687:                                                   # assigned to this person
                    688:                                                   # - this should not happen,
1.345     www       689:                                                   # unless something went wrong
                    690:                                                   # the first time around
                    691: # ready to assign
1.364     www       692:         $logentry=$1.'; '.$logentry;
                    693:         if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
                    694:                                                  $cdom,$cnum) eq 'ok') {
1.345     www       695: # key now belongs to user
1.346     www       696: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       697:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    698:                 &appenv('environment.'.$envkey => $ckey);
                    699:                 return 'ok';
                    700:             } else {
                    701:                 return 
                    702:   'error: Count not permanently assign key, will need to be re-entered later.';
                    703: 	    }
                    704:         } else {
                    705:             return 'error: Could not assign key, try again later.';
                    706:         }
1.364     www       707:     } elsif (!$existing{$ckey}) {
1.345     www       708: # the key does not exist
                    709: 	return 'error: The key does not exist';
                    710:     } else {
                    711: # the key is somebody else's
                    712: 	return 'error: The key is already in use';
                    713:     }
1.344     www       714: }
                    715: 
1.364     www       716: # ------------------------------------------ put an additional comment on a key
                    717: 
                    718: sub comment_access_key {
                    719: #
                    720: # a valid key looks like uname:udom#comments
                    721: # comments are being appended
                    722: #
                    723:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    724:     $cdom=
                    725:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    726:     $cnum=
                    727:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    728:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    729:     if ($existing{$ckey}) {
                    730:         $existing{$ckey}.='; '.$logentry;
                    731: # ready to assign
1.367     www       732:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       733:                                                  $cdom,$cnum) eq 'ok') {
                    734: 	    return 'ok';
                    735:         } else {
                    736: 	    return 'error: Count not store comment.';
                    737:         }
                    738:     } else {
                    739: # the key does not exist
                    740: 	return 'error: The key does not exist';
                    741:     }
                    742: }
                    743: 
1.344     www       744: # ------------------------------------------------------ Generate a set of keys
                    745: 
                    746: sub generate_access_keys {
1.364     www       747:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       748:     $cdom=
                    749:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    750:     $cnum=
                    751:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       752:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       753:     unless (($cdom) && ($cnum)) { return 0; }
                    754:     if ($number>10000) { return 0; }
                    755:     sleep(2); # make sure don't get same seed twice
                    756:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    757:     my $total=0;
                    758:     for (my $i=1;$i<=$number;$i++) {
                    759:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    760:                   sprintf("%lx",int(100000*rand)).'-'.
                    761:                   sprintf("%lx",int(100000*rand));
                    762:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    763:        $newkey=~s/0/h/g; # and also 0 and O
                    764:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    765:        if ($existing{$newkey}) {
                    766:            $i--;
                    767:        } else {
1.364     www       768: 	  if (&put('accesskeys',
                    769:               { $newkey => '# generated '.localtime().
                    770:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
                    771:                            '; '.$logentry },
                    772: 		   $cdom,$cnum) eq 'ok') {
1.344     www       773:               $total++;
                    774: 	  }
                    775:        }
                    776:     }
                    777:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                    778:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    779:     return $total;
                    780: }
                    781: 
                    782: # ------------------------------------------------------- Validate an accesskey
                    783: 
                    784: sub validate_access_key {
                    785:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    786:     $cdom=
                    787:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    788:     $cnum=
                    789:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    790:     $udom=$ENV{'user.name'} unless (defined($udom));
                    791:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       792:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       793:     return ($existing{$ckey}=~/^$uname\:$udom\#/);
1.70      www       794: }
                    795: 
                    796: # ------------------------------------- Find the section of student in a course
1.298     matthew   797: 
                    798: sub getsection {
                    799:     my ($udom,$unam,$courseid)=@_;
                    800:     $courseid=~s/\_/\//g;
                    801:     $courseid=~s/^(\w)/\/$1/;
                    802:     my %Pending; 
                    803:     my %Expired;
                    804:     #
                    805:     # Each role can either have not started yet (pending), be active, 
                    806:     #    or have expired.
                    807:     #
                    808:     # If there is an active role, we are done.
                    809:     #
                    810:     # If there is more than one role which has not started yet, 
                    811:     #     choose the one which will start sooner
                    812:     # If there is one role which has not started yet, return it.
                    813:     #
                    814:     # If there is more than one expired role, choose the one which ended last.
                    815:     # If there is a role which has expired, return it.
                    816:     #
                    817:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    818:                         &homeserver($unam,$udom)))) {
                    819:         my ($key,$value)=split(/\=/,$_);
                    820:         $key=&unescape($key);
                    821:         next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
                    822:         my $section=$1;
                    823:         if ($key eq $courseid.'_st') { $section=''; }
                    824:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    825:         my $now=time;
                    826:         if (defined($end) && ($now > $end)) {
                    827:             $Expired{$end}=$section;
                    828:             next;
                    829:         }
                    830:         if (defined($start) && ($now < $start)) {
                    831:             $Pending{$start}=$section;
                    832:             next;
                    833:         }
                    834:         return $section;
                    835:     }
                    836:     #
                    837:     # Presumedly there will be few matching roles from the above
                    838:     # loop and the sorting time will be negligible.
                    839:     if (scalar(keys(%Pending))) {
                    840:         my ($time) = sort {$a <=> $b} keys(%Pending);
                    841:         return $Pending{$time};
                    842:     } 
                    843:     if (scalar(keys(%Expired))) {
                    844:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    845:         my $time = pop(@sorted);
                    846:         return $Expired{$time};
                    847:     }
                    848:     return '-1';
                    849: }
1.70      www       850: 
1.452     albertel  851: 
                    852: my $disk_caching_disabled=1;
                    853: 
1.416     albertel  854: sub devalidate_cache {
1.428     albertel  855:     my ($cache,$id,$name) = @_;
1.417     albertel  856:     delete $$cache{$id.'.time'};
                    857:     delete $$cache{$id};
1.452     albertel  858:     if ($disk_caching_disabled) { return; }
1.442     albertel  859:     my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428     albertel  860:     open(DB,"$filename.lock");
                    861:     flock(DB,LOCK_EX);
                    862:     my %hash;
                    863:     if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
1.442     albertel  864: 	eval <<'EVALBLOCK';
                    865: 	    delete($hash{$id});
                    866: 	    delete($hash{$id.'.time'});
                    867: EVALBLOCK
                    868:         if ($@) {
                    869: 	    &logthis("<font color='red'>devalidate_cache blew up :$@:$name</font>");
                    870: 	    unlink($filename);
                    871: 	}
1.428     albertel  872:     } else {
1.442     albertel  873: 	if (-e $filename) {
                    874: 	    &logthis("Unable to tie hash (devalidate cache): $name");
                    875: 	    unlink($filename);
                    876: 	}
1.428     albertel  877:     }
                    878:     untie(%hash);
                    879:     flock(DB,LOCK_UN);
                    880:     close(DB);
1.416     albertel  881: }
                    882: 
                    883: sub is_cached {
1.425     albertel  884:     my ($cache,$id,$name,$time) = @_;
1.420     albertel  885:     if (!$time) { $time=300; }
1.416     albertel  886:     if (!exists($$cache{$id.'.time'})) {
1.428     albertel  887: 	&load_cache_item($cache,$name,$id);
1.425     albertel  888:     }
                    889:     if (!exists($$cache{$id.'.time'})) {
                    890: #	&logthis("Didn't find $id");
1.417     albertel  891: 	return (undef,undef);
1.416     albertel  892:     } else {
1.425     albertel  893: 	if (time-($$cache{$id.'.time'})>$time) {
1.435     www       894: #	    &logthis("Devalidating $id - ".time-($$cache{$id.'.time'}));
1.428     albertel  895: 	    &devalidate_cache($cache,$id,$name);
1.417     albertel  896: 	    return (undef,undef);
1.416     albertel  897: 	}
                    898:     }
1.417     albertel  899:     return ($$cache{$id},1);
1.416     albertel  900: }
                    901: 
                    902: sub do_cache {
1.425     albertel  903:     my ($cache,$id,$value,$name) = @_;
1.416     albertel  904:     $$cache{$id.'.time'}=time;
1.425     albertel  905:     $$cache{$id}=$value;
1.428     albertel  906: #    &logthis("Caching $id as :$value:");
                    907:     &save_cache_item($cache,$name,$id);
1.416     albertel  908:     # do_cache implictly return the set value
1.425     albertel  909:     $$cache{$id};
                    910: }
                    911: 
1.428     albertel  912: sub save_cache_item {
                    913:     my ($cache,$name,$id)=@_;
1.452     albertel  914:     if ($disk_caching_disabled) { return; }
1.428     albertel  915:     my $starttime=&Time::HiRes::time();
1.442     albertel  916: #    &logthis("Saving :$name:$id");
1.428     albertel  917:     my %hash;
1.442     albertel  918:     my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428     albertel  919:     open(DB,"$filename.lock");
                    920:     flock(DB,LOCK_EX);
                    921:     if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
1.442     albertel  922: 	eval <<'EVALBLOCK';
                    923: 	    $hash{$id.'.time'}=$$cache{$id.'.time'};
                    924: 	    $hash{$id}=freeze({'item'=>$$cache{$id}});
                    925: EVALBLOCK
                    926:         if ($@) {
                    927: 	    &logthis("<font color='red'>save_cache blew up :$@:$name</font>");
                    928: 	    unlink($filename);
                    929: 	}
1.428     albertel  930:     } else {
1.442     albertel  931: 	if (-e $filename) {
1.445     www       932: 	    &logthis("Unable to tie hash (save cache item): $name ($!)");
1.442     albertel  933: 	    unlink($filename);
                    934: 	}
1.428     albertel  935:     }
                    936:     untie(%hash);
                    937:     flock(DB,LOCK_UN);
                    938:     close(DB);
                    939: #    &logthis("save_cache_item $name took ".(&Time::HiRes::time()-$starttime));
                    940: }
                    941: 
                    942: sub load_cache_item {
                    943:     my ($cache,$name,$id)=@_;
1.452     albertel  944:     if ($disk_caching_disabled) { return; }
1.428     albertel  945:     my $starttime=&Time::HiRes::time();
                    946: #    &logthis("Before Loading $name  for $id size is ".scalar(%$cache));
                    947:     my %hash;
1.442     albertel  948:     my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428     albertel  949:     open(DB,"$filename.lock");
                    950:     flock(DB,LOCK_SH);
                    951:     if (tie(%hash,'GDBM_File',$filename,&GDBM_READER(),0640)) {
1.442     albertel  952: 	eval <<'EVALBLOCK';
                    953: 	    if (!%$cache) {
                    954: 		my $count;
                    955: 		while (my ($key,$value)=each(%hash)) { 
                    956: 		    $count++;
                    957: 		    if ($key =~ /\.time$/) {
                    958: 			$$cache{$key}=$value;
                    959: 		    } else {
                    960: 			my $hashref=thaw($value);
                    961: 			$$cache{$key}=$hashref->{'item'};
                    962: 		    }
1.428     albertel  963: 		}
1.442     albertel  964: #	    &logthis("Initial load: $count");
                    965: 	    } else {
                    966: 		my $hashref=thaw($hash{$id});
                    967: 		$$cache{$id}=$hashref->{'item'};
                    968: 		$$cache{$id.'.time'}=$hash{$id.'.time'};
1.428     albertel  969: 	    }
1.442     albertel  970: EVALBLOCK
                    971:         if ($@) {
                    972: 	    &logthis("<font color='red'>load_cache blew up :$@:$name</font>");
                    973: 	    unlink($filename);
                    974: 	}        
                    975:     } else {
                    976: 	if (-e $filename) {
1.445     www       977: 	    &logthis("Unable to tie hash (load cache item): $name ($!)");
1.442     albertel  978: 	    unlink($filename);
1.428     albertel  979: 	}
                    980:     }
                    981:     untie(%hash);
                    982:     flock(DB,LOCK_UN);
                    983:     close(DB);
                    984: #    &logthis("After Loading $name size is ".scalar(%$cache));
                    985: #    &logthis("load_cache_item $name took ".(&Time::HiRes::time()-$starttime));
                    986: }
                    987: 
1.70      www       988: sub usection {
                    989:     my ($udom,$unam,$courseid)=@_;
1.416     albertel  990:     my $hashid="$udom:$unam:$courseid";
                    991:     
1.425     albertel  992:     my ($result,$cached)=&is_cached(\%usectioncache,$hashid,'usection');
1.417     albertel  993:     if (defined($cached)) { return $result; }
1.70      www       994:     $courseid=~s/\_/\//g;
                    995:     $courseid=~s/^(\w)/\/$1/;
1.191     harris41  996:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    997:                         &homeserver($unam,$udom)))) {
1.70      www       998:         my ($key,$value)=split(/\=/,$_);
                    999:         $key=&unescape($key);
                   1000:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
                   1001:             my $section=$1;
                   1002:             if ($key eq $courseid.'_st') { $section=''; }
                   1003: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                   1004:             my $now=time;
                   1005:             my $notactive=0;
                   1006:             if ($start) {
                   1007: 		if ($now<$start) { $notactive=1; }
                   1008:             }
                   1009:             if ($end) {
                   1010:                 if ($now>$end) { $notactive=1; }
                   1011:             } 
1.416     albertel 1012:             unless ($notactive) {
1.425     albertel 1013: 		return &do_cache(\%usectioncache,$hashid,$section,'usection');
1.416     albertel 1014: 	    }
1.70      www      1015:         }
1.191     harris41 1016:     }
1.425     albertel 1017:     return &do_cache(\%usectioncache,$hashid,'-1','usection');
1.70      www      1018: }
                   1019: 
                   1020: # ------------------------------------- Read an entry from a user's environment
                   1021: 
                   1022: sub userenvironment {
                   1023:     my ($udom,$unam,@what)=@_;
                   1024:     my %returnhash=();
                   1025:     my @answer=split(/\&/,
                   1026:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1027:                       &homeserver($unam,$udom)));
                   1028:     my $i;
                   1029:     for ($i=0;$i<=$#what;$i++) {
                   1030: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1031:     }
                   1032:     return %returnhash;
1.1       albertel 1033: }
                   1034: 
1.263     www      1035: # -------------------------------------------------------------------- New chat
                   1036: 
                   1037: sub chatsend {
                   1038:     my ($newentry,$anon)=@_;
                   1039:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1040:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1041:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                   1042:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
                   1043: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
                   1044: 		   &escape($newentry)),$chome);
1.292     www      1045: }
                   1046: 
                   1047: # ------------------------------------------ Find current version of a resource
                   1048: 
                   1049: sub getversion {
                   1050:     my $fname=&clutter(shift);
                   1051:     unless ($fname=~/^\/res\//) { return -1; }
                   1052:     return &currentversion(&filelocation('',$fname));
                   1053: }
                   1054: 
                   1055: sub currentversion {
                   1056:     my $fname=shift;
1.440     www      1057:     my ($result,$cached)=&is_cached(\%resversioncache,$fname,'resversion',600);
                   1058:     if (defined($cached)) { return $result; }
1.292     www      1059:     my $author=$fname;
                   1060:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1061:     my ($udom,$uname)=split(/\//,$author);
                   1062:     my $home=homeserver($uname,$udom);
                   1063:     if ($home eq 'no_host') { 
                   1064:         return -1; 
                   1065:     }
                   1066:     my $answer=reply("currentversion:$fname",$home);
                   1067:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1068: 	return -1;
                   1069:     }
1.440     www      1070:     return &do_cache(\%resversioncache,$fname,$answer,'resversion');
1.263     www      1071: }
                   1072: 
1.1       albertel 1073: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1074: 
1.1       albertel 1075: sub subscribe {
                   1076:     my $fname=shift;
1.312     www      1077:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.1       albertel 1078:     my $author=$fname;
                   1079:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1080:     my ($udom,$uname)=split(/\//,$author);
                   1081:     my $home=homeserver($uname,$udom);
1.335     albertel 1082:     if ($home eq 'no_host') {
                   1083:         return 'not_found';
1.1       albertel 1084:     }
                   1085:     my $answer=reply("sub:$fname",$home);
1.64      www      1086:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1087: 	$answer.=' by '.$home;
                   1088:     }
1.1       albertel 1089:     return $answer;
                   1090: }
                   1091:     
1.8       www      1092: # -------------------------------------------------------------- Replicate file
                   1093: 
                   1094: sub repcopy {
                   1095:     my $filename=shift;
1.23      www      1096:     $filename=~s/\/+/\//g;
1.214     www      1097:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
1.8       www      1098:     my $transname="$filename.in.transfer";
1.17      www      1099:     if ((-e $filename) || (-e $transname)) { return OK; }
1.8       www      1100:     my $remoteurl=subscribe($filename);
1.64      www      1101:     if ($remoteurl =~ /^con_lost by/) {
                   1102: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www      1103:            return HTTP_SERVICE_UNAVAILABLE;
                   1104:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1105: 	   #&logthis("Subscribe returned not_found: $filename");
1.8       www      1106: 	   return HTTP_NOT_FOUND;
1.64      www      1107:     } elsif ($remoteurl =~ /^rejected by/) {
                   1108: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www      1109:            return FORBIDDEN;
1.20      www      1110:     } elsif ($remoteurl eq 'directory') {
                   1111:            return OK;
1.8       www      1112:     } else {
1.290     www      1113:         my $author=$filename;
                   1114:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1115:         my ($udom,$uname)=split(/\//,$author);
                   1116:         my $home=homeserver($uname,$udom);
                   1117:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1118:            my @parts=split(/\//,$filename);
                   1119:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1120:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1121:                &logthis("Malconfiguration for replication: $filename");
                   1122: 	       return HTTP_BAD_REQUEST;
                   1123:            }
                   1124:            my $count;
                   1125:            for ($count=5;$count<$#parts;$count++) {
                   1126:                $path.="/$parts[$count]";
                   1127:                if ((-e $path)!=1) {
                   1128: 		   mkdir($path,0777);
                   1129:                }
                   1130:            }
                   1131:            my $ua=new LWP::UserAgent;
                   1132:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1133:            my $response=$ua->request($request,$transname);
                   1134:            if ($response->is_error()) {
                   1135: 	       unlink($transname);
                   1136:                my $message=$response->status_line;
1.12      www      1137:                &logthis("<font color=blue>WARNING:"
                   1138:                        ." LWP get: $message: $filename</font>");
1.8       www      1139:                return HTTP_SERVICE_UNAVAILABLE;
                   1140:            } else {
1.16      www      1141: 	       if ($remoteurl!~/\.meta$/) {
                   1142:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1143:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1144:                   if ($mresponse->is_error()) {
                   1145: 		      unlink($filename.'.meta');
                   1146:                       &logthis(
                   1147:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                   1148:                   }
                   1149: 	       }
1.8       www      1150:                rename($transname,$filename);
                   1151:                return OK;
                   1152:            }
1.290     www      1153:        }
1.8       www      1154:     }
1.330     www      1155: }
                   1156: 
                   1157: # ------------------------------------------------ Get server side include body
                   1158: sub ssi_body {
1.381     albertel 1159:     my ($filelink,%form)=@_;
1.330     www      1160:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1161:                                      &ssi($filelink,%form));
1.451     albertel 1162:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1163:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.331     www      1164:     $output=~
                   1165:             s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
1.330     www      1166:     return $output;
1.8       www      1167: }
                   1168: 
1.15      www      1169: # --------------------------------------------------------- Server Side Include
                   1170: 
                   1171: sub ssi {
                   1172: 
1.23      www      1173:     my ($fn,%form)=@_;
1.15      www      1174: 
                   1175:     my $ua=new LWP::UserAgent;
1.23      www      1176:     
                   1177:     my $request;
                   1178:     
                   1179:     if (%form) {
                   1180:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1181:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1182:     } else {
                   1183:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1184:     }
                   1185: 
1.15      www      1186:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1187:     my $response=$ua->request($request);
                   1188: 
1.324     www      1189:     return $response->content;
                   1190: }
                   1191: 
                   1192: sub externalssi {
                   1193:     my ($url)=@_;
                   1194:     my $ua=new LWP::UserAgent;
                   1195:     my $request=new HTTP::Request('GET',$url);
                   1196:     my $response=$ua->request($request);
1.15      www      1197:     return $response->content;
                   1198: }
1.254     www      1199: 
                   1200: # ------- Add a token to a remote URI's query string to vouch for access rights
                   1201: 
                   1202: sub tokenwrapper {
                   1203:     my $uri=shift;
1.259     www      1204:     $uri=~s/^http\:\/\/([^\/]+)//;
                   1205:     $uri=~s/^\///;
                   1206:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
                   1207:     my $token=$1;
                   1208:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
                   1209: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
                   1210:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
1.304     www      1211:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   1212:                                '&tokenissued='.$perlvar{'lonHostID'};
1.259     www      1213:     } else {
                   1214: 	return '/adm/notfound.html';
                   1215:     }
1.254     www      1216: }
                   1217:     
1.257     www      1218: # --------------- Take an uploaded file and put it into the userfiles directory
1.259     www      1219: # input: name of form element, coursedoc=1 means this is for the course
1.257     www      1220: # output: url of file in userspace
                   1221: 
                   1222: sub userfileupload {
1.259     www      1223:     my ($formname,$coursedoc)=@_;
1.257     www      1224:     my $fname=$ENV{'form.'.$formname.'.filename'};
1.315     www      1225: # Replace Windows backslashes by forward slashes
1.257     www      1226:     $fname=~s/\\/\//g;
1.315     www      1227: # Get rid of everything but the actual filename
1.257     www      1228:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1229: # Replace spaces by underscores
                   1230:     $fname=~s/\s+/\_/g;
                   1231: # Replace all other weird characters by nothing
1.317     www      1232:     $fname=~s/[^\w\.\-]//g;
1.315     www      1233: # See if there is anything left
1.257     www      1234:     unless ($fname) { return 'error: no uploaded file'; }
                   1235:     chop($ENV{'form.'.$formname});
1.258     www      1236: # Create the directory if not present
1.259     www      1237:     my $docuname='';
                   1238:     my $docudom='';
                   1239:     my $docuhome='';
                   1240:     if ($coursedoc) {
                   1241: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1242: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1243: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                   1244:     } else {
                   1245:         $docuname=$ENV{'user.name'};
                   1246:         $docudom=$ENV{'user.domain'};
                   1247:         $docuhome=$ENV{'user.home'};
                   1248:     }
1.271     www      1249:     return 
                   1250:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
                   1251: }
                   1252: 
                   1253: sub finishuserfileupload {
                   1254:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
1.259     www      1255:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1256:     my $filepath=$perlvar{'lonDocRoot'};
1.259     www      1257:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1258:     my $count;
                   1259:     for ($count=4;$count<=$#parts;$count++) {
                   1260:         $filepath.="/$parts[$count]";
                   1261:         if ((-e $filepath)!=1) {
                   1262: 	    mkdir($filepath,0777);
                   1263:         }
                   1264:     }
                   1265: # Save the file
                   1266:     {
1.448     albertel 1267:        open(my $fh,'>'.$filepath.'/'.$fname);
1.258     www      1268:        print $fh $ENV{'form.'.$formname};
1.448     albertel 1269:        close($fh);
1.258     www      1270:     }
1.259     www      1271: # Notify homeserver to grep it
                   1272: #
1.295     www      1273:     
                   1274:     my $fetchresult= 
                   1275:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
                   1276:     if ($fetchresult eq 'ok') {
1.259     www      1277: #
1.258     www      1278: # Return the URL to it
1.263     www      1279:         return '/uploaded/'.$path.$fname;
                   1280:     } else {
1.295     www      1281:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
                   1282:          ' to host '.$docuhome.': '.$fetchresult);
1.263     www      1283:         return '/adm/notfound.html';
                   1284:     }    
1.257     www      1285: }
1.15      www      1286: 
1.14      www      1287: # ------------------------------------------------------------------------- Log
                   1288: 
                   1289: sub log {
                   1290:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1291:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1292: }
                   1293: 
                   1294: # ------------------------------------------------------------------ Course Log
1.352     www      1295: #
                   1296: # This routine flushes several buffers of non-mission-critical nature
                   1297: #
1.157     www      1298: 
                   1299: sub flushcourselogs {
1.352     www      1300:     &logthis('Flushing log buffers');
                   1301: #
                   1302: # course logs
                   1303: # This is a log of all transactions in a course, which can be used
                   1304: # for data mining purposes
                   1305: #
                   1306: # It also collects the courseid database, which lists last transaction
                   1307: # times and course titles for all courseids
                   1308: #
                   1309:     my %courseidbuffer=();
1.191     harris41 1310:     foreach (keys %courselogs) {
1.157     www      1311:         my $crsid=$_;
1.352     www      1312:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1313: 		          &escape($courselogs{$crsid}),
                   1314: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1315: 	    delete $courselogs{$crsid};
                   1316:         } else {
                   1317:             &logthis('Failed to flush log buffer for '.$crsid);
                   1318:             if (length($courselogs{$crsid})>40000) {
                   1319:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                   1320:                         " exceeded maximum size, deleting.</font>");
                   1321:                delete $courselogs{$crsid};
                   1322:             }
1.352     www      1323:         }
                   1324:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1325:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
                   1326: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1327:         } else {
                   1328:            $courseidbuffer{$coursehombuf{$crsid}}=
                   1329: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1330:         }    
1.191     harris41 1331:     }
1.352     www      1332: #
                   1333: # Write course id database (reverse lookup) to homeserver of courses 
                   1334: # Is used in pickcourse
                   1335: #
                   1336:     foreach (keys %courseidbuffer) {
1.353     www      1337:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1338:     }
                   1339: #
                   1340: # File accesses
                   1341: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1342: #
1.449     matthew  1343:     foreach my $entry (keys(%accesshash)) {
                   1344:         my ($dom,$name,undef,$type)=($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
                   1345:         if ($type eq 'count'){
1.450     matthew  1346:             my $value = $accesshash{$entry};
                   1347:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1348:             my %temphash=($url => $value);
1.449     matthew  1349:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1350:             if ($result eq 'ok') {
                   1351:                 delete $accesshash{$entry};
                   1352:             } elsif ($result eq 'unknown_cmd') {
                   1353:                 # Target server has old code running on it.
1.450     matthew  1354:                 my %temphash=($entry => $value);
1.449     matthew  1355:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1356:                     delete $accesshash{$entry};
                   1357:                 }
                   1358:             }
                   1359:         } else {
1.450     matthew  1360:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1361:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1362:                 delete $accesshash{$entry};
                   1363:             }
1.185     www      1364:         }
1.191     harris41 1365:     }
1.352     www      1366: #
                   1367: # Roles
                   1368: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1369: #
1.349     www      1370:     foreach (keys %userrolehash) {
                   1371:         my $entry=$_;
1.351     www      1372:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1373: 	    split(/\:/,$entry);
                   1374:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1375:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1376:                 $rudom,$runame) eq 'ok') {
                   1377: 	    delete $userrolehash{$entry};
                   1378:         }
                   1379:     }
1.186     www      1380:     $dumpcount++;
1.157     www      1381: }
                   1382: 
                   1383: sub courselog {
                   1384:     my $what=shift;
1.158     www      1385:     $what=time.':'.$what;
1.157     www      1386:     unless ($ENV{'request.course.id'}) { return ''; }
1.188     www      1387:     $coursedombuf{$ENV{'request.course.id'}}=
1.352     www      1388:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1389:     $coursenumbuf{$ENV{'request.course.id'}}=
1.188     www      1390:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1391:     $coursehombuf{$ENV{'request.course.id'}}=
                   1392:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.352     www      1393:     $coursedescrbuf{$ENV{'request.course.id'}}=
                   1394:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.157     www      1395:     if (defined $courselogs{$ENV{'request.course.id'}}) {
                   1396: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
                   1397:     } else {
                   1398: 	$courselogs{$ENV{'request.course.id'}}.=$what;
                   1399:     }
1.450     matthew  1400: #    if (length($courselogs{$ENV{'request.course.id'}})>4048) {
                   1401:     if (length($courselogs{$ENV{'request.course.id'}})>48) {
1.157     www      1402: 	&flushcourselogs();
                   1403:     }
1.158     www      1404: }
                   1405: 
                   1406: sub courseacclog {
                   1407:     my $fnsymb=shift;
                   1408:     unless ($ENV{'request.course.id'}) { return ''; }
                   1409:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.408     www      1410:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187     www      1411:         $what.=':POST';
1.191     harris41 1412: 	foreach (keys %ENV) {
1.158     www      1413:             if ($_=~/^form\.(.*)/) {
                   1414: 		$what.=':'.$1.'='.$ENV{$_};
                   1415:             }
1.191     harris41 1416:         }
1.158     www      1417:     }
                   1418:     &courselog($what);
1.149     www      1419: }
                   1420: 
1.185     www      1421: sub countacc {
                   1422:     my $url=&declutter(shift);
                   1423:     unless ($ENV{'request.course.id'}) { return ''; }
                   1424:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1425:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1426:     $accesshash{$key}++;
1.185     www      1427: }
1.349     www      1428: 
1.361     www      1429: sub linklog {
                   1430:     my ($from,$to)=@_;
                   1431:     $from=&declutter($from);
                   1432:     $to=&declutter($to);
                   1433:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1434:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1435: }
                   1436:   
1.349     www      1437: sub userrolelog {
                   1438:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
                   1439:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
                   1440:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   1441:         ($trole=~/^cr/)) {
1.350     www      1442:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1443:        $userrolehash
                   1444:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1445:                     =$tend.':'.$tstart;
                   1446:    }
1.351     www      1447: }
                   1448: 
                   1449: sub get_course_adv_roles {
                   1450:     my $cid=shift;
                   1451:     $cid=$ENV{'request.course.id'} unless (defined($cid));
                   1452:     my %coursehash=&coursedescription($cid);
                   1453:     my %returnhash=();
                   1454:     my %dumphash=
                   1455:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1456:     my $now=time;
                   1457:     foreach (keys %dumphash) {
                   1458: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1459:         if (($tstart) && ($tstart<0)) { next; }
                   1460:         if (($tend) && ($tend<$now)) { next; }
                   1461:         if (($tstart) && ($now<$tstart)) { next; }
                   1462:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1463:         my $key=&plaintext($role);
                   1464:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1465:         if ($returnhash{$key}) {
                   1466: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1467:         } else {
                   1468:             $returnhash{$key}=$username.':'.$domain;
                   1469:         }
1.400     www      1470:      }
                   1471:     return %returnhash;
                   1472: }
                   1473: 
                   1474: sub get_my_roles {
                   1475:     my ($uname,$udom)=@_;
                   1476:     unless (defined($uname)) { $uname=$ENV{'user.name'}; }
                   1477:     unless (defined($udom)) { $udom=$ENV{'user.domain'}; }
                   1478:     my %dumphash=
                   1479:             &dump('nohist_userroles',$udom,$uname);
                   1480:     my %returnhash=();
                   1481:     my $now=time;
                   1482:     foreach (keys %dumphash) {
                   1483: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1484:         if (($tstart) && ($tstart<0)) { next; }
                   1485:         if (($tend) && ($tend<$now)) { next; }
                   1486:         if (($tstart) && ($now<$tstart)) { next; }
                   1487:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1488: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1489:      }
                   1490:     return %returnhash;
1.399     www      1491: }
                   1492: 
                   1493: # ----------------------------------------------------- Frontpage Announcements
                   1494: #
                   1495: #
                   1496: 
                   1497: sub postannounce {
                   1498:     my ($server,$text)=@_;
                   1499:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1500:     unless ($text=~/\w/) { $text=''; }
                   1501:     return &reply('setannounce:'.&escape($text),$server);
                   1502: }
                   1503: 
                   1504: sub getannounce {
1.448     albertel 1505: 
                   1506:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1507: 	my $announcement='';
                   1508: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1509: 	close($fh);
1.399     www      1510: 	if ($announcement=~/\w/) { 
                   1511: 	    return 
                   1512:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
                   1513:    '<tr><td bgcolor="#FFFFFF"><pre>'.$announcement.'</pre></td></tr></table>'; 
                   1514: 	} else {
                   1515: 	    return '';
                   1516: 	}
                   1517:     } else {
                   1518: 	return '';
                   1519:     }
1.351     www      1520: }
1.353     www      1521: 
                   1522: # ---------------------------------------------------------- Course ID routines
                   1523: # Deal with domain's nohist_courseid.db files
                   1524: #
                   1525: 
                   1526: sub courseidput {
                   1527:     my ($domain,$what,$coursehome)=@_;
                   1528:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1529: }
                   1530: 
                   1531: sub courseiddump {
                   1532:     my ($domfilter,$descfilter,$sincefilter)=@_;
                   1533:     my %returnhash=();
1.355     www      1534:     unless ($domfilter) { $domfilter=''; }
1.353     www      1535:     foreach my $tryserver (keys %libserv) {
1.355     www      1536: 	if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.353     www      1537: 	    foreach (
                   1538:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.354     www      1539: 			       $sincefilter.':'.&escape($descfilter),
                   1540:                                $tryserver))) {
1.353     www      1541: 		my ($key,$value)=split(/\=/,$_);
                   1542:                 if (($key) && ($value)) {
                   1543: 		    $returnhash{&unescape($key)}=&unescape($value);
                   1544:                 }
                   1545:             }
                   1546: 
                   1547:         }
                   1548:     }
                   1549:     return %returnhash;
                   1550: }
                   1551: 
                   1552: #
1.149     www      1553: # ----------------------------------------------------------- Check out an item
                   1554: 
                   1555: sub checkout {
                   1556:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1557:     my $now=time;
                   1558:     my $lonhost=$perlvar{'lonHostID'};
                   1559:     my $infostr=&escape(
1.234     www      1560:                  'CHECKOUTTOKEN&'.
1.149     www      1561:                  $tuname.'&'.
                   1562:                  $tudom.'&'.
                   1563:                  $tcrsid.'&'.
                   1564:                  $symb.'&'.
                   1565: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1566:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1567:     if ($token=~/^error\:/) { 
                   1568:         &logthis("<font color=blue>WARNING: ".
                   1569:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1570:                  "</font>");
                   1571:         return ''; 
                   1572:     }
                   1573: 
1.149     www      1574:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   1575:     $token=~tr/a-z/A-Z/;
                   1576: 
1.153     www      1577:     my %infohash=('resource.0.outtoken' => $token,
                   1578:                   'resource.0.checkouttime' => $now,
                   1579:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      1580: 
                   1581:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1582:        return '';
1.151     www      1583:     } else {
                   1584:         &logthis("<font color=blue>WARNING: ".
                   1585:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1586:                  "</font>");
1.149     www      1587:     }    
                   1588: 
                   1589:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1590:                          &escape('Checkout '.$infostr.' - '.
                   1591:                                                  $token)) ne 'ok') {
                   1592: 	return '';
1.151     www      1593:     } else {
                   1594:         &logthis("<font color=blue>WARNING: ".
                   1595:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1596:                  "</font>");
1.149     www      1597:     }
1.151     www      1598:     return $token;
1.149     www      1599: }
                   1600: 
                   1601: # ------------------------------------------------------------ Check in an item
                   1602: 
                   1603: sub checkin {
                   1604:     my $token=shift;
1.150     www      1605:     my $now=time;
                   1606:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   1607:     $lonhost=~tr/A-Z/a-z/;
                   1608:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
                   1609:     $dtoken=~s/\W/\_/g;
1.234     www      1610:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      1611:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   1612: 
1.154     www      1613:     unless (($tuname) && ($tudom)) {
                   1614:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   1615:         return '';
                   1616:     }
                   1617:     
                   1618:     unless (&allowed('mgr',$tcrsid)) {
                   1619:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   1620:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
                   1621:         return '';
                   1622:     }
                   1623: 
1.153     www      1624:     my %infohash=('resource.0.intoken' => $token,
                   1625:                   'resource.0.checkintime' => $now,
                   1626:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      1627: 
                   1628:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1629:        return '';
                   1630:     }    
                   1631: 
                   1632:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1633:                          &escape('Checkin - '.$token)) ne 'ok') {
                   1634: 	return '';
                   1635:     }
                   1636: 
                   1637:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      1638: }
                   1639: 
                   1640: # --------------------------------------------- Set Expire Date for Spreadsheet
                   1641: 
                   1642: sub expirespread {
                   1643:     my ($uname,$udom,$stype,$usymb)=@_;
                   1644:     my $cid=$ENV{'request.course.id'}; 
                   1645:     if ($cid) {
                   1646:        my $now=time;
                   1647:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                   1648:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
                   1649:                             $ENV{'course.'.$cid.'.num'}.
                   1650: 	        	    ':nohist_expirationdates:'.
                   1651:                             &escape($key).'='.$now,
                   1652:                             $ENV{'course.'.$cid.'.home'})
                   1653:     }
                   1654:     return 'ok';
1.14      www      1655: }
                   1656: 
1.109     www      1657: # ----------------------------------------------------- Devalidate Spreadsheets
                   1658: 
                   1659: sub devalidate {
1.325     www      1660:     my ($symb,$uname,$udom)=@_;
1.109     www      1661:     my $cid=$ENV{'request.course.id'}; 
                   1662:     if ($cid) {
1.391     matthew  1663:         # delete the stored spreadsheets for
                   1664:         # - the student level sheet of this user in course's homespace
                   1665:         # - the assessment level sheet for this resource 
                   1666:         #   for this user in user's homespace
1.325     www      1667: 	my $key=$uname.':'.$udom.':';
1.109     www      1668:         my $status=
1.299     matthew  1669: 	    &del('nohist_calculatedsheets',
1.391     matthew  1670: 		 [$key.'studentcalc:'],
1.133     albertel 1671: 		 $ENV{'course.'.$cid.'.domain'},
                   1672: 		 $ENV{'course.'.$cid.'.num'})
                   1673: 		.' '.
                   1674: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  1675: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      1676:         unless ($status eq 'ok ok') {
                   1677:            &logthis('Could not devalidate spreadsheet '.
1.325     www      1678:                     $uname.' at '.$udom.' for '.
1.109     www      1679: 		    $symb.': '.$status);
1.133     albertel 1680:         }
1.109     www      1681:     }
                   1682: }
                   1683: 
1.265     albertel 1684: sub get_scalar {
                   1685:     my ($string,$end) = @_;
                   1686:     my $value;
                   1687:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   1688: 	$value = $1;
                   1689:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   1690: 	$value = $1;
                   1691:     }
                   1692:     return &unescape($value);
                   1693: }
                   1694: 
                   1695: sub array2str {
                   1696:   my (@array) = @_;
                   1697:   my $result=&arrayref2str(\@array);
                   1698:   $result=~s/^__ARRAY_REF__//;
                   1699:   $result=~s/__END_ARRAY_REF__$//;
                   1700:   return $result;
                   1701: }
                   1702: 
1.204     albertel 1703: sub arrayref2str {
                   1704:   my ($arrayref) = @_;
1.265     albertel 1705:   my $result='__ARRAY_REF__';
1.204     albertel 1706:   foreach my $elem (@$arrayref) {
1.265     albertel 1707:     if(ref($elem) eq 'ARRAY') {
                   1708:       $result.=&arrayref2str($elem).'&';
                   1709:     } elsif(ref($elem) eq 'HASH') {
                   1710:       $result.=&hashref2str($elem).'&';
                   1711:     } elsif(ref($elem)) {
                   1712:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 1713:     } else {
                   1714:       $result.=&escape($elem).'&';
                   1715:     }
                   1716:   }
                   1717:   $result=~s/\&$//;
1.265     albertel 1718:   $result .= '__END_ARRAY_REF__';
1.204     albertel 1719:   return $result;
                   1720: }
                   1721: 
1.168     albertel 1722: sub hash2str {
1.204     albertel 1723:   my (%hash) = @_;
                   1724:   my $result=&hashref2str(\%hash);
1.265     albertel 1725:   $result=~s/^__HASH_REF__//;
                   1726:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 1727:   return $result;
                   1728: }
                   1729: 
                   1730: sub hashref2str {
                   1731:   my ($hashref)=@_;
1.265     albertel 1732:   my $result='__HASH_REF__';
1.204     albertel 1733:   foreach (keys(%$hashref)) {
                   1734:     if (ref($_) eq 'ARRAY') {
1.265     albertel 1735:       $result.=&arrayref2str($_).'=';
1.204     albertel 1736:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 1737:       $result.=&hashref2str($_).'=';
1.204     albertel 1738:     } elsif (ref($_)) {
1.265     albertel 1739:       $result.='=';
                   1740:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 1741:     } else {
1.265     albertel 1742: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 1743:     }
                   1744: 
1.265     albertel 1745:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   1746:       $result.=&arrayref2str($hashref->{$_}).'&';
                   1747:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   1748:       $result.=&hashref2str($hashref->{$_}).'&';
                   1749:     } elsif(ref($hashref->{$_})) {
                   1750:        $result.='&';
                   1751:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 1752:     } else {
1.265     albertel 1753:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 1754:     }
                   1755:   }
1.168     albertel 1756:   $result=~s/\&$//;
1.265     albertel 1757:   $result .= '__END_HASH_REF__';
1.168     albertel 1758:   return $result;
                   1759: }
                   1760: 
                   1761: sub str2hash {
1.265     albertel 1762:     my ($string)=@_;
                   1763:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   1764:     return %$hash;
                   1765: }
                   1766: 
                   1767: sub str2hashref {
1.168     albertel 1768:   my ($string) = @_;
1.265     albertel 1769: 
                   1770:   my %hash;
                   1771: 
                   1772:   if($string !~ /^__HASH_REF__/) {
                   1773:       if (! ($string eq '' || !defined($string))) {
                   1774: 	  $hash{'error'}='Not hash reference';
                   1775:       }
                   1776:       return (\%hash, $string);
                   1777:   }
                   1778: 
                   1779:   $string =~ s/^__HASH_REF__//;
                   1780: 
                   1781:   while($string !~ /^__END_HASH_REF__/) {
                   1782:       #key
                   1783:       my $key='';
                   1784:       if($string =~ /^__HASH_REF__/) {
                   1785:           ($key, $string)=&str2hashref($string);
                   1786:           if(defined($key->{'error'})) {
                   1787:               $hash{'error'}='Bad data';
                   1788:               return (\%hash, $string);
                   1789:           }
                   1790:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1791:           ($key, $string)=&str2arrayref($string);
                   1792:           if($key->[0] eq 'Array reference error') {
                   1793:               $hash{'error'}='Bad data';
                   1794:               return (\%hash, $string);
                   1795:           }
                   1796:       } else {
                   1797:           $string =~ s/^(.*?)=//;
1.267     albertel 1798: 	  $key=&unescape($1);
1.265     albertel 1799:       }
                   1800:       $string =~ s/^=//;
                   1801: 
                   1802:       #value
                   1803:       my $value='';
                   1804:       if($string =~ /^__HASH_REF__/) {
                   1805:           ($value, $string)=&str2hashref($string);
                   1806:           if(defined($value->{'error'})) {
                   1807:               $hash{'error'}='Bad data';
                   1808:               return (\%hash, $string);
                   1809:           }
                   1810:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1811:           ($value, $string)=&str2arrayref($string);
                   1812:           if($value->[0] eq 'Array reference error') {
                   1813:               $hash{'error'}='Bad data';
                   1814:               return (\%hash, $string);
                   1815:           }
                   1816:       } else {
                   1817: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   1818:       }
                   1819:       $string =~ s/^&//;
                   1820: 
                   1821:       $hash{$key}=$value;
1.204     albertel 1822:   }
1.265     albertel 1823: 
                   1824:   $string =~ s/^__END_HASH_REF__//;
                   1825: 
                   1826:   return (\%hash, $string);
1.204     albertel 1827: }
                   1828: 
                   1829: sub str2array {
1.265     albertel 1830:     my ($string)=@_;
                   1831:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   1832:     return @$array;
                   1833: }
                   1834: 
                   1835: sub str2arrayref {
1.204     albertel 1836:   my ($string) = @_;
1.265     albertel 1837:   my @array;
                   1838: 
                   1839:   if($string !~ /^__ARRAY_REF__/) {
                   1840:       if (! ($string eq '' || !defined($string))) {
                   1841: 	  $array[0]='Array reference error';
                   1842:       }
                   1843:       return (\@array, $string);
                   1844:   }
                   1845: 
                   1846:   $string =~ s/^__ARRAY_REF__//;
                   1847: 
                   1848:   while($string !~ /^__END_ARRAY_REF__/) {
                   1849:       my $value='';
                   1850:       if($string =~ /^__HASH_REF__/) {
                   1851:           ($value, $string)=&str2hashref($string);
                   1852:           if(defined($value->{'error'})) {
                   1853:               $array[0] ='Array reference error';
                   1854:               return (\@array, $string);
                   1855:           }
                   1856:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1857:           ($value, $string)=&str2arrayref($string);
                   1858:           if($value->[0] eq 'Array reference error') {
                   1859:               $array[0] ='Array reference error';
                   1860:               return (\@array, $string);
                   1861:           }
                   1862:       } else {
                   1863: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   1864:       }
                   1865:       $string =~ s/^&//;
                   1866: 
                   1867:       push(@array, $value);
1.191     harris41 1868:   }
1.265     albertel 1869: 
                   1870:   $string =~ s/^__END_ARRAY_REF__//;
                   1871: 
                   1872:   return (\@array, $string);
1.168     albertel 1873: }
                   1874: 
1.167     albertel 1875: # -------------------------------------------------------------------Temp Store
                   1876: 
1.168     albertel 1877: sub tmpreset {
                   1878:   my ($symb,$namespace,$domain,$stuname) = @_;
                   1879:   if (!$symb) {
                   1880:     $symb=&symbread();
1.380     albertel 1881:     if (!$symb) { $symb= $ENV{'request.url'}; }
1.168     albertel 1882:   }
                   1883:   $symb=escape($symb);
                   1884: 
                   1885:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1886:   $namespace=~s/\//\_/g;
                   1887:   $namespace=~s/\W//g;
                   1888: 
                   1889:   #FIXME needs to do something for /pub resources
                   1890:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1891:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1892:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1893:   my %hash;
                   1894:   if (tie(%hash,'GDBM_File',
                   1895: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1896: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1897:     foreach my $key (keys %hash) {
1.180     albertel 1898:       if ($key=~ /:$symb/) {
1.168     albertel 1899: 	delete($hash{$key});
                   1900:       }
                   1901:     }
                   1902:   }
                   1903: }
                   1904: 
1.167     albertel 1905: sub tmpstore {
1.168     albertel 1906:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1907: 
                   1908:   if (!$symb) {
                   1909:     $symb=&symbread();
                   1910:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1911:   }
                   1912:   $symb=escape($symb);
                   1913: 
                   1914:   if (!$namespace) {
                   1915:     # I don't think we would ever want to store this for a course.
                   1916:     # it seems this will only be used if we don't have a course.
                   1917:     #$namespace=$ENV{'request.course.id'};
                   1918:     #if (!$namespace) {
                   1919:       $namespace=$ENV{'request.state'};
                   1920:     #}
                   1921:   }
                   1922:   $namespace=~s/\//\_/g;
                   1923:   $namespace=~s/\W//g;
                   1924: #FIXME needs to do something for /pub resources
                   1925:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1926:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1927:   my $now=time;
                   1928:   my %hash;
                   1929:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1930:   if (tie(%hash,'GDBM_File',
                   1931: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1932: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1933:     $hash{"version:$symb"}++;
                   1934:     my $version=$hash{"version:$symb"};
                   1935:     my $allkeys=''; 
                   1936:     foreach my $key (keys(%$storehash)) {
                   1937:       $allkeys.=$key.':';
                   1938:       $hash{"$version:$symb:$key"}=$$storehash{$key};
                   1939:     }
                   1940:     $hash{"$version:$symb:timestamp"}=$now;
                   1941:     $allkeys.='timestamp';
                   1942:     $hash{"$version:keys:$symb"}=$allkeys;
                   1943:     if (untie(%hash)) {
                   1944:       return 'ok';
                   1945:     } else {
                   1946:       return "error:$!";
                   1947:     }
                   1948:   } else {
                   1949:     return "error:$!";
                   1950:   }
                   1951: }
1.167     albertel 1952: 
1.168     albertel 1953: # -----------------------------------------------------------------Temp Restore
1.167     albertel 1954: 
1.168     albertel 1955: sub tmprestore {
                   1956:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 1957: 
1.168     albertel 1958:   if (!$symb) {
                   1959:     $symb=&symbread();
                   1960:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1961:   }
                   1962:   $symb=escape($symb);
                   1963: 
                   1964:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1965:   #FIXME needs to do something for /pub resources
                   1966:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1967:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1968: 
                   1969:   my %returnhash;
                   1970:   $namespace=~s/\//\_/g;
                   1971:   $namespace=~s/\W//g;
                   1972:   my %hash;
                   1973:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1974:   if (tie(%hash,'GDBM_File',
                   1975: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1976: 	  &GDBM_READER(),0640)) {
1.168     albertel 1977:     my $version=$hash{"version:$symb"};
                   1978:     $returnhash{'version'}=$version;
                   1979:     my $scope;
                   1980:     for ($scope=1;$scope<=$version;$scope++) {
                   1981:       my $vkeys=$hash{"$scope:keys:$symb"};
                   1982:       my @keys=split(/:/,$vkeys);
                   1983:       my $key;
                   1984:       $returnhash{"$scope:keys"}=$vkeys;
                   1985:       foreach $key (@keys) {
                   1986: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
                   1987: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167     albertel 1988:       }
                   1989:     }
1.168     albertel 1990:     if (!(untie(%hash))) {
                   1991:       return "error:$!";
                   1992:     }
                   1993:   } else {
                   1994:     return "error:$!";
                   1995:   }
                   1996:   return %returnhash;
1.167     albertel 1997: }
                   1998: 
1.9       www      1999: # ----------------------------------------------------------------------- Store
                   2000: 
                   2001: sub store {
1.124     www      2002:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2003:     my $home='';
                   2004: 
1.168     albertel 2005:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2006: 
1.213     www      2007:     $symb=&symbclean($symb);
1.122     albertel 2008:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2009: 
1.325     www      2010:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   2011:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   2012: 
                   2013:     &devalidate($symb,$stuname,$domain);
1.109     www      2014: 
                   2015:     $symb=escape($symb);
1.187     www      2016:     if (!$namespace) { 
                   2017:        unless ($namespace=$ENV{'request.course.id'}) { 
                   2018:           return ''; 
                   2019:        } 
                   2020:     }
1.122     albertel 2021:     if (!$home) { $home=$ENV{'user.home'}; }
1.447     www      2022: 
                   2023:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2024:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2025: 
1.12      www      2026:     my $namevalue='';
1.191     harris41 2027:     foreach (keys %$storehash) {
1.122     albertel 2028:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 2029:     }
1.12      www      2030:     $namevalue=~s/\&$//;
1.187     www      2031:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2032:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2033: }
                   2034: 
1.47      www      2035: # -------------------------------------------------------------- Critical Store
                   2036: 
                   2037: sub cstore {
1.124     www      2038:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2039:     my $home='';
                   2040: 
1.168     albertel 2041:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2042: 
1.213     www      2043:     $symb=&symbclean($symb);
1.122     albertel 2044:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2045: 
1.325     www      2046:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   2047:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   2048: 
                   2049:     &devalidate($symb,$stuname,$domain);
1.109     www      2050: 
                   2051:     $symb=escape($symb);
1.187     www      2052:     if (!$namespace) { 
                   2053:        unless ($namespace=$ENV{'request.course.id'}) { 
                   2054:           return ''; 
                   2055:        } 
                   2056:     }
1.122     albertel 2057:     if (!$home) { $home=$ENV{'user.home'}; }
1.447     www      2058: 
                   2059:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2060:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2061: 
1.47      www      2062:     my $namevalue='';
1.191     harris41 2063:     foreach (keys %$storehash) {
1.122     albertel 2064:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 2065:     }
1.47      www      2066:     $namevalue=~s/\&$//;
1.187     www      2067:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2068:     return critical
                   2069:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2070: }
                   2071: 
1.9       www      2072: # --------------------------------------------------------------------- Restore
                   2073: 
                   2074: sub restore {
1.124     www      2075:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2076:     my $home='';
                   2077: 
1.168     albertel 2078:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2079: 
1.122     albertel 2080:     if (!$symb) {
                   2081:       unless ($symb=escape(&symbread())) { return ''; }
                   2082:     } else {
1.213     www      2083:       $symb=&escape(&symbclean($symb));
1.122     albertel 2084:     }
1.188     www      2085:     if (!$namespace) { 
                   2086:        unless ($namespace=$ENV{'request.course.id'}) { 
                   2087:           return ''; 
                   2088:        } 
                   2089:     }
1.122     albertel 2090:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   2091:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   2092:     if (!$home) { $home=$ENV{'user.home'}; }
                   2093:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2094: 
1.12      www      2095:     my %returnhash=();
1.191     harris41 2096:     foreach (split(/\&/,$answer)) {
1.12      www      2097: 	my ($name,$value)=split(/\=/,$_);
                   2098:         $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41 2099:     }
1.75      www      2100:     my $version;
                   2101:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2102:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2103:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2104:        }
1.75      www      2105:     }
1.13      www      2106:     return %returnhash;
1.34      www      2107: }
                   2108: 
                   2109: # ---------------------------------------------------------- Course Description
                   2110: 
                   2111: sub coursedescription {
                   2112:     my $courseid=shift;
                   2113:     $courseid=~s/^\///;
1.49      www      2114:     $courseid=~s/\_/\//g;
1.34      www      2115:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2116:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2117:     my $normalid=$cdomain.'_'.$cnum;
                   2118:     # need to always cache even if we get errors otherwise we keep 
                   2119:     # trying and trying and trying to get the course description.
                   2120:     my %envhash=();
                   2121:     my %returnhash=();
                   2122:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      2123:     if ($chome ne 'no_host') {
1.302     albertel 2124:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2125:        if (!exists($returnhash{'con_lost'})) {
                   2126:            $returnhash{'home'}= $chome;
                   2127: 	   $returnhash{'domain'} = $cdomain;
                   2128: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2129:            while (my ($name,$value) = each %returnhash) {
1.53      www      2130:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2131:            }
1.270     www      2132:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2133:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38      www      2134: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2135:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2136:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2137:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2138:        }
                   2139:     }
1.302     albertel 2140:     &appenv(%envhash);
                   2141:     return %returnhash;
1.9       www      2142: }
1.1       albertel 2143: 
1.103     harris41 2144: # -------------------------------------------------------- Get user privileges
1.11      www      2145: 
                   2146: sub rolesinit {
                   2147:     my ($domain,$username,$authhost)=@_;
                   2148:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2149:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2150:     my %allroles=();
                   2151:     my %thesepriv=();
                   2152:     my $now=time;
1.21      www      2153:     my $userroles="user.login.time=$now\n";
1.11      www      2154:     my $thesestr;
                   2155: 
                   2156:     if ($rolesdump ne '') {
1.191     harris41 2157:         foreach (split(/&/,$rolesdump)) {
1.21      www      2158: 	  if ($_!~/^rolesdef\&/) {
1.11      www      2159:             my ($area,$role)=split(/=/,$_);
1.21      www      2160:             $area=~s/\_\w\w$//;
1.11      www      2161:             my ($trole,$tend,$tstart)=split(/_/,$role);
1.21      www      2162:             $userroles.='user.role.'.$trole.'.'.$area.'='.
                   2163:                         $tstart.'.'.$tend."\n";
1.349     www      2164: # log the associated role with the area
                   2165:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.11      www      2166:             if ($tend!=0) {
                   2167: 	        if ($tend<$now) {
                   2168: 	            $trole='';
                   2169:                 } 
                   2170:             }
                   2171:             if ($tstart!=0) {
                   2172:                 if ($tstart>$now) {
                   2173:                    $trole='';        
                   2174:                 }
                   2175:             }
                   2176:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2177: 		my $spec=$trole.'.'.$area;
                   2178: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2179: 		if ($trole =~ /^cr\//) {
                   2180: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.392     www      2181:  		    my $homsvr=homeserver($rauthor,$rdomain);
1.347     albertel 2182: 		    if ($hostname{$homsvr} ne '') {
1.392     www      2183: 			my ($rdummy,$roledef)=
                   2184: 			   &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2185: 				
                   2186: 			if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.347     albertel 2187: 			    my ($syspriv,$dompriv,$coursepriv)=
1.392     www      2188: 				split(/\_/,$roledef);
1.347     albertel 2189: 			    if (defined($syspriv)) {
                   2190: 				$allroles{'cm./'}.=':'.$syspriv;
                   2191: 				$allroles{$spec.'./'}.=':'.$syspriv;
                   2192: 			    }
                   2193: 			    if ($tdomain ne '') {
                   2194: 				if (defined($dompriv)) {
                   2195: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2196: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2197: 				}
                   2198: 				if ($trest ne '') {
                   2199: 				    if (defined($coursepriv)) {
                   2200: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2201: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2202: 				    }
                   2203: 				}
                   2204: 			    }
                   2205: 			}
                   2206: 		    }
                   2207: 		} else {
                   2208: 		    if (defined($pr{$trole.':s'})) {
                   2209: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2210: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2211: 		    }
                   2212: 		    if ($tdomain ne '') {
                   2213: 			if (defined($pr{$trole.':d'})) {
                   2214: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2215: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2216: 			}
                   2217: 			if ($trest ne '') {
                   2218: 			    if (defined($pr{$trole.':c'})) {
                   2219: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2220: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2221: 			    }
                   2222: 			}
                   2223: 		    }
                   2224: 		}
1.12      www      2225:             }
                   2226:           } 
1.191     harris41 2227:         }
1.125     www      2228:         my $adv=0;
1.128     www      2229:         my $author=0;
1.191     harris41 2230:         foreach (keys %allroles) {
1.11      www      2231:             %thesepriv=();
1.146     www      2232:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128     www      2233:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191     harris41 2234:             foreach (split(/:/,$allroles{$_})) {
1.11      www      2235:                 if ($_ ne '') {
1.103     harris41 2236: 		    my ($privilege,$restrictions)=split(/&/,$_);
1.11      www      2237:                     if ($restrictions eq '') {
1.103     harris41 2238: 			$thesepriv{$privilege}='F';
1.11      www      2239:                     } else {
1.103     harris41 2240:                         if ($thesepriv{$privilege} ne 'F') {
                   2241: 			    $thesepriv{$privilege}.=$restrictions;
1.11      www      2242:                         }
                   2243:                     }
                   2244:                 }
1.191     harris41 2245:             }
1.11      www      2246:             $thesestr='';
1.191     harris41 2247:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11      www      2248:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191     harris41 2249:         }
1.128     www      2250:         $userroles.='user.adv='.$adv."\n".
                   2251: 	            'user.author='.$author."\n";
1.126     www      2252:         $ENV{'user.adv'}=$adv;
1.11      www      2253:     }
                   2254:     return $userroles;  
                   2255: }
                   2256: 
1.12      www      2257: # --------------------------------------------------------------- get interface
                   2258: 
                   2259: sub get {
1.131     albertel 2260:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2261:    my $items='';
1.191     harris41 2262:    foreach (@$storearr) {
1.12      www      2263:        $items.=escape($_).'&';
1.191     harris41 2264:    }
1.12      www      2265:    $items=~s/\&$//;
1.131     albertel 2266:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2267:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2268:    my $uhome=&homeserver($uname,$udomain);
                   2269: 
1.133     albertel 2270:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2271:    my @pairs=split(/\&/,$rep);
1.273     albertel 2272:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2273:      return @pairs;
                   2274:    }
1.15      www      2275:    my %returnhash=();
1.42      www      2276:    my $i=0;
1.191     harris41 2277:    foreach (@$storearr) {
1.42      www      2278:       $returnhash{$_}=unescape($pairs[$i]);
                   2279:       $i++;
1.191     harris41 2280:    }
1.15      www      2281:    return %returnhash;
1.27      www      2282: }
                   2283: 
                   2284: # --------------------------------------------------------------- del interface
                   2285: 
                   2286: sub del {
1.133     albertel 2287:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2288:    my $items='';
1.191     harris41 2289:    foreach (@$storearr) {
1.27      www      2290:        $items.=escape($_).'&';
1.191     harris41 2291:    }
1.27      www      2292:    $items=~s/\&$//;
1.133     albertel 2293:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2294:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2295:    my $uhome=&homeserver($uname,$udomain);
                   2296: 
                   2297:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2298: }
                   2299: 
                   2300: # -------------------------------------------------------------- dump interface
                   2301: 
                   2302: sub dump {
1.193     www      2303:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.129     albertel 2304:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2305:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2306:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2307:    if ($regexp) {
                   2308:        $regexp=&escape($regexp);
                   2309:    } else {
                   2310:        $regexp='.';
                   2311:    }
                   2312:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2313:    my @pairs=split(/\&/,$rep);
                   2314:    my %returnhash=();
1.191     harris41 2315:    foreach (@pairs) {
1.12      www      2316:       my ($key,$value)=split(/=/,$_);
1.29      www      2317:       $returnhash{unescape($key)}=unescape($value);
1.318     matthew  2318:    }
                   2319:    return %returnhash;
1.407     www      2320: }
                   2321: 
                   2322: # -------------------------------------------------------------- keys interface
                   2323: 
                   2324: sub getkeys {
                   2325:    my ($namespace,$udomain,$uname)=@_;
                   2326:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2327:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2328:    my $uhome=&homeserver($uname,$udomain);
                   2329:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2330:    my @keyarray=();
                   2331:    foreach (split(/\&/,$rep)) {
                   2332:       push (@keyarray,&unescape($_));
                   2333:    }
                   2334:    return @keyarray;
1.318     matthew  2335: }
                   2336: 
1.319     matthew  2337: # --------------------------------------------------------------- currentdump
                   2338: sub currentdump {
1.328     matthew  2339:    my ($courseid,$sdom,$sname)=@_;
1.326     matthew  2340:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2341:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
                   2342:    $sname    = $ENV{'user.name'}         if (! defined($sname));
                   2343:    my $uhome = &homeserver($sname,$sdom);
                   2344:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2345:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2346:    #
1.318     matthew  2347:    my %returnhash=();
1.319     matthew  2348:    #
                   2349:    if ($rep eq "unknown_cmd") { 
                   2350:        # an old lond will not know currentdump
                   2351:        # Do a dump and make it look like a currentdump
1.326     matthew  2352:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2353:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2354:        my %hash = @tmp;
                   2355:        @tmp=();
1.424     matthew  2356:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2357:    } else {
                   2358:        my @pairs=split(/\&/,$rep);
                   2359:        foreach (@pairs) {
                   2360:            my ($key,$value)=split(/=/,$_);
                   2361:            my ($symb,$param) = split(/:/,$key);
                   2362:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
                   2363:                                                           &unescape($value);
                   2364:        }
1.191     harris41 2365:    }
1.12      www      2366:    return %returnhash;
1.424     matthew  2367: }
                   2368: 
                   2369: sub convert_dump_to_currentdump{
                   2370:     my %hash = %{shift()};
                   2371:     my %returnhash;
                   2372:     # Code ripped from lond, essentially.  The only difference
                   2373:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2374:     # we might run in to problems with parameter names =~ /^v\./
                   2375:     while (my ($key,$value) = each(%hash)) {
                   2376:         my ($v,$symb,$param) = split(/:/,$key);
                   2377:         next if ($v eq 'version' || $symb eq 'keys');
                   2378:         next if (exists($returnhash{$symb}) &&
                   2379:                  exists($returnhash{$symb}->{$param}) &&
                   2380:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2381:         $returnhash{$symb}->{$param}=$value;
                   2382:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2383:     }
                   2384:     #
                   2385:     # Remove all of the keys in the hashes which keep track of
                   2386:     # the version of the parameter.
                   2387:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2388:         # use a foreach because we are going to delete from the hash.
                   2389:         foreach my $key (keys(%$param_hash)) {
                   2390:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2391:         }
                   2392:     }
                   2393:     return \%returnhash;
1.12      www      2394: }
                   2395: 
1.449     matthew  2396: # --------------------------------------------------------------- inc interface
                   2397: 
                   2398: sub inc {
                   2399:     my ($namespace,$store,$udomain,$uname) = @_;
                   2400:     if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2401:     if (!$uname) { $uname=$ENV{'user.name'}; }
                   2402:     my $uhome=&homeserver($uname,$udomain);
                   2403:     my $items='';
                   2404:     if (! ref($store)) {
                   2405:         # got a single value, so use that instead
                   2406:         $items = &escape($store).'=&';
                   2407:     } elsif (ref($store) eq 'SCALAR') {
                   2408:         $items = &escape($$store).'=&';        
                   2409:     } elsif (ref($store) eq 'ARRAY') {
                   2410:         $items = join('=&',map {&escape($_);} @{$store});
                   2411:     } elsif (ref($store) eq 'HASH') {
                   2412:         while (my($key,$value) = each(%{$store})) {
                   2413:             $items.= &escape($key).'='.&escape($value).'&';
                   2414:         }
                   2415:     }
                   2416:     $items=~s/\&$//;
                   2417:     return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2418: }
                   2419: 
1.12      www      2420: # --------------------------------------------------------------- put interface
                   2421: 
                   2422: sub put {
1.134     albertel 2423:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2424:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2425:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2426:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2427:    my $items='';
1.191     harris41 2428:    foreach (keys %$storehash) {
1.134     albertel 2429:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191     harris41 2430:    }
1.12      www      2431:    $items=~s/\&$//;
1.134     albertel 2432:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2433: }
                   2434: 
                   2435: # ------------------------------------------------------ critical put interface
                   2436: 
                   2437: sub cput {
1.134     albertel 2438:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2439:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2440:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2441:    my $uhome=&homeserver($uname,$udomain);
1.47      www      2442:    my $items='';
1.191     harris41 2443:    foreach (keys %$storehash) {
1.134     albertel 2444:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 2445:    }
1.47      www      2446:    $items=~s/\&$//;
1.134     albertel 2447:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2448: }
                   2449: 
                   2450: # -------------------------------------------------------------- eget interface
                   2451: 
                   2452: sub eget {
1.133     albertel 2453:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2454:    my $items='';
1.191     harris41 2455:    foreach (@$storearr) {
1.12      www      2456:        $items.=escape($_).'&';
1.191     harris41 2457:    }
1.12      www      2458:    $items=~s/\&$//;
1.133     albertel 2459:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2460:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2461:    my $uhome=&homeserver($uname,$udomain);
                   2462:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2463:    my @pairs=split(/\&/,$rep);
                   2464:    my %returnhash=();
1.42      www      2465:    my $i=0;
1.191     harris41 2466:    foreach (@$storearr) {
1.42      www      2467:       $returnhash{$_}=unescape($pairs[$i]);
                   2468:       $i++;
1.191     harris41 2469:    }
1.12      www      2470:    return %returnhash;
                   2471: }
                   2472: 
1.341     www      2473: # ---------------------------------------------- Custom access rule evaluation
                   2474: 
                   2475: sub customaccess {
                   2476:     my ($priv,$uri)=@_;
1.342     www      2477:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
1.343     www      2478:     $urealm=~s/^\W//;
                   2479:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      2480:     my $access=0;
                   2481:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      2482: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      2483:         if ($role) {
                   2484: 	   if ($role ne $urole) { next; }
                   2485:         }
                   2486:         foreach (split(/\s*\,\s*/,$realm)) {
                   2487:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   2488:             if ($tdom) {
                   2489: 		if ($tdom ne $udom) { next; }
                   2490:             }
                   2491:             if ($tcrs) {
                   2492: 		if ($tcrs ne $ucrs) { next; }
                   2493:             }
                   2494:             if ($tsec) {
                   2495: 		if ($tsec ne $usec) { next; }
                   2496:             }
                   2497:             $access=($effect eq 'allow');
                   2498:             last;
1.342     www      2499:         }
1.402     bowersj2 2500: 	if ($realm eq '' && $role eq '') {
                   2501:             $access=($effect eq 'allow');
                   2502: 	}
1.341     www      2503:     }
                   2504:     return $access;
                   2505: }
                   2506: 
1.103     harris41 2507: # ------------------------------------------------- Check for a user privilege
1.12      www      2508: 
                   2509: sub allowed {
                   2510:     my ($priv,$uri)=@_;
1.439     www      2511:     $uri=&deversion($uri);
1.152     www      2512:     my $orguri=$uri;
1.52      www      2513:     $uri=&declutter($uri);
1.29      www      2514: 
1.398     albertel 2515:     if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
1.54      www      2516: # Free bre access to adm and meta resources
1.29      www      2517: 
1.54      www      2518:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      2519: 	return 'F';
1.159     www      2520:     }
                   2521: 
                   2522: # Free bre to public access
                   2523: 
                   2524:     if ($priv eq 'bre') {
1.238     www      2525:         my $copyright=&metadata($uri,'copyright');
1.301     www      2526: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
                   2527:            return 'F'; 
                   2528:         }
1.238     www      2529:         if ($copyright eq 'priv') {
                   2530:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2531: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
                   2532: 		return '';
                   2533:             }
                   2534:         }
                   2535:         if ($copyright eq 'domain') {
                   2536:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2537: 	    unless (($ENV{'user.domain'} eq $1) ||
                   2538:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
                   2539: 		return '';
                   2540:             }
1.262     matthew  2541:         }
                   2542:         if ($ENV{'request.role'}=~ /li\.\//) {
                   2543:             # Library role, so allow browsing of resources in this domain.
                   2544:             return 'F';
1.238     www      2545:         }
1.341     www      2546:         if ($copyright eq 'custom') {
                   2547: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   2548:         }
1.14      www      2549:     }
1.264     matthew  2550:     # Domain coordinator is trying to create a course
                   2551:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
                   2552:         # uri is the requested domain in this case.
                   2553:         # comparison to 'request.role.domain' shows if the user has selected
                   2554:         # a role of dc for the domain in question. 
                   2555:         return 'F' if ($uri eq $ENV{'request.role.domain'});
                   2556:     }
1.29      www      2557: 
1.52      www      2558:     my $thisallowed='';
                   2559:     my $statecond=0;
                   2560:     my $courseprivid='';
                   2561: 
                   2562: # Course
                   2563: 
                   2564:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   2565:        $thisallowed.=$1;
                   2566:     }
1.29      www      2567: 
1.52      www      2568: # Domain
                   2569: 
                   2570:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   2571:        =~/$priv\&([^\:]*)/) {
1.12      www      2572:        $thisallowed.=$1;
                   2573:     }
1.52      www      2574: 
                   2575: # Course: uri itself is a course
1.66      www      2576:     my $courseuri=$uri;
                   2577:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      2578:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      2579: 
1.83      www      2580:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      2581:        =~/$priv\&([^\:]*)/) {
1.12      www      2582:        $thisallowed.=$1;
                   2583:     }
1.29      www      2584: 
1.314     www      2585: # URI is an uploaded document for this course
                   2586: 
                   2587:     if (($priv eq 'bre') && 
                   2588:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
                   2589:         return 'F';
                   2590:     }
1.52      www      2591: # Full access at system, domain or course-wide level? Exit.
1.29      www      2592: 
                   2593:     if ($thisallowed=~/F/) {
                   2594: 	return 'F';
                   2595:     }
                   2596: 
1.52      www      2597: # If this is generating or modifying users, exit with special codes
1.29      www      2598: 
1.166     www      2599:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      2600: 	return $thisallowed;
                   2601:     }
                   2602: #
1.103     harris41 2603: # Gathered so far: system, domain and course wide privileges
1.52      www      2604: #
                   2605: # Course: See if uri or referer is an individual resource that is part of 
                   2606: # the course
                   2607: 
                   2608:     if ($ENV{'request.course.id'}) {
1.232     www      2609: 
1.52      www      2610:        $courseprivid=$ENV{'request.course.id'};
                   2611:        if ($ENV{'request.course.sec'}) {
                   2612:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   2613:        }
                   2614:        $courseprivid=~s/\_/\//;
                   2615:        my $checkreferer=1;
1.232     www      2616:        my ($match,$cond)=&is_on_map($uri);
                   2617:        if ($match) {
                   2618:            $statecond=$cond;
1.52      www      2619:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2620:                =~/$priv\&([^\:]*)/) {
                   2621:                $thisallowed.=$1;
                   2622:                $checkreferer=0;
                   2623:            }
1.29      www      2624:        }
1.83      www      2625:        
1.148     www      2626:        if ($checkreferer) {
1.152     www      2627: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      2628:             unless ($refuri) {
1.191     harris41 2629:                 foreach (keys %ENV) {
1.148     www      2630: 		    if ($_=~/^httpref\..*\*/) {
                   2631: 			my $pattern=$_;
1.156     www      2632:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      2633:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   2634:                         $pattern=~s/\//\\\//g;
1.152     www      2635:                         if ($orguri=~/$pattern/) {
1.148     www      2636: 			    $refuri=$ENV{$_};
                   2637:                         }
                   2638:                     }
1.191     harris41 2639:                 }
1.148     www      2640:             }
1.232     www      2641: 
1.148     www      2642:          if ($refuri) { 
1.152     www      2643: 	  $refuri=&declutter($refuri);
1.232     www      2644:           my ($match,$cond)=&is_on_map($refuri);
                   2645:             if ($match) {
                   2646:               my $refstatecond=$cond;
1.52      www      2647:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2648:                   =~/$priv\&([^\:]*)/) {
                   2649:                   $thisallowed.=$1;
1.53      www      2650:                   $uri=$refuri;
                   2651:                   $statecond=$refstatecond;
1.52      www      2652:               }
                   2653:           }
1.148     www      2654:         }
1.29      www      2655:        }
1.52      www      2656:    }
1.29      www      2657: 
1.52      www      2658: #
1.103     harris41 2659: # Gathered now: all privileges that could apply, and condition number
1.52      www      2660: # 
                   2661: #
                   2662: # Full or no access?
                   2663: #
1.29      www      2664: 
1.52      www      2665:     if ($thisallowed=~/F/) {
                   2666: 	return 'F';
                   2667:     }
1.29      www      2668: 
1.52      www      2669:     unless ($thisallowed) {
                   2670:         return '';
                   2671:     }
1.29      www      2672: 
1.52      www      2673: # Restrictions exist, deal with them
                   2674: #
                   2675: #   C:according to course preferences
                   2676: #   R:according to resource settings
                   2677: #   L:unless locked
                   2678: #   X:according to user session state
                   2679: #
                   2680: 
                   2681: # Possibly locked functionality, check all courses
1.54      www      2682: # Locks might take effect only after 10 minutes cache expiration for other
                   2683: # courses, and 2 minutes for current course
1.52      www      2684: 
                   2685:     my $envkey;
                   2686:     if ($thisallowed=~/L/) {
                   2687:         foreach $envkey (keys %ENV) {
1.54      www      2688:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   2689:                my $courseid=$2;
                   2690:                my $roleid=$1.'.'.$2;
1.92      www      2691:                $courseid=~s/^\///;
1.54      www      2692:                my $expiretime=600;
                   2693:                if ($ENV{'request.role'} eq $roleid) {
                   2694: 		  $expiretime=120;
                   2695:                }
                   2696: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   2697:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   2698:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   2699: 		   &coursedescription($courseid);
                   2700:                }
                   2701:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   2702:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   2703: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      2704:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2705:                             $ENV{'user.home'},
1.57      www      2706:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      2707:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2708:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2709: 		       return '';
                   2710:                    }
                   2711:                }
1.54      www      2712:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   2713:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   2714: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      2715:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2716:                             $ENV{'user.home'},
1.57      www      2717:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      2718:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2719:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2720: 		       return '';
                   2721:                    }
                   2722:                }
                   2723: 	   }
1.29      www      2724:        }
1.52      www      2725:     }
                   2726:    
                   2727: #
                   2728: # Rest of the restrictions depend on selected course
                   2729: #
                   2730: 
                   2731:     unless ($ENV{'request.course.id'}) {
                   2732:        return '1';
                   2733:     }
1.29      www      2734: 
1.52      www      2735: #
                   2736: # Now user is definitely in a course
                   2737: #
1.53      www      2738: 
                   2739: 
                   2740: # Course preferences
                   2741: 
                   2742:    if ($thisallowed=~/C/) {
1.54      www      2743:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237     www      2744:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54      www      2745:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      2746: 	   =~/$rolecode/) {
1.57      www      2747:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2748:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237     www      2749:                 $ENV{'request.course.id'});
                   2750:            return '';
                   2751:        }
                   2752: 
                   2753:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
                   2754: 	   =~/$unamedom/) {
                   2755:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2756:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54      www      2757:                 $ENV{'request.course.id'});
                   2758:            return '';
                   2759:        }
1.53      www      2760:    }
                   2761: 
                   2762: # Resource preferences
                   2763: 
                   2764:    if ($thisallowed=~/R/) {
1.54      www      2765:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.341     www      2766:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
                   2767: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1.57      www      2768:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      2769:           return '';
1.54      www      2770:        }
1.53      www      2771:    }
1.30      www      2772: 
1.246     www      2773: # Restricted by state or randomout?
1.30      www      2774: 
1.52      www      2775:    if ($thisallowed=~/X/) {
1.247     www      2776:       if ($ENV{'acc.randomout'}) {
1.249     www      2777:          my $symb=&symbread($uri,1);
1.248     www      2778:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
                   2779:             return ''; 
                   2780:          }
1.247     www      2781:       }
                   2782:       if (&condval($statecond)) {
1.52      www      2783: 	 return '2';
                   2784:       } else {
                   2785:          return '';
                   2786:       }
                   2787:    }
1.30      www      2788: 
1.52      www      2789:    return 'F';
1.232     www      2790: }
                   2791: 
                   2792: # --------------------------------------------------- Is a resource on the map?
                   2793: 
                   2794: sub is_on_map {
                   2795:     my $uri=&declutter(shift);
1.435     www      2796:     $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232     www      2797:     my @uriparts=split(/\//,$uri);
                   2798:     my $filename=$uriparts[$#uriparts];
                   2799:     my $pathname=$uri;
1.289     bowersj2 2800:     $pathname=~s|/\Q$filename\E$||;
1.332     www      2801:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 2802:     #Trying to find the conditional for the file
1.232     www      2803:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 2804: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      2805:     if ($match) {
1.289     bowersj2 2806: 	return (1,$1);
                   2807:     } else {
1.434     www      2808: 	return (0,0);
1.289     bowersj2 2809:     }
1.12      www      2810: }
                   2811: 
1.427     www      2812: # --------------------------------------------------------- Get symb from alias
                   2813: 
                   2814: sub get_symb_from_alias {
                   2815:     my $symb=shift;
                   2816:     my ($map,$resid,$url)=&decode_symb($symb);
                   2817: # Already is a symb
                   2818:     if ($url) { return $symb; }
                   2819: # Must be an alias
                   2820:     my $aliassymb='';
                   2821:     my %bighash;
                   2822:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   2823:                             &GDBM_READER(),0640)) {
                   2824:         my $rid=$bighash{'mapalias_'.$symb};
                   2825: 	if ($rid) {
                   2826: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 2827: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   2828: 				    $resid,$bighash{'src_'.$rid});
1.427     www      2829: 	}
                   2830:         untie %bighash;
                   2831:     }
                   2832:     return $aliassymb;
                   2833: }
                   2834: 
1.12      www      2835: # ----------------------------------------------------------------- Define Role
                   2836: 
                   2837: sub definerole {
                   2838:   if (allowed('mcr','/')) {
                   2839:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      2840:     foreach (split(':',$sysrole)) {
1.21      www      2841: 	my ($crole,$cqual)=split(/\&/,$_);
                   2842:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   2843:         if ($pr{'cr:s'}=~/$crole\&/) {
                   2844: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   2845:                return "refused:s:$crole&$cqual"; 
                   2846:             }
                   2847:         }
1.191     harris41 2848:     }
1.392     www      2849:     foreach (split(':',$domrole)) {
1.21      www      2850: 	my ($crole,$cqual)=split(/\&/,$_);
                   2851:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   2852:         if ($pr{'cr:d'}=~/$crole\&/) {
                   2853: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   2854:                return "refused:d:$crole&$cqual"; 
                   2855:             }
                   2856:         }
1.191     harris41 2857:     }
1.392     www      2858:     foreach (split(':',$courole)) {
1.21      www      2859: 	my ($crole,$cqual)=split(/\&/,$_);
                   2860:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   2861:         if ($pr{'cr:c'}=~/$crole\&/) {
                   2862: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   2863:                return "refused:c:$crole&$cqual"; 
                   2864:             }
                   2865:         }
1.191     harris41 2866:     }
1.12      www      2867:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2868:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      2869: 	        "rolesdef_$rolename=".
                   2870:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      2871:     return reply($command,$ENV{'user.home'});
                   2872:   } else {
                   2873:     return 'refused';
                   2874:   }
1.105     harris41 2875: }
                   2876: 
                   2877: # ---------------- Make a metadata query against the network of library servers
                   2878: 
                   2879: sub metadata_query {
1.244     matthew  2880:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 2881:     my %rhash;
1.244     matthew  2882:     my @server_list = (defined($server_array) ? @$server_array
                   2883:                                               : keys(%libserv) );
                   2884:     for my $server (@server_list) {
1.118     harris41 2885: 	unless ($custom or $customshow) {
                   2886: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   2887: 	    $rhash{$server}=$reply;
                   2888: 	}
                   2889: 	else {
                   2890: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   2891: 			     &escape($custom).':'.&escape($customshow),
                   2892: 			     $server);
                   2893: 	    $rhash{$server}=$reply;
                   2894: 	}
1.112     harris41 2895:     }
1.118     harris41 2896:     return \%rhash;
1.240     www      2897: }
                   2898: 
                   2899: # ----------------------------------------- Send log queries and wait for reply
                   2900: 
                   2901: sub log_query {
                   2902:     my ($uname,$udom,$query,%filters)=@_;
                   2903:     my $uhome=&homeserver($uname,$udom);
                   2904:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   2905:     my $uhost=$hostname{$uhome};
1.241     www      2906:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      2907:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   2908:                        $uhome);
                   2909:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
1.242     www      2910:     return get_query_reply($queryid);
                   2911: }
                   2912: 
                   2913: sub get_query_reply {
                   2914:     my $queryid=shift;
1.240     www      2915:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   2916:     my $reply='';
                   2917:     for (1..100) {
                   2918: 	sleep 2;
                   2919:         if (-e $replyfile.'.end') {
1.448     albertel 2920: 	    if (open(my $fh,$replyfile)) {
1.240     www      2921:                $reply.=<$fh>;
1.448     albertel 2922:                close($fh);
1.240     www      2923: 	   } else { return 'error: reply_file_error'; }
1.242     www      2924:            return &unescape($reply);
                   2925: 	}
1.240     www      2926:     }
1.242     www      2927:     return 'timeout:'.$queryid;
1.240     www      2928: }
                   2929: 
                   2930: sub courselog_query {
1.241     www      2931: #
                   2932: # possible filters:
                   2933: # url: url or symb
                   2934: # username
                   2935: # domain
                   2936: # action: view, submit, grade
                   2937: # start: timestamp
                   2938: # end: timestamp
                   2939: #
1.240     www      2940:     my (%filters)=@_;
                   2941:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241     www      2942:     if ($filters{'url'}) {
                   2943: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   2944:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   2945:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   2946:     }
1.240     www      2947:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   2948:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   2949:     return &log_query($cname,$cdom,'courselog',%filters);
                   2950: }
                   2951: 
                   2952: sub userlog_query {
                   2953:     my ($uname,$udom,%filters)=@_;
                   2954:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      2955: }
                   2956: 
                   2957: # ------------------------------------------------------------------ Plain Text
                   2958: 
                   2959: sub plaintext {
1.22      www      2960:     my $short=shift;
1.414     www      2961:     return &mt($prp{$short});
1.12      www      2962: }
                   2963: 
                   2964: # ----------------------------------------------------------------- Assign Role
                   2965: 
                   2966: sub assignrole {
1.357     www      2967:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      2968:     my $mrole;
                   2969:     if ($role =~ /^cr\//) {
1.393     www      2970:         my $cwosec=$url;
                   2971:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   2972: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      2973:            &logthis('Refused custom assignrole: '.
                   2974:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2975: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2976:            return 'refused'; 
                   2977:         }
1.21      www      2978:         $mrole='cr';
                   2979:     } else {
1.82      www      2980:         my $cwosec=$url;
1.83      www      2981:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      2982:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      2983:            &logthis('Refused assignrole: '.
                   2984:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2985: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2986:            return 'refused'; 
                   2987:         }
1.21      www      2988:         $mrole=$role;
                   2989:     }
                   2990:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2991:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      2992:     if ($end) { $command.='_'.$end; }
1.21      www      2993:     if ($start) {
                   2994: 	if ($end) { 
1.81      www      2995:            $command.='_'.$start; 
1.21      www      2996:         } else {
1.81      www      2997:            $command.='_0_'.$start;
1.21      www      2998:         }
                   2999:     }
1.357     www      3000: # actually delete
                   3001:     if ($deleteflag) {
1.373     www      3002: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      3003: # modify command to delete the role
                   3004:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   3005:                 "$udom:$uname:$url".'_'."$mrole";
1.373     www      3006: 	   &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      3007: # set start and finish to negative values for userrolelog
                   3008:            $start=-1;
                   3009:            $end=-1;
                   3010:         }
                   3011:     }
                   3012: # send command
1.349     www      3013:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      3014: # log new user role if status is ok
1.349     www      3015:     if ($answer eq 'ok') {
                   3016: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
                   3017:     }
                   3018:     return $answer;
1.169     harris41 3019: }
                   3020: 
                   3021: # -------------------------------------------------- Modify user authentication
1.197     www      3022: # Overrides without validation
                   3023: 
1.169     harris41 3024: sub modifyuserauth {
                   3025:     my ($udom,$uname,$umode,$upass)=@_;
                   3026:     my $uhome=&homeserver($uname,$udom);
1.197     www      3027:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   3028:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272     matthew  3029:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   3030:              ' in domain '.$ENV{'request.role.domain'});  
1.169     harris41 3031:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   3032: 		     &escape($upass),$uhome);
1.197     www      3033:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   3034:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   3035:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   3036:     &log($udom,,$uname,$uhome,
                   3037:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   3038:                                      $ENV{'user.name'}.', '.$umode.
                   3039:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 3040:     unless ($reply eq 'ok') {
1.197     www      3041:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 3042: 	return 'error: '.$reply;
                   3043:     }   
1.170     harris41 3044:     return 'ok';
1.80      www      3045: }
                   3046: 
1.81      www      3047: # --------------------------------------------------------------- Modify a user
1.80      www      3048: 
1.81      www      3049: sub modifyuser {
1.206     matthew  3050:     my ($udom,    $uname, $uid,
                   3051:         $umode,   $upass, $first,
                   3052:         $middle,  $last,  $gene,
1.387     www      3053:         $forceid, $desiredhome, $email)=@_;
1.198     www      3054:     $udom=~s/\W//g;
                   3055:     $uname=~s/\W//g;
1.81      www      3056:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3057:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  3058: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   3059:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   3060:                                      ' desiredhome not specified'). 
1.272     matthew  3061:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   3062:              ' in domain '.$ENV{'request.role.domain'});
1.230     stredwic 3063:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      3064: # ----------------------------------------------------------------- Create User
1.406     albertel 3065:     if (($uhome eq 'no_host') && 
                   3066: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      3067:         my $unhome='';
1.209     matthew  3068:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   3069:             $unhome = $desiredhome;
                   3070: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80      www      3071: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209     matthew  3072:         } else { # load balancing routine for determining $unhome
1.80      www      3073:             my $tryserver;
1.81      www      3074:             my $loadm=10000000;
1.80      www      3075:             foreach $tryserver (keys %libserv) {
                   3076: 	       if ($hostdom{$tryserver} eq $udom) {
                   3077:                   my $answer=reply('load',$tryserver);
                   3078:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   3079: 		      $loadm=$answer;
                   3080:                       $unhome=$tryserver;
                   3081:                   }
                   3082: 	       }
                   3083: 	    }
                   3084:         }
                   3085:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  3086: 	    return 'error: unable to find a home server for '.$uname.
                   3087:                    ' in domain '.$udom;
1.80      www      3088:         }
                   3089:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   3090:                          &escape($upass),$unhome);
                   3091: 	unless ($reply eq 'ok') {
                   3092:             return 'error: '.$reply;
                   3093:         }   
1.230     stredwic 3094:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      3095:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  3096: 	    return 'error: unable verify users home machine.';
1.80      www      3097:         }
1.209     matthew  3098:     }   # End of creation of new user
1.80      www      3099: # ---------------------------------------------------------------------- Add ID
                   3100:     if ($uid) {
                   3101:        $uid=~tr/A-Z/a-z/;
                   3102:        my %uidhash=&idrget($udom,$uname);
1.196     www      3103:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   3104:          && (!$forceid)) {
1.80      www      3105: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  3106: 	      return 'error: user id "'.$uid.'" does not match '.
                   3107:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      3108:           }
                   3109:        } else {
                   3110: 	  &idput($udom,($uname => $uid));
                   3111:        }
                   3112:     }
                   3113: # -------------------------------------------------------------- Add names, etc
1.313     matthew  3114:     my @tmp=&get('environment',
1.134     albertel 3115: 		   ['firstname','middlename','lastname','generation'],
                   3116: 		   $udom,$uname);
1.313     matthew  3117:     my %names;
                   3118:     if ($tmp[0] =~ m/^error:.*/) { 
                   3119:         %names=(); 
                   3120:     } else {
                   3121:         %names = @tmp;
                   3122:     }
1.388     www      3123: #
                   3124: # Make sure to not trash student environment if instructor does not bother
                   3125: # to supply name and email information
                   3126: #
                   3127:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  3128:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      3129:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  3130:     if (defined($gene))   { $names{'generation'} = $gene; }
1.388     www      3131:     if ($email)  { $names{'notification'} = $email;
                   3132:                    $names{'critnotification'} = $email; }
1.387     www      3133: 
1.134     albertel 3134:     my $reply = &put('environment', \%names, $udom,$uname);
                   3135:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      3136:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3137:              $umode.', '.$first.', '.$middle.', '.
                   3138: 	     $last.', '.$gene.' by '.
                   3139:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 3140:     return 'ok';
1.80      www      3141: }
                   3142: 
1.81      www      3143: # -------------------------------------------------------------- Modify student
1.80      www      3144: 
1.81      www      3145: sub modifystudent {
                   3146:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.387     www      3147:         $end,$start,$forceid,$desiredhome,$email)=@_;
1.81      www      3148:     my $cid='';
                   3149:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      3150: 	return 'not_in_class';
                   3151:     }
                   3152: # --------------------------------------------------------------- Make the user
1.81      www      3153:     my $reply=&modifyuser
1.209     matthew  3154: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      3155:          $desiredhome,$email);
1.80      www      3156:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  3157:     # This will cause &modify_student_enrollment to get the uid from the
                   3158:     # students environment
                   3159:     $uid = undef if (!$forceid);
                   3160:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
                   3161:                                         $last,$gene,$usec,$end,$start);
                   3162:     return $reply;
                   3163: }
                   3164: 
                   3165: sub modify_student_enrollment {
                   3166:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
                   3167:     # Get the course id from the environment
                   3168:     my $cid='';
                   3169:     unless ($cid=$ENV{'request.course.id'}) {
                   3170: 	return 'not_in_class';
                   3171:     }
                   3172:     # Make sure the user exists
1.81      www      3173:     my $uhome=&homeserver($uname,$udom);
                   3174:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3175: 	return 'error: no such user';
                   3176:     }
1.297     matthew  3177:     #
                   3178:     # Get student data if we were not given enough information
                   3179:     if (!defined($first)  || $first  eq '' || 
                   3180:         !defined($last)   || $last   eq '' || 
                   3181:         !defined($uid)    || $uid    eq '' || 
                   3182:         !defined($middle) || $middle eq '' || 
                   3183:         !defined($gene)   || $gene   eq '') {
1.294     matthew  3184:         # They did not supply us with enough data to enroll the student, so
                   3185:         # we need to pick up more information.
1.297     matthew  3186:         my %tmp = &get('environment',
1.294     matthew  3187:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  3188:                        ,$udom,$uname);
                   3189: 
                   3190:         foreach (keys(%tmp)) {
                   3191:             &logthis("key $_ = ".$tmp{$_});
                   3192:         }
1.294     matthew  3193:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   3194:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   3195:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  3196:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  3197:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   3198:     }
                   3199:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
                   3200:                                                            $first,$middle);
1.297     matthew  3201:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      3202: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   3203:                       &escape($uname.':'.$udom).'='.
1.294     matthew  3204:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
1.81      www      3205: 	              $ENV{'course.'.$cid.'.home'});
                   3206:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   3207: 	return 'error: '.$reply;
                   3208:     }
1.297     matthew  3209:     # Add student role to user
1.83      www      3210:     my $uurl='/'.$cid;
1.81      www      3211:     $uurl=~s/\_/\//g;
                   3212:     if ($usec) {
                   3213: 	$uurl.='/'.$usec;
                   3214:     }
                   3215:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      3216: }
                   3217: 
1.84      www      3218: # ------------------------------------------------- Write to course preferences
                   3219: 
                   3220: sub writecoursepref {
                   3221:     my ($courseid,%prefs)=@_;
                   3222:     $courseid=~s/^\///;
                   3223:     $courseid=~s/\_/\//g;
                   3224:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   3225:     my $chome=homeserver($cnum,$cdomain);
                   3226:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   3227: 	return 'error: no such course';
                   3228:     }
                   3229:     my $cstring='';
1.191     harris41 3230:     foreach (keys %prefs) {
1.84      www      3231: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 3232:     }
1.84      www      3233:     $cstring=~s/\&$//;
                   3234:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   3235: }
                   3236: 
                   3237: # ---------------------------------------------------------- Make/modify course
                   3238: 
                   3239: sub createcourse {
1.271     www      3240:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
1.84      www      3241:     $url=&declutter($url);
                   3242:     my $cid='';
1.264     matthew  3243:     unless (&allowed('ccc',$udom)) {
1.84      www      3244:         return 'refused';
                   3245:     }
                   3246: # ------------------------------------------------------------------- Create ID
                   3247:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3248:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   3249: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 3250:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      3251:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3252:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3253:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 3254:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      3255:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3256:            return 'error: unable to generate unique course-ID';
                   3257:        } 
                   3258:    }
1.264     matthew  3259: # ------------------------------------------------ Check supplied server name
                   3260:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
                   3261:     if (! exists($libserv{$course_server})) {
                   3262:         return 'error:bad server name '.$course_server;
                   3263:     }
1.84      www      3264: # ------------------------------------------------------------- Make the course
                   3265:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  3266:                       $course_server);
1.84      www      3267:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 3268:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      3269:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3270: 	return 'error: no such course';
                   3271:     }
1.271     www      3272: # ----------------------------------------------------------------- Course made
1.358     www      3273: # log existance
                   3274:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
                   3275:                  $uhome);
                   3276:     &flushcourselogs();
                   3277: # set toplevel url
1.271     www      3278:     my $topurl=$url;
                   3279:     unless ($nonstandard) {
                   3280: # ------------------------------------------ For standard courses, make top url
                   3281:         my $mapurl=&clutter($url);
1.278     www      3282:         if ($mapurl eq '/res/') { $mapurl=''; }
1.271     www      3283:         $ENV{'form.initmap'}=(<<ENDINITMAP);
                   3284: <map>
                   3285: <resource id="1" type="start"></resource>
                   3286: <resource id="2" src="$mapurl"></resource>
                   3287: <resource id="3" type="finish"></resource>
                   3288: <link index="1" from="1" to="2"></link>
                   3289: <link index="2" from="2" to="3"></link>
                   3290: </map>
                   3291: ENDINITMAP
                   3292:         $topurl=&declutter(
                   3293:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
                   3294:                           );
                   3295:     }
                   3296: # ----------------------------------------------------------- Write preferences
1.84      www      3297:     &writecoursepref($udom.'_'.$uname,
                   3298:                      ('description' => $description,
1.271     www      3299:                       'url'         => $topurl));
1.84      www      3300:     return '/'.$udom.'/'.$uname;
                   3301: }
                   3302: 
1.21      www      3303: # ---------------------------------------------------------- Assign Custom Role
                   3304: 
                   3305: sub assigncustomrole {
1.357     www      3306:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      3307:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      3308:                        $end,$start,$deleteflag);
1.21      www      3309: }
                   3310: 
                   3311: # ----------------------------------------------------------------- Revoke Role
                   3312: 
                   3313: sub revokerole {
1.357     www      3314:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      3315:     my $now=time;
1.357     www      3316:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      3317: }
                   3318: 
                   3319: # ---------------------------------------------------------- Revoke Custom Role
                   3320: 
                   3321: sub revokecustomrole {
1.357     www      3322:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      3323:     my $now=time;
1.357     www      3324:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   3325:            $deleteflag);
1.17      www      3326: }
                   3327: 
                   3328: # ------------------------------------------------------------ Directory lister
                   3329: 
                   3330: sub dirlist {
1.253     stredwic 3331:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   3332: 
1.18      www      3333:     $uri=~s/^\///;
                   3334:     $uri=~s/\/$//;
1.253     stredwic 3335:     my ($udom, $uname);
                   3336:     (undef,$udom,$uname)=split(/\//,$uri);
                   3337:     if(defined($userdomain)) {
                   3338:         $udom = $userdomain;
                   3339:     }
                   3340:     if(defined($username)) {
                   3341:         $uname = $username;
                   3342:     }
                   3343: 
                   3344:     my $dirRoot = $perlvar{'lonDocRoot'};
                   3345:     if(defined($alternateDirectoryRoot)) {
                   3346:         $dirRoot = $alternateDirectoryRoot;
                   3347:         $dirRoot =~ s/\/$//;
                   3348:     }
                   3349: 
                   3350:     if($udom) {
                   3351:         if($uname) {
                   3352:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   3353:                               homeserver($uname,$udom));
                   3354:             return split(/:/,$listing);
                   3355:         } elsif(!defined($alternateDirectoryRoot)) {
                   3356:             my $tryserver;
                   3357:             my %allusers=();
                   3358:             foreach $tryserver (keys %libserv) {
                   3359:                 if($hostdom{$tryserver} eq $udom) {
                   3360:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   3361:                                       $udom, $tryserver);
                   3362:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   3363:                         && ($listing ne 'con_lost')) {
                   3364:                         foreach (split(/:/,$listing)) {
                   3365:                             my ($entry,@stat)=split(/&/,$_);
                   3366:                             $allusers{$entry}=1;
                   3367:                         }
                   3368:                     }
1.191     harris41 3369:                 }
1.253     stredwic 3370:             }
                   3371:             my $alluserstr='';
                   3372:             foreach (sort keys %allusers) {
                   3373:                 $alluserstr.=$_.'&user:';
                   3374:             }
                   3375:             $alluserstr=~s/:$//;
                   3376:             return split(/:/,$alluserstr);
                   3377:         } else {
                   3378:             my @emptyResults = ();
                   3379:             push(@emptyResults, 'missing user name');
                   3380:             return split(':',@emptyResults);
                   3381:         }
                   3382:     } elsif(!defined($alternateDirectoryRoot)) {
                   3383:         my $tryserver;
                   3384:         my %alldom=();
                   3385:         foreach $tryserver (keys %libserv) {
                   3386:             $alldom{$hostdom{$tryserver}}=1;
                   3387:         }
                   3388:         my $alldomstr='';
                   3389:         foreach (sort keys %alldom) {
1.397     albertel 3390:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 3391:         }
                   3392:         $alldomstr=~s/:$//;
                   3393:         return split(/:/,$alldomstr);       
                   3394:     } else {
                   3395:         my @emptyResults = ();
                   3396:         push(@emptyResults, 'missing domain');
                   3397:         return split(':',@emptyResults);
1.275     stredwic 3398:     }
                   3399: }
                   3400: 
                   3401: # --------------------------------------------- GetFileTimestamp
                   3402: # This function utilizes dirlist and returns the date stamp for
                   3403: # when it was last modified.  It will also return an error of -1
                   3404: # if an error occurs
                   3405: 
1.410     matthew  3406: ##
                   3407: ## FIXME: This subroutine assumes its caller knows something about the
                   3408: ## directory structure of the home server for the student ($root).
                   3409: ## Not a good assumption to make.  Since this is for looking up files
                   3410: ## in user directories, the full path should be constructed by lond, not
                   3411: ## whatever machine we request data from.
                   3412: ##
1.275     stredwic 3413: sub GetFileTimestamp {
                   3414:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   3415:     $studentDomain=~s/\W//g;
                   3416:     $studentName=~s/\W//g;
                   3417:     my $subdir=$studentName.'__';
                   3418:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3419:     my $proname="$studentDomain/$subdir/$studentName";
                   3420:     $proname .= '/'.$filename;
1.375     matthew  3421:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   3422:                                               $studentName, $root);
1.275     stredwic 3423:     my @stats = split('&', $fileStat);
                   3424:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  3425:         # @stats contains first the filename, then the stat output
                   3426:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 3427:     } else {
                   3428:         return -1;
1.253     stredwic 3429:     }
1.26      www      3430: }
                   3431: 
                   3432: # -------------------------------------------------------- Value of a Condition
                   3433: 
1.40      www      3434: sub directcondval {
                   3435:     my $number=shift;
                   3436:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   3437:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   3438:     } else {
                   3439:        return 2;
                   3440:     }
                   3441: }
                   3442: 
1.26      www      3443: sub condval {
                   3444:     my $condidx=shift;
                   3445:     my $result=0;
1.54      www      3446:     my $allpathcond='';
1.191     harris41 3447:     foreach (split(/\|/,$condidx)) {
1.54      www      3448:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   3449: 	   $allpathcond.=
                   3450:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   3451:        }
1.191     harris41 3452:     }
1.54      www      3453:     $allpathcond=~s/\|$//;
1.33      www      3454:     if ($ENV{'request.course.id'}) {
1.54      www      3455:        if ($allpathcond) {
1.26      www      3456:           my $operand='|';
                   3457: 	  my @stack;
1.191     harris41 3458:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      3459:               if ($_ eq '(') {
                   3460:                  push @stack,($operand,$result)
                   3461:               } elsif ($_ eq ')') {
                   3462:                   my $before=pop @stack;
                   3463: 		  if (pop @stack eq '&') {
                   3464: 		      $result=$result>$before?$before:$result;
                   3465:                   } else {
                   3466:                       $result=$result>$before?$result:$before;
                   3467:                   }
                   3468:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   3469:                   $operand=$_;
                   3470:               } else {
1.40      www      3471:                   my $new=directcondval($_);
1.26      www      3472:                   if ($operand eq '&') {
                   3473:                      $result=$result>$new?$new:$result;
                   3474:                   } else {
                   3475:                      $result=$result>$new?$result:$new;
1.191     harris41 3476:                   }
1.26      www      3477:               }
1.191     harris41 3478:           }
1.26      www      3479:        }
                   3480:     }
                   3481:     return $result;
1.421     albertel 3482: }
                   3483: 
                   3484: # ---------------------------------------------------- Devalidate courseresdata
                   3485: 
                   3486: sub devalidatecourseresdata {
                   3487:     my ($coursenum,$coursedomain)=@_;
                   3488:     my $hashid=$coursenum.':'.$coursedomain;
1.428     albertel 3489:     &devalidate_cache(\%courseresdatacache,$hashid,'courseres');
1.28      www      3490: }
                   3491: 
1.200     www      3492: # --------------------------------------------------- Course Resourcedata Query
                   3493: 
                   3494: sub courseresdata {
                   3495:     my ($coursenum,$coursedomain,@which)=@_;
                   3496:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   3497:     my $hashid=$coursenum.':'.$coursedomain;
1.425     albertel 3498:     my ($result,$cached)=&is_cached(\%courseresdatacache,$hashid,'courseres');
1.417     albertel 3499:     unless (defined($cached)) {
1.251     albertel 3500: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 3501: 	$result=\%dumpreply;
1.251     albertel 3502: 	my ($tmp) = keys(%dumpreply);
                   3503: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.425     albertel 3504: 	    &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.306     albertel 3505: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3506: 	    return $tmp;
1.416     albertel 3507: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 3508: 	    $result=undef;
1.425     albertel 3509: 	    &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.250     albertel 3510: 	}
                   3511:     }
1.251     albertel 3512:     foreach my $item (@which) {
1.417     albertel 3513: 	if (defined($result->{$item})) {
                   3514: 	    return $result->{$item};
1.251     albertel 3515: 	}
1.250     albertel 3516:     }
1.291     albertel 3517:     return undef;
1.200     www      3518: }
                   3519: 
1.379     matthew  3520: #
                   3521: # EXT resource caching routines
                   3522: #
                   3523: 
                   3524: sub clear_EXT_cache_status {
1.383     albertel 3525:     &delenv('cache.EXT.');
1.379     matthew  3526: }
                   3527: 
                   3528: sub EXT_cache_status {
                   3529:     my ($target_domain,$target_user) = @_;
1.383     albertel 3530:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.389     www      3531:     if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
1.379     matthew  3532:         # We know already the user has no data
                   3533:         return 1;
                   3534:     } else {
                   3535:         return 0;
                   3536:     }
                   3537: }
                   3538: 
                   3539: sub EXT_cache_set {
                   3540:     my ($target_domain,$target_user) = @_;
1.383     albertel 3541:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379     matthew  3542:     &appenv($cachename => time);
                   3543: }
                   3544: 
1.28      www      3545: # --------------------------------------------------------- Value of a Variable
1.58      www      3546: sub EXT {
1.395     albertel 3547:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 3548: 
1.68      www      3549:     unless ($varname) { return ''; }
1.218     albertel 3550:     #get real user name/domain, courseid and symb
                   3551:     my $courseid;
1.359     albertel 3552:     my $publicuser;
1.427     www      3553:     if ($symbparm) {
                   3554: 	$symbparm=&get_symb_from_alias($symbparm);
                   3555:     }
1.218     albertel 3556:     if (!($uname && $udom)) {
1.360     albertel 3557:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  3558: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 3559:       if (!$symbparm) {	$symbparm=$cursymb; }
                   3560:     } else {
                   3561: 	$courseid=$ENV{'request.course.id'};
                   3562:     }
1.48      www      3563:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   3564:     my $rest;
1.320     albertel 3565:     if (defined($therest[0])) {
1.48      www      3566:        $rest=join('.',@therest);
                   3567:     } else {
                   3568:        $rest='';
                   3569:     }
1.320     albertel 3570: 
1.57      www      3571:     my $qualifierrest=$qualifier;
                   3572:     if ($rest) { $qualifierrest.='.'.$rest; }
                   3573:     my $spacequalifierrest=$space;
                   3574:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      3575:     if ($realm eq 'user') {
1.48      www      3576: # --------------------------------------------------------------- user.resource
                   3577: 	if ($space eq 'resource') {
1.335     albertel 3578: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
                   3579: 		return $Apache::lonhomework::history{$qualifierrest};
                   3580: 	    } else {
1.359     albertel 3581: 		my %restored;
                   3582: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
                   3583: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   3584: 		} else {
                   3585: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   3586: 		}
1.335     albertel 3587: 		return $restored{$qualifierrest};
                   3588: 	    }
1.48      www      3589: # ----------------------------------------------------------------- user.access
                   3590:         } elsif ($space eq 'access') {
1.218     albertel 3591: 	    # FIXME - not supporting calls for a specific user
1.48      www      3592:             return &allowed($qualifier,$rest);
                   3593: # ------------------------------------------ user.preferences, user.environment
                   3594:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218     albertel 3595: 	    if (($uname eq $ENV{'user.name'}) &&
                   3596: 		($udom eq $ENV{'user.domain'})) {
                   3597: 		return $ENV{join('.',('environment',$qualifierrest))};
                   3598: 	    } else {
1.359     albertel 3599: 		my %returnhash;
                   3600: 		if (!$publicuser) {
                   3601: 		    %returnhash=&userenvironment($udom,$uname,
                   3602: 						 $qualifierrest);
                   3603: 		}
1.218     albertel 3604: 		return $returnhash{$qualifierrest};
                   3605: 	    }
1.48      www      3606: # ----------------------------------------------------------------- user.course
                   3607:         } elsif ($space eq 'course') {
1.218     albertel 3608: 	    # FIXME - not supporting calls for a specific user
1.48      www      3609:             return $ENV{join('.',('request.course',$qualifier))};
                   3610: # ------------------------------------------------------------------- user.role
                   3611:         } elsif ($space eq 'role') {
1.218     albertel 3612: 	    # FIXME - not supporting calls for a specific user
1.48      www      3613:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   3614:             if ($qualifier eq 'value') {
                   3615: 		return $role;
                   3616:             } elsif ($qualifier eq 'extent') {
                   3617:                 return $where;
                   3618:             }
                   3619: # ----------------------------------------------------------------- user.domain
                   3620:         } elsif ($space eq 'domain') {
1.218     albertel 3621:             return $udom;
1.48      www      3622: # ------------------------------------------------------------------- user.name
                   3623:         } elsif ($space eq 'name') {
1.218     albertel 3624:             return $uname;
1.48      www      3625: # ---------------------------------------------------- Any other user namespace
1.29      www      3626:         } else {
1.359     albertel 3627: 	    my %reply;
                   3628: 	    if (!$publicuser) {
                   3629: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   3630: 	    }
                   3631: 	    return $reply{$qualifierrest};
1.48      www      3632:         }
1.236     www      3633:     } elsif ($realm eq 'query') {
                   3634: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 3635:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   3636: 						[$spacequalifierrest]);
1.376     albertel 3637: 	return $ENV{'form.'.$spacequalifierrest}; 
1.236     www      3638:    } elsif ($realm eq 'request') {
1.48      www      3639: # ------------------------------------------------------------- request.browser
                   3640:         if ($space eq 'browser') {
1.430     www      3641: 	    if ($qualifier eq 'textremote') {
                   3642: 		if (&mt('textual_remote_display') eq 'on') {
                   3643: 		    return 1;
                   3644: 		} else {
                   3645: 		    return 0;
                   3646: 		}
                   3647: 	    } else {
                   3648: 		return $ENV{'browser.'.$qualifier};
                   3649: 	    }
1.57      www      3650: # ------------------------------------------------------------ request.filename
                   3651:         } else {
                   3652:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      3653:         }
1.28      www      3654:     } elsif ($realm eq 'course') {
1.48      www      3655: # ---------------------------------------------------------- course.description
1.218     albertel 3656:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      3657:     } elsif ($realm eq 'resource') {
1.165     www      3658: 
1.395     albertel 3659: 	my $section;
1.359     albertel 3660: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.165     www      3661: 
1.218     albertel 3662: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      3663: 
1.60      www      3664: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 3665: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   3666: 	    my $symbp=$symbparm;
1.409     www      3667: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 3668: 
                   3669: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   3670: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   3671: 
                   3672: 	    if (($ENV{'user.name'} eq $uname) &&
                   3673: 		($ENV{'user.domain'} eq $udom)) {
1.255     albertel 3674: 		$section=$ENV{'request.course.sec'};
1.218     albertel 3675: 	    } else {
1.377     matthew  3676:                 if (! defined($usection)) {
                   3677:                     $section=&usection($udom,$uname,$courseid);
                   3678:                 } else {
                   3679:                     $section = $usection;
                   3680:                 }
1.218     albertel 3681: 	    }
                   3682: 
                   3683: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   3684: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   3685: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   3686: 
                   3687: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
                   3688: 	    my $courselevelr=$courseid.'.'.$symbparm;
                   3689: 	    my $courselevelm=$courseid.'.'.$mapparm;
1.69      www      3690: 
1.60      www      3691: # ----------------------------------------------------------- first, check user
1.379     matthew  3692: 	    #most student don\'t have any data set, check if there is some data
                   3693: 	    if (! &EXT_cache_status($udom,$uname)) {
1.420     albertel 3694: 		my $hashid="$udom:$uname";
1.425     albertel 3695: 		my ($result,$cached)=&is_cached(\%userresdatacache,$hashid,
                   3696: 						'userres');
1.420     albertel 3697: 		if (!defined($cached)) { 
                   3698: 		    my %resourcedata=&get('resourcedata',
                   3699: 					  [$courselevelr,$courselevelm,
                   3700: 					   $courselevel],$udom,$uname);
                   3701: 		    $result=\%resourcedata;
1.425     albertel 3702: 		    &do_cache(\%userresdatacache,$hashid,$result,'userres');
1.420     albertel 3703: 		}
                   3704: 		my ($tmp)=keys(%$result);
1.308     albertel 3705: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
1.420     albertel 3706: 		    if ($$result{$courselevelr}) {
                   3707: 			return $$result{$courselevelr}; }
                   3708: 		    if ($$result{$courselevelm}) {
                   3709: 			return $$result{$courselevelm}; }
                   3710: 		    if ($$result{$courselevel}) {
                   3711: 			return $$result{$courselevel}; }
1.308     albertel 3712: 		} else {
                   3713: 		    if ($tmp!~/No such file/) {
                   3714: 			&logthis("<font color=blue>WARNING:".
                   3715: 				 " Trying to get resource data for ".
                   3716: 				 $uname." at ".$udom.": ".
                   3717: 				 $tmp."</font>");
                   3718: 		    } elsif ($tmp=~/error:No such file/) {
1.379     matthew  3719:                         &EXT_cache_set($udom,$uname);
1.308     albertel 3720: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3721: 			return $tmp;
                   3722: 		    }
1.218     albertel 3723: 		}
                   3724: 	    }
1.95      www      3725: 
1.60      www      3726: # -------------------------------------------------------- second, check course
1.96      www      3727: 
1.218     albertel 3728: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
                   3729: 					  $ENV{'course.'.$courseid.'.domain'},
                   3730: 					  ($seclevelr,$seclevelm,$seclevel,
                   3731: 					   $courselevelr,$courselevelm,
                   3732: 					   $courselevel));
1.287     albertel 3733: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      3734: 
1.60      www      3735: # ------------------------------------------------------ third, check map parms
1.218     albertel 3736: 	    my %parmhash=();
                   3737: 	    my $thisparm='';
                   3738: 	    if (tie(%parmhash,'GDBM_File',
                   3739: 		    $ENV{'request.course.fn'}.'_parms.db',
1.256     albertel 3740: 		    &GDBM_READER(),0640)) {
1.218     albertel 3741: 		$thisparm=$parmhash{$symbparm};
                   3742: 		untie(%parmhash);
                   3743: 	    }
                   3744: 	    if ($thisparm) { return $thisparm; }
                   3745: 	}
1.60      www      3746: # --------------------------------------------- last, look in resource metadata
1.71      www      3747: 
1.218     albertel 3748: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 3749: 	my $filename;
                   3750: 	if (!$symbparm) { $symbparm=&symbread(); }
                   3751: 	if ($symbparm) {
1.409     www      3752: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 3753: 	} else {
                   3754: 	    $filename=$ENV{'request.filename'};
                   3755: 	}
                   3756: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 3757: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 3758: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 3759: 	if (defined($metadata)) { return $metadata; }
1.142     www      3760: 
1.145     www      3761: # ------------------------------------------------------------------ Cascade up
1.218     albertel 3762: 	unless ($space eq '0') {
1.336     albertel 3763: 	    my @parts=split(/_/,$space);
                   3764: 	    my $id=pop(@parts);
                   3765: 	    my $part=join('_',@parts);
                   3766: 	    if ($part eq '') { $part='0'; }
                   3767: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 3768: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 3769: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 3770: 	}
1.395     albertel 3771: 	if ($recurse) { return undef; }
                   3772: 	my $pack_def=&packages_tab_default($filename,$varname);
                   3773: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      3774: 
1.48      www      3775: # ---------------------------------------------------- Any other user namespace
                   3776:     } elsif ($realm eq 'environment') {
                   3777: # ----------------------------------------------------------------- environment
1.219     albertel 3778: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
                   3779: 	    return $ENV{'environment.'.$spacequalifierrest};
                   3780: 	} else {
                   3781: 	    my %returnhash=&userenvironment($udom,$uname,
                   3782: 					    $spacequalifierrest);
                   3783: 	    return $returnhash{$spacequalifierrest};
                   3784: 	}
1.28      www      3785:     } elsif ($realm eq 'system') {
1.48      www      3786: # ----------------------------------------------------------------- system.time
                   3787: 	if ($space eq 'time') {
                   3788: 	    return time;
                   3789:         }
1.28      www      3790:     }
1.48      www      3791:     return '';
1.61      www      3792: }
                   3793: 
1.395     albertel 3794: sub packages_tab_default {
                   3795:     my ($uri,$varname)=@_;
                   3796:     my (undef,$part,$name)=split(/\./,$varname);
                   3797:     my $packages=&metadata($uri,'packages');
                   3798:     foreach my $package (split(/,/,$packages)) {
                   3799: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
                   3800: 	if ($pack_part eq $part) {
                   3801: 	    return $packagetab{"$pack_type&$name&default"};
                   3802: 	}
                   3803:     }
                   3804:     return undef;
                   3805: }
                   3806: 
1.334     albertel 3807: sub add_prefix_and_part {
                   3808:     my ($prefix,$part)=@_;
                   3809:     my $keyroot;
                   3810:     if (defined($prefix) && $prefix !~ /^__/) {
                   3811: 	# prefix that has a part already
                   3812: 	$keyroot=$prefix;
                   3813:     } elsif (defined($prefix)) {
                   3814: 	# prefix that is missing a part
                   3815: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   3816:     } else {
                   3817: 	# no prefix at all
                   3818: 	if (defined($part)) { $keyroot='_'.$part; }
                   3819:     }
                   3820:     return $keyroot;
                   3821: }
                   3822: 
1.71      www      3823: # ---------------------------------------------------------------- Get metadata
                   3824: 
                   3825: sub metadata {
1.176     www      3826:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      3827:     $uri=&declutter($uri);
1.288     albertel 3828:     # if it is a non metadata possible uri return quickly
1.293     matthew  3829:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
1.423     albertel 3830:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
                   3831: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.288     albertel 3832: 	return '';
                   3833:     }
1.73      www      3834:     my $filename=$uri;
                   3835:     $uri=~s/\.meta$//;
1.172     www      3836: #
                   3837: # Is the metadata already cached?
1.177     www      3838: # Look at timestamp of caching
1.172     www      3839: # Everything is cached by the main uri, libraries are never directly cached
                   3840: #
1.428     albertel 3841:     if (!defined($liburi)) {
                   3842: 	my ($result,$cached)=&is_cached(\%metacache,$uri,'meta');
                   3843: 	if (defined($cached)) { return $result->{':'.$what}; }
                   3844:     }
                   3845:     {
1.172     www      3846: #
                   3847: # Is this a recursive call for a library?
                   3848: #
1.453   ! albertel 3849: 	if (! exists($metacache{$uri})) {
        !          3850: 	    $metacache{$uri}={};
        !          3851: 	}
1.171     www      3852:         if ($liburi) {
                   3853: 	    $liburi=&declutter($liburi);
                   3854:             $filename=$liburi;
1.401     bowersj2 3855:         } else {
1.428     albertel 3856: 	    &devalidate_cache(\%metacache,$uri,'meta');
1.401     bowersj2 3857: 	}
1.140     www      3858:         my %metathesekeys=();
1.73      www      3859:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.335     albertel 3860: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
1.208     albertel 3861:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      3862:         my $token;
1.140     www      3863:         undef %metathesekeys;
1.71      www      3864:         while ($token=$parser->get_token) {
1.339     albertel 3865: 	    if ($token->[0] eq 'S') {
                   3866: 		if (defined($token->[2]->{'package'})) {
1.172     www      3867: #
                   3868: # This is a package - get package info
                   3869: #
1.339     albertel 3870: 		    my $package=$token->[2]->{'package'};
                   3871: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3872: 		    if (defined($token->[2]->{'id'})) { 
                   3873: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   3874: 		    }
1.453   ! albertel 3875: 		    if ($metacache{$uri}->{':packages'}) {
        !          3876: 			$metacache{$uri}->{':packages'}.=','.$package.$keyroot;
1.339     albertel 3877: 		    } else {
1.453   ! albertel 3878: 			$metacache{$uri}->{':packages'}=$package.$keyroot;
1.339     albertel 3879: 		    }
                   3880: 		    foreach (keys %packagetab) {
1.432     albertel 3881: 			my $part=$keyroot;
                   3882: 			$part=~s/^\_//;
                   3883: 			if ($_=~/^\Q$package\E\&/ || 
                   3884: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 3885: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 3886: 			    # ignore package.tab specified default values
                   3887:                             # here &package_tab_default() will fetch those
                   3888: 			    if ($subp eq 'default') { next; }
1.339     albertel 3889: 			    my $value=$packagetab{$_};
1.432     albertel 3890: 			    my $unikey;
                   3891: 			    if ($pack =~ /_0$/) {
                   3892: 				$unikey='parameter_0_'.$name;
                   3893: 				$part=0;
                   3894: 			    } else {
                   3895: 				$unikey='parameter'.$keyroot.'_'.$name;
                   3896: 			    }
1.339     albertel 3897: 			    if ($subp eq 'display') {
                   3898: 				$value.=' [Part: '.$part.']';
                   3899: 			    }
1.453   ! albertel 3900: 			    $metacache{$uri}->{':'.$unikey.'.part'}=$part;
1.395     albertel 3901: 			    $metathesekeys{$unikey}=1;
1.453   ! albertel 3902: 			    unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) {
        !          3903: 				$metacache{$uri}->{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 3904: 			    }
1.453   ! albertel 3905: 			    if (defined($metacache{$uri}->{':'.$unikey.'.default'})) {
        !          3906: 				$metacache{$uri}->{':'.$unikey}=
        !          3907: 				    $metacache{$uri}->{':'.$unikey.'.default'};
1.356     albertel 3908: 			    }
1.339     albertel 3909: 			}
                   3910: 		    }
                   3911: 		} else {
1.172     www      3912: #
                   3913: # This is not a package - some other kind of start tag
1.339     albertel 3914: #
                   3915: 		    my $entry=$token->[1];
                   3916: 		    my $unikey;
                   3917: 		    if ($entry eq 'import') {
                   3918: 			$unikey='';
                   3919: 		    } else {
                   3920: 			$unikey=$entry;
                   3921: 		    }
                   3922: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3923: 
                   3924: 		    if (defined($token->[2]->{'id'})) { 
                   3925: 			$unikey.='_'.$token->[2]->{'id'}; 
                   3926: 		    }
1.175     www      3927: 
1.339     albertel 3928: 		    if ($entry eq 'import') {
1.175     www      3929: #
                   3930: # Importing a library here
1.339     albertel 3931: #
                   3932: 			if ($depthcount<20) {
                   3933: 			    my $location=$parser->get_text('/import');
                   3934: 			    my $dir=$filename;
                   3935: 			    $dir=~s|[^/]*$||;
                   3936: 			    $location=&filelocation($dir,$location);
                   3937: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3938: 							       $location,$unikey,
                   3939: 							       $depthcount+1)))) {
1.453   ! albertel 3940: 				$metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 3941: 				$metathesekeys{$_}=1;
                   3942: 			    }
                   3943: 			}
                   3944: 		    } else { 
                   3945: 			
                   3946: 			if (defined($token->[2]->{'name'})) { 
                   3947: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   3948: 			}
                   3949: 			$metathesekeys{$unikey}=1;
                   3950: 			foreach (@{$token->[3]}) {
1.453   ! albertel 3951: 			    $metacache{$uri}->{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 3952: 			}
                   3953: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.453   ! albertel 3954: 			my $default=$metacache{$uri}->{':'.$unikey.'.default'};
1.339     albertel 3955: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   3956: 		 # only ws inside the tag, and not in default, so use default
                   3957: 		 # as value
1.453   ! albertel 3958: 			    $metacache{$uri}->{':'.$unikey}=$default;
1.339     albertel 3959: 			} else {
1.321     albertel 3960: 		  # either something interesting inside the tag or default
                   3961:                   # uninteresting
1.453   ! albertel 3962: 			    $metacache{$uri}->{':'.$unikey}=$internaltext;
1.339     albertel 3963: 			}
1.172     www      3964: # end of not-a-package not-a-library import
1.339     albertel 3965: 		    }
1.172     www      3966: # end of not-a-package start tag
1.339     albertel 3967: 		}
1.172     www      3968: # the next is the end of "start tag"
1.339     albertel 3969: 	    }
                   3970: 	}
1.338     www      3971: # are there custom rights to evaluate
1.453   ! albertel 3972: 	if ($metacache{$uri}->{':copyright'} eq 'custom') {
1.339     albertel 3973: 
1.338     www      3974:     #
                   3975:     # Importing a rights file here
1.339     albertel 3976:     #
                   3977: 	    unless ($depthcount) {
1.453   ! albertel 3978: 		my $location=$metacache{$uri}->{':customdistributionfile'};
1.339     albertel 3979: 		my $dir=$filename;
                   3980: 		$dir=~s|[^/]*$||;
                   3981: 		$location=&filelocation($dir,$location);
                   3982: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3983: 						   $location,'_rights',
                   3984: 						   $depthcount+1)))) {
1.453   ! albertel 3985: 		    $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 3986: 		    $metathesekeys{$_}=1;
                   3987: 		}
                   3988: 	    }
                   3989: 	}
1.453   ! albertel 3990: 	$metacache{$uri}->{':keys'}=join(',',keys %metathesekeys);
        !          3991: 	&metadata_generate_part0(\%metathesekeys,$metacache{$uri},$uri);
        !          3992: 	$metacache{$uri}->{':allpossiblekeys'}=join(',',keys %metathesekeys);
        !          3993: 	&do_cache(\%metacache,$uri,$metacache{$uri},'meta');
1.177     www      3994: # this is the end of "was not already recently cached
1.71      www      3995:     }
1.428     albertel 3996:     return $metacache{$uri}->{':'.$what};
1.261     albertel 3997: }
                   3998: 
                   3999: sub metadata_generate_part0 {
                   4000:     my ($metadata,$metacache,$uri) = @_;
                   4001:     my %allnames;
                   4002:     foreach my $metakey (sort keys %$metadata) {
                   4003: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 4004: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   4005: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 4006: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 4007: 	    $allnames{$name}=$part;
                   4008: 	  }
                   4009: 	}
                   4010:     }
                   4011:     foreach my $name (keys(%allnames)) {
                   4012:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 4013:       my $key=":parameter_0_$name";
1.261     albertel 4014:       $$metacache{"$key.part"}='0';
                   4015:       $$metacache{"$key.name"}=$name;
1.428     albertel 4016:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 4017: 					   $allnames{$name}.'_'.$name.
                   4018: 					   '.type'};
1.428     albertel 4019:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 4020: 			     '.display'};
                   4021:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
                   4022:       $olddis=~s/$expr/\[Part: 0\]/;
                   4023:       $$metacache{"$key.display"}=$olddis;
                   4024:     }
1.71      www      4025: }
                   4026: 
1.301     www      4027: # ------------------------------------------------- Get the title of a resource
                   4028: 
                   4029: sub gettitle {
                   4030:     my $urlsymb=shift;
                   4031:     my $symb=&symbread($urlsymb);
                   4032:     unless ($symb) {
                   4033: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
                   4034:         return &metadata($urlsymb,'title'); 
                   4035:     }
1.425     albertel 4036:     my ($result,$cached)=&is_cached(\%titlecache,$symb,'title',600);
1.419     albertel 4037:     if (defined($cached)) { return $result; }
1.409     www      4038:     my ($map,$resid,$url)=&decode_symb($symb);
1.301     www      4039:     my $title='';
                   4040:     my %bighash;
                   4041:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   4042:                             &GDBM_READER(),0640)) {
                   4043:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   4044:         $title=$bighash{'title_'.$mapid.'.'.$resid};
                   4045:         untie %bighash;
                   4046:     }
1.363     www      4047:     $title=~s/\&colon\;/\:/gs;
1.301     www      4048:     if ($title) {
1.425     albertel 4049:         return &do_cache(\%titlecache,$symb,$title,'title');
1.301     www      4050:     } else {
                   4051: 	return &metadata($urlsymb,'title');
                   4052:     }
                   4053: }
                   4054:     
1.31      www      4055: # ------------------------------------------------- Update symbolic store links
                   4056: 
                   4057: sub symblist {
                   4058:     my ($mapname,%newhash)=@_;
1.438     www      4059:     $mapname=&deversion(&declutter($mapname));
1.31      www      4060:     my %hash;
                   4061:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   4062:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 4063:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 4064: 	    foreach (keys %newhash) {
1.438     www      4065:                 $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_});
1.191     harris41 4066:             }
1.31      www      4067:             if (untie(%hash)) {
                   4068: 		return 'ok';
                   4069:             }
                   4070:         }
                   4071:     }
                   4072:     return 'error';
1.212     www      4073: }
                   4074: 
                   4075: # --------------------------------------------------------------- Verify a symb
                   4076: 
                   4077: sub symbverify {
                   4078:     my ($symb,$thisfn)=@_;
1.439     www      4079:     $thisfn=&declutter($thisfn);
1.215     www      4080: # direct jump to resource in page or to a sequence - will construct own symbs
                   4081:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   4082: # check URL part
1.409     www      4083:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      4084: 
1.431     www      4085:     unless ($url eq $thisfn) { return 0; }
1.213     www      4086: 
1.216     www      4087:     $symb=&symbclean($symb);
1.439     www      4088:     $thisfn=&deversion($thisfn);
1.213     www      4089: 
                   4090:     my %bighash;
                   4091:     my $okay=0;
1.431     www      4092: 
1.213     www      4093:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 4094:                             &GDBM_READER(),0640)) {
1.280     www      4095:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.216     www      4096:         unless ($ids) { 
                   4097:            $ids=$bighash{'ids_/'.$thisfn};
                   4098:         }
                   4099:         if ($ids) {
                   4100: # ------------------------------------------------------------------- Has ID(s)
                   4101: 	    foreach (split(/\,/,$ids)) {
                   4102:                my ($mapid,$resid)=split(/\./,$_);
                   4103:                if (
                   4104:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   4105:    eq $symb) { 
                   4106:                   $okay=1; 
                   4107:                }
                   4108: 	   }
                   4109:         }
1.213     www      4110: 	untie(%bighash);
                   4111:     }
                   4112:     return $okay;
1.31      www      4113: }
                   4114: 
1.210     www      4115: # --------------------------------------------------------------- Clean-up symb
                   4116: 
                   4117: sub symbclean {
                   4118:     my $symb=shift;
1.213     www      4119: 
1.210     www      4120: # remove version from map
                   4121:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      4122: 
1.210     www      4123: # remove version from URL
                   4124:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      4125: 
1.210     www      4126:     return $symb;
1.409     www      4127: }
                   4128: 
                   4129: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 4130: 
                   4131: sub encode_symb {
                   4132:     my ($map,$resid,$url)=@_;
                   4133:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   4134: }
1.409     www      4135: 
                   4136: sub decode_symb {
1.413     www      4137:     my ($map,$resid,$url)=split(/\_\_\_/,shift);
                   4138:     return (&fixversion($map),$resid,&fixversion($url));
                   4139: }
                   4140: 
                   4141: sub fixversion {
                   4142:     my $fn=shift;
                   4143:     if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
1.435     www      4144:     my %bighash;
                   4145:     my $uri=&clutter($fn);
1.440     www      4146:     my $key=$ENV{'request.course.id'}.'_'.$uri;
                   4147: # is this cached?
                   4148:     my ($result,$cached)=&is_cached(\%courseresversioncache,$key,
                   4149: 				    'courseresversion',600);
                   4150:     if (defined($cached)) { return $result; }
                   4151: # unfortunately not cached, or expired
1.435     www      4152:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.440     www      4153: 	    &GDBM_READER(),0640)) {
                   4154:  	if ($bighash{'version_'.$uri}) {
                   4155:  	    my $version=$bighash{'version_'.$uri};
1.444     www      4156:  	    unless (($version eq 'mostrecent') || 
                   4157: 		    ($version==&getversion($uri))) {
1.440     www      4158:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   4159:  	    }
                   4160:  	}
                   4161:  	untie %bighash;
1.413     www      4162:     }
1.440     www      4163:     return &do_cache
                   4164: 	(\%courseresversioncache,$key,&declutter($uri),'courseresversion');
1.438     www      4165: }
                   4166: 
                   4167: sub deversion {
                   4168:     my $url=shift;
                   4169:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   4170:     return $url;
1.210     www      4171: }
                   4172: 
1.31      www      4173: # ------------------------------------------------------ Return symb list entry
                   4174: 
                   4175: sub symbread {
1.249     www      4176:     my ($thisfn,$donotrecurse)=@_;
1.242     www      4177: # no filename provided? try from environment
1.44      www      4178:     unless ($thisfn) {
1.210     www      4179:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44      www      4180: 	$thisfn=$ENV{'request.filename'};
                   4181:     }
1.242     www      4182: # is that filename actually a symb? Verify, clean, and return
                   4183:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
                   4184: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
                   4185:     }
1.44      www      4186:     $thisfn=declutter($thisfn);
1.31      www      4187:     my %hash;
1.37      www      4188:     my %bighash;
                   4189:     my $syval='';
1.45      www      4190:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      4191:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 4192:                       &GDBM_READER(),0640)) {
1.31      www      4193: 	    $syval=$hash{$thisfn};
1.37      www      4194:             untie(%hash);
                   4195:         }
                   4196: # ---------------------------------------------------------- There was an entry
                   4197:         if ($syval) {
                   4198:            unless ($syval=~/\_\d+$/) {
                   4199: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      4200:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      4201:                   return '';
                   4202:                }    
                   4203:                $syval.=$1;
                   4204: 	   }
                   4205:         } else {
                   4206: # ------------------------------------------------------- Was not in symb table
                   4207:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 4208:                             &GDBM_READER(),0640)) {
1.37      www      4209: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      4210:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      4211:               unless ($ids) { 
                   4212:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      4213:               }
                   4214:               unless ($ids) {
                   4215: # alias?
                   4216: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      4217:               }
1.37      www      4218:               if ($ids) {
                   4219: # ------------------------------------------------------------------- Has ID(s)
                   4220:                  my @possibilities=split(/\,/,$ids);
1.39      www      4221:                  if ($#possibilities==0) {
                   4222: # ----------------------------------------------- There is only one possibility
1.37      www      4223: 		     my ($mapid,$resid)=split(/\./,$ids);
                   4224:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249     www      4225:                  } elsif (!$donotrecurse) {
1.39      www      4226: # ------------------------------------------ There is more than one possibility
                   4227:                      my $realpossible=0;
1.191     harris41 4228:                      foreach (@possibilities) {
1.39      www      4229: 			 my $file=$bighash{'src_'.$_};
                   4230:                          if (&allowed('bre',$file)) {
                   4231:          		    my ($mapid,$resid)=split(/\./,$_);
                   4232:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   4233: 				$realpossible++;
                   4234:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   4235:                                        '___'.$resid;
                   4236:                             }
                   4237: 			 }
1.191     harris41 4238:                      }
1.39      www      4239: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      4240:                  } else {
                   4241:                      $syval='';
1.37      www      4242:                  }
                   4243: 	      }
                   4244:               untie(%bighash)
                   4245:            } 
1.31      www      4246:         }
1.62      www      4247:         if ($syval) {
1.210     www      4248:            return &symbclean($syval.'___'.$thisfn); 
1.62      www      4249:         }
1.31      www      4250:     }
1.44      www      4251:     &appenv('request.ambiguous' => $thisfn);
1.31      www      4252:     return '';
                   4253: }
                   4254: 
                   4255: # ---------------------------------------------------------- Return random seed
                   4256: 
1.32      www      4257: sub numval {
                   4258:     my $txt=shift;
                   4259:     $txt=~tr/A-J/0-9/;
                   4260:     $txt=~tr/a-j/0-9/;
                   4261:     $txt=~tr/K-T/0-9/;
                   4262:     $txt=~tr/k-t/0-9/;
                   4263:     $txt=~tr/U-Z/0-5/;
                   4264:     $txt=~tr/u-z/0-5/;
                   4265:     $txt=~s/\D//g;
                   4266:     return int($txt);
1.368     albertel 4267: }
                   4268: 
                   4269: sub latest_rnd_algorithm_id {
1.443     albertel 4270:     return '64bit2';
1.366     albertel 4271: }
1.32      www      4272: 
1.31      www      4273: sub rndseed {
1.155     albertel 4274:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 4275: 
                   4276:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 4277:     if (!$symb) {
1.366     albertel 4278: 	unless ($symb=$wsymb) { return time; }
                   4279:     }
                   4280:     if (!$courseid) { $courseid=$wcourseid; }
                   4281:     if (!$domain) { $domain=$wdomain; }
                   4282:     if (!$username) { $username=$wusername }
                   4283:     my $which=$ENV{"course.$courseid.rndseed"};
                   4284:     my $CODE=$ENV{'scantron.CODE'};
                   4285:     if (defined($CODE)) {
                   4286: 	&rndseed_CODE_64bit($symb,$courseid,$domain,$username);
1.443     albertel 4287:     } elsif ($which eq '64bit2') {
                   4288: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 4289:     } elsif ($which eq '64bit') {
                   4290: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   4291:     }
                   4292:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   4293: }
                   4294: 
                   4295: sub rndseed_32bit {
                   4296:     my ($symb,$courseid,$domain,$username)=@_;
                   4297:     {
                   4298: 	use integer;
                   4299: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   4300: 	my $symbseed=numval($symb) << 22;
                   4301: 	my $namechck=unpack("%32C*",$username) << 17;
                   4302: 	my $nameseed=numval($username) << 12;
                   4303: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   4304: 	my $courseseed=unpack("%32C*",$courseid);
                   4305: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   4306: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   4307: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   4308: 	return $num;
                   4309:     }
                   4310: }
                   4311: 
                   4312: sub rndseed_64bit {
                   4313:     my ($symb,$courseid,$domain,$username)=@_;
                   4314:     {
                   4315: 	use integer;
                   4316: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   4317: 	my $symbseed=numval($symb) << 10;
                   4318: 	my $namechck=unpack("%32S*",$username);
                   4319: 	
                   4320: 	my $nameseed=numval($username) << 21;
                   4321: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   4322: 	my $courseseed=unpack("%32S*",$courseid);
                   4323: 	
                   4324: 	my $num1=$symbchck+$symbseed+$namechck;
                   4325: 	my $num2=$nameseed+$domainseed+$courseseed;
                   4326: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   4327: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   4328: 	return "$num1,$num2";
1.155     albertel 4329:     }
1.366     albertel 4330: }
                   4331: 
1.443     albertel 4332: sub rndseed_64bit2 {
                   4333:     my ($symb,$courseid,$domain,$username)=@_;
                   4334:     {
                   4335: 	use integer;
                   4336: 	# strings need to be an even # of cahracters long, it it is odd the
                   4337:         # last characters gets thrown away
                   4338: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   4339: 	my $symbseed=numval($symb) << 10;
                   4340: 	my $namechck=unpack("%32S*",$username.' ');
                   4341: 	
                   4342: 	my $nameseed=numval($username) << 21;
                   4343: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   4344: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   4345: 	
                   4346: 	my $num1=$symbchck+$symbseed+$namechck;
                   4347: 	my $num2=$nameseed+$domainseed+$courseseed;
                   4348: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   4349: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   4350: 	return "$num1,$num2";
                   4351:     }
                   4352: }
                   4353: 
1.366     albertel 4354: sub rndseed_CODE_64bit {
                   4355:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 4356:     {
1.366     albertel 4357: 	use integer;
1.443     albertel 4358: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.366     albertel 4359: 	my $symbseed=numval($symb);
                   4360: 	my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
1.443     albertel 4361: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.366     albertel 4362: 	my $num1=$symbseed+$CODEseed;
                   4363: 	my $num2=$courseseed+$symbchck;
                   4364: 	#&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
                   4365: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   4366: 	return "$num1,$num2";
                   4367:     }
                   4368: }
                   4369: 
                   4370: sub setup_random_from_rndseed {
                   4371:     my ($rndseed)=@_;
                   4372:     if ($rndseed =~/,/) {
                   4373: 	my ($num1,$num2)=split(/,/,$rndseed);
                   4374: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   4375:     } else {
                   4376: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 4377:     }
1.36      albertel 4378: }
                   4379: 
1.76      www      4380: sub ireceipt {
                   4381:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   4382:     my $cuname=unpack("%32C*",$funame);
                   4383:     my $cudom=unpack("%32C*",$fudom);
                   4384:     my $cucourseid=unpack("%32C*",$fucourseid);
                   4385:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      4386:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      4387:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   4388:            ($cunique%$cuname+
                   4389:             $cunique%$cudom+
                   4390:             $cusymb%$cuname+
                   4391:             $cusymb%$cudom+
                   4392:             $cucourseid%$cuname+
                   4393:             $cucourseid%$cudom);
                   4394: }
                   4395: 
                   4396: sub receipt {
1.260     ng       4397:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   4398:   return &ireceipt($name,$domain,$courseid,$symb);
1.76      www      4399: }
1.260     ng       4400: 
1.36      albertel 4401: # ------------------------------------------------------------ Serves up a file
                   4402: # returns either the contents of the file or a -1
                   4403: sub getfile {
1.269     www      4404:  my $file=shift;
                   4405:  if ($file=~/^\/*uploaded\//) { # user file
                   4406:     my $ua=new LWP::UserAgent;
                   4407:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
                   4408:     my $response=$ua->request($request);
                   4409:     if ($response->is_success()) {
                   4410:        return $response->content;
                   4411:     } else { 
                   4412:        return -1; 
                   4413:     }
                   4414:  } else { # normal file from res space
1.37      www      4415:   &repcopy($file);
1.36      albertel 4416:   if (! -e $file ) { return -1; };
1.448     albertel 4417:   my $fh;
                   4418:   open($fh,"<$file");
1.36      albertel 4419:   my $a='';
                   4420:   while (<$fh>) { $a .=$_; }
1.269     www      4421:   return $a;
                   4422:  }
1.36      albertel 4423: }
                   4424: 
                   4425: sub filelocation {
                   4426:   my ($dir,$file) = @_;
                   4427:   my $location;
                   4428:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 4429:   if ($file=~m:^/~:) { # is a contruction space reference
                   4430:     $location = $file;
                   4431:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270     www      4432:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
                   4433:     $location=$file;
1.36      albertel 4434:   } else {
1.59      albertel 4435:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   4436:     $file=~s:^/*res::;
                   4437:     if ( !( $file =~ m:^/:) ) {
                   4438:       $location = $dir. '/'.$file;
                   4439:     } else {
                   4440:       $location = '/home/httpd/html/res'.$file;
                   4441:     }
1.36      albertel 4442:   }
                   4443:   $location=~s://+:/:g; # remove duplicate /
1.46      www      4444:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   4445:   return $location;
                   4446: }
1.36      albertel 4447: 
1.46      www      4448: sub hreflocation {
                   4449:     my ($dir,$file)=@_;
1.191     harris41 4450:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      4451:        my $finalpath=filelocation($dir,$file);
                   4452:        $finalpath=~s/^\/home\/httpd\/html//;
1.225     albertel 4453:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
1.46      www      4454:        return $finalpath;
                   4455:     } else {
                   4456:        return $file;
                   4457:     }
1.31      www      4458: }
                   4459: 
                   4460: # ------------------------------------------------------------- Declutters URLs
                   4461: 
                   4462: sub declutter {
                   4463:     my $thisfn=shift;
                   4464:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   4465:     $thisfn=~s/^\///;
                   4466:     $thisfn=~s/^res\///;
1.235     www      4467:     $thisfn=~s/\?.+$//;
1.268     www      4468:     return $thisfn;
                   4469: }
                   4470: 
                   4471: # ------------------------------------------------------------- Clutter up URLs
                   4472: 
                   4473: sub clutter {
                   4474:     my $thisfn='/'.&declutter(shift);
1.270     www      4475:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
                   4476:        $thisfn='/res'.$thisfn; 
                   4477:     }
1.31      www      4478:     return $thisfn;
1.12      www      4479: }
                   4480: 
                   4481: # -------------------------------------------------------- Escape Special Chars
                   4482: 
                   4483: sub escape {
                   4484:     my $str=shift;
                   4485:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   4486:     return $str;
                   4487: }
                   4488: 
                   4489: # ----------------------------------------------------- Un-Escape Special Chars
                   4490: 
                   4491: sub unescape {
                   4492:     my $str=shift;
                   4493:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   4494:     return $str;
                   4495: }
1.11      www      4496: 
1.415     albertel 4497: sub mod_perl_version {
                   4498:     if (defined($perlvar{'MODPERL2'})) {
                   4499: 	return 2;
                   4500:     }
                   4501:     return 1;
1.436     albertel 4502: }
                   4503: 
                   4504: sub correct_line_ends {
                   4505:     my ($result)=@_;
                   4506:     $$result =~s/\r\n/\n/mg;
                   4507:     $$result =~s/\r/\n/mg;
1.415     albertel 4508: }
1.1       albertel 4509: # ================================================================ Main Program
                   4510: 
1.184     www      4511: sub goodbye {
1.204     albertel 4512:    &logthis("Starting Shut down");
1.443     albertel 4513: #not converted to using infrastruture and probably shouldn't be
1.425     albertel 4514:    &logthis(sprintf("%-20s is %s",'%badServerCache',scalar(%badServerCache)));
1.443     albertel 4515: #converted
1.425     albertel 4516:    &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.443     albertel 4517:    &logthis(sprintf("%-20s is %s",'%homecache',scalar(%homecache)));
1.425     albertel 4518:    &logthis(sprintf("%-20s is %s",'%titlecache',scalar(%titlecache)));
                   4519:    &logthis(sprintf("%-20s is %s",'%courseresdatacache',scalar(%courseresdatacache)));
                   4520: #1.1 only
                   4521:    &logthis(sprintf("%-20s is %s",'%userresdatacache',scalar(%userresdatacache)));
                   4522:    &logthis(sprintf("%-20s is %s",'%usectioncache',scalar(%usectioncache)));
1.440     www      4523:    &logthis(sprintf("%-20s is %s",'%courseresversioncache',scalar(%courseresversioncache)));
                   4524:    &logthis(sprintf("%-20s is %s",'%resversioncache',scalar(%resversioncache)));
1.184     www      4525:    &flushcourselogs();
                   4526:    &logthis("Shutting down");
1.362     albertel 4527:    return DONE;
1.184     www      4528: }
                   4529: 
1.179     www      4530: BEGIN {
1.228     harris41 4531: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      4532:     unless ($readit) {
1.217     harris41 4533: {
1.448     albertel 4534:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 4535: 
                   4536:     while (my $configline=<$config>) {
                   4537:         if ($configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 4538: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      4539:            chomp($varvalue);
1.1       albertel 4540:            $perlvar{$varname}=$varvalue;
                   4541:         }
                   4542:     }
1.448     albertel 4543:     close($config);
1.1       albertel 4544: }
1.227     harris41 4545: {
1.448     albertel 4546:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 4547: 
                   4548:     while (my $configline=<$config>) {
                   4549:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   4550: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   4551:            chomp($varvalue);
                   4552:            $perlvar{$varname}=$varvalue;
                   4553:         }
                   4554:     }
1.448     albertel 4555:     close($config);
1.227     harris41 4556: }
1.1       albertel 4557: 
1.327     albertel 4558: # ------------------------------------------------------------ Read domain file
                   4559: {
                   4560:     %domaindescription = ();
                   4561:     %domain_auth_def = ();
                   4562:     %domain_auth_arg_def = ();
1.448     albertel 4563:     my $fh;
                   4564:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 4565:        while (<$fh>) {
1.390     matthew  4566:            next if (/^(\#|\s*$)/);
                   4567: #           next if /^\#/;
1.327     albertel 4568:            chomp;
1.403     www      4569:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   4570: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   4571: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 4572:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      4573: 	   $domaindescription{$domain}=$domain_description;
                   4574: 	   $domain_lang_def{$domain}=$def_lang;
                   4575: 	   $domain_city{$domain}=$city;
                   4576: 	   $domain_longi{$domain}=$longi;
                   4577: 	   $domain_lati{$domain}=$lati;
                   4578: 
1.448     albertel 4579:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 4580: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 4581: 	}
1.327     albertel 4582:     }
1.448     albertel 4583:     close ($fh);
1.327     albertel 4584: }
                   4585: 
                   4586: 
1.1       albertel 4587: # ------------------------------------------------------------- Read hosts file
                   4588: {
1.448     albertel 4589:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 4590: 
                   4591:     while (my $configline=<$config>) {
1.303     matthew  4592:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      4593:        chomp($configline);
1.245     www      4594:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252     albertel 4595:        if ($id && $domain && $role && $name && $ip) {
                   4596: 	 $hostname{$id}=$name;
                   4597: 	 $hostdom{$id}=$domain;
                   4598: 	 $hostip{$id}=$ip;
1.300     albertel 4599: 	 $iphost{$ip}=$id;
1.252     albertel 4600: 	 if ($role eq 'library') { $libserv{$id}=$name; }
                   4601:        } else {
                   4602: 	 if ($configline) {
                   4603: 	   &logthis("Skipping hosts.tab line -$configline-");
                   4604: 	 }
1.245     www      4605:        }
1.1       albertel 4606:     }
1.448     albertel 4607:     close($config);
1.1       albertel 4608: }
                   4609: 
                   4610: # ------------------------------------------------------ Read spare server file
                   4611: {
1.448     albertel 4612:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 4613: 
                   4614:     while (my $configline=<$config>) {
                   4615:        chomp($configline);
1.284     matthew  4616:        if ($configline) {
1.1       albertel 4617:           $spareid{$configline}=1;
                   4618:        }
                   4619:     }
1.448     albertel 4620:     close($config);
1.1       albertel 4621: }
1.11      www      4622: # ------------------------------------------------------------ Read permissions
                   4623: {
1.448     albertel 4624:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      4625: 
                   4626:     while (my $configline=<$config>) {
1.448     albertel 4627: 	chomp($configline);
                   4628: 	if ($configline) {
                   4629: 	    my ($role,$perm)=split(/ /,$configline);
                   4630: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   4631: 	}
1.11      www      4632:     }
1.448     albertel 4633:     close($config);
1.11      www      4634: }
                   4635: 
                   4636: # -------------------------------------------- Read plain texts for permissions
                   4637: {
1.448     albertel 4638:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      4639: 
                   4640:     while (my $configline=<$config>) {
1.448     albertel 4641: 	chomp($configline);
                   4642: 	if ($configline) {
                   4643: 	    my ($short,$plain)=split(/:/,$configline);
                   4644: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   4645: 	}
1.135     www      4646:     }
1.448     albertel 4647:     close($config);
1.135     www      4648: }
                   4649: 
                   4650: # ---------------------------------------------------------- Read package table
                   4651: {
1.448     albertel 4652:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      4653: 
                   4654:     while (my $configline=<$config>) {
1.448     albertel 4655: 	chomp($configline);
                   4656: 	my ($short,$plain)=split(/:/,$configline);
                   4657: 	my ($pack,$name)=split(/\&/,$short);
                   4658: 	if ($plain ne '') {
                   4659: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   4660: 	    $packagetab{$short}=$plain; 
                   4661: 	}
1.11      www      4662:     }
1.448     albertel 4663:     close($config);
1.329     matthew  4664: }
                   4665: 
                   4666: # ------------- set up temporary directory
                   4667: {
                   4668:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   4669: 
1.11      www      4670: }
                   4671: 
1.71      www      4672: %metacache=();
1.185     www      4673: 
1.281     www      4674: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      4675: $dumpcount=0;
1.22      www      4676: 
1.163     harris41 4677: &logtouch();
1.12      www      4678: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      4679: $readit=1;
                   4680: }
1.1       albertel 4681: }
1.179     www      4682: 
1.1       albertel 4683: 1;
1.191     harris41 4684: __END__
                   4685: 
1.243     albertel 4686: =pod
                   4687: 
1.191     harris41 4688: =head1 NAME
                   4689: 
1.243     albertel 4690: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 4691: 
                   4692: =head1 SYNOPSIS
                   4693: 
1.243     albertel 4694: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 4695: 
                   4696:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   4697: 
1.243     albertel 4698: Common parameters:
                   4699: 
                   4700: =over 4
                   4701: 
                   4702: =item *
                   4703: 
                   4704: $uname : an internal username (if $cname expecting a course Id specifically)
                   4705: 
                   4706: =item *
                   4707: 
                   4708: $udom : a domain (if $cdom expecting a course's domain specifically)
                   4709: 
                   4710: =item *
                   4711: 
                   4712: $symb : a resource instance identifier
                   4713: 
                   4714: =item *
                   4715: 
                   4716: $namespace : the name of a .db file that contains the data needed or
                   4717: being set.
                   4718: 
                   4719: =back
                   4720: 
1.394     bowersj2 4721: =head1 OVERVIEW
1.191     harris41 4722: 
1.394     bowersj2 4723: lonnet provides subroutines which interact with the
                   4724: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   4725: about classes, users, and resources.
1.243     albertel 4726: 
                   4727: For many of these objects you can also use this to store data about
                   4728: them or modify them in various ways.
1.191     harris41 4729: 
1.394     bowersj2 4730: =head2 Symbs
1.191     harris41 4731: 
1.394     bowersj2 4732: To identify a specific instance of a resource, LON-CAPA uses symbols
                   4733: or "symbs"X<symb>. These identifiers are built from the URL of the
                   4734: map, the resource number of the resource in the map, and the URL of
                   4735: the resource itself. The latter is somewhat redundant, but might help
                   4736: if maps change.
                   4737: 
                   4738: An example is
                   4739: 
                   4740:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   4741: 
                   4742: The respective map entry is
                   4743: 
                   4744:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   4745:   title="Problem 2">
                   4746:  </resource>
                   4747: 
                   4748: Symbs are used by the random number generator, as well as to store and
                   4749: restore data specific to a certain instance of for example a problem.
                   4750: 
                   4751: =head2 Storing And Retrieving Data
                   4752: 
                   4753: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   4754: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   4755: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   4756: is is the non-critical message twin of cstore. These functions are for
                   4757: handlers to store a perl hash to a user's permanent data space in an
                   4758: easy manner, and to retrieve it again on another call. It is expected
                   4759: that a handler would use this once at the beginning to retrieve data,
                   4760: and then again once at the end to send only the new data back.
                   4761: 
                   4762: The data is stored in the user's data directory on the user's
                   4763: homeserver under the ID of the course.
                   4764: 
                   4765: The hash that is returned by restore will have all of the previous
                   4766: value for all of the elements of the hash.
                   4767: 
                   4768: Example:
                   4769: 
                   4770:  #creating a hash
                   4771:  my %hash;
                   4772:  $hash{'foo'}='bar';
                   4773: 
                   4774:  #storing it
                   4775:  &Apache::lonnet::cstore(\%hash);
                   4776: 
                   4777:  #changing a value
                   4778:  $hash{'foo'}='notbar';
                   4779: 
                   4780:  #adding a new value
                   4781:  $hash{'bar'}='foo';
                   4782:  &Apache::lonnet::cstore(\%hash);
                   4783: 
                   4784:  #retrieving the hash
                   4785:  my %history=&Apache::lonnet::restore();
                   4786: 
                   4787:  #print the hash
                   4788:  foreach my $key (sort(keys(%history))) {
                   4789:    print("\%history{$key} = $history{$key}");
                   4790:  }
                   4791: 
                   4792: Will print out:
1.191     harris41 4793: 
1.394     bowersj2 4794:  %history{1:foo} = bar
                   4795:  %history{1:keys} = foo:timestamp
                   4796:  %history{1:timestamp} = 990455579
                   4797:  %history{2:bar} = foo
                   4798:  %history{2:foo} = notbar
                   4799:  %history{2:keys} = foo:bar:timestamp
                   4800:  %history{2:timestamp} = 990455580
                   4801:  %history{bar} = foo
                   4802:  %history{foo} = notbar
                   4803:  %history{timestamp} = 990455580
                   4804:  %history{version} = 2
                   4805: 
                   4806: Note that the special hash entries C<keys>, C<version> and
                   4807: C<timestamp> were added to the hash. C<version> will be equal to the
                   4808: total number of versions of the data that have been stored. The
                   4809: C<timestamp> attribute will be the UNIX time the hash was
                   4810: stored. C<keys> is available in every historical section to list which
                   4811: keys were added or changed at a specific historical revision of a
                   4812: hash.
                   4813: 
                   4814: B<Warning>: do not store the hash that restore returns directly. This
                   4815: will cause a mess since it will restore the historical keys as if the
                   4816: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 4817: 
1.394     bowersj2 4818: Calling convention:
1.191     harris41 4819: 
1.394     bowersj2 4820:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   4821:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 4822: 
1.394     bowersj2 4823: For more detailed information, see lonnet specific documentation.
1.191     harris41 4824: 
1.394     bowersj2 4825: =head1 RETURN MESSAGES
1.191     harris41 4826: 
1.394     bowersj2 4827: =over 4
1.191     harris41 4828: 
1.394     bowersj2 4829: =item * B<con_lost>: unable to contact remote host
1.191     harris41 4830: 
1.394     bowersj2 4831: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   4832: when the connection is brought back up
1.191     harris41 4833: 
1.394     bowersj2 4834: =item * B<con_failed>: unable to contact remote host and unable to save message
                   4835: for later delivery
1.191     harris41 4836: 
1.394     bowersj2 4837: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 4838: 
1.394     bowersj2 4839: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 4840: that was requested
1.191     harris41 4841: 
1.243     albertel 4842: =back
1.191     harris41 4843: 
1.243     albertel 4844: =head1 PUBLIC SUBROUTINES
1.191     harris41 4845: 
1.243     albertel 4846: =head2 Session Environment Functions
1.191     harris41 4847: 
1.243     albertel 4848: =over 4
1.191     harris41 4849: 
1.394     bowersj2 4850: =item * 
                   4851: X<appenv()>
                   4852: B<appenv(%hash)>: the value of %hash is written to
                   4853: the user envirnoment file, and will be restored for each access this
                   4854: user makes during this session, also modifies the %ENV for the current
                   4855: process
1.191     harris41 4856: 
                   4857: =item *
1.394     bowersj2 4858: X<delenv()>
                   4859: B<delenv($regexp)>: removes all items from the session
                   4860: environment file that matches the regular expression in $regexp. The
                   4861: values are also delted from the current processes %ENV.
1.191     harris41 4862: 
1.243     albertel 4863: =back
                   4864: 
                   4865: =head2 User Information
1.191     harris41 4866: 
1.243     albertel 4867: =over 4
1.191     harris41 4868: 
                   4869: =item *
1.394     bowersj2 4870: X<queryauthenticate()>
                   4871: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 4872: authentication scheme
                   4873: 
                   4874: =item *
1.394     bowersj2 4875: X<authenticate()>
                   4876: B<authenticate($uname,$upass,$udom)>: try to
                   4877: authenticate user from domain's lib servers (first use the current
                   4878: one). C<$upass> should be the users password.
1.191     harris41 4879: 
                   4880: =item *
1.394     bowersj2 4881: X<homeserver()>
                   4882: B<homeserver($uname,$udom)>: find the server which has
                   4883: the user's directory and files (there must be only one), this caches
                   4884: the answer, and also caches if there is a borken connection.
1.191     harris41 4885: 
                   4886: =item *
1.394     bowersj2 4887: X<idget()>
                   4888: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   4889: (IDs are a unique resource in a domain, there must be only 1 ID per
                   4890: username, and only 1 username per ID in a specific domain) (returns
                   4891: hash: id=>name,id=>name)
1.191     harris41 4892: 
                   4893: =item *
1.394     bowersj2 4894: X<idrget()>
                   4895: B<idrget($udom,@unames)>: find the IDs behind a list of
                   4896: usernames (returns hash: name=>id,name=>id)
1.191     harris41 4897: 
                   4898: =item *
1.394     bowersj2 4899: X<idput()>
                   4900: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 4901: 
                   4902: =item *
1.394     bowersj2 4903: X<rolesinit()>
                   4904: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 4905: 
                   4906: =item *
1.394     bowersj2 4907: X<usection()>
                   4908: B<usection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 4909: course $cname, return section name/number or '' for "not in course"
                   4910: and '-1' for "no section"
                   4911: 
                   4912: =item *
1.394     bowersj2 4913: X<userenvironment()>
                   4914: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 4915: passed in @what from the requested user's environment, returns a hash
                   4916: 
                   4917: =back
                   4918: 
                   4919: =head2 User Roles
                   4920: 
                   4921: =over 4
                   4922: 
                   4923: =item *
                   4924: 
                   4925: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   4926: actions
                   4927:  F: full access
                   4928:  U,I,K: authentication modes (cxx only)
                   4929:  '': forbidden
                   4930:  1: user needs to choose course
                   4931:  2: browse allowed
                   4932: 
                   4933: =item *
                   4934: 
                   4935: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   4936: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   4937: and course level
                   4938: 
                   4939: =item *
                   4940: 
                   4941: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   4942: explanation of a user role term
                   4943: 
                   4944: =back
                   4945: 
                   4946: =head2 User Modification
                   4947: 
                   4948: =over 4
                   4949: 
                   4950: =item *
                   4951: 
                   4952: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   4953: user for the level given by URL.  Optional start and end dates (leave empty
                   4954: string or zero for "no date")
1.191     harris41 4955: 
                   4956: =item *
                   4957: 
1.243     albertel 4958: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   4959: change a users, password, possible return values are: ok,
                   4960: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   4961: refused
1.191     harris41 4962: 
                   4963: =item *
                   4964: 
1.243     albertel 4965: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 4966: 
                   4967: =item *
                   4968: 
1.243     albertel 4969: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   4970: modify user
1.191     harris41 4971: 
                   4972: =item *
                   4973: 
1.286     matthew  4974: modifystudent
                   4975: 
                   4976: modify a students enrollment and identification information.
                   4977: The course id is resolved based on the current users environment.  
                   4978: This means the envoking user must be a course coordinator or otherwise
                   4979: associated with a course.
                   4980: 
1.297     matthew  4981: This call is essentially a wrapper for lonnet::modifyuser and
                   4982: lonnet::modify_student_enrollment
1.286     matthew  4983: 
                   4984: Inputs: 
                   4985: 
                   4986: =over 4
                   4987: 
                   4988: =item B<$udom> Students loncapa domain
                   4989: 
                   4990: =item B<$uname> Students loncapa login name
                   4991: 
                   4992: =item B<$uid> Students id/student number
                   4993: 
                   4994: =item B<$umode> Students authentication mode
                   4995: 
                   4996: =item B<$upass> Students password
                   4997: 
                   4998: =item B<$first> Students first name
                   4999: 
                   5000: =item B<$middle> Students middle name
                   5001: 
                   5002: =item B<$last> Students last name
                   5003: 
                   5004: =item B<$gene> Students generation
                   5005: 
                   5006: =item B<$usec> Students section in course
                   5007: 
                   5008: =item B<$end> Unix time of the roles expiration
                   5009: 
                   5010: =item B<$start> Unix time of the roles start date
                   5011: 
                   5012: =item B<$forceid> If defined, allow $uid to be changed
                   5013: 
                   5014: =item B<$desiredhome> server to use as home server for student
                   5015: 
                   5016: =back
1.297     matthew  5017: 
                   5018: =item *
                   5019: 
                   5020: modify_student_enrollment
                   5021: 
                   5022: Change a students enrollment status in a class.  The environment variable
                   5023: 'role.request.course' must be defined for this function to proceed.
                   5024: 
                   5025: Inputs:
                   5026: 
                   5027: =over 4
                   5028: 
                   5029: =item $udom, students domain
                   5030: 
                   5031: =item $uname, students name
                   5032: 
                   5033: =item $uid, students user id
                   5034: 
                   5035: =item $first, students first name
                   5036: 
                   5037: =item $middle
                   5038: 
                   5039: =item $last
                   5040: 
                   5041: =item $gene
                   5042: 
                   5043: =item $usec
                   5044: 
                   5045: =item $end
                   5046: 
                   5047: =item $start
                   5048: 
                   5049: =back
                   5050: 
1.191     harris41 5051: 
                   5052: =item *
                   5053: 
1.243     albertel 5054: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   5055: custom role; give a custom role to a user for the level given by URL.  Specify
                   5056: name and domain of role author, and role name
1.191     harris41 5057: 
                   5058: =item *
                   5059: 
1.243     albertel 5060: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 5061: 
                   5062: =item *
                   5063: 
1.243     albertel 5064: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   5065: 
                   5066: =back
                   5067: 
                   5068: =head2 Course Infomation
                   5069: 
                   5070: =over 4
1.191     harris41 5071: 
                   5072: =item *
                   5073: 
1.243     albertel 5074: coursedescription($courseid) : course description
1.191     harris41 5075: 
                   5076: =item *
                   5077: 
1.243     albertel 5078: courseresdata($coursenum,$coursedomain,@which) : request for current
                   5079: parameter setting for a specific course, @what should be a list of
                   5080: parameters to ask about. This routine caches answers for 5 minutes.
                   5081: 
                   5082: =back
                   5083: 
                   5084: =head2 Course Modification
                   5085: 
                   5086: =over 4
1.191     harris41 5087: 
                   5088: =item *
                   5089: 
1.243     albertel 5090: writecoursepref($courseid,%prefs) : write preferences (environment
                   5091: database) for a course
1.191     harris41 5092: 
                   5093: =item *
                   5094: 
1.243     albertel 5095: createcourse($udom,$description,$url) : make/modify course
                   5096: 
                   5097: =back
                   5098: 
                   5099: =head2 Resource Subroutines
                   5100: 
                   5101: =over 4
1.191     harris41 5102: 
                   5103: =item *
                   5104: 
1.243     albertel 5105: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 5106: 
                   5107: =item *
                   5108: 
1.243     albertel 5109: repcopy($filename) : subscribes to the requested file, and attempts to
                   5110: replicate from the owning library server, Might return
                   5111: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
                   5112: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
                   5113: resource. Expects the local filesystem pathname
                   5114: (/home/httpd/html/res/....)
                   5115: 
                   5116: =back
                   5117: 
                   5118: =head2 Resource Information
                   5119: 
                   5120: =over 4
1.191     harris41 5121: 
                   5122: =item *
                   5123: 
1.243     albertel 5124: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   5125: a vairety of different possible values, $varname should be a request
                   5126: string, and the other parameters can be used to specify who and what
                   5127: one is asking about.
                   5128: 
                   5129: Possible values for $varname are environment.lastname (or other item
                   5130: from the envirnment hash), user.name (or someother aspect about the
                   5131: user), resource.0.maxtries (or some other part and parameter of a
                   5132: resource)
1.204     albertel 5133: 
                   5134: =item *
                   5135: 
1.243     albertel 5136: directcondval($number) : get current value of a condition; reads from a state
                   5137: string
1.204     albertel 5138: 
                   5139: =item *
                   5140: 
1.243     albertel 5141: condval($condidx) : value of condition index based on state
1.204     albertel 5142: 
                   5143: =item *
                   5144: 
1.243     albertel 5145: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   5146: resource's metadata, $what should be either a specific key, or either
                   5147: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   5148: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   5149: 
                   5150: this function automatically caches all requests
1.191     harris41 5151: 
                   5152: =item *
                   5153: 
1.243     albertel 5154: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   5155: network of library servers; returns file handle of where SQL and regex results
                   5156: will be stored for query
1.191     harris41 5157: 
                   5158: =item *
                   5159: 
1.243     albertel 5160: symbread($filename) : return symbolic list entry (filename argument optional);
                   5161: returns the data handle
1.191     harris41 5162: 
                   5163: =item *
                   5164: 
1.243     albertel 5165: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
                   5166: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
                   5167: failure, user must be in a course, as it assumes the existance of the
                   5168: course initi hash, and uses $ENV('request.course.id'}
                   5169: 
1.191     harris41 5170: 
                   5171: =item *
                   5172: 
1.243     albertel 5173: symbclean($symb) : removes versions numbers from a symb, returns the
                   5174: cleaned symb
1.191     harris41 5175: 
                   5176: =item *
                   5177: 
1.243     albertel 5178: is_on_map($uri) : checks if the $uri is somewhere on the current
                   5179: course map, user must be in a course for it to work.
1.191     harris41 5180: 
                   5181: =item *
                   5182: 
1.243     albertel 5183: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 5184: 
                   5185: =item *
                   5186: 
1.243     albertel 5187: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   5188: a random seed, all arguments are optional, if they aren't sent it uses the
                   5189: environment to derive them. Note: if symb isn't sent and it can't get one
                   5190: from &symbread it will use the current time as its return value
1.191     harris41 5191: 
                   5192: =item *
                   5193: 
1.243     albertel 5194: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   5195: unfakeable, receipt
1.191     harris41 5196: 
                   5197: =item *
                   5198: 
1.243     albertel 5199: receipt() : API to ireceipt working off of ENV values; given out to users
1.191     harris41 5200: 
                   5201: =item *
                   5202: 
1.243     albertel 5203: countacc($url) : count the number of accesses to a given URL
1.191     harris41 5204: 
                   5205: =item *
                   5206: 
1.243     albertel 5207: 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
1.191     harris41 5208: 
                   5209: =item *
                   5210: 
1.243     albertel 5211: 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)
1.191     harris41 5212: 
                   5213: =item *
                   5214: 
1.243     albertel 5215: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 5216: 
                   5217: =item *
                   5218: 
1.243     albertel 5219: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   5220: forcing spreadsheet to reevaluate the resource scores next time.
                   5221: 
                   5222: =back
                   5223: 
                   5224: =head2 Storing/Retreiving Data
                   5225: 
                   5226: =over 4
1.191     harris41 5227: 
                   5228: =item *
                   5229: 
1.243     albertel 5230: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   5231: for this url; hashref needs to be given and should be a \%hashname; the
                   5232: remaining args aren't required and if they aren't passed or are '' they will
                   5233: be derived from the ENV
1.191     harris41 5234: 
                   5235: =item *
                   5236: 
1.243     albertel 5237: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   5238: uses critical subroutine
1.191     harris41 5239: 
                   5240: =item *
                   5241: 
1.243     albertel 5242: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   5243: all args are optional
1.191     harris41 5244: 
                   5245: =item *
                   5246: 
1.243     albertel 5247: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   5248: works very similar to store/cstore, but all data is stored in a
                   5249: temporary location and can be reset using tmpreset, $storehash should
                   5250: be a hash reference, returns nothing on success
1.191     harris41 5251: 
                   5252: =item *
                   5253: 
1.243     albertel 5254: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   5255: similar to restore, but all data is stored in a temporary location and
                   5256: can be reset using tmpreset. Returns a hash of values on success,
                   5257: error string otherwise.
1.191     harris41 5258: 
                   5259: =item *
                   5260: 
1.243     albertel 5261: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   5262: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 5263: 
                   5264: =item *
                   5265: 
1.243     albertel 5266: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   5267: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 5268: 
                   5269: =item *
                   5270: 
1.243     albertel 5271: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   5272: namesp ($udom and $uname are optional)
1.191     harris41 5273: 
                   5274: =item *
                   5275: 
1.243     albertel 5276: dump($namespace,$udom,$uname,$regexp) : 
                   5277: dumps the complete (or key matching regexp) namespace into a hash
                   5278: ($udom, $uname and $regexp are optional)
1.449     matthew  5279: 
                   5280: =item *
                   5281: 
                   5282: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   5283: $store can be a scalar, an array reference, or if the amount to be 
                   5284: incremented is > 1, a hash reference.
                   5285: 
                   5286: ($udom and $uname are optional)
1.191     harris41 5287: 
                   5288: =item *
                   5289: 
1.243     albertel 5290: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   5291: ($udom and $uname are optional)
1.191     harris41 5292: 
                   5293: =item *
                   5294: 
1.243     albertel 5295: cput($namespace,$storehash,$udom,$uname) : critical put
                   5296: ($udom and $uname are optional)
1.191     harris41 5297: 
                   5298: =item *
                   5299: 
1.243     albertel 5300: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   5301: reference filled in from namesp (encrypts the return communication)
                   5302: ($udom and $uname are optional)
1.191     harris41 5303: 
                   5304: =item *
                   5305: 
1.243     albertel 5306: log($udom,$name,$home,$message) : write to permanent log for user; use
                   5307: critical subroutine
                   5308: 
                   5309: =back
                   5310: 
                   5311: =head2 Network Status Functions
                   5312: 
                   5313: =over 4
1.191     harris41 5314: 
                   5315: =item *
                   5316: 
                   5317: dirlist($uri) : return directory list based on URI
                   5318: 
                   5319: =item *
                   5320: 
1.243     albertel 5321: spareserver() : find server with least workload from spare.tab
                   5322: 
                   5323: =back
                   5324: 
                   5325: =head2 Apache Request
                   5326: 
                   5327: =over 4
1.191     harris41 5328: 
                   5329: =item *
                   5330: 
1.243     albertel 5331: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   5332: localhost, posts hash
                   5333: 
                   5334: =back
                   5335: 
                   5336: =head2 Data to String to Data
                   5337: 
                   5338: =over 4
1.191     harris41 5339: 
                   5340: =item *
                   5341: 
1.243     albertel 5342: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   5343: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 5344: 
                   5345: =item *
                   5346: 
1.243     albertel 5347: hashref2str($hashref) : convert a hashref into a string complete with
                   5348: escaping and '=' and '&' separators, supports elements that are
                   5349: arrayrefs and hashrefs
1.191     harris41 5350: 
                   5351: =item *
                   5352: 
1.243     albertel 5353: arrayref2str($arrayref) : convert an arrayref into a string complete
                   5354: with escaping and '&' separators, supports elements that are arrayrefs
                   5355: and hashrefs
1.191     harris41 5356: 
                   5357: =item *
                   5358: 
1.243     albertel 5359: str2hash($string) : convert string to hash using unescaping and
                   5360: splitting on '=' and '&', supports elements that are arrayrefs and
                   5361: hashrefs
1.191     harris41 5362: 
                   5363: =item *
                   5364: 
1.243     albertel 5365: str2array($string) : convert string to hash using unescaping and
                   5366: splitting on '&', supports elements that are arrayrefs and hashrefs
                   5367: 
                   5368: =back
                   5369: 
                   5370: =head2 Logging Routines
                   5371: 
                   5372: =over 4
                   5373: 
                   5374: These routines allow one to make log messages in the lonnet.log and
                   5375: lonnet.perm logfiles.
1.191     harris41 5376: 
                   5377: =item *
                   5378: 
1.243     albertel 5379: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 5380: 
                   5381: =item *
                   5382: 
1.243     albertel 5383: logthis() : append message to the normal lonnet.log file, it gets
                   5384: preiodically rolled over and deleted.
1.191     harris41 5385: 
                   5386: =item *
                   5387: 
1.243     albertel 5388: logperm() : append a permanent message to lonnet.perm.log, this log
                   5389: file never gets deleted by any automated portion of the system, only
                   5390: messages of critical importance should go in here.
                   5391: 
                   5392: =back
                   5393: 
                   5394: =head2 General File Helper Routines
                   5395: 
                   5396: =over 4
1.191     harris41 5397: 
                   5398: =item *
                   5399: 
1.243     albertel 5400: getfile($file) : returns the entire contents of a file or -1; it
                   5401: properly subscribes to and replicates the file if neccessary.
1.191     harris41 5402: 
                   5403: =item *
                   5404: 
1.243     albertel 5405: filelocation($dir,$file) : returns file system location of a file
                   5406: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   5407: directory that relative $file lookups are to looked in ($dir of /a/dir
                   5408: and a file of ../bob will become /a/bob)
1.191     harris41 5409: 
                   5410: =item *
                   5411: 
                   5412: hreflocation($dir,$file) : returns file system location or a URL; same as
                   5413: filelocation except for hrefs
                   5414: 
                   5415: =item *
                   5416: 
                   5417: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   5418: 
1.243     albertel 5419: =back
                   5420: 
                   5421: =head2 HTTP Helper Routines
                   5422: 
                   5423: =over 4
                   5424: 
1.191     harris41 5425: =item *
                   5426: 
                   5427: escape() : unpack non-word characters into CGI-compatible hex codes
                   5428: 
                   5429: =item *
                   5430: 
                   5431: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   5432: 
1.243     albertel 5433: =back
                   5434: 
                   5435: =head1 PRIVATE SUBROUTINES
                   5436: 
                   5437: =head2 Underlying communication routines (Shouldn't call)
                   5438: 
                   5439: =over 4
                   5440: 
                   5441: =item *
                   5442: 
                   5443: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   5444: 
                   5445: =item *
                   5446: 
                   5447: reply() : uses subreply to send a message to remote machine, logs all failures
                   5448: 
                   5449: =item *
                   5450: 
                   5451: critical() : passes a critical message to another server; if cannot
                   5452: get through then place message in connection buffer directory and
                   5453: returns con_delayed, if incapable of saving message, returns
                   5454: con_failed
                   5455: 
                   5456: =item *
                   5457: 
                   5458: reconlonc() : tries to reconnect lonc client processes.
                   5459: 
                   5460: =back
                   5461: 
                   5462: =head2 Resource Access Logging
                   5463: 
                   5464: =over 4
                   5465: 
                   5466: =item *
                   5467: 
                   5468: flushcourselogs() : flush (save) buffer logs and access logs
                   5469: 
                   5470: =item *
                   5471: 
                   5472: courselog($what) : save message for course in hash
                   5473: 
                   5474: =item *
                   5475: 
                   5476: courseacclog($what) : save message for course using &courselog().  Perform
                   5477: special processing for specific resource types (problems, exams, quizzes, etc).
                   5478: 
1.191     harris41 5479: =item *
                   5480: 
                   5481: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   5482: as a PerlChildExitHandler
1.243     albertel 5483: 
                   5484: =back
                   5485: 
                   5486: =head2 Other
                   5487: 
                   5488: =over 4
                   5489: 
                   5490: =item *
                   5491: 
                   5492: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 5493: 
                   5494: =back
                   5495: 
                   5496: =cut

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