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

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

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