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

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

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