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

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

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