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

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

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