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

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

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