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

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

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