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

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

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