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

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

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