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

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

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