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

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

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