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

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

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