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

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

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