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

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

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