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

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

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