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

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

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