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

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

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