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

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

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