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

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

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