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

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

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