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

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

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